starting to feel this might need some refactoring and tests...