with some patches from @chmod007