Fixes and test for .toHTML

Fixes #576, though I feel like a just treated the symptom and this code could be improved.

Test for #573 added.