/*
 * GLIB - a Generic LIBrarian and editor for synths
 *
 * Machine dependent stuff.
 *
 * Unix version
 */

#include "glib.h"
#include <ctype.h>

int Rows, Cols;

#include <curses.h>

hello()
{
}

bye()
{
	windgoto(22,0);
	windrefresh();
	windexit(0);
}

/* getmouse - get currect row and column of mouse */
getmouse(amr,amc)
int *amr;
int *amc;
{
#ifdef USEMOUSE
	/* no such */
#else
	*amr = -1;
	*amc = -1;
#endif
}

/* statmouse - return mouse button state (0=nothing pressed,1=left,2=right) */
statmouse()
{
#ifdef USEMOUSE
	/* no such */
#else
	return(-1);
#endif
}

/* Return when either a console key or mouse button is pressed. */
mouseorkey()
{
#ifdef USEMOUSE
	/* no such */
#else
	return(getconsole());
#endif
}

flushconsole()
{
}

statconsole()
{
	return(1);
}

getconsole()
{
	return(getchar());
}

getmidi()
{
	return(-1);
}

statmidi()
{
	return(0);
}

/*ARGSUSED*/
sendmidi(c)
{
}

flushmidi()
{
	while ( STATMIDI )
		getmidi();
}

long milliclock()
{
	static long hzcount = 0;

	return(hzcount++);
}

millisleep(n)
{
	sleep((n+500)/1000);
}

char *
alloc(n)
{
	char *p;

	if ( (p=malloc((unsigned)n)) == (char *)NULL ) {
		printf("*** Whoops *** alloc has failed?!?  No more memory!\n");
		fflush(stdout);
		bye();
	}
	return(p);
}

windinit()
{
	char *getenv();

	initscr();
	Cols = 80;
	Rows = 24;
	noecho();
	nonl();
	cbreak();
}

windgoto(r,c)
int r,c;
{
	move(r,c);
}

windeeol()
{
	clrtoeol();
}

winderaserow(r)
{
	windgoto(r,0);
	windeeol();
}

windexit(r)
int r;
{
	nocbreak();
	nl();
	echo();
	endwin();
	exit(r);
}

windclear()
{
	clear();
}

/* windgets - get a line of input from the console, handling backspaces */
windgets(s)
char *s;
{
	char *origs = s;
	int c;

	while ( (c=getconsole()) != '\n' && c!='\r' && c!= EOF ) {
		if ( c == '\b' ) {
			if ( s > origs ) {
				windstr("\b \b");
				s--;
			}
		}
		else {
			windputc(c);
			*s++ = c;
		}
		windrefresh();
	}
	*s = '\0';
}

windstr(s)
char *s;
{
	int c;

	while ( (c=(*s++)) != '\0' )
		windputc(c);
}

windputc(c)
int c;
{
	addch(c);
}

windrefresh()
{
	refresh();
}

beep()
{
	putchar('\007');
}

windhigh()
{
	standout();
}

windnorm()
{
	standend();
}

/****************
 * openls(), nextls(), and closels() are used to scan the current directory.
 ***************/

FILE *Phrlist = NULL;

openls()
{
	FILE *popen();
	
	Phrlist = popen("ls","r");
}
char *
nextls()
{
	static char fname[65];

	if ( fscanf(Phrlist,"%s",fname) != 1 )
		return(NULL);
	return(fname);
}
closels()
{
	pclose(Phrlist);
}

#ifdef FAKECBREAK
#include <sys/termio.h>
struct termio Initterm;
static int First = 1;
cbreak()
{
	struct termio termbuff;

	if ( First  ) {
		First = 0;
		ioctl(0,TCGETA,&Initterm);
	}
	termbuff = Initterm;
	termbuff.c_lflag &= (~ICANON);
	termbuff.c_cc[4] = 1;
	termbuff.c_cc[5] = 1;
	ioctl(0,TCSETA,&termbuff);
}
nocbreak()
{
	ioctl(0,TCSETA,&Initterm);
}
#endif
