Cleaned up, modularized and optimized the code