fixing bugs and refactoring.