Restore several reverted commits, and fix some others

Somehow I managed to overwrite the changes to the working branch while working on a fork. This replaces all of those changes, and adds several fixes suggested by PR #148.