Reorganized the code and added comments