Reorganized code to be clearer