unit MainForm;

{$INCLUDE RA.INC}

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TMain = class(TForm)
    RunDynamic: TButton;
    procedure RunDynamicClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Main: TMain;

implementation

//uses rai2_stdctrls, rai2_classes;

{$R *.dfm}

const
{$IFDEF RA_D5}
  PackageFileName    = 'rai5.bpl';
  ALLPackageFileName = 'raia5.bpl';
{$ENDIF RA_D5}
{$IFDEF RA_D6}
  PackageFileName    = 'rai6.bpl';
  ALLPackageFileName = 'raia6.bpl';
{$ENDIF RA_D6}

procedure DynamicRAI2RunFormModal(const FileName: TFileName);
var
  Pak, ALLPak: HModule;
  Proc     : procedure;
type
  TRunFormModal = function (const FileName: TFileName): TModalResult;
  TMakeForm     = function (const FileName: TFileName): TForm;
begin

  try
    Pak := LoadPackage(PackageFileName);
  except
    raise Exception.CreateFmt('Package %s konnte nicht geladen werden!', [ExtractFileName(PackageFileName)]);
  end;

  try
    ALLPak := LoadPackage(ALLPackageFileName);
  except
    raise Exception.CreateFmt('Package %s konnte nicht geladen werden!', [ExtractFileName(AllPackageFileName)]);
  end;

  try
     Proc := GetProcAddress(ALLPak, ('@Rai2_all@initialization$qqrv'));

     if not Assigned(Proc) then
        raise Exception.CreateFmt('Funktion %s.Initialization nicht gefunden!', [ExtractFileName(AllPackageFileName)]);

     Proc;

     Proc := GetProcAddress(Pak, ('@Rai2fm@RAI2RunFormModal$qqrx17System@AnsiString'));
     if not Assigned(Proc) then
        raise Exception.CreateFmt('Funktion %s nicht gefunden!', ['RunFormModal']);

     TRunFormModal(Proc)(FileName);

 finally
     UnloadPackage(ALLPak);
     UnloadPackage(Pak);
  end;
end;

function LoadRAI2Package(const PackageFileName: TFileName; const UnitName: String): HModule;
var
  Proc: procedure;
  FuncName: String;
begin

  try
    Result := LoadPackage(PackageFileName);
  except
    raise Exception.CreateFmt('Package %s konnte nicht geladen werden!', [ExtractFileName(PackageFileName)]);
  end;
   FuncName := '@' + UnitName + '@initialization$qqrv';
   Proc := GetProcAddress(Result, PChar(FuncName));

   if not Assigned(Proc) then
      raise Exception.CreateFmt('Funktion %s.Initialization nicht gefunden!', [FuncName]);

   Proc;
end;

procedure TMain.RunDynamicClick(Sender: TObject);
var
  PackageFileName: String;
  RAI2_MyLabelPackage: HModule;
begin
  PackageFileName := ExtractFilePath(Application.ExeName) + 'RAI2_MyLabelPackage.bpl';
  RAI2_MyLabelPackage := 0;
  try
    try
      RAI2_MyLabelPackage := LoadRAI2Package(PackageFileName, 'Rai2_mylabel');
    except
      raise Exception.CreateFmt('Package %s konnte nicht geladen werden!', [ExtractFileName(PackageFileName)]);
    end;
    DynamicRAI2RunFormModal(ExtractFilePath(Application.ExeName) + 'ScriptForm.pas');
  finally
    FreeLibrary(RAI2_MyLabelPackage);
  end;
end;

initialization
end.
