{*********************************************
 ***         OVERLAY MANAGER INITIALISER   ***
 *********************************************}
{$I compflgs}
{$O-}
{Needs to be initialised in a unit initialisation procedure,
so that it can load up other overlaid units to do their
initialisations. Trying to initialise after the main body
has started running is too late.}

unit OVERINIT;

INTERFACE

var OverlayBufferSize : longint;

IMPLEMENTATION

uses 	minilib, {so don't overlay minilib! - see below command line /ovs}
			overlay;

const
	ovrMessage 	: array[-6..0] of string
							= (	'No EMS Memory',
									'No EMS Driver',
									'IO Error',
									'No Memory',
              		'Not Found',
                  'Error',
									'OK');

var
	ExtraBufferSize : longint;
	I : longint;
	S : string;

begin
	{Locate overlay file}
	OvrInit(Copy(ParamStr(0),1,length(ParamStr(0))-4)+'.ovr');  {take filename & Change extension}

	Write('  Overlay Manager ');
	if ovrResult <> ovrOK then begin
		OvrInit(ParamStr(0));						{Try loading from self - is possible! copy KAMELEON.EXE+KAMELEON.OVR KAMELEON.EXE /b}

		if ovrResult<>ovrOK then begin
			writeln('failed to load: (',ovrResult,': '+ovrMessage[ovrResult]+')');
			halt(1);
		end;
	end;
	write('Loaded ');

	{Increase size if memory available}
  ExtraBufferSize := 0;
	if MemAvail >$10000 then
		ExtraBufferSize := (MemAvail - $10000) *2 div 3; {leave at least 6K free}

  OverlayBufferSize := OvrGetBuf + ExtraBufferSize;
	{look for /ovs = on command line}
	{be careful here, as it calls routines in minilib which is overlaid,
	resulting in the overlay manager running, which then cannot change the
	buffer size (I think).  Got out of this by unoverlaying minilib - which
	shouldn't really be an overlay anyway, it gets called too much...}
	for I := 1 to ParamCount do
		if ucase(Copy(ParamStr(I),1,5))='/OVS=' then begin
			S := Copy(ParamStr(I),6,99);
			if S[1] = '$' then OverlayBufferSize := Hex2Dec(S) else OverlayBufferSize := S2Num(S);
		end;{}

	OvrSetBuf(OverlayBufferSize);
	if OvrResult <> ovrOK then write('not expanded (',ovrResult,' not enough memory?) ');

	{Try and load into EMS}
	OvrInitEMS;
	if OvrResult = ovrOK then Write('in extended memory ')
											 else Write('in ordinary memory (',ovrResult,')');
{}
	OverlayBufferSize := OvrGetBuf;
	writeln('  (Size: ',OverlayBufferSize,')');
end.
