Added unit tests, and some minor bug fixes