/* This program reads an sgf file and breaks it up into separate
   files, one for each variation. The file is prefaced by a line
   of the form: 

   sgf2dg -n -im -il -break [nn] [filename]

   where nn is the move number at which the variation begins.
   This is a command which can be used to invoke sgf2dg,
   producing a diagram in which the variation begins as move
   1. (Actually two diagrams are produced. The first may be
   discarded.)

   sgfsplit is copyright 1997 by Daniel Bump, and is published
   under the GNU General Public Licence, version 2. Consult the
   file COPYING for details, or write the Free Software Foundation,
   Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
*/

#ifdef PERL_POD

=head1 NAME

B<sgfsplit> - split Smart Go Format (SGF) files into their component variations

=head1 SYNOPSIS

B<sgfsplit> [ option(s) ] file[.sgf|.mgt]

=head1 DESCRIPTION

B<sgfsplit> takes a Smart Go Format (SGF) file containing variations, and
splits it up into a series of files, named I<filename>.0.sgf,
I<filename>.1.sgf, ..., one for each variation. The first file
I<filename>.0.sgf is the main line.

B<sgfsplit> also creates a shell script called I<filename.sgf2dg> which
contains suggested options for invoking sgf2dg on the individual files. In
particular, a breakpoint is specified in each variation file so that a single
diagram is created, the first move of the variation being move 1.

The options(s) to B<sgfsplit>, if specified, are incorporated into
I<filename.sgf2dg> and are passed as options to sgf2dg.  I<filename.sgf2dg>
may of course be edited before being invoked if different options are wanted
for the different variations.

=head1 SEE ALSO

L<sgf2dg>(1) for description of the option(s).

=head1 AUTHOR

Daniel Bump (bump@math.stanford.edu):
    L<http://match.stanford.edu/bump/go.html>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 1997-2005 by Daniel Bump

This program 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.

sgfsplit is published under the terms of the GNU General Public Licence,
version 2. Consult the file COPYING for details, or write the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.

=cut

#endif /* endif PERL_POD */

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <sys/stat.h>

#define MAXSIZE 16384
#define PERMISSIONS 0700

void parse(char str[],char sgfout[],char name[],int filecount,int movebreak);
 
char sgf[MAXSIZE],sgfout[MAXSIZE];
char name[128],oname[128],bname[128],extra_args[128];
FILE *bp;

int main(int argc,char *argv[])
{
  FILE *fp;
  int c,i;
  char *name;
  if (argc==1) {
    fprintf(stderr,"sgfsplit: no filename specified\n");
    return(1);
  }
  if (!strcmp(argv[1],"-h")) {
    printf(
"\n\nUsage: sgfsplit (filename) [extra arguments].\
\
This will split a Smart Go Format file into a series of\
files with names (filename).0.sgf, (filename).1.sgf,\
(filename).2.sgf ...  representing the individual variations\
in the file.  The file (filename).0.sgf is the main line;\
the remaining files contain variations.\
\
Also produced is an executable file (with permissions\
rwx------) called (filename).sgf2dg containing shell\
commands invoking sgf2dg for processing these files into\
TeX. The sgf2dg commands in (filename).sgf2dg for\
processing the variation files each specify a breakpoint,\
producing two diagrams. The first may be discarded, but the\
second represents the variation. Extra arguments (such as\
-simple) given to sgfsplit will be incorporated in the\
suggested sgf2dg commands.\n\n");
    return(1);
  }
  name=argv[1];
  extra_args[0]='\0';
  for (i=2; i<argc; i++) {
    strcat(extra_args,name);
    strcat(extra_args," ");
  }
  if (((fp=fopen(name,"r"))==NULL) &&
      ((fp=fopen(strcat(name,".sgf"),"r"))==NULL)) {
    fprintf(stderr,"sgfsplit: can't open file %s\n",name);
    return(1);
  }
  if (!strcmp(name+strlen(name)-4,".sgf")) name[strlen(name)-4]='\0';
  i=0;
  while ((c=getc(fp))!=EOF) sgf[i++]=c;
  if (i>=MAXSIZE) {
    fprintf(stderr,"%s: file too long\n",name);
    return(1);
  }
  sprintf(bname,"%s.sgf2dg",name);
  if ((bp=fopen(bname,"w"))==NULL) {
    fprintf(stderr, "sgfsplit: can't open file %s for output\n",bname);
  } else
    fprintf(bp,"#\
# File automatically generated by sgfsplit.\
# Edit this file if you will but remember: it will be\
# overwritten if sgfsplit %s is invoked again.\n#\n", name);
  sgf[i]='\0';
  parse(sgf,sgfout,name,0,0);
  fclose(bp);
  printf("Writing %s.\n\n",bname);
  chmod(bname,PERMISSIONS);
  return(0);
}

/* cuts a piece from a string */

void cutstr(char str[],int left,int right)
{
  int i=left;
  while ((str[i]=str[i-left+right+1])!='\0') i++;
}
  
/* parse() is an LR parser for Smart Go Format, paying attention
   only to sgf structure relevant to finding variations and counting
   moves. State of the parser is determined by three four variables,
   pstate, mstate, bracecount and escape. pstate parses the structure
   for variations, keeping track of '(' and ')'. mstate parses the
   sgftags enough to recognize moves B[] and W[]. bracecount and
   escape count non-escaped braces, i.e. [ counts as +1, ] as -1,
   and \[, \] do not count. This feeds back into the pstate machine
   since '(' and ')' in regions where bracecount is positive are
   not counted. These could be parentheses within comments.

   Actions taken by the pstate parser are as follows. If after reading
   the game record we are in state 4, this means that a structure of
   the form (a(b(c ...(d(e)(f) ... has been recognized. Then
   (abc ... de) is written to a file, the sgf string is replaced by
   (a(b(c( ...(d(f) ...) and fed back to the parser. If the game
   record is in state 5, this means that a structure of the form
   (a(b(c ...(d(e))... has been recognized. The braces surrounding
   e are discarded, and the sgf string is fed back to the parser.
   State 6 indicates a structure (abc ... f). This is written to
   a file and the program terminates. */


void parse(char str[],char sgfout[],char name[],int filecount,int movebreak)
{
  int i=0,j=0,lparen=0,rparen=0,pstate=0,mstate=0;
  int bracecount=0,movenum=0,nextbreak=0,escape=0;
  char oname[128];
  FILE *fp;
  while (str[i]!='\0') {
    if ((escape==0)&&(str[i]=='[')) bracecount++;
    if ((escape==0)&&(str[i]==']')) bracecount--;
    if (str[i]=='\\') {escape=1;
    } else escape=0;
    if (bracecount<0) {
      fprintf(stderr,"sgfsplit: unmatched ] in %s\n",name);
      return;
    }
    switch (pstate) {
    case 0:
      switch (str[i]) {
      case '(': if (bracecount==0) {pstate=1; break;}
      case ')': fprintf(stderr,"sgfsplit: unmatched ) in %s",name); 
        return;
      default: sgfout[j++]=str[i];
      } break;
    case 1:
      switch (str[i]) {
      case '(': if (bracecount==0) {
        pstate=2; nextbreak=movenum; lparen=i; break;
      }
      case ')': if (bracecount==0) {pstate=6; break;}
      default: sgfout[j++]=str[i];
      } break;
    case 2:
      switch (str[i]) {
      case '(': if (bracecount==0) {
        pstate=2; nextbreak=movenum; lparen=i; break;
      }
      case ')': if (bracecount==0) {pstate=3; rparen=i; break;}
      default: sgfout[j++]=str[i];
      } break;
    case 3:
      switch (str[i]) {
      case '(': if (bracecount==0) {pstate=4; break;}
      case ')': if (bracecount==0) {pstate=5; break;}
      default: sgfout[j++]=str[i];
      } break;
    }
    if ((bracecount==0)&&(pstate>0)) {
      if ((sgf[i]==';')||(sgf[i]==']')) {
        mstate=0;
      } else if (isupper(sgf[i])&&(sgf[i]!='B')&&(sgf[i]!='W')) {mstate=2;
      } else if ((mstate==0)&&((sgf[i]=='B')||(sgf[i]=='W'))) {mstate=1;
      } else if ((mstate==1)&&(isupper(sgf[i]))) {mstate=2;}
    }
    if ((bracecount==1)&&(sgf[i]=='[')&&(mstate==1)) {
      movenum++;
    }
    i++;
  }
  sgfout[j]='\0';
  if (pstate==4) {
    cutstr(str,lparen,rparen);
    sprintf(oname,"%s.%d.sgf",name,filecount++);
    if((fp=fopen(oname,"w"))==NULL) {
      fprintf(stderr,"sgfsplit: can't open output file\n");
      return;
    }
    if (movebreak!=0) {
      fprintf(bp,"sgf2dg -n -im -il -firstDiagram 2 -break %d %s%s\n",movebreak,extra_args,oname);
    } else fprintf(bp,"sgf2dg -n -im -il %s%s\n",extra_args,oname);
    fprintf(fp,"(%s)",sgfout);
    fclose(fp);
      printf("Writing %s. Break is at %d.\n",oname,movebreak);
    parse(str,sgfout,name,filecount,nextbreak);
  } else if (pstate==5) {
    cutstr(str,rparen,rparen);
    cutstr(str,lparen,lparen);
    parse(str,sgfout,name,filecount,movebreak);
  } 
  else if (pstate==6)
    {
      sprintf(oname,"%s.%d.sgf",name,filecount++);
      if((fp=fopen(oname,"w"))==NULL) {
        fprintf(stderr,"sgfsplit: can't open output file\n");
        return;
      }
      if (movebreak!=0) {
        fprintf(bp,"sgf2dg -n -im -il -firstDiagram 2 -break %d %s%s\n",movebreak,extra_args,oname);
      } else fprintf(bp,"sgf2dg -n -im -il %s%s\n",extra_args,oname);
      fprintf(fp,"%s",str);
      fclose(fp);
      printf("Writing %s. Break is at %d.\n",oname,movebreak);
   }
  return;
}


