refactoring and pulled in a lot of things from @shaddi