refactored, working code, ready for unit tests