You have obviously worked a lot on this code, but I think you should rewrite this. Start from scratch. It seems like a big mess. I couldn't test it, because my perl interpreter crashes every time I try to run your script. :( Btw this is the first time I've ever seen perl crash.