Cleaned up the code

Cleaned up and restructured code to make it more readable.