Applied huge patch (slightly modified) from David Chisnall

These fixes are for the FreeBSD/OpenBSD port.