revised mainly to make compatible with freebsd. Required moving some code segments around.