/*--------------------------------------------------------------------------*/
/*	Program name: 4_2_4.C                                               */
/*	Compile mode: Tiny                                                  */
/*	Image   file: 4_2_4.COM                                             */
/*	Remove  tool: REMOVE.COM                                            */
/*      Note        : This TSR program can save screen text mode to disk    */
/*                      and restore it from disk.                           */
/*		      You must include 4_2_3.C.                             */
/*                    All rights reserved !!                                */
/*--------------------------------------------------------------------------*/


#include	<stdio.h>
#include	<dos.h>
#include	<io.h>
#include	<fcntl.h>
#include	<conio.h>

#include	"4_2_3.c"
#define		ScreenMode	*(char far *)0x00400049
#define		HERC		7

char	far	*scr_ptr;
char		scrbuf[80*2];

/*----------------- Screen maintenance subroutine --------------------------*/

void	save_msg(void)
{	unsigned	i;
	for(i=0;i<80*2;i++)	scrbuf[i]=*(scr_ptr+i);
}

void	restore_msg(void)
{	unsigned	i;
	for(i=0;i<80*2;i++)	*(scr_ptr+i)=scrbuf[i];
}

void	clean_msg(void)
{	unsigned	i;
	for(i=0;i<80*2;i+=2)	*(scr_ptr+i)=0x20;
	gotoxy(1,1);
}

/*----------------- Screen save/load subroutine ----------------------------*/

void	load_screen(void)
{	int	fh;
	char	filename[80];
	union	REGS	reg;
	struct	SREGS	sreg;

	clean_msg();
	Printf("Load file: ");
	if (Scanf("%s",filename)==-1) return;
	if ((fh=_open(filename,O_RDWR))==-1)
	{	clean_msg();
		Printf("Load error! Press any key to continue...");
		Getch();
		return;
	}
	reg.x.ax=0x3F00;
	reg.x.bx=fh;
	reg.x.cx=4000;
	reg.x.dx=FP_OFF(scr_ptr);
	sreg.ds =FP_SEG(scr_ptr);
	int86x(0x21,&reg,&reg,&sreg);
	_close(fh);
	save_msg();
}

void	save_screen(void)
{	int	fh;
	char	filename[80];
	union	REGS	reg;
	struct	SREGS	sreg;

	clean_msg();
	Printf("Save file: ");
	if (Scanf("%s",filename)==-1) return;
	if ((fh=_creat(filename,FA_ARCH))==-1)
	{	clean_msg();
		Printf("Save error! Press any key to continue...");
		Getch();
		return;
	}
	restore_msg();
	reg.x.ax=0x4000;
	reg.x.bx=fh;
	reg.x.cx=4000;
	reg.x.dx=FP_OFF(scr_ptr);
	sreg.ds =FP_SEG(scr_ptr);
	int86x(0x21,&reg,&reg,&sreg);
	_close(fh);
}

/*----------------- TSR entry subroutine -----------------------------------*/

void	Tsr_subroutine(void)
{	char	ch;
	int	x,y;

	if (ScreenMode==HERC)	scr_ptr=(char far *)0xb0000000;
	else			scr_ptr=(char far *)0xb8000000;

	x=wherex();
	y=wherey();
	save_msg();

	do
	{	clean_msg();
		Printf("Save Load Quit: ");
		switch(ch=Getch())
		{	case	'S':
			case	's':	save_screen();
					break;
			case	'L':
			case	'l':	load_screen();
					break;
		}
	}	while(ch!='q'&&ch!='Q');

	restore_msg();
	gotoxy(x,y);
}
