#ifndef lint
static char rcsid[] = "$Header: /ful/chris/ctex_dist/lib/RCS/findpost.c,v 1.1 84/05/20 23:11:57 chris Exp $";
#endif

/* FindPostAmble - Find the postamble of a DVI file */

#include <stdio.h>
#include "types.h"
#include "dvicodes.h"
#include "fio.h"

long ftell ();

FindPostAmble (f)
register FILE *f;
{
    register long   offset;
    char    postbuf[16];	/* I'm making the assumption that 16 bytes
				   will always be enough to find the end
				   of the DVI file---this should be true
				   since there are 4 to 8 DVI_FILLER bytes
				   preceded by the version number,
				   preceded by the 4 byte postamble ptr */

    {
	register char  *p = postbuf;
	register int    i;

	fseek (f, -16L, 2);	/* seek to 16 bytes before EOF */
	for (i = 0; i < 16; i++) {
	    *p++ = getc (f);
	    if (feof (f)) {	/* shouldn't happen but what the heck */
		p--;
		break;
	    }
	}
	offset = ftell (f);
	while (--i >= 0) {
	    offset--;
	    if (UnSign8 (*--p) == DVI_VERSION)
		goto foundit;
	    if (UnSign8 (*p) != DVI_FILLER)
		break;
	}
	return -1;		/* couldn't find postamble ptr */
    }

foundit: 
    {
	register i32    n;

	fseek (f, offset - 4L, 0);
	fGetLong (f, n);
	offset = n;
	fseek (f, offset, 0);
	return 0;		/* success */
    }
}
