Most refactoring done. Needs some cleanup and debugging.
Ready for jenkins test run.