Can you provide a reduced and condensed version of the actual problem you are having? This would make it easier for everyone here to help you with the Perl. Like this it looks like an awful lot of problem-specific code the meaning of which you probably know better than anyone else here.