Added unit tests. Fixed some bugs.