Fixing bugs, adding unit tests