Yeah, it is a bit obfuscated, but not too much. The
$w--+1-2*$d means that it outputs one extra byte per group when encrypting ($d==0) and then strips that extra byte per group when decrypting ($d==1 because the script specified -s to perl and you specified -d to the script).
Stepping through the algorythm, it appears at least close. I haven't had time to debug the problem, though. If I could find a better all-Perl implementation of this, I might be able to compare the behavior of the two and figure out the problem.