Why are your files opened in text mode? If you're doing all of this file manipulation down to the byte level, the file(s) need to be opened as binary files.

Regards,

Paul McKenzie