/* This program is licensed under the GNU General Public License, version 2,
 * a copy of which is included with this program.
 *
 * (c) 2003 jan gerber <j@thing.net>
 *
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <ogg/ogg.h>
#include <vorbis/codec.h>
#include "vorbis/vorbisfile.h"

#define COMP_SAMPLE 4096

int compare_samples(char *buffer1, char *buffer2,int samples) {
  int i=0;
  for(i=0;i< samples;i++) {
    if(buffer1[i]!=buffer2[i])
      return 0;
  }

  return 1;
}

int main(int argc, char **argv) {
  OggVorbis_File ov1,ov2;
  char buffer1[COMP_SAMPLE],buffer2[COMP_SAMPLE];
  FILE *file1, *file2, *output, *output_t; 
  char output_t_name[1024];
  int point1=0,point2=0;
  double pos1=0,pos2=0;
  long bytes_read=0,bytes_read2=0;
  ogg_int64_t  raw1=0,raw2=0,i;
  int lettre;

  if(argc<4) {
    printf("%s - no copyright (c) 2003 \n",argv[0]);
    printf("usage:%s file1.ogg file2.ogg output.ogg\n",argv[0]);
    exit(-1);
  }
  file1=fopen(argv[1],"r");
  if(!file1) {
    fprintf(stderr,"Couldn't open %s for reading\n", argv[1]);
    exit(1);
  }
  file2=fopen(argv[2],"r");
  if(!file2) {
    fprintf(stderr,"Couldn't open %s for reading\n", argv[2]);
    exit(1);
  }

  ov_open(file1,&ov1,NULL,-1);
  ov_open(file2,&ov2,NULL,-1);
  pos1=ov_time_total(&ov1,point1)-66;
  if(!ov_time_seek(&ov1,pos1)) {
    if(!ov_time_seek(&ov2,0)) {
      while (bytes_read2!=COMP_SAMPLE && bytes_read2>=0) {
	bytes_read2 = ov_read(&ov2, buffer2,COMP_SAMPLE,0,2,1,&point2);
      }
      if(!bytes_read2) {
	fprintf(stderr,"Couldn't open %s for reading\n", argv[2]);
	exit(1);
      }
      while (bytes_read = ov_read(&ov1, buffer1,COMP_SAMPLE,0,2,1,&point1)) { 
	if(bytes_read == bytes_read2) {
	  if(compare_samples(buffer2,buffer1,bytes_read)) {
	    printf("found sample match in files:\n");
	    printf("in %s here: %d\n",argv[1],ov_raw_tell(&ov1));
	    printf("in %s here: %d\n",argv[2],ov_raw_tell(&ov2));
	    raw1=ov_raw_tell(&ov1);
	    raw2=ov_raw_tell(&ov2);
	  }
	  
	}
      }
    }
  }
 fclose(file1);
 fclose(file2);

 /* now lets put them together */
 if(raw1 && raw2) {
 printf("writing output to %s ..\n",argv[3]);
 file1=fopen(argv[1],"r");
 file2=fopen(argv[2],"r");
 sprintf(output_t_name,"%s.fix.tmp",argv[3]);
 output=fopen(output_t_name,"w");
 for (i=0;i<raw1; i++)
   {
     if((lettre = fgetc(file1)) != EOF)
       {
	 fputc(lettre,output); //put text in the new file
       }
     else {
       printf("error: could not copy %s up to %d\n",argv[1],raw1);
       exit(0);
     }
   }
 for (i=0;i<raw2; i++)
   {     
     lettre = fgetc(file2);
   }

 while ((lettre = fgetc(file2)) != EOF) 
   {
     fputc(lettre,output); //put text in the new file
   }
 

 fclose(output);
 fclose(file1);
 fclose(file2);
 printf("fix file.\n");

 /* fix output ogg stream  */
 output_t=fopen(output_t_name,"r");
 output=fopen(argv[3],"w");
 oggfix(output_t,output);
 fclose(output_t);
 fclose(output);
 remove(output_t_name);
 printf("done.\n");
 }
}
