Moved functions outside of main() and some code clean-up