Simplifications, bug fixes, added test code.