Refactoring, code cleanup and more comments