I think your header is a fixed size? It reads correctly for
the first header, but then you change $size in the loop for
the data portion. For the next header, $size is incorrect,
having the size of the last data portion. I quit looking
when I saw this, it may or may not fix all your problems.