Refactored code.
Bug fixing and refactoring.