based on patch by nik
thanks to Peter Mazinger (psm) for pointing many of these issues out and submitting a patch on which this commit is loosely based