Reverted earlier fix for pull-request #15, this solution is much more robust. Sorry for the spam, will stop committing now until all this is reviewed and accepted or denied.