Refactor for maintainability, misc errors