/*
    REFERENCES -- bibliographic software
    Copyright (C) 1995-2007  Volker Kiefel

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
    USA
*/

/*
  bbf_fun.c
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "refs.h"
#include "str_fun.h"
#include "fl_ut.h"
#include "interf.h"
#include "bbf_fun.h"

 extern char wrtxtbu[WRTXTBU_LEN+1];

/*
  greift auf *.bbt-Dateien zu: Wenn die Datensaetze in src_name sortiert
  sind, uebertraegt dupl_ex_bbf die Datensaetze nach destin_name, wobei die
  Doubletten nicht beruecksichtigt werden.
*/

void dupl_ex_bbf( char * src_name, char * destin_name)
{
   FILE * fpsrc;
   FILE * fpdestin;
   long i,anzahl_records;
   bbatchtable_rec one_batch_rec;
   char kennz_alt[KENNZIFFER_LEN+1];

   if (!isfile(src_name))
   {
      fprintf(stderr,"\nProblem: %s not found\n",src_name);
      exit(1);
   }

   if (filesize(src_name) < 2*sizeof(one_batch_rec))
   {
      if (isfile(destin_name)) remove(destin_name);
      rename(src_name,destin_name);
      return;
   }

   if ((fpsrc=fopen(src_name,"rb"))==NULL)
   {
      fprintf(stderr,"\nProblem: Cannot read %s\n",src_name);
      exit(1);
   }

   if (setvbuf(fpsrc,NULL,_IOFBF,7000)!=0)
   {
      fprintf(stderr,"\nProblem: Allocation of "
          "memory in buffer `dupl_ex_bbf' failed\n");
      exit(1);
   }


   if ((fpdestin=fopen(destin_name,"wb"))==NULL)
   {
      fprintf(stderr,"\nProblem: Cannot create %s\n",src_name);
      exit(1);
   }

   if (setvbuf(fpdestin,NULL,_IOFBF,5000)!=0)
   {
      fprintf(stderr,"\nProblem: Allocation of memory "
          "in `dupl_ex_bbf' failed\n");
      exit(1);
   }
   strncpy(kennz_alt,"",KENNZIFFER_LEN+1);
   memset(&one_batch_rec,0,sizeof(one_batch_rec));
   fseek(fpsrc,0L,SEEK_END);
   anzahl_records = ftell(fpsrc)/sizeof(one_batch_rec);
   rewind(fpsrc);
   for (i=1;i<=anzahl_records;i++)
   {
       if (fread(&one_batch_rec,sizeof(one_batch_rec),1,fpsrc)==0)
       {
          wrtxt("\nProblem: ERROR record not read!\n");
       }
       if (strcmp(kennz_alt,one_batch_rec.kennziffer)!=0)   /* ungleich... */
       {
          if (fwrite(&one_batch_rec,sizeof(one_batch_rec),1,fpdestin) < 1) schreibfehler();
       }
       strncpy(kennz_alt,one_batch_rec.kennziffer,KENNZIFFER_LEN+1);
   }
   fclose(fpsrc);
   fclose(fpdestin);
}

