Reorganized the code to make the implementation clearer