Thanks for the suggestions. You're right it was quite hard to read. Hopefully, I've updated the code to make it clearer. It should run as a standalone now. I tried to simplify it further but the results started to change so I guess this is as reduced as I can make it.
Thanks again
PJ
use strict; use warnings; use diagnostics; (if needed)