Fixes #29, #37, and various bugs