Refactored the codebase for better readability and reliability

Pulled out some of the code that could be reused and made them into
methods of their own; also fixed trailing whitespace and mixed
indentation.