#include "parse.h"

lesson *parseLessonFile(char *lessonFileName)
{
  int lessFD;
  char *instr, *tmp, *sltitle;
  lesson *retval = NULLL;
  lesson *temp;
  sublesson *sltemp = NULLSL;
  char *sep = "\t\n ";
  char *fullFileName;

  fullFileName = (char *)malloc(strlen(KQDATADIR)+strlen(lessonFileName)+2);
  sprintf (fullFileName, "%s/%s", KQDATADIR, lessonFileName);

  lessFD = open (fullFileName, O_RDONLY);
  
  if (lessFD < 0) {
    fprintf (stderr, "Unable to read lesson file %s.\n", lessonFileName);
    exit (1);
  }
  else {
    instr = (char *)malloc (MAXLENGTH);
    tmp   = (char *)malloc (MAXLENGTH);
    readLine (lessFD, instr, MAXLENGTH);
    while (*instr != '\0') {                 /* Until the end of the file,  */
      if (*instr == '%') {                   /* If the line is a comment,   */
	readLine (lessFD, instr, MAXLENGTH); /* Ignore and get anotherline.*/ 
	continue;
      }
      tmp = strtok (instr, sep);             /* Otherwise,take the 1st token*/
      if (tmp == NULL) {                     /* If there isn't a 1st token, */
	readLine (lessFD, instr, MAXLENGTH); /* Ignore and get another line.*/
	continue;
      }
      if (strcmp (tmp, "lesson") == 0) {     /* If 1st token = "lesson"     */
	tmp = strtok (NULL, sep);            /* Get 2nd token (lesson name) */
	if (tmp != NULL) {                   /* if there is a 2nd token,    */
	  temp = newLesson (tmp);            /* call newLesson (creator)    */
	  if (retval == NULLL) {             /* If 1st call to newLesson,   */
	    retval = temp; }                 /* make list from lesson.      */
	  else {
	    lessonTail (retval, temp); }     /* else put lesson at list-tail*/
	  readLine (lessFD, instr, MAXLENGTH); /* get another line.         */
	}  
	else {                                /* If 2nd token == NULL,      */
	  readLine (lessFD, instr, MAXLENGTH);/* Ignore and get anotherline.*/
	  continue; }
      }
      else {                                 /* If 1st token != "lesson",   */
	sltitle = getTitle (tmp);    /* use as filename, and get lesson name*/
	sltemp = newSubLesson(sltitle, tmp);  /* call newSubLesson (creator)*/
	addSLtoL (temp, sltemp);          /* add sublesson to current lesson*/
	readLine (lessFD, instr, MAXLENGTH);   }  /* get another line.      */
    }  
  }
  close (lessFD);
  free (instr);
  free (tmp);
  free (fullFileName);
  return retval;
}

SLData *parseDataFile(char *dataFileName)
{
  int dataFD;
  char *instr, *kan, *jread, *read, *bmfile, *mean, *mem, *use;
  char *tmp, *copy, *instr2, *instr3;
  SLData *retval = NULLSLDATA;
  kanji *ktemp = NULLKANJI;
  mQuestion *mqtemp = NULLMQ;
  rQuestion *rqtemp = NULLRQ;
  char *sep = "\t\n ";
  char *ret = "\n";
  char *fullFileName;
  answer *tempanswer = NULLANSWER;
  char *qtemp, *qtemp2, *atemp, *ntemp;
  char *newr = "NEWREADING";
  char *newn = "";
  int firstK = 0;
  ktype curtype;

  fullFileName = (char *)malloc(strlen(KQDATADIR)+strlen(dataFileName)+2);
  sprintf (fullFileName, "%s/%s", KQDATADIR, dataFileName);

  printf ("Began parsing %s.\n", dataFileName);

  dataFD = open (fullFileName, O_RDONLY);

  if (dataFD < 0) {
    fprintf (stderr, "Unable to open data file %s.\n", dataFileName);
  }
  else {
    instr   = (char *)malloc (MAXLENGTH);
    instr2  = (char *)malloc (MAXLENGTH);
    instr3  = (char *)malloc (MAXLENGTH);
    copy    = (char *)malloc (MAXLENGTH);
    qtemp2  = (char *)malloc (MAXLENGTH);
    mem     = (char *)malloc (MAXMEM * MAXLENGTH);
    use     = (char *)malloc (MAXMEM * MAXLENGTH);
    readLine (dataFD, instr, MAXLENGTH);
    while (*instr != '\0') {
      if (*instr == '%') {
	readLine (dataFD, instr, MAXLENGTH);
	continue;
      }
      strcpy (copy, instr);
      tmp = strtok (instr, sep);
      if ((tmp == NULL) || (*tmp == ' ')) {
	readLine (dataFD, instr, MAXLENGTH);
	continue;
      }
      if ((strcmp(tmp,"newreading") ==0) || (strcmp(tmp,"newreadings") ==0)) {
	readLine (dataFD, instr, MAXLENGTH);
	while ((*instr != ' ') && (*instr != '\012') && (*instr != NULL)) {
/*-----------------------------------------------------------------*/
	  while (strncmp (instr, "{usage}", 7) == 0) {
	    strcpy (use, "");
	    firstK = 0;
	    strcpy (instr, instr+7);
	    qtemp = strtok (instr, sep);
	    strcpy (qtemp2, qtemp);
	    strcat (use, qtemp);
	    strcat (use, " [ ");
	    rqtemp = newRQuestion (qtemp2);
	    atemp = strtok (NULL, sep);
	    while (atemp != NULL) {
	      if (firstK == 1) {
		strcat (use, " / "); }
	      strcat (use, atemp);
	      if (firstK == 0) {
		firstK = 1; }
	      tempanswer = newAnswer (atemp);
	      if (rqtemp->ans == NULLANSWER) {
		rqtemp->ans == tempanswer; }
	      else {
		addAtoRQ (rqtemp, tempanswer); }
	      atemp = strtok (NULL, sep); }
	    strcat (use, " ]   ");
	    readLine (dataFD, instr, MAXLENGTH);
	    if (strncmp (instr, "{note}", 6) == 0) {
	      strcpy (instr, instr+6);
	      if (rqtemp->notes == (char *)0) {
		rqtemp->notes = instr; }
	      else {
		addNoteToRQ (rqtemp, instr); }
	      readLine (dataFD, instr, MAXLENGTH); }
	    strcpy (instr, strtok (instr, ret));
	    strcat (use, instr);
	    strcat (use, "\n");
	    mqtemp = newMQuestion (qtemp2, instr);
	    tempanswer = newAnswer (instr);
	    if (retval->allAns == NULLANSWER) {
	      retval->allAns = tempanswer; }
	    else {
	      addAtoSLData (retval, tempanswer); }
	    readLine (dataFD, instr, MAXLENGTH);
	    while ((*instr != '\n')&& (*instr != '%') && (*instr != '\0')
		   && (strncmp (instr, "{usage}", 7) != 0)) {
       	      tempanswer = newAnswer (instr);
	      addAtoSLData (retval, tempanswer);
	      addAtoMQ (mqtemp, tempanswer->ans);
	      readLine (dataFD, instr, MAXLENGTH); }
	    if (retval->rQues == NULLRQ) {
	      retval->rQues == rqtemp; }
	    else {
	      addRQtoSLData (retval, rqtemp); }
	    if (retval->mQues == NULLMQ) {
	      retval->mQues = mqtemp; }
	    else {
	      addMQtoSLData (retval, mqtemp); }
	    while ((instr == NULL) || (*instr == ' ') || (*instr == '%')
		   || (*instr == '\012')) {
	      readLine (dataFD, instr, MAXLENGTH); }
	    ktemp = newKanji (newr, newn, newn, newn, newn, newn, use);
	    if (retval->kan == NULLKANJI) {
	      retval->kan = ktemp; }
	    else {
	      addKtoSLData (retval, ktemp); }
	  }
	}
      }
/*-----------------------------------------------------------------*/	  
      if ((strcmp (tmp, "kanji") == 0) || (strcmp (tmp, "kana") == 0)) {
	if (strcmp (tmp, "kanji") == 0) {
	  curtype = KANJI; }
	else {
	  curtype = KANA; }
	kan = strtok (NULL, sep);
	if (kan == NULL) {
	  readLine (dataFD, instr, MAXLENGTH);
	  continue; }
	if (curtype == KANJI) {
	  jread = strtok (NULL, sep);
	  if (jread == NULL) {
	    readLine (dataFD, instr, MAXLENGTH);
	    continue; }
	}
	read = strtok (NULL, sep);
	if (read == NULL) {
	  readLine (dataFD, instr, MAXLENGTH);
	  continue; }
	if (curtype == KANJI) {
	  bmfile = strtok (NULL, sep);
	  readLine (dataFD, instr2, MAXLENGTH);
	  mean = instr2;
	  if (mean == NULL) {
	    readLine (dataFD, instr2, MAXLENGTH);
	    continue; }
	  strcpy (mem, "");
	  strcpy (use, "");
	  readLine (dataFD, instr3, MAXLENGTH);
	  if (strncmp (instr3, "{memory}", 8) == 0) {
	    strcpy (instr3, instr3+8);
	    while ((*instr3 != '\n') && (*instr3 != '\0') && (*instr != '%')
		   && (strncmp (instr3, "{usage}", 7) != 0)
		   && (strncmp (instr3, "kanji", 5) != 0)) {
	      strcat (mem, instr3);
	      readLine (dataFD, instr3, MAXLENGTH); }
	    while (strncmp (instr3, "{usage}", 7) == 0) {
	      firstK = 0;
	      strcpy (instr3, instr3+7);
	      qtemp = strtok (instr3, sep);
	      strcpy (qtemp2, qtemp);
	      strcat (use, qtemp);
	      strcat (use, " [ ");
	      rqtemp = newRQuestion (qtemp2);
	      atemp = strtok (NULL, sep);
	      while (atemp != NULL) {
		if (firstK == 1) {
		  strcat (use, " / "); }
		strcat (use, atemp);
		if (firstK == 0) {
		  firstK = 1; }
		tempanswer = newAnswer (atemp);
		if (rqtemp->ans == NULLANSWER) {
		  rqtemp->ans == tempanswer; }
		else {
		  addAtoRQ (rqtemp, tempanswer); }
		atemp = strtok (NULL, sep); }
	      strcat (use, " ]   ");
	      readLine (dataFD, instr3, MAXLENGTH);
	      if (strncmp (instr3, "{note}", 6) == 0) {
		strcpy (instr3, instr3+6);
		if (rqtemp->notes == (char *)0) {
		  rqtemp->notes = instr3; }
		else {
		  addNoteToRQ (rqtemp, instr3); }
		readLine (dataFD, instr3, MAXLENGTH); }
	      strcpy (instr3, strtok (instr3, ret));
	      strcat (use, instr3);
	      strcat (use, "\n");
	      mqtemp = newMQuestion (qtemp2, instr3);
	      tempanswer = newAnswer (instr3);
	      if (retval->allAns == NULLANSWER) {
		retval->allAns = tempanswer; }
	      else {
		addAtoSLData (retval, tempanswer); }
	      readLine (dataFD, instr3, MAXLENGTH);
	      while ((*instr3 != '\n')&& (*instr3 != '%') && (*instr3 != '\0')
		     && (strncmp (instr3, "{usage}", 7) != 0)) {
		strcpy (instr3, strtok (instr3, ret));
		tempanswer = newAnswer (instr3);
		addAtoSLData (retval, tempanswer);
		addAtoMQ (mqtemp, tempanswer->ans);
		readLine (dataFD, instr3, MAXLENGTH); }
	      if (retval->rQues == NULLRQ) {
		retval->rQues == rqtemp; }
	      else {
		addRQtoSLData (retval, rqtemp); }
	      if (retval->mQues == NULLMQ) {
		retval->mQues = mqtemp; }
	      else {
	      addMQtoSLData (retval, mqtemp); }
	      while ((instr3 == NULL) || (*instr3 == ' ') || (*instr3 == '%')
		     || (*instr3 == '\012')) {
		readLine (dataFD, instr3, MAXLENGTH); }
	    }
	  }
	  ktemp = newKanji (kan, jread, read, bmfile, mean, mem, use);}
	else {
	  ktemp = newKana (kan, read); }
	/*printf ("Created kanji %s\n", read);*/
	if (retval->kan == NULLKANJI) {
	  retval->kan = ktemp; }
	else {
	  addKtoSLData (retval, ktemp); }
	strcpy (instr, instr3);
	if (curtype == KANA) {
	  readLine (dataFD, instr, MAXLENGTH); }
      }
      else {
	if (retval == NULLSLDATA) {
	  printf("\nTitle = %s", copy);
	  readLine (dataFD, instr2, MAXLENGTH);
	  while ((*instr2 == '%') || (*instr2 == '\0') || (*instr2 == '\n')) {
	    readLine (dataFD, instr2, MAXLENGTH); }
	  printf("\nSubtitle - %s", instr2);
	  retval = newSLData (copy, instr2);
	  readLine (dataFD, instr, MAXLENGTH);
	}
      }
    }
    free (instr);
    free (instr2);
    free (instr3);  
    free (qtemp2);
    free (copy);
    free (mem);
    free (use);
  }
  close (dataFD);
  return retval;
}


void readLine(int fd, char *buf, int maxlen)
{
  int nread, nleft;
  char *where;

  nleft = maxlen;
  where = buf;
  nread = read (fd, where, 1);
  if (nread < 1) {
    *buf = '\0';
    return;
  }
  nleft--;
  where++;
  while (nleft>0 && *(where-1) != '\n') {
    nread = read (fd, where, 1);
    if (nread < 1) {
      *where = '\0';
      return;
    }
    nleft --;
    where ++;
  }
  *where = '\0';
}


char *getTitle(char *dataFileName)
{
  int dataFD;
  int done = 0;
  char *instr = (char *)malloc (MAXLENGTH);
  char *tmp = (char *)malloc(MAXLENGTH);
  char *sep = "\n";
  char *fullFileName;

  fullFileName = (char *)malloc(strlen(KQDATADIR)+strlen(dataFileName)+2);
  sprintf(fullFileName, "%s/%s", KQDATADIR, dataFileName);

  dataFD = open (fullFileName, O_RDONLY);

  if (dataFD < 0) {
    fprintf (stderr, "Unable to read data file %s.\n", dataFileName);
    strcpy (tmp, "");
  }
  else {
    readLine (dataFD, instr, MAXLENGTH);
    tmp = strtok (instr, sep);
    while ((*instr == '\0') || (*instr == '%') || (tmp == NULL)) {
      readLine (dataFD, instr, MAXLENGTH);
      tmp = strtok (instr, sep); }
    readLine (dataFD, instr, MAXLENGTH);
    tmp = strtok (instr, sep);
    while ((*instr == '\0') || (*instr == '%') || (tmp == NULL)) {
      readLine (dataFD, instr, MAXLENGTH);
      tmp = strtok (instr, sep); }
  }
  free (instr);
  free (fullFileName);
  close (dataFD);
  return tmp;
}

/* void getUsageNote (int dataFD, char *oldstr)
{
  char *instr = (char *)malloc(MAXLENGTH);
  int firstK = 0;
  sep = " \n\t";
  ret = "\n";

  while (*oldstr != '{') {
    strcpy (oldstr, oldstr+1); }

  strcpy (oldstr, oldstr

*/



