Refactored main code section into function reducing global variables usage greatly.