Bug fixes, refactoring, adding comments