Based on work from rsadowski@ (in openbsd-wip) and with lots of input from sthen@. OK sthen@, thanks!