refactoring and lots of tweaks