perl port of the script (must clean code yet)