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