This isn't very elegant, but you could scatter print statements through the suspect areas to see what is being executed and in what order and what your variable values are.
$tesing = 1;
.
.
print "At second 'if' in do-loop, \$target_name is $target_name" if ($
+testing);
.
.
(untested)
Or something similar.
Theo