Fixed bugs in code, added clarifying comments