Fixing some bugs, adding some tests.