Refactored a bit, organizing the code and putting in appropriate functions. (INCOMPLETE).