#include <stdlib.h>
#include <dos.h>
#include <conio.h>
#include <string.h>

#include "window.h"

extern int _wscroll;

void		NewWindow(x1,y1,x2,y2,bc,fc,title,bdchar)
int			x1,y1,x2,y2,bc,fc;
char		*title,bdchar;
{
	int			w,tw;
	char		ctitle[80];

	if ((x1 == x2) || (y1 == y2)) return;
	if (x1 > x2)
	{
		w = x1;
		x1 = x2;
		x2 = w;
	}
	if (y1 > y2)
	{
		w = y1;
		y1 = y2;
		y2 = w;
	}
	w = x2 - x1 + 1;
	textbackground(bc);
	textcolor(fc);
	window(x1,y1,x2,y2);
	clrscr();
	window(1,1,80,25);
	box(x1,y1,x2,y2,bdchar);
	if (strlen(title))
	{
		if (w > 6)
		{
			if (strlen(title) >= (w-6))
			{
				strncpy(ctitle,title,w-6);
				ctitle[w-6] = 0;
			}
			else
			{
				strcpy(ctitle,title);
			}
			tw = strlen(ctitle) / 2;
			w /= 2;
			gotoxy(x1+(w-tw)-1,y1);
			putch(' ');
			cputs(ctitle);
			putch(' ');
		}
	}
}

void		box(x1,y1,x2,y2,type)
int			x1,y1,x2,y2,type;
{
	int			i;
	char		tr,tl,br,bl,hc,vc;

	_wscroll = 0;
	if ((x1 != x2) && (y1 != y2))
	{
		if (x1 > x2)
		{
			i = x1;
			x1 = x2;
			x2 = i;
		}
		if (y1 > y2)
		{
			i = y1;
			y1 = y2;
			y2 = i;
		}
		switch (type)
		{
			case SINGLE:
				tr = '¿';
				tl = 'Ú';
				br = 'Ù';
				bl = 'À';
				hc = 'Ä';
				vc = '³';
				break;
			case DOUBLE:
				tr = '»';
				tl = 'É';
				br = '¼';
				bl = 'È';
				hc = 'Í';
				vc = 'º';
				break;
		}

		gotoxy(x1,y1);
		putch(tl);
		for (i=x1+1; i<x2; i++) putch(hc);
		putch(tr);

		for (i=y1+1; i<y2; i++)
		{
			gotoxy(x1,i);
			putch(vc);
			gotoxy(x2,i);
			putch(vc);
		}

		gotoxy(x1,y2);
		putch(bl);
		for (i=x1+1; i<x2; i++) putch(hc);
		putch(br);
	}
	_wscroll = 1;
}

void		CenterString(char *str)
{
	int 		x,y,w;

	x = wherex();
	y = wherey();
	w = strlen(str) / 2;
	gotoxy(x-w+1,y);
	cputs(str);
}

void		clearbox(char x1,char y1,char x2,char y2,char bc,char fc)
{
	struct text_info ti;

	gettextinfo(&ti);

	window(x1,y1,x2,y2);
	textcolor(fc);
	textbackground(bc);
	clrscr();

	puttextinfo(&ti);
}


void    puttextinfo(struct text_info *ti)
{
	window(ti->winleft,ti->wintop,ti->winright,ti->winbottom);
	textattr(ti->attribute);
	gotoxy(ti->curx,ti->cury);
}
