Refactoring, code cleanup, error handling and more comments