Hmmm, both closefiles should be within the "if file opened"'s, but that shouldn't cause mentioned bug. Try replacing openfile with readfile. I'm still not shure what the bug might be.
Edit: I tried to replicate your bug, the code you have given seemed to work fine.
Edit: I tried to replicate your bug, the code you have given seemed to work fine.