Reorganized logic and added comments