Made some unit tests and fixed up the code somewhat.