#include <ascii.h>
#include <fido.h>
#include <\mailer\fidomem.h>
#include <xfbuf.h>

/* Make calls until (1) too many tries or connects or (2) success. */

fidonet() {
char buff[SS];

	open_log("fidonet.log");
	gtod(buff);
	clprintf(0,"\r\n * \"MAIL\" FidoNet session starts at %s\r\n",buff);
	packet();				/* make packets */
	modem_init(17);				/* init the modem */

	doscode= fido.byecode;			/* assume "normal" exit */
	while (1) {
		if (chkabort()) break;		/* manual abort */
		if (answer() > 0) {		/* if incoming call */
			clprintf(0,"! Incoming call\r\n");
			break;			/* skip all this */
		}
		send_mail();			/* send it, */
		if ((tries >= dial_tries) || (connects >= connect_tries)) {
			break;
		}
		clr_clk();
		clprintf(FM+1);
	}
	close_up();
	delete("packet.out");
	delete("filelist.out");
	gtod(buff);
	clprintf(0," * FidoNet session ends at %s\r\n",buff);
	close_log();
}

/* Generate a packet with all the files attached. */

packet() {
int file,flo;			/* packet file, file list file, */

	clprintf(0," * Packet for %s\r\n",str_node(&node));

	file= creat("packet.out",2);		/* packet file */
	if (file == -1) {
		clprintf(SM+10,"packet.out");
		frc_abort();
	}

/* Create the file list for this packet. */

	flo= creat("filelist.out",1);		/* file list */
	if (flo == -1) {
		clprintf(SM+10,"filelist.out");	/* "can't create" */
		close(file);
		frc_abort();
	}
	make_header(file,&node);		/* create new empty packet */
	end_hdr(file);
	close(file);

	clprintf(0,"   Sending files: %s\r\n",filelist);
	write(flo,filelist,strlen(filelist));	/* write the file list */
	close(flo);
}

/* Create the packet header, and write it to disk. Abort if the disk is full. */

static make_header(file,n)
int file;
struct _node *n;
{
int i;
struct _pkthdr pkthdr;
char *cp;

	cp= (char *) &pkthdr;			/* clear it all */
	for (i= 0; i < sizeof(pkthdr); ++i) *cp++= NUL;

	pkthdr.orig_number= id.number;	/* assemble it all, */
	pkthdr.orig_net= id.net;
	pkthdr.orig_zone= id.zone;

	pkthdr.dest_number= n-> number;		/* destination node */
	pkthdr.dest_net= n-> net;
	pkthdr.dest_zone= n-> zone;

	pkthdr.year= gtod3(0);			/* set date, etc */
	pkthdr.month= gtod3(1);
	pkthdr.day= gtod3(2);
	pkthdr.hour= gtod3(4);
	pkthdr.minute= gtod3(5);
	pkthdr.second= gtod3(6);

	pkthdr.ver= PKTVER; 			/* packet version */

	sprintf(&pkthdr.extra,0,"FidoNet %d%c",FIDOVER,96+FILEVER);

	if (write(file,&pkthdr,sizeof(pkthdr)) != sizeof(pkthdr))
		frc_abort();
}

/* Mark the end of the packet. */

static end_hdr(file)
int file;
{
	cputi(file,0);
}

/* Write a character to the file. */

static cputc(file,c)
int file;
char c;
{
	if (write(file,&c,1) != 1) frc_abort();
}

/* Write an integer to the packet. */

static cputi(file,i)
int file,i;
{
	if (write(file,&i,sizeof(i)) != sizeof(i))
		frc_abort();
}
