unit UnitPOS_CIDR;

interface
uses
  Windows, Classes;

const
  LibName = 'POS_CIDR.dll';
{$define dynamiclib}

type
  Int32 = Integer;

{$ifdef dynamiclib}

type
  TCIDR_Info =
    function (): PWideChar; stdcall;
  TCIDR_RegisterEvent =
    function (FuncPtr: Pointer; Mask: Int32): Int32; stdcall;
  TCIDR_SaveLine =
    function (Line: Int32; FileName: PWideChar; Param: PWideChar): Int32; stdcall;
  TCIDR_PlayLine =
    function (Line: Int32): Int32; stdcall;

var
  CIDR_Info : TCIDR_Info;
  CIDR_RegisterEvent : TCIDR_RegisterEvent;
  CIDR_SaveLine : TCIDR_SaveLine;
  CIDR_PlayLine : TCIDR_PlayLine;

  CIDR_Loaded: Boolean = False;

{$else}

function CIDR_Info(): PWideChar; cdecl; external LibName;
function CIDR_RegisterEvent(FuncPtr: Pointer; Mask: Int32): Int32; cdecl; external LibName;
function CIDR_SaveLine(Line: Int32; FileName: PWideChar; Param: PWideChar): Int32; cdecl; external LibName;
function CIDR_PlayLine(Line: Int32): Int32; cdecl; external LibName;

var
  CIDR_Loaded: Boolean = True;
{$endif}

type
  TCIDR_Callback = procedure(line: Int32; msg: WideString) of object;


function CIDR_RegisterMethod(Callback: TCIDR_Callback; Mask: Int32): Int32;
procedure CIDR_GetInfo(var dll_version: WideString; var totallines: Integer);

implementation

uses Math, SysUtils;

var
  FProc: TCIDR_Callback = nil;

procedure CIDR_Event(line: Int32; msg: PWideChar); stdcall;
var
  s: WideString;
begin
  if (msg=nil) then
    s:= ''
  else
    s:= msg;

  if Assigned(FProc) then
  begin
    FProc(line, s);
  end;
end;

function CIDR_RegisterMethod(Callback: TCIDR_Callback; Mask: Int32): Int32;
begin
  FProc:= Callback;
  if Assigned(FProc) then
    Result:= CIDR_RegisterEvent(@CIDR_Event, Mask)
  else
    Result:= CIDR_RegisterEvent(nil, 0);
end;

procedure CIDR_GetInfo(var dll_version: WideString; var totallines: Integer);
var
  SL: TStringList;
  s: WideString;
begin
  totallines:= 0;
  dll_version:= '';
  SL:= TStringList.Create;
  try
    SL.Text:= CIDR_Info;
    if (SL.Count>=3) then
    begin
      dll_version:= SL[0];
      s:= SL[2];
      Delete(s, 1, Pos(':', s));
      totallines:= StrToIntDef(s, 0);
    end;
  finally
    SL.Free;
  end;
end;

{$ifdef dynamiclib}
var
  LibHandle: HMODULE;

initialization
  LibHandle := LoadLibraryEx(LibName, 0, 0);
  if (LibHandle<>0) then
  begin
    CIDR_Info := GetProcAddress(LibHandle, 'CIDR_Info');
    CIDR_RegisterEvent := GetProcAddress(LibHandle, 'CIDR_RegisterEvent');
    CIDR_SaveLine := GetProcAddress(LibHandle, 'CIDR_SaveLine');
    CIDR_PlayLine := GetProcAddress(LibHandle, 'CIDR_PlayLine');
    CIDR_Loaded:=
      (@CIDR_Info <> nil) and
      (@CIDR_RegisterEvent <> nil) and
      (@CIDR_SaveLine <> nil) and
      (@CIDR_PlayLine <> nil);
  end;

{$endif}

end.
