cleaned up version, some refactoring ready to make exhaustive testing