Restructured the code and added comments.