Added unit tests and fixed bugs