Ported from C to Perl