#include <stdio.h>

#define ML 132

main(int argc, char **argv)
{
    char fn[ML], s[ML];
    int sec, sections_seen;
    char *tag;
    FILE *ip, *op;

    if(argv[1]==NULL)
    {
        printf("usage: sep <file> [prefix] [suffix]\n");
        exit(0);
    }

    /*
     * First, find the first section number.
     */
    ip = fopen(argv[1],"r");
    while(fgets(s,ML,ip))
    {
        if(strncmp(s,"\\section",8)==0)
        {
            sscanf(s,"\\section %d.",&sec);
            break;
        }
        if(strncmp(s,"\\introsec",9)==0)
        {
            sscanf(s,"\\introsec %d.",&sec);
            break;
        }
        if(strncmp(s,"\\smallsec",9)==0)
        {
            sscanf(s,"\\smallsec %d.",&sec);
            break;
        }
    }
    rewind(ip);

    /*
     * For each section, make a separate file with that section in it.
     */

    sections_seen=0;
    s[0]='\0';
    do {
        /* printf("%d.\n",sec); */
        if(argv[2])
            sprintf(fn,"%s.%d",argv[2],sec);
        else
            sprintf(fn,"%s.%d",argv[1],sec);
        if(argv[3])
            strcat(fn,argv[3]);

        op = fopen(fn,"w");
        fprintf(op,"%%tex2asc-version: 1.3\n");
        fprintf(op,"%s",s);
        if(strncmp(s,"\\section",8)==0
           || strncmp(s,"\\introsec",9)==0
           || strncmp(s,"\\smallsec",9)==0)
            sections_seen++;
        while((tag=fgets(s,ML,ip))!=NULL)
        {
            if(strncmp(s,"\\section",8)==0
               || strncmp(s,"\\head",5)==0
               || strncmp(s,"\\subhead",8)==0
               || strncmp(s,"\\superhead",10)==0
               || strncmp(s,"\\subsuperhead",13)==0
               || strncmp(s,"\\introsec",9)==0
               || strncmp(s,"\\smallsec",9)==0)
            {
                if(sections_seen)
                {
                    fprintf(op, "\\bye\n");
                    fclose(op);
                    sec++;
                    printf("section %d at %.60s\n",sec,s);
                    break;
                }
                if(strncmp(s,"\\section",8)==0
                   || strncmp(s,"\\introsec",9)==0
                   || strncmp(s,"\\smallsec",9)==0)
                    sections_seen++;
            }
            fprintf(op,"%s",s);
        }
        sections_seen=0;
    } while(tag);
    fprintf(op, "\\bye\n");
    fclose(op);
    return;
}

                
