Fix to close files as soon as possible
make id a local variable