#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

/* 250610
NO determination of gps_offset
NO determination of mean lat/long

*/

/* globale Arbeitsvariablen */

#define MXSMP 70000000


void main(argc,argv)
int argc;
char **argv;
{  
  char 			*filename;
  FILE			*fp;
  unsigned char         byte, xbyte;
  int			i,j,dhc,fileno,fileno_prev;
  char			help[1000],dheader[100][1000],hh[1000];


  if (argc<2) { fprintf(stderr,"%s ERROR: needs at least one input file\n",argv[0]); exit(200);}

  for ( i=1; i<argc; i++ )
  {


  	if ((fp=fopen(argv[i], "r"))==NULL) { fprintf(stderr,"%s ERROR: opening input file: %s\n",argv[0],argv[i]); exit(200); }
/* read start header */  
	help[0]='\0';
	for (j=0; j<100; j++) dheader[j][0]='\0';  
	dhc=0;
	byte=0;
/*  	while (( byte != 128) && ( byte != 144) && ( byte != 160) && ( byte != 176) && ( byte != 207 ) && ( byte != 192 )) */
/* old        while (( byte != 128 ) && ( byte != 207 ) && ( byte != 192 ))    */
        while (( byte < 128 ) || ( byte==240 ))

  	{
		fread(&byte,1,1,fp);
/* old 		if ((byte != 240) && (byte != 128))	*/
               if ((byte != 240) && (byte != 128) && ( byte != 207 ) && ( byte != 192 )) 
		{		
			if ( byte == 32 ) {byte=95;} /* replaces spaces by _ in entry */		
			xbyte=byte;
			if ( byte == 61 ) {xbyte = 32;}
			if ( byte == 59 ) {xbyte = 32;}
			strncat(help,&xbyte,1);
			if ( xbyte == 32 ) 
			{		
				dhc++;	
			} else
			{
				strncat(dheader[dhc],&xbyte,1);
			}
		}
/* output start header of 1st file */ 
		if ( i==1 ) { fwrite(&byte,1,1,stdout); }
		if (feof(fp)) { fprintf(stderr,"%s ERROR: no header/data in file %s\n",argv[0],argv[i]); exit(200);}
  	}
	fileno=0; for (j=0; j<=dhc/2; j++) if (!strcmp(dheader[2*j], "DAT_NO")) {strcpy(hh, dheader[2*j+1]); fileno=atoi(hh);}
	fprintf(stderr,"processing file #%d %s (seqno %d)\n",i,argv[i],fileno); 
	if ((fileno_prev!=(fileno-1)) && (i>1)) 
	{
		fprintf(stderr,"%s ERROR: File %s can not be merged with File %s\n",argv[0], argv[i],argv[i-1]);
		exit(200);
	}
	fileno_prev=fileno;

	if ( i!=1 ) fwrite(&byte,1,1,stdout); 
/*	fprintf(stderr,"File #%d with sequential number %d %s header ",i,fileno,argv[i]);
	if ( i==1 ) fprintf(stderr,"copied\n"); else fprintf(stderr,"skipped\n"); */

/* output everything until end block or EOF */
  	while ( !feof(fp) ) 
	{
		fread(&byte,1,1,fp);
		if ( byte != 239 ) 
		{
			fwrite(&byte,1,1,stdout);
		}  else
		{
			if ( i==(argc-1) ) fwrite(&byte,1,1,stdout);
		}

	}   

	fclose(fp);
  }
/* output EF after last file if missing
  if (byte != 239)
  {
	byte=239;
  	fwrite(&byte,1,1,stdout);
  }*/
 }



