refactored some code. I think this fixes #1