Tentative fix for #61. Seems to work OK, but might needs some more tweaks before we can close the issue.