refactoring and bug fixes
final version