diffs from Nick Hibma <n_hibma@freebsd.org>, but with substantial changes from me. XXX Not tested on FreeBSD yet.
Better error checking. Some code rearrengment.