adding unit tests, fixed some bugs discovered while adding unit tests.