Program Loadext;
{$IFDEF DEBUG}
{$A-,B-,D+,F+,I-,N-,R-,S-,V-,L+,O-}
{$ELSE}
{$A-,B-,D-,F+,I-,N-,R-,S-,V-,L-,O-}
{$ENDIF}

{ Please see LOADEXT.DOC }
{ This source file is provided to show how easy it is to write a new }
{ function using the E! API }

Uses Dos, Crt, Api;

VAR

  IntStr     : string[3];  { Interrupt number used by E! }
  IntNum     : byte;       {   "         "     "   "  "  }
  valretcode : integer;
  FileName   : pathstr;
  NamePtr    : ^pathstr;
  Ext        : string[3];

Function Lastpos(needle,haystack:string;start:integer):integer;
 { -This function is extracted from the E! source code }
 { It returns the the last position of needle in haystack }

var
    textbuffer,
    needlebuffer : string;
    limit,newpos,
    len1,len2    : integer;
    i            : byte;

begin
 len2:=Length(needle);
 limit:=Length(haystack) - len2 + 1;
 if start < 1 then begin
   LastPos:=0;
   Exit;
 end
 else if start > limit then
   start:=limit;
 Delete(haystack,start + len2, 255);
 len1:=Length(haystack);
 textbuffer[0]:=Char(len1);
 needlebuffer[0]:=Char(len2);
 for i:=1 to len1 do
   textbuffer[Succ(len1) - i]:=haystack[i];
 for i:=1 to len2 do
   needlebuffer[Succ(len2) - i]:=needle[i];
 newpos:=Pos(needlebuffer,textbuffer);
 if newpos = 0 then
   LastPos:=0
 else
   LastPos:=Succ(len1 - Pred(newpos) - len2);
end;


begin
 { Is E! present ? }
 IntStr:=GetEnv('E!PRESENT');
 { Retrieve the number of the interrupt used by E! }
 if IntStr = '' then
   Halt;
 Val(IntStr, IntNum, valretcode);
 if valretcode <> 0 then
   Halt
 else
   E_Vec:=IntNum;
 { Is E! busy ? }
 if not Is_E_Idle then
   Halt;
 { Get the name of the current file }
 NamePtr:=Request_E_Address(NAME_REQUEST);
 FileName:=NamePtr^;
 { ... and its extension }
 Ext:=Copy(FileName, Succ(LastPos('.', FileName, Length(FileName))), 3);
 if Ext = '' then
   halt;
 { Load the relevant profile }
 RegisterCommand('PRO '+ Ext);
END.
