ENH: refactored some code, added useful comments