initial port of Dr. Trangenstein's c code