/*
 * writetext.c,v 1.1 1994/01/28 17:06:49 franktor Exp
 */

#include "marctext.h"

/*
 * I suppose it's fair to assume that there are no \0 in the text format.
 * (Thus I use str- functions)
 */

octetString *
WriteMarcText (Marcrecord *rec)
{
  octetString *os, lbl;
  char buf[CHARS_IN_NORMARC_LINE];
  Marcdata *entry;
  unsigned long length;
  char buf2[10];

  os = (octetString *) malloc(sizeof(octetString));

  strcpy(buf,"*000");
  lbl = WriteMarcData_Label(&rec->label);
  strcat(buf, lbl.value);
  free(lbl.value);
  strcat(buf, "\n");
  length = strlen(buf);
  for (entry = rec->entries; entry; entry = entry->next)
    WriteMarcTextEntry(entry, buf, &length);
  sprintf(buf2, "%c", NORMARC_END_OF_RECORD);
  strcat(buf,buf2);
  /* os = (octetString *) malloc(sizeof(octetString)); */
  os->len = strlen(buf);
  os->value = (char *) malloc(sizeof(char) * os->len + 1);
  strcpy(os->value, buf);
  return os;
}

void
WriteMarcTextEntry (Marcdata *entry, char *data, unsigned long *length)
{
  char format[10];

  data[(*length)++] = MARC_TEXT_LINE_START;
  if (entry->indicators == True) {
    sprintf(format, "%%0%dlu%%c%%c%%s\n", TAG_LENGTH);
    sprintf (data + *length, format, entry->tag,
             entry->indicator1, entry->indicator2, entry->data);
  }
  else
  {
    sprintf(format, "%%0%dlu%%s\n", TAG_LENGTH);
    sprintf (data + *length, format, entry->tag, entry->data);
  }
  *length += strlen (data + *length);
}
