Bugs fixed and tests added