lots of clean-up and a few bug fixes