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

struct glstringrec {
  int stringnum;
  int textlength;
  int numlines;
};
char text[20480];

void writerec(FILE *destf, struct glstringrec rec);

int main(int argc, char *argv[]) {
  FILE *inputf, *outputf;
  struct glstringrec rec;
  char *inputfilename, *outputfname;
  char oneline[1024];
  int len = 0;

  if (argc > 1) {
    if (strcmp(argv[1], "-h") == 0) {
      printf("Usage: %s input_file [output_file]\n", argv[0]);
      return 0;
    } else
      inputfilename = argv[1];
  } else
    inputfilename = "glstrings.txt";

  if ((inputf = fopen(inputfilename, "r")) == NULL) {
    printf("Unable to open input file %s\n", inputfilename);
    return 0;
  }

  if (argc == 3)
    outputfname = argv[2];
  else
    outputfname = "glstrings.bin";

  if ((outputf = fopen(outputfname, "wb")) == NULL) {
    printf("Unable to create output file %s\n", outputfname);
    return 0;
  }

  rec.stringnum = 0;
  rec.numlines = 0;
  memset(text, '\0', sizeof(text));

  while (fgets(oneline, sizeof(oneline), inputf)) {
    if (oneline[0] == '%' && atoi(oneline+1) > 0) { /* new string */
      if (rec.stringnum)  /* we have a full record */
        writerec(outputf, rec);
      rec.stringnum = atoi(oneline+1);
      memset(text, '\0', sizeof(text));
      rec.numlines = 0;
      len = 0;
    } else if (oneline[0] == '\n' || oneline[0] == '#') { /* comment */
      continue;
    } else if (oneline[strlen(oneline)-2] == '\\') { /* multi-line line */
      oneline[strlen(oneline)-2] = '\0';
      len = len + strlen(oneline) + 4;  /* extra 4 for \r and \n */
      if (len < sizeof(text)) {
        strcat(text, oneline);
        strcat(text, "\\r\\n");
      }
    } else {
      len += strlen(oneline);
      if (len < sizeof(text)) {
        strcat(text, oneline);
        rec.numlines++;
      }
    } /* else */
  } /* while */
  if (rec.stringnum)  /* we have a full record */
    writerec(outputf, rec);
  fclose(inputf);
  fclose(outputf);
  return 0;
}

void writerec(FILE *destf, struct glstringrec rec) {
  rec.textlength = strlen(text);
  if (rec.textlength < 1) {
    printf("Error: record %d has no text!\n", rec.stringnum);
    fclose(destf);
    exit(1);
  }
  if (text[rec.textlength - 1] == '\n')
    text[rec.textlength - 1] = '\0';
  if (fwrite(&rec, sizeof(rec), 1, destf) != 1) {
    printf("Error writing to output file\n");
    fclose(destf);
    exit(1);
  }
  if (fwrite(text, rec.textlength, 1, destf) != 1) {
    printf("Error writing to output file\n");
    fclose(destf);
    exit(1);
  }
}

