Initial refactoring - it all works now.