added tests and refactored slightly