General refactoring and revision for bugs