/* ------------------------------------------------------------------- */
/* M2Mconv   : Convert an ISO 2709 record into MARC format             */
/* Author    : Ole Husby, BIBSYS                                       */
/* Updated   : 1998-09-30                                              */
/* ------------------------------------------------------------------- */

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <unistd.h>




int M2Mconv(char *dfile, char *buffer, char *tfile, int format)
{
  char mtype[16], line[50000];
  char *l, *p, *bf;
  int lines;
  FILE *df, *tf;

  tf = (FILE *) NULL;
  strcpy(mtype, "bibsys");


/* Open inputfile */

  df = fopen(dfile, "r");
  if (!df)
    return 0;                            /* Error: Unable to read data */



/* Open tracefile */

   if (*tfile)
   {
     tf = fopen(tfile, "w");
     if (!tf)
     {
       fclose(df);
       return 0;                         /* Error: Unable to create trace */
     }
   }


/* Reads the file */ 

   lines = 0;

   while (l = fgets(line, 49999, df))
   {
/*   Remove trailing lf or cr     */

     while ( (l[strlen(l) - 1] == '\n') || (l[strlen(l) - 1] == '\r') )
       l[strlen(l) -1] = '\0';

     lines++;
     if (lines > 1)
       break;                            /* Error: Not a 2709 file       */
     p = l;
   }


/* Close files */ 

  fclose(df);

  if (tf)
    fclose(tf);

  if ( lines > 1 )
    return 0;


/* Convert to line format */

  bf = (char *) marc2line(p, mtype);

  strcpy(buffer, bf);

  return 1;
}
