some code restructuring
added comments