/******************************************************************************/
{$X+}
UNIT Screen;

INTERFACE

FUNCTION  SaveScreen : BOOLEAN;
PROCEDURE ReleaseScreen;
FUNCTION  RestoreScreen : BOOLEAN;

FUNCTION  PrevVideoSeg : WORD;
FUNCTION  PrevAttr : BYTE;
FUNCTION  PrevMode : WORD;
FUNCTION  PrevX : BYTE;
FUNCTION  PrevY : BYTE;
FUNCTION  PrevCols : BYTE;
FUNCTION  PrevRows : BYTE;

IMPLEMENTATION

USES
	Crt,
	MemBios;

TYPE
	BytePtr	= ^BYTE;

CONST
	Scr		: BytePtr	= NIL;
	Vseg	: WORD		= HercVideoSeg;
	X		: BYTE		= 0;
	Y		: BYTE		= 0;
	Attr	: BYTE		= 0;
	Mode	: WORD		= 0;
	Saved	: BOOLEAN	= FALSE;
	ScrSize	: WORD		= 0;
	ScrPtr	: BytePtr	= NIL;
	BPtr	: BytePtr	= NIL;
	Cols	: BYTE		= 80;
	Rows	: BYTE		= 25;

FUNCTION  SaveScreen : BOOLEAN;
VAR
	i	: WORD;
BEGIN
	Saved	:= TRUE;
	X		:= WhereX;
	Y		:= WhereY;
	Attr	:= TextAttr;
	Mode	:= LastMode;

	IF MemBios.COLS <> 0 THEN
		Cols := MemBios.COLS;
	IF MemBios.ROWS <> 0 THEN
		Rows := MemBios.ROWS + 1;

	ScrSize	:= Cols * Rows SHL 2;

	IF MaxAvail > ScrSize THEN
	BEGIN
		GetMem (Scr, ScrSize);

		IF VideoMode <> Herc720x348 THEN
			Vseg := NoHercVideoSeg;

		BPtr	:= Ptr (Vseg, 0);
		ScrPtr	:= Scr;

		ASM
			CLI
		END;
{
		FOR i := 1 TO ScrSize DO
		BEGIN
			ScrPtr^ := BPtr^;
			INC (BPtr);
			INC (ScrPtr);
		END;
 }
		Move (BPtr^, ScrPtr^, ScrSize);

		ASM
			STI
		END;

		SaveScreen := TRUE;
	END
	ELSE
		SaveScreen := FALSE;
END;


PROCEDURE ReleaseScreen;
BEGIN
	IF Saved THEN
	BEGIN
		FreeMem (Scr, ScrSize);
		Scr		:= NIL;
		ScrSize	:= 0;
		Saved	:= FALSE;
	END;
END;


FUNCTION  RestoreScreen : BOOLEAN;
VAR
	i	: WORD;
BEGIN
	IF NOT Saved THEN
	BEGIN
		RestoreScreen	:= FALSE;
		EXIT;
	END;

	TextAttr	:= Attr;
	TextMode (Mode);

	IF Scr <> NIL THEN
	BEGIN
		BPtr	:= Ptr (Vseg, 0);
		ScrPtr	:= Scr;

		ClrScr;

		ASM
			CLI
		END;
{
		FOR i := 1 TO ScrSize DO
		BEGIN
			BPtr^ := ScrPtr^;
			INC (BPtr);
			INC (ScrPtr);
		END;
}
		Move (ScrPtr^, BPtr^, ScrSize);

		ASM
			STI
		END;

		FreeMem (Scr, ScrSize);

		GotoXY (X, Y);

		RestoreScreen := TRUE;
	END
	ELSE
		RestoreScreen := FALSE;
END;



FUNCTION  PrevVideoSeg : WORD;
BEGIN
	PrevVideoSeg := Vseg;
END;



FUNCTION  PrevAttr : BYTE;
BEGIN
	PrevAttr := Attr;
END;


FUNCTION  PrevMode : WORD;
BEGIN
	PrevMode := Mode;
END;


FUNCTION  PrevX : BYTE;
BEGIN
	PrevX := X;
END;


FUNCTION  PrevY : BYTE;
BEGIN
	PrevY := Y;
END;


FUNCTION  PrevCols : BYTE;
BEGIN
	PrevCols := Cols;
END;


FUNCTION  PrevRows : BYTE;
BEGIN
	PrevRows := Rows;
END;




END.
