patch from Anthony Deaver <bishop@projectmagnus.org> and some rewrites