Patched fixes from issue 40 into issue 33 for easier merging.

If you pull this into issue-33 it should take care of any conflicts from my fix.