lots of refactoring and code cleaning