Fixed a serious bug. Added more tests.