Fixed a critical bug and several minor ones. Added some tests.