Fix several bugs listed in Issue #3

Unit tests included.