Fixed some bugs found by adding tests.
Added tests.