Cleaned up main routine and made code more modular