Refactoring complete with bug fixes