improved code structure, added commments