OK fixed it, had to close some files at the end of some loops, and then reset some variables to 0 and it worked fine :-/

Stupid mistakes...