optimized code, divided main into a few more functions.