Fixed bugs. Added new unit tests