*Note from cwebber on merge of this branch:* Thanks also to Sturm who provided an early version of this patch.