Adding tests, fixing various bugs occuring during refactoring.