#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "readtext.h"

extern TXTFIELD txtfields[];

int getfield(char *field)
{
   int i;

   for (i = 0;; i++) {
       if (txtfields[i].tag == 0)
           break;
       if (! strcmp(field, txtfields[i].name))
           return i;
   }

   return -1;
}

void readtext(char *name)
{
   FILE *fp;
   char textline[256];
   int textpos;
   int i, j = -1, text_length;
   int c;
   char *cp = NULL, *field = NULL;

   if (! (fp = fopen(name, "r"))) {
       perror("fopen");
       exit(1);
   }

   textpos = 0;
   while ((c = getc(fp)) != EOF) {
       if (c != '\n' && c != EOF) {
           textline[textpos++] = c;
       } else {
           textline[textpos++] = '\0';
           if (textline[0] == '\0') { /* check for keyword-on-own-line case */
               textpos = 0;
               continue;
           }
           if ((textline[0] != ' ') && (textline[0] != '\t')) {
               cp = malloc(textpos);
               field = cp;
               i = 0;
               if (textline[0] == '"') {
                   i++;
                   while (textline[i] != '"' && textline[i] != '\n' &&
                           textline[i] != '\0')
                       *(cp++) = textline[i++];
                       i++;
               } else {
                   while (textline[i] != ' '  && textline[i] != '\t' &&
                           textline[i] != '\n' && textline[i] != '\0')
                       *(cp++) = textline[i++];
               }
               *(cp++) = '\0';
               cp = malloc(textpos);
               if ((j = getfield(field)) == -1) {
                   fprintf(stderr, "mytiffcp: Invalid field name \"%s\"\n",
                           field);
                   exit(1);
               }
               txtfields[j].value = cp;
               while (textline[i] == ' ' || textline[i] == '\t')
                   i++;
               strcpy(cp, &textline[i]);
               text_length = strlen(cp);
           } else {
               if (j == -1) {
                   fprintf(stderr, "mytiffcp: Missing field name\n");
                   exit(1);
               }
               cp = realloc(cp, text_length + textpos);
               txtfields[j].value = cp;
               strcat(cp, "\n");
               i = 0;
               while (textline[i] == ' ' || textline[i] == '\t')
                   i++;
               strcat(cp, &textline[i]);
               text_length = strlen(cp);
           }
           textpos = 0;
       }
   }
}