Fixed bugs and small refactoring.