/*=============================================================================

                              HydraCom Version 1.00

                         A sample implementation of the
                   HYDRA Bi-Directional File Transfer Protocol

                             HydraCom was written by
                   Arjen G. Lentz, LENTZ SOFTWARE-DEVELOPMENT
                  COPYRIGHT (C) 1991-1993; ALL RIGHTS RESERVED

                       The HYDRA protocol was designed by
                 Arjen G. Lentz, LENTZ SOFTWARE-DEVELOPMENT and
                             Joaquim H. Homrighausen
                  COPYRIGHT (C) 1991-1993; ALL RIGHTS RESERVED


  Revision history:
  06 Sep 1991 - (AGL) First tryout
  .. ... .... - Internal development
  11 Jan 1993 - HydraCom version 1.00, Hydra revision 001 (01 Dec 1992)


  For complete details of the Hydra and HydraCom licensing restrictions,
  please refer to the license agreements which are published in their entirety
  in HYDRACOM.C and LICENSE.DOC, and also contained in the documentation file
  HYDRACOM.DOC

  Use of this file is subject to the restrictions contained in the Hydra and
  HydraCom licensing agreements. If you do not find the text of this agreement
  in any of the aforementioned files, or if you do not have these files, you
  should immediately contact LENTZ SOFTWARE-DEVELOPMENT and/or Joaquim
  Homrighausen at one of the addresses listed below. In no event should you
  proceed to use this file without having accepted the terms of the Hydra and
  HydraCom licensing agreements, or such other agreement as you are able to
  reach with LENTZ SOFTWARE-DEVELOMENT and Joaquim Homrighausen.


  Hydra protocol design and HydraCom driver:         Hydra protocol design:
  Arjen G. Lentz                                     Joaquim H. Homrighausen
  LENTZ SOFTWARE-DEVELOPMENT                         389, route d'Arlon
  Langegracht 7B                                     L-8011 Strassen
  3811 BT  Amersfoort                                Luxembourg
  The Netherlands
  FidoNet 2:283/512, AINEX-BBS +31-33-633916         FidoNet 2:270/17
  arjen_lentz@f512.n283.z2.fidonet.org               joho@ae.lu

  Please feel free to contact us at any time to share your comments about our
  software and/or licensing policies.

=============================================================================*/

#include "hydracom.h"

#ifdef AMIGA
#include <dos/dosextens.h>
#include <clib/dos_protos.h>
#endif	/* AMIGA */

static char *chatstart = "\007\007 * Chat mode start\r\n";
static char *chatend   = "\007\007\r\n * Chat mode end\r\n";
static char *chattime  = "\007\007\r\n * Chat mode end -- timeout\r\n";

//#include <libraries/mui.h>

#include "microdot.h"

#include <constructor.h>

extern void hyd_addchatin( char *);

void loc_puts (char *s)
{
	int l;
	char newline[ 256 ], *p;
	int ch;

	while( *s )
	{
		p = newline;
		while( *s && *s != '\n' )
		{
			ch = *s++;
			if( ch == '\r' )
			{
				s++;
				continue;
			}
			if( ch == 0x7 )
				DisplayBeep( NULL );
			else
				*p++ = ch;
		}
		*p = 0;
		if( *s )
			s++;

		if( newline[ 0 ] )
			hyd_addchatin( newline );
	}
}/*loc_puts()*/

extern void enablechat( int );

static char cb1[ 256 ], cb2[ 256 ];
char *chatbuffer = cb1;

/*static char *cb1, *cb2;
char *chatbuffer;

CONSTRUCTOR_P(initcb,200)
{
	cb1 = AllocMem( 512, MEMF_CLEAR );
	if( !cb1 )
	{
		outofmem();
		return( 1 );
	}
	cb2 = cb1 + 256;
	chatbuffer = cb1;
	return( 0 );
}

DESTRUCTOR_P(initcb,200)
{
	if( cb1 )
		FreeMem( cb1, 512 );
}
*/

extern int warned;

int keyabort (void)
{
#define CHATLEN 256
        boolean         esc = false;
        char           *p;
        word            c;

        if (chattimer > 0L) {
           if (time(NULL) > chattimer) {
              chattimer = lasttimer = 0L;
              hydra_devsend("CON",(byte *) chattime,strlen(chattime));
              loc_puts(&chattime[2]);
           }
           else if ((time(NULL) + 10L) > chattimer && !warned) {
              loc_puts("\007\r\n * Warning: chat mode timeout in 10 seconds\r\n");
              warned = true;
           }
        }
        else if (chattimer != lasttimer) {
           if (chattimer ==  0L) {
              if (nobell) p = " * Remote has chat facility with bell disabled\n";
              else        p = " * Remote has chat facility with bell enabled\n";

              hydra_devsend("CON",(byte *) p,(int) strlen(p));
              loc_puts(" * Hydra session in progress, chat facility now available\r\n");
			  if( prefs.hydra_autochat )
			  {
                     hydra_devsend("CON",(byte *) chatstart,strlen(chatstart));
                     loc_puts(&chatstart[2]);
					 enablechat( TRUE );
					 if( prefs.hydra_nochattimeout )
						chattimer = lasttimer = MAXINT;
					 else
						chattimer = lasttimer = time(NULL) + CHAT_TIMEOUT;
			  }
           }
           else if (chattimer == -1L)
              loc_puts(" * Hydra session in init state, can't chat yet\r\n");
           else if (chattimer == -2L)
              loc_puts(" * Remote has no chat facility available\r\n");
           else if (chattimer == -3L) {
              if (lasttimer > 0L) loc_puts("\r\n");
              loc_puts(" * Hydra session in exit state, can't chat anymore\r\n");
           }
           lasttimer = chattimer;
        }

#if WIN_AGL
        while (win_keyscan()) {
#else
#ifdef AMIGA
        while (ConScanKey()) {
#else
        while (kbhit()) {
#endif
#endif
              switch (c = get_key()) {
                     case Esc:
                          esc = true;
                          break;

                     case Alt_C:
                          if (chattimer == 0L) {
                             hydra_devsend("CON",(byte *) chatstart,strlen(chatstart));
                             loc_puts(&chatstart[2]);
							 enablechat( TRUE );
							 if( prefs.hydra_nochattimeout )
								chattimer = lasttimer = MAXINT;
							 else
	                             chattimer = lasttimer = time(NULL) + CHAT_TIMEOUT;
                          }
                          else if (chattimer > 0L) {
                             chattimer = lasttimer = 0L;
                             hydra_devsend("CON",(byte *) chatend,strlen(chatend));
							 enablechat( FALSE );
                             loc_puts(&chatend[2]);
                          }
                          else
                             loc_puts("\007");
                          break;

              }
        }

		while( chatbuffer[ 0 ] && hydra_devsend("CON",chatbuffer,strlen( chatbuffer )))
		{
			chatbuffer = ( chatbuffer == cb2 ) ? cb1 : cb2;
			chatbuffer[ 0 ] = 0;
	    }

        return (esc);
}/*keyabort()*/

extern void hyd_addchatin( char *);

/*static char *tchatbuffer;

ALLOCSTATIC( tchatbuffer, 512, MEMF_CLEAR )*/
static char tchatbuffer[ 512 ];

void rem_chat (byte *data, word len)
{
	//static UBYTE buffer[ 512 ];
	char *p, *p2;

	p = strchr( tchatbuffer, 0 );
	memcpy( p, data, len );
	p[ len ] = 0;
	sibm2iso( p );

	while( p = stpbrk( tchatbuffer, "\r\n" ) )
	{
		*p++ = 0;

		p2 = tchatbuffer;
		while( *p2 )
		{
			if( *p2 == 8 || *p2 == 127 )
			{
				if( p2 > tchatbuffer )
				{
					p2--;
					strcpy( p2, &p2[ 2 ] );
				}
				else
					strcpy( p2, &p2[ 1 ] );
			}
			else if( *p2 == 7 )
			{
				strcpy( p2, &p2[ 1 ] );
			}
			else
				p2++;
		}
		if( tchatbuffer[ 0 ] )
			hyd_addchatin( tchatbuffer );
		strcpy( tchatbuffer, p );
	}
}

#if 0
int parse(char *string)
{
        int ac = 0;
        char *p;

        p = strchr(string,';');
        if (p) *p = '\0';
#ifndef AMIGA
        strupr(string);
#endif	/* AMIGA */
        av[ac] = strtok(string," \t\r\n\032");

        while (av[ac]) {
              if (++ac > MAXARGS) {
                 message(6,"!Too many arguments!");
                 endprog(2);
              }
              av[ac]=strtok(NULL," \t\r\n\032");
        }

        return (ac);
}/*parse()*/
#endif

void splitpath(char *filepath,char *path,char *file)
{
#ifdef AMIGA
	STRPTR path_name,file_name;
	LONG len;

	path_name = PathPart(filepath);
	file_name = FilePart(filepath);

	strcpy(file,file_name);

	len = path_name - filepath;

	memcpy(path,filepath,len);

	path[len] = 0;
#else
        char *p,*q;

        for (p=filepath;*p;p++) ;
        while (p!=filepath && *p!=':' && *p!='\\' && *p!='/') --p;
        if (*p==':' || *p=='\\' || *p=='/') ++p;        /* begin     */
        q=filepath;
        while (q!=p) *path++=*q++;                      /* copy path */
        *path='\0';
        strcpy(file,p);
#endif	/* AMIGA */
}/*splitpath()*/


void mergepath(char *filepath,char *path,char *file)
{
#ifdef AMIGA
	strcpy(filepath,path);
	AddPart(filepath,file,256);
#else
        strcpy(filepath,path);
        strcat(filepath,file);
#endif	/* AMIGA */
}/*mergepath()*/


int fexist (char *filename)
{
#ifdef AMIGA
	BPTR file_lock;

	if(file_lock = Lock(filename,SHARED_LOCK))
	{
		UnLock(file_lock);

		return(1);
	}
	else
		return(0);
#else
        struct stat f;

        return ((stat(filename,&f) != -1) ? 1 : 0);
#endif	/* AMIGA */
}/*fexist()*/


int get_key (void)
{
        return(ConGetKey());
}/*get_key()*/

void resultlog (boolean xmit, char *fname, long bytes, long xfertime)
{          /* Omen's DSZ compatible logfile - for RBBS-PC XFER-?.DEF reports */
        FILE *fp;

		// Generate clxfer_recfile-node
		if( !xmit )
			addrecfile( fname, xfertime );

        if (opuslog) {
           if ((fp = sfopen(opuslog,"at",DENY_WRITE)) != NULL) {
              if (fname) {
                 fprintf(fp, "%s %s%s %ld", xmit ? "Sent" : "Got",
                             xmit ? "" : download, fname, bytes);
                 if (mailer)
                    fprintf(fp," %ld",xfertime);
                 fprintf(fp,"\n");
              }
              fclose(fp);
           }
           else
              message(3,"-Couldn't append opus log-file %s",opuslog);
        }

        if (result) {
           if ((fp = sfopen(result,"at",DENY_WRITE)) != NULL) {
              if (fname) {
                 fprintf(fp, "%c %6ld %5lu bps %4ld cps 0 errors     0 1024 %s -1\n",
                             xmit ? 'H' : 'R',
                             bytes, cur_speed,
                             xfertime ? (bytes / xfertime) : 9999L,
                             fname);
              }
              fclose(fp);
           }
           else
              message(3,"-Couldn't append result-file %s",result);
        }
}/*resultlog()*/


static char *mon[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
                         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };

char *h_revdate (long revstamp)
{
        static char  buf[12];
        struct tm   *t;

        t = localtime(&revstamp);
        sprintf(buf, "%02ld %s %ld",
                     t->tm_mday, mon[t->tm_mon], t->tm_year + 1900);

        return (buf);
}/*h_revdate()*/


extern void hyd_addlog( char* );
void message (int level, char *fmt,...)
{
        char       buf[255];
        long       tim;
        struct tm *t;
        va_list    arg_ptr;

        tim = time(NULL);
        t = localtime(&tim);

        va_start(arg_ptr,fmt);
        sprintf(buf, "%lc %02ld %03s %02ld:%02ld:%02ld %-4s ",
                     *fmt, t->tm_mday, mon[t->tm_mon],
                     t->tm_hour, t->tm_min, t->tm_sec, LOGID);
        vsprintf(&buf[23], &fmt[1], arg_ptr);
        va_end(arg_ptr);

        if (level >= loglevel && logfp)
           fprintf(logfp, "%s\n", buf);

#if WIN_AGL
        if (!file_win)
           cprint("\r%s\n",buf);
        else {
           if (!log_first)
              log_first = true;
           else
              win_putc(log_win,'\n');
           win_puts(log_win,buf);
        }
#else
#ifdef AMIGA
		hyd_addlog( buf );
/*		DoMethod( lv_log, MUIM_List_InsertSingle, buf, MUIV_List_Insert_Bottom );
		get( lv_log, MUIA_List_Entries, &tim );
		DoMethod( lv_log, MUIM_List_Jump, tim - 1 );*/

/*        if (!LogRequest)
           cprint("%s\n",buf);
        else
           ConPrintf(LogRequest,"%s\n",buf);*/
#else
        if (!file_x)
           cprint("\r%s\n",buf);
        else {
           local_x = wherex();
           local_y = wherey();
           window(1,2,80,6);
           if (log_y) {
              gotoxy(1,log_y);
              putch('\n');
           }
           cputs(buf);
           log_y = wherey();
           window(1,19,80,25);
           gotoxy(local_x,local_y);
        }
#endif
#endif
}/*message()*/


void cprint (char *fmt, ...)
{
        char    buf[255];
        va_list arg_ptr;

        va_start(arg_ptr,fmt);
        vsprintf(buf, fmt, arg_ptr);
        va_end(arg_ptr);

#if WIN_AGL
        if (didsome)
           win_puts(0,buf);
        else
#else
#ifdef AMIGA
		hyd_addlog( buf );
//		DoMethod( lv_chatout, MUIM_List_InsertSingle, buf, MUIV_List_Insert_Bottom );
/*        if (LocalRequest)
           ConPrintf(LocalRequest,buf);
        else*/
#endif
#endif
/*           fputs(buf,stdout);*/
}/*cprint()*/

