/* Miscellaneous functions for use with HAYES smart modems
   Kees Lemmens; Aug 1992

   Remarks or suggestions to:
   lemmens@dv.twi.tudelft.nl

*/

#ifdef __PUREC__
#include <tos.h>
#else
#include <osbind.h>
#endif

#include <stdio.h>
#include <string.h>
#include <time.h>
#include "modem.h"

/* Cauxin() reads from stdaux line */
/* Cauxout() writes to stdaux line */
/* Cauxis() tells if a char is available on stdaux */

void exit(int stat);

#ifdef MINT
void Mysleep(unsigned s);
#else
#define Mysleep(s)
#endif

void mod_flush(int echo)
{	char c;
	while(Cauxis() < 0)
	{	Delay(50);
		c=(char)Cauxin();
		if (echo) putchar(c & 0x7f);
	}
}

int mod_getc(void)
{	time_t t1,t2,mxtm=4;

	time(&t1);
	while (Cauxis() == 0)
	{	Delay(50);
		if( time(&t2) - t1 >= mxtm ) /* wait max 4 sec */
			return 0;
	}
	return Cauxin() & 0x7f;	/* only 7 bits/character */
}

void mod_putc(char k)
{	Delay(50);		/* safe delaytime on 2400 baud */
	Cauxout(k);
}

void mod_puts(char *cmd)
{	int x;

	Delay(50);
	for(x=0;x<strlen(cmd);x++)
	{	Delay(35);
		Cauxout(cmd[x]);
	}
}
	
void mod_gets(char *str,int nr)
{	int cnt=0;

	while(*str=mod_getc(),cnt++ < nr)
	{	if(*str == '\15' || *str == '\n')
		{	*str = '\0';
			return;
		}
		str++;
	}
}

int mod_wait(char *string,int max_tm,int echo)
{	time_t t1,t2;
	int c,fl;

	time(&t1); t1 += max_tm;
	while(fl=0,time(&t2) < t1)
	{
		while(fl < strlen(string))
		{	while(Cauxis() == 0 && time(&t2) < t1)
				Mysleep(1); /* avoid useless system load */

			c=mod_getc();
			if (echo) putchar(c);
			if(c == string[fl])	fl++;
			else 				break;
		}
		if (fl>= strlen(string)) return fl; /* string ok */
	}
	return -1;	/* timeout: string not received !! */
}

int mod_reset(void)
{	mod_flush(0);
	mod_puts("\r\natz\r\n");
	return mod_wait("OK",10,0);
}

void mod_hangup(void)
{	Delay(1500);		/* guard time before/after escape */
	mod_puts("+++");
	Delay(1500);
	mod_puts("\r\nath0\r\n");	/* hangup modem and reinitialize */
	Delay(1500);
	mod_flush(0);
}
