/*
 *	texfix.c
 *
 *	version 1.5 (September 25, 1992)
 *	written by Kazuhiro Kazama (kazama@square.ntt.jp)
 *
 *	This original program is "retexps" made by takeba@otsl.oki.co.jp.
 */
#include	<stdio.h>
#include	<string.h>
#include	<signal.h>
char	*mktemp();

#ifdef	STRSTR
char	*strstr();
#endif

#define	PAGECOM	"%%Page:"
#define	BSP	"@beginspecial\n"
#define	ESP	"@endspecial\n"

#ifdef JDVI2KPS || JDVI2KPS2
#define	BOP	"@bop0\n"
#define	EOP	"@eop\n"
#else
#ifdef JDVI2KPS3
#define	BOP	"@bop\n"
#define	EOP	"@eop\n"
#else
#define	BOP	"BP\n"
#define	EOP	"EP\n"
#endif
#endif

char	line[BUFSIZ], line2[BUFSIZ];
char	tmpstr[] = "/tmp/tfXXXXXX";
char	*tmpfn;
int	cleanup();

main()
{
    if ((tmpfn = mktemp(tmpstr)) == NULL) {
        perror("mktemp failed.");
        exit(1);
    }
    signal(SIGHUP, cleanup);
    signal(SIGINT, cleanup);
    signal(SIGQUIT, cleanup);
    signal(SIGPIPE, cleanup);
    signal(SIGTERM, cleanup);
    while (fgets(line, BUFSIZ, stdin) != NULL) {
	fputs(line, stdout);
	if (strncmp(line, PAGECOM, sizeof(PAGECOM) - 1) == 0)
	    if (pageout()) {
		fprintf(stderr, "unexpected EOF\n");
		unlink(tmpfn);
		exit(1);
	    }
    }
    unlink(tmpfn);
    exit(0);
}

pageout()
{
    FILE	*tmpfp;

    while (fgets(line, BUFSIZ, stdin) != NULL) {
	fputs(line, stdout);
	if (strcmp(line, BOP) == 0) {
	    if ((tmpfp = fopen(tmpfn, "w")) == NULL) {
		perror("fopen failed.");
		exit(1);
	    }
	    while (fgets(line, BUFSIZ, stdin) != NULL)
		if (strcmp(line, EOP) == 0) {
		    fclose(tmpfp);
		    if ((tmpfp = fopen(tmpfn, "r")) == NULL) {
			perror("fopen failed.");
			exit(1);
		    }
		    while (fgets(line2, BUFSIZ, tmpfp) != NULL)
			fputs(line2, stdout);
		    fclose(tmpfp);
		    fputs(line, stdout);
		    return 0;
		} else if (strstr(line, BSP) != NULL) {
		    fputs(line, stdout);
		    if (specialout()) {
			fclose(tmpfp);
			return 1;
		    }
		} else
		    fputs(line, tmpfp);
	}
    }
    return 0;
}

specialout()
{
    int	inspecial = 1;

    while (fgets(line, BUFSIZ, stdin) != NULL) {
	fputs(line, stdout);
	if (strcmp(line, ESP) == 0 && --inspecial == 0)
	    return 0;
	else if (strstr(line, BSP) != NULL)
	    inspecial++;
    }
    return 1;
}

cleanup()
{
    unlink(tmpfn);
    exit(0);
}

#ifdef	STRSTR
char	*strstr(s1, s2)
register char	*s1, *s2;
{
    register int	l1, l2;
    register char	c2;

    if ((c2 = *s2) != '\0')
	for (l1 = strlen(s1), l2 = strlen(++s2); l1 > l2; l1--)
	    if (*s1++ == c2 && strncmp(s1, s2, l2) == 0)
		return --s1;
    return NULL;
}
#endif
