/* champ_unwrap.c Take stdin and write to stdout same with GFZ champ wrapper removed. Write data to stdout when observe that next ID or EOF has occurred on schedule Write errors to stderr. */ #include #include #include #define MAXLEN 40000 main(int argc, char *argv[]) { unsigned char b,bytea,byteb,bbuf[MAXLEN],byte; unsigned short int len=0; int nbyte=0; /* # of bytes read */ int nskip=0; /* # of bytes wasted searching for header bytes */ int ndrop=0; /* # of bytes read as data but not written */ int nskip_last=0; /* nskip at time of last write */ int oknow=1; /* current packet is OK so far */ char *pnam = argv[0]; int flip=0; char y,*x; bytea=0xf1; byteb=0xf2; if(argc != 1) { if(strcmp(argv[1],"-flip")==0) flip = 1; else { fprintf(stderr, "Usage: For big-endian platform,\n" " cat file1 file2 | %s > outputfile\n" " For little-endian platform,\n" " cat file1 file2 | %s -flip > outputfile\n",pnam,pnam); return 1; } } while(1) { /* Read first byte of format */ /* if normal end of file write latest data and write message */ if(fread(&b, sizeof(byte), 1, stdin) != 1) { if(oknow&&len) fwrite(bbuf, sizeof(byte), (size_t) len, stdout); if(nskip==0) { fprintf(stderr,"%s: Normal end of file after %d bytes\n",pnam,nbyte); return 0; } else { fprintf(stderr,"%s: Normal end of file, but skipped %d bytes, dropped %d bytes, after %d bytes\n",pnam,nskip,ndrop,nbyte); return 1; } } nbyte++; /* if ID byte 1 funny */ if((b!=bytea)&&(b!=byteb)) { if(oknow) fprintf(stderr,"%s: First ID byte after %d bytes is 0x%0x not 0xf1 or 0xf2\n",pnam,nbyte,b); nskip++; oknow=0; continue; } /* Read second byte of format */ if(fread(&b, sizeof(byte), 1, stdin) != 1) { fprintf(stderr,"%s: Second ID byte missing after %d bytes\n",pnam,nbyte); return 1; } nbyte++; /* if ID byte 2 funny */ if(b!=0x00) { if(oknow) fprintf(stderr,"%s: Second ID byte is not 0x00 after %d bytes\n",pnam,nbyte); nskip++; oknow=0; continue; } oknow=1; /* If ID bytes good, print previous buffer */ if(len) { if(nskip==nskip_last) fwrite(bbuf, sizeof(byte), (size_t) len, stdout); else { fprintf(stderr,"%s: Dropping %d bytes of data due to bad subsequent ID byte\n",pnam,len); ndrop+=len; } } len=0; nskip_last=nskip; /* Read data length bytes */ if(fread(&len, sizeof(short int), 1, stdin) != 1) { fprintf(stderr,"%s: End of file in length bytes after %d bytes\n",pnam,nbyte); return 1; } /* if(flip) { flip_len(char*)(&len)) } */ if(flip) { x = (char *)(&len); y=x[0]; x[0]=x[1]; x[1]=y; } nbyte+=2; if(len>MAXLEN) { fprintf(stderr,"%s: Length %d greater than %d after %d bytes\n",pnam,len,MAXLEN,nbyte); return 1; } /* Read data */ if(fread(bbuf, sizeof(byte), (size_t) len, stdin) != len) { fprintf(stderr,"%s: End of file in middle of data after %d bytes\n",pnam,nbyte); return 1; } nbyte+=len; } return 0; } /* void flip_len(char *a) { char b; b=a[0] a[0]=a[1]; a[1]=b; return; } */