/* GNU Chess 5.0 - pgn.c - pgn game format code
   Copyright (c) 1999-2002 Free Software Foundation, Inc.

   GNU Chess is based on the two research programs 
   Cobalt by Chua Kong-Sian and Gazebo by Stuart Cracraft.

   GNU Chess is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2, or (at your option)
   any later version.

   GNU Chess is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with GNU Chess; see the file COPYING.  If not, write to
   the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
   Boston, MA 02111-1307, USA.

   Contact Info: 
     bug-gnu-chess@gnu.org
     cracraft@ai.mit.edu, cracraft@stanfordalumni.org, cracraft@earthlink.net
*/

#include <stdio.h>
#include <sys/time.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <errno.h>

#include "util.h"
#include "version.h"
#include "book.h"
//#include "lexpgn.h"
#include "move.h"
#include "pgn.h"
#include "log.h"

pgn_iter_t PGNIter[1];

void yylex_init(void**);
void yylex_destroy(void*);
void yyset_in(FILE*,void*);
void yyset_extra(void*,void*);
int yylex(void*);

void PGNIterInit(pgn_iter_t *pgn_iter){
  pgn_iter->fp=NULL;
}

int PGNIterStart(pgn_iter_t *pgn_iter, const char *file){
  if(pgn_iter->fp!=NULL){
    fclose(pgn_iter->fp);
    yylex_destroy(pgn_iter->scanner);
  }
  yylex_init(&pgn_iter->scanner);
  pgn_iter->fp = fopen (file, "r");
  if (pgn_iter->fp == NULL){
    yylex_destroy(pgn_iter->scanner);
    return false;
  }
  return true;
}

void PGNIterClose(pgn_iter_t *pgn_iter){
  if(!pgn_iter->fp){
    return;
  }
  fclose (pgn_iter->fp);
  pgn_iter->fp=NULL;
  yylex_destroy(pgn_iter->scanner);
}


int PGNIterNext (pgn_iter_t *pgn_iter, game_t *game)
/****************************************************************************
 *
 *  To read a game from a PGN file.
 *
 ****************************************************************************/
{
  FILE *fp;
  int ret;
  fp=pgn_iter->fp;
  yyset_in(fp,pgn_iter->scanner);

  if(!pgn_iter->fp){
    return false;
  }
  
  yyset_extra(game,pgn_iter->scanner);

  ret=yylex(pgn_iter->scanner);

  if(ret==2){
    return false;
  }else if(ret==1){
    Log("Game has errors.\n");
  }
  return true;
}

