#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "xutil.h"
#include "lutil.h"
#include "ttyio.h"
#include "session.h"
#include "config.h"
#include "emsi.h"
#include "janus.h"

#define JBLKSIZE 2048
#define RECV_TIMEOUT 10
#define DEAD_TIMEOUT 120
#define GOODNEEDED 65536

#define TX_CASE(x) \
	break;\
	case x:\
		debug(15,"janus tx state %s (%d)",#x,x);

#define RX_CASE(x) \
	break;\
	case x:\
		debug(15,"janus rx state %s (%d)",#x,x);

static void sendpkt(int,char*,int);

#if 0
static char *txbuf=NULL,*rxbuf=NULL;
#endif

extern int janus(void);
extern int janus(void)
{
#if 0
	int cleartosend=1;
	int rxstate=JR_RCVFNAME;
	int txstate=JS_SENDFNAME;
	int tx_inhibit=0;
	off_t txpos=0L,lasttx,txlen=0L;
	off_t rxpos=0L;
	int txblkmax=JBLKSIZE;
	int rxblkmax=JBLKSIZE;
	int txblksize=JBLKSIZE;
	int rxblksize=JBLKSIZE;
	int blklen;
	long goodbytes=0L;
	char *txfname=NULL,*rxfname=NULL;
	FILE *txfile=NULL,*rxfile=NULL;

	debug(11,"start janus transfer");

	if (txbuf == NULL) txbuf=xmalloc(JBLKSIZE*2+8);
	if (rxbuf == NULL) rxbuf=xmalloc(JBLKSIZE*2+8);

	debug(14,"entering janus state machine rx=%d, tx=%d",
		rxstate,txstate);
	do
	{

		/*--------------- Transmit ----------------*/

		debug(15,"janus transmit stage");
		if (cleartosend) switch (txstate)
		{
		default: logerr("Internal janus error: tx=%d",txstate);
			goto abrt;
		TX_CASE(JS_SENDBLK)
			lasttx=txpos;
			txbuf[0]=(txpos >> 0)&0xff;
			txbuf[1]=(txpos >> 8)&0xff;
			txbuf[2]=(txpos >> 16)&0xff;
			txbuf[3]=(txpos >> 24)&0xff;
			blklen=fread(txbuf+4,txblksize,1,txfile);
			if (blklen < 0)
			{
				logerr("$error reading file \"%s\"",
					S(txfname));
				goto abrt;
			}
			sendpkt(JPKT_BLK,txbuf,blklen+4);
			if ((txpos >= txlen) || (blklen < txblksize))
			{
				SETTIMER(1,RECV_TIMEOUT);
				txstate=JS_RCVEOFACK;
			}
			else
			{
				SETTIMER(0,DEAD_TIMEOUT);
			}
			if ((txblksize < txblkmax) &&
			    ((goodbytes += txlen) >= GOODNEEDED))
			{
				txblksize <<= 1;
				goodbytes=0;
			}
		TX_CASE(JS_SENDFNAME)
		TX_CASE(JS_SENDFREQNAK)
		}

		/*--------------- I/O --------------------*/
		/*--------------- Receive ----------------*/

		debug(15,"janus receive stage");

	}
	while (rxstate || txstate);

abrt:
	debug(14,"exiting janus state machine rx=%d, tx=%d",
		rxstate,txstate);
#endif

	return 0;
}

static void sendpkt(typ,buf,len)
int typ;
char *buf;
int len;
{
	debug(18,"sendpkt '%s' \"%s\" (%d)",
		printablec(typ),printable(buf,len),len);
}
