Fixed errors, beautified code, added commentary