lots of clean-up and refactoring