Reorganized the code into a more readable form