/* Miscellaneous functions. Kees Lemmens; Aug 1992

   Any questions or suggestions about this program can be send to:
   lemmens@dv.twi.tudelft.nl
*/

#ifdef __PUREC__
#include <tos.h>
#else
#include <osbind.h>
#endif

#include <stdio.h>
#include <string.h>
#include <pwd.h>
#include <signal.h>
#include <time.h>
#include <cookie.h>
#include "ux_misc.h"

#undef sleep(s)	/* for running under TOS */

void Delay(clock_t ticks)	/* 1 tick =1/1000 sec */
{	clock_t start = clock();

	while((clock() - start) * (1000 / CLK_TCK) < ticks);
}


int RunningMint(void)
{	long suret;
	int flag=0;
	COOKIE *jar;

	if(Super((void *)1L)==0L)
	{	suret=Super(0L);
		jar=*CJAR;
		Super((void *)suret);
	}
	else
		jar=*CJAR;
	
	while(jar->tag.aslong != 0)
	{	if(!strncmp(jar->tag.aschar,"MiNT",4))
			flag=1;
#ifdef DEBUG
	printf("cookie: %.4s, value: %lx\n",jar->tag.aschar,jar->value);
#endif
		jar++;
	}
	return flag;
}

void MyDummy(void)
{  return;
}

void Mysleep(unsigned seconds)
{
/* Avoid heavy system load while waiting for input :
   Standard sleep functions in PURE C cause enormous load on a
   multitasking system, as they are stupid loops !!
*/
	void sleep(unsigned);
	
	if(RunningMint())
	{	Psignal(SIGALRM,MyDummy);
		Talarm(seconds);	/* set alarm time */
		(void)Pause();		/* wait for alarm */
	}
	else sleep(seconds);
}	

char *ux2dos(char *string)	/* convert / to \ */
{	char *tmp;
	while((tmp=strchr(string,'/')) != NULL)
		*tmp='\\';
	return string;
}

void *encrypt(char *passwd)
{	int x;		/* simple passwd encrypt/decript routine */

	for(x=0;x<strlen(passwd);x++)
		passwd[x] ^= 19+x;

	return passwd;
}

int check_pw(char *login_pw,struct passwd *pwent)
{
	if(strcmp(encrypt(login_pw),pwent->pw_passwd))
		return -1;
	return 0;
}

void tty_flush(void)
{	/* Cconis() determines if a character is available */
    while (Delay(50),Cconis() == -1)
		Cnecin();
}

void Put(char *cmd)
{	int x;

	for(Delay(50),x=0;x<strlen(cmd);x++)
		Cconout(cmd[x]);
}

void Get(char *str,int nr,int mode)
{	int cnt=0;	/* mode 0: no echo ; mode=1 echo */
	while(*str=Cnecin(),cnt++ < nr)
	{	if (mode) Cconout(*str);
		if(*str == '\15' || *str == '\n')
		{	*str = '\0';
			return;
		}
		str++;
	}
}

int mk_devnm(char *dev,char *arg)
{	char *devpath  =DEV;

	if(arg==NULL) return -1;
	if(strchr(arg,'\\') != NULL || strchr(arg,':') != NULL)
		strcpy(dev,arg);
	else
	{	strcpy(dev,devpath);
		strcat(dev,arg);
	}
	ux2dos(dev);
	return 0;
}
