Fixed bugs and added unit tests