Done refactoring. Need to comment and test.