refactored the long main function into readable pieces