Reorganized code and added comments