Reorganized the code to be clearer