implemented optimal reverse, some refactoring