/*
 *      ffwd.c	-	file I/O version of forward ref handler
 *
 *	From Motorola BBS.
 *	See ../doc/ChangeLog to examine and/or add change descriptions.
 */
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>

#ifndef O_BINARY
#	define O_BINARY 0
#endif
#define	UPDATE		(O_RDWR | O_BINARY | O_TRUNC)	/* file open mode */
#define	FILEMODE	(S_IWRITE | S_IREAD)		/* file creat mode */
#define	ABS		SEEK_SET			/* absolute seek */

int	Forward =0;		/* temp file's file descriptor	*/
char	Fwd_name[] = { "Fwd_refs" } ;

/*
 *      fwdinit --- initialize forward ref file
 */
void
fwdinit(void)
{
	Forward = creat(Fwd_name,FILEMODE);
	if(Forward <0)
		fatal("Can't create temp file");
	close(Forward); /* close and reopen for reads and writes */
	Forward = open(Fwd_name,UPDATE);
	if(Forward <0)
		fatal("Forward ref file has gone.");
}

/*
 *      fwdreinit --- reinitialize forward ref file
 */
void
fwdreinit(void)
{
	int stat;
	long lstat;

	F_ref   = 0;
	Ffn     = 0;
	lstat = lseek(Forward,0L,ABS);   /* rewind forward refs */
	if( lstat == (long)ERR ) fatal("Unable to read forward ref file");
	stat = read(Forward,(char *)&Ffn,sizeof(Ffn));
	if( stat == ERR ) fatal("Unable to read forward ref file");
	stat = read(Forward,(char *)&F_ref,sizeof(F_ref)); /* read first forward ref into mem */
	if( stat == ERR ) fatal ("Unable to read forward ref file");
#ifdef DEBUG
	if (DebugMess)
		printf("First fwd ref: %d,%d\n",Ffn,F_ref);
#endif
}

/*
 *      fwdmark --- mark current file/line as containing a forward ref
 */
void
fwdmark(void)
{
	int stat;

	stat = write(Forward,(char *)&Cfn,sizeof(Cfn));
	if( stat == ERR ) fatal("Unable to write to forward ref file");
	stat = write(Forward,(char *)&Line_num,sizeof(Line_num));
	if( stat == ERR ) fatal("Unable to write to forward ref file");
}

/*
 *      fwdnext --- get next forward ref
 */
void
fwdnext(void)
{
	int stat;

	stat = read(Forward,(char *)&Ffn,sizeof(Ffn));
	if( stat == ERR ) fatal("Unable to read forward ref file");
#ifdef DEBUG
	if (DebugMess)
		printf("Ffn stat=%d ",stat);
#endif
	stat = read(Forward,(char *)&F_ref,sizeof(F_ref));
	if( stat < sizeof(F_ref) ){
		if( stat == ERR ) fatal("Unable to read forward ref file");
		F_ref=0;
		Ffn=0;
		}
#ifdef DEBUG
	if (DebugMess)
	{
		printf("F_ref stat=%d  ",stat);
		printf("Next Fwd ref: %d,%d\n",Ffn,F_ref);
	}
#endif
}

/*
 *  fwd_done --- closes & deletes forward reference file
 */
void
fwd_done(void)
{
	int stat;

	stat = close(Forward); /* Have to close first on MS-DOS or you leave lost clusters. */
#ifndef DEBUG
	if( stat == 0 ) /* If close was successful, delete file */
		unlink(Fwd_name);
#else
	if ( (stat == 0) && DelErr )
		unlink(Fwd_name);
#endif
}
