
#include <stdio.h>
#include <windefs.h>
#include <termio.h>
#include <sgtty.h>

/* EXTERNAL VARIABLES */
int WinX, WinY;
int CurX, CurY;
int MaxX, MaxY;
int CharX, CharY;
int Windowfd;   /* ? */
int Flag=0;    /* ? */


/* LOCAL VARIABLES */
static WinoffX, WinoffY ,OffY;
static Highlight = 0;
static GrMode = 0;

WINDOWDATA Win;
char window_file_name[32];
static oldcolours[2]; 

struct termio term;


FILE *fp;
FILE *ifp;


                    /* WINDOW MANAGEMENT */
Window_error(where)
	int where;
{
	fprintf(stderr,"Window error %d\n",where);
	mgideagp();
	exit(1);
}

Set_colour_map()
{	mgigetcms(1,3,oldcolours);
	mgicm(1,0xA0A0A0);
	mgicm(2,0xF0F0F0);
	mgicm(3,0x000000);
}

Reset_colour_map()
{	mgicms(1,3,oldcolours);  }


InitScreen(argc, argv)
	int argc;
	char **argv;
{	
	int view, xl, yb, xr, yt, placed;
	mgiasngp(0,0);
	mgigetv(&view);
	mgigetvcoor(view, &xl, &yb, &xr, &yt, &placed);
	Set_colour_map();
      /* Check validity of viewport data */ 
	if (placed>0) Window_error(0);

/* Make a window and set up device files and external variables */
	WinX = xr - xl;       /* raster window size */
	WinY = yt - yb; 
	MaxX = WinX/8;      /* char window size */
	MaxY = WinY/16 - 1;
	CurX = 0;                   /* char curr posn */
	CurY = 0;
	CharX = 8;     /* raster char size */
	CharY = 16;
	WinoffX = xl;        /* raster offset window */
	WinoffY = yb;
	OffY = 0;                /* for now */
	/* LetterX = ; LetterY = ;  */

/*	ioctl(fileno(stdout), WIOCGETPATH, window_file_name);
	strcat(window_file_name, Win.wd_name); */
	fp = fopen("/dev/tty","r+");
	if (fp == NULL) {
		fprintf(stderr,"fopen failed\n");
		exit(0);
	}
}

KillWindow()
{
Reset_colour_map();
shut_input();
}


Add_string_char(str, asc)
	char str[];
	int asc;
{	char ch, convert[2] ;
	ch = asc;
	sprintf(convert, "%c", ch);
	strcat(str, convert);
}

Add_string_int(str, num)
	char str[];
	int num;
{	char convert[7] ;
	sprintf(convert, "%d", num);
	strcat(str, convert);
}

Escape_seq(prefix, num1, com1, num2, com2)
	int prefix,num1,com1,num2,com2;
{
	char str[15];
	strcpy(str, "\033");
	Add_string_char(str, prefix);
	if (num1 >= 0)   Add_string_int(str, num1);
	if (com1 > 0)   Add_string_char(str, com1);
	if (num2 >= 0)   Add_string_int(str, num2);
	if (com2 > 0)   Add_string_char(str, com2);
	fprintf(fp, "%s", str); 	
	fflush(fp);
}

                       /* TEXT */
PrGraph(Ch)
	int Ch;
{
	switch (Ch) {
	  case 'j': return('j');
	  case 'k': return('k');
	  case 'l': return('l');
	  case 'm': return('m');
	  case 'n': return(218);
	  case 'q': return(173);
	  case 't': return('t');
	  case 'v': return(218);
	  case 'w': return('|');  /*175*/
	  case 'x': return(220);
	}
	return(Ch);
}

Strlen(s)
	char *s;
{	int n;
	for (n=0; *s !='\0' ; s++)
	n++;
	return(n);
}


/*
 * Initialise the input stream
 */

static	int	dev_channel;
struct	sgttyb	dev_org_parm, dev_cur_parm;
static	int	dev_status;
static	int	input_init = 0;

init_input()
{
	short x;
	if (input_init != 0) return;
	input_init = 1;
	ifp = fopen("/dev/tty","r+");
	dev_channel = fileno(ifp);
	dev_status = gtty(dev_channel,&dev_org_parm);
	dev_cur_parm = dev_org_parm;
	/* set up the input mask - first turn off echo */
        x = !ECHO; dev_cur_parm.sg_flags &= x;
	/* set into raw mode */
	x = (RAW | CRMOD);
	dev_cur_parm.sg_flags |= x;
	stty(dev_channel,&dev_cur_parm);
}

shut_input()
{
	/* end of input or quit */
	if (input_init == 0) return;
	input_init = 0;
	stty(dev_channel,&dev_org_parm);
}

TTGet()
{
	char ch;
	int status,i;

	init_input();
	status = read(dev_channel,&ch,1);
	i = ch;
	if (( i == 4) || (i == 3) || (i == 26)) {
		shut_input();
	}
	return(i);
}


TTPut(Ch)
	int Ch;
{
	if (GrMode==1) Ch=PrGraph(Ch);
	putc(Ch, fp);
	fflush(fp); 
	MoveTo( CurX+1,CurY);
}

TTString(Ch)
	char *Ch;
{	
	int j,i=0;
	char str[255];
	Escape_seq('G' , -1 , 'a' , -1 , 'w' );  
	if (GrMode==1) {
	  while (*Ch!='\0') {
	    str[i]=PrGraph(*Ch);
	    Ch++; i++; }
	fprintf(fp, "%s", str);
	} 
	fprintf(fp,"%s", Ch);
	Escape_seq('G' , -1 , 'w' , -1 , 0 );  
	fflush(fp);
	/*   set cursor posn by adding string length */
	MoveTo(CurX+Strlen(Ch), CurY); 
}	

                    /* CLEAR */
ClearLine()
{	int last , X1,Y1,X2,Y2;
	X1=0;
/*	X2=MaxX*CharX; */
	X2=WinX;
	Y1=( MaxY-CurY) * CharY;
	Y2=Y1+CharY;	
	if (CurY=0) Y2=WinY; 
	Escape_seq('[' , 2 , 'K' , -1 , 0 );  
	last = Highlight;
	mgihue(3);
	mgibox(X1,Y1,X2,Y2);
	mgihue(last);
}

ClearScreen()
{	int x,y,i;
	Escape_seq( '[' , 2 , 'J' , -1 , 0 );
	mgigetv(&i);
	mgimodfunc(3,0,3);
	mgiclearpln(i,-1,0);
}

                     /* SCROLLING */
Scroll(LLn, HLn, By)
	int LLn, HLn, By;
{
	if (By<0) {            /* text upwards  */
	  MoveTo( 0,LLn);
	  Escape_seq( '[' , -By , 'M' , -1 , 0 );
	  MoveTo( 0, HLn+By);
	  Escape_seq( '[' , -By , 'L' , -1 , 0 );
	}
	if (By>0) {           /* text downwards  */
	  MoveTo( 0,HLn-By+1);
	  Escape_seq( '[' , By , 'M' , -1 , 0 );
	  MoveTo( 0, LLn);
	  Escape_seq( '[' , By , 'L' , -1 , 0 );
	}
}

ScrollUp(N)
	int N;
{	Scroll(0, MaxY, N);  }

ScrollDown(N)
	int N;
{	Scroll(0, MaxY, -N);  }


                /* MOVEMENT and CURSOR */
MoveTo(x,y)
	int x,y;
{
	/* Coord system is from (1,1) not (0,0)
	   therefor adjust accordingly.        */
	if (x>MaxX) x=MaxX;
	if (x<0)    x=0;
	if (y>MaxY) y=MaxY;
	if (y<0)    y=0;
	CurX=x; CurY=y;
	Escape_seq( '['  , CurY+1 , ';' , CurX+1 , 'H' );
}

DrawCursor()
{
	Escape_seq( 'G' , -1 , 'c' , -1 , 0 );
	Escape_seq( 'G' , -1 , 'b' , -1 , 0 );
}

DrawOrgCursor()
{	fprintf(stdout,"\033Gc");
	fflush(stdout);              }

DeleteCursor()
{
	Escape_seq( 'G' , -1 , 'a' , -1 , 'c' );
}

Home()
{	MoveTo(0,0);  }   /* changed from (1,1) */

DownLine()
{	
	MoveTo(CurX, CurY+1);   }

UpLine()
{
	MoveTo(CurX, CurY-1);   }

                    /* DRAW */

DrawLine(X, Y, X1, Y1)
{	mgil(X,WinY-Y,X1,WinY-Y1);
}

Rectangle(X, Y, W, H)
{	int X1=X+W;
	int Y1=Y+H;	
/*	mgibox(X,WinY-Y,X+W,WinY-Y+H); */
	DrawLine(X,Y,X1,Y); DrawLine(X,Y,X,Y1);
	DrawLine(X,Y1,X1,Y1); DrawLine(X1,Y,X1,Y1);
}	

                    /* OTHER */

SetIntensity(LoHi)
	int LoHi;
{	Highlight = LoHi;
	if (Highlight>1) Highlight=1;
	mgihue(Highlight+1);
}

SetGraphics(Mode)
	int Mode;
{	GrMode = Mode;  }


FlushOutput()
{	fflush(fp);      }

refresh()
{
}

/*
main(argc, argv)
	int argc;
	char **argv;
{
	int x, y, ch, i;
	char str[2];

	InitScreen();
	MoveTo(0,0);
	TTPut(32);   
	fprintf(fp, "Input a char - q to quit");
	fflush(fp);
	i=0;
	DrawCursor();
	while (i<60) {  
	  ch=TTGet();
	  if (ch=='q') break;
	  if (ch==13 || ch==10) continue;
	  MoveTo(i,i);
	  TTPut(ch);
	  i=i+1;
	}
	Scroll(10,20,-5);
	TTPut(32);  
		
	fflush(fp);
	ch=TTGet();
	ch=TTGet();
	ClearScreen();
	KillWindow();
	mgideagp();
	DrawCursor();
}
*/

Print_term_characteristics(term)
	struct termio *term;
{

	fprintf(stdout, "Term flag line discipline %x\n", 
                         term->c_line) ;
	fprintf(stdout, "Term flag line discipline modes %x\n", 
                         term->c_lflag) ;
	fprintf(stdout, "Term flag input mode %x\n", 
                         term->c_iflag) ;
	fprintf(stdout, "Term flag output mode %x\n", 
                         term->c_oflag) ;
	fprintf(stdout, "Term flag control mode %x\n", 
                         term->c_cflag) ;
}
PrintWindow(Win)
	WINDOWDATA	*Win ;
{
	fprintf(stdout, "Flags %x\n", Win->wd_flags) ;
	fprintf(stdout, "X, Y, W, L %d %d %d %d \n", Win->wd_x, Win->wd_y,
					 Win->wd_width, Win->wd_height) ;
	fprintf(stdout, "Text Window X, Y, L, W %d %d %d %d\n",
				Win->wd_tx, Win->wd_ty, Win->wd_twidth,
							Win->wd_theight) ;
	fprintf(stdout, "Name %s\n", Win->wd_name) ;
	fprintf(stdout, "Label %s\n", Win->wd_label) ;
	fprintf(stdout, "Wiewport No %d\n", Win->wd_viewport) ;
	fprintf(stdout, "Save planes %X\n", Win->wd_saveplanes) ;

	fprintf(stdout, "Font %d\n", Win->wd_tfont) ;
	fprintf(stdout, "Fonts heights %d %d %d %d\n", Win->wd_c_height,
						     	Win->wd_c_width,
							Win->wd_lc_height,
							Win->wd_lc_width) ;

}

