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

char **strings;
long baseloc;
FILE *db;
long natlong(long lval)             /* coerce a bigendian long into a natural long */
{
    unsigned char benchar[4];
    unsigned char *p = benchar;
    long natlong;

    *(long *)benchar = lval;
    natlong = *p++;
    natlong <<= 8;
    natlong |= *p++;
    natlong <<= 8;
    natlong |= *p++;
    natlong <<= 8;
    natlong |= *p;
    return(natlong);
}

void getstring(int n)
{
    long loc;
    int len;

    if (strings[n]!=NULL) return;
    fseek(db, n*sizeof(long)+baseloc, SEEK_SET);
    fread(&loc, sizeof(long), 1, db);
    if (loc==0) {
      printf("No such string\n");
      strings[n] = "? ? ?";
      return;
    }
    loc = natlong(loc);
    fseek(db, loc, SEEK_SET);
    fread(&len, sizeof(int), 1, db);
    len = natlong(len);
    strings[n] = (char*)malloc(len);
    fread(strings[n], 1, len, db);
}

int main(int argc, char **argv)
{
    char header[20];
    char lang[30];
    long maxnum;
    int j;
    int order;

    db = fopen(argv[1], "rb");
    if (db == NULL) {
      fprintf(stderr, "Failed to find DB file\n");
      exit(1);
    }
    fread(&order, sizeof(int), 1, db);
    fread(header, sizeof(X_HEADER)-1, 1, db);
    fread(lang, sizeof(char), 30, db);
    fread(&maxnum, sizeof(long), 1, db);
    maxnum = natlong(maxnum);
    strings = (char**) malloc(maxnum*sizeof(char*));
    if (strings==NULL) {
      printf("No memory for strings\n");
      exit(1);
    }
    for (j=0; j<maxnum; j++) strings[j] = NULL;
    baseloc = ftell(db);
    printf("Headers %*s : %s (%d)\n",
           sizeof(X_HEADER)-1, header, lang, maxnum);
    for (;;) {
      int n;
      printf("String number?\n");
      scanf("%d", &n);
      if (n>=maxnum) {
        printf(">>>>>>>>>>>>>>>Test error: Too big\n");
        continue;
      }
      if (n<0) exit(0);
      getstring(n);
      printf("%s\n", strings[n]);
    }
}
