OK, but it's not clear what you are trying to do. Can you split it into two separate scripts for clarity?