Except for the sets, these look like they should all be declared inside the loop (at point of first use)