The only problem I can see is that your open fails, possibly due to that $basepath or $filename does not contain what you expect.
Are they global vars or my'ed ??
Update: Rereading your post I see that you only have $filename inside the loop which explains why the open fails. Why is this so ?