#include "gameinc.h"

#define LEN 8*1024
char history[LEN];

void hist_open() {
  FILE *f;
  char str[256];
  int avail = LEN;
  sprintf(str,"%s%s", dir_cfg.share_path,"history.dat");
  f = fopen (str, "r");
  *history = 0;
  if (f) {
    while (!feof(f)) {
      fgets(str,255,f);
      if (!strncmp(str,"$info=",6)) {
	char *s = strstr(str,current_game->main_name);
	int len = strlen(current_game->main_name);
	if (s && (*(s-1)=='=' || *(s-1)==',' || *(s-1) == ' ') &&
	    (*(s+len)==',' || *(s+len)==' ')) { // found it...
	  do {
	    fgets(str,255,f);
	    len = strlen(str)-1;
	    while (str[len]<32 && len>=0) // crlf ?
	      str[len--] = 0;
	    len++;
	    // The use of strncmp is to be able to handle crlfs files in unix
	    if (!strncmp(str,"$end",4) || feof(f))
	      break;
	    if ((str[0]!='$' || strncmp(str,"$bio",4)) && avail > len) {
	      strcat(history,str);
	      strcat(history,"\n");
	      avail -= len+1;
	    } else if (avail < len)
	      printf("buffer overflow in history.dat %d needed, have %d\n",len,avail);
	  } while (1);
	  break;
	}
      }
    } // while ...
    fclose(f);
  }
}
