Actually, it doesn't work "fine". Or, to be more accurate, the version posted by MMX doesn't work fine because it uses variables which are also used by the ROM.
It uses variables 0x7030 - 0x7033 (if I remember correctly) which are "illegal" variables in FR. That is, they share RAM space with the PC box.
That said, the routine itself works fine, its just the variables chosen which cause the problem.
And I actually ported this routine to Ruby before, but have long since lost the code, and I can tell you, that the code was very similar to the original FR code. But that was by sheer coincidence - SQ is right, normally a routine will not use the same registers between 2 versions.