Reorganized the code to make it a bit more readable.