lots of debugging and refactoring