Major refactoring of python code in place. Now needs to be tested.