Restructured code and added comments