Added more thorough tests and refactored a little