Various fixes and literal translation of original Perl script.