Is there a reason you write $type=='vertical' content to a file, then read it back in, then write it out to a different file?  You could keep this in an array and then write it out once right?