Maintenance

A bunch of bugfixes I've been sitting on the for the past few years.  All tested and necessary.  Please merge them in, or if you think the fix is not right, let me know, and I'll happily adjust the patches and resubmit.