program advancedscripting;

uses
  Windows, StrUtils, SysUtils, UserDefined;

var
  GetPipe : THandle;
  Ovl : TOverlapped;
  ExitApp : Boolean;
  fConnected: Boolean;
  bytesRead : Cardinal;
  Buffer    : array [0..512] of char;
  strBuffer : String;
  Command : String;
begin
  if (WaitNamedPipe(PAnsiChar('\\.\pipe\AdvancedScripting'),25)) then
    exit;
  GetPipe:=CreateNamedPipe(PAnsiChar('\\.\pipe\AdvancedScripting'),
                          FILE_FLAG_OVERLAPPED or
                          PIPE_ACCESS_INBOUND,
                          PIPE_TYPE_BYTE or PIPE_WAIT,
                          10,
                          0,
                          sizeof(buffer),
                          10000, // timeout in millseconds
                          Nil);
  Ovl.hEvent:=CreateEvent(nil, True, False, 'PipeConnected');
  ExitApp:=false;
  repeat
    strbuffer:='';
    try
      fConnected := ConnectNamedPipe(GetPipe, @Ovl) or (GetLastError = ERROR_PIPE_CONNECTED);
  
      while not (fConnected) do
        fConnected := WaitForSingleObject(Ovl.hEvent, 20) <> WAIT_TIMEOUT;
  
      if fConnected then
      begin
        ResetEvent(Ovl.hEvent);
  
        while ReadFile(GetPipe,Buffer,sizeof(Buffer),bytesRead,nil) do
        begin
          strBuffer:=strBuffer+copy(Buffer,0,bytesRead);
          buffer:='';
        end;

        if (AnsiStartsStr('LogLine:',strBuffer)) then
          On_LogLine(RightStr(strBuffer,Length(strBuffer)-8));
        if (AnsiStartsStr('HotKey:',strBuffer)) then
          On_HotKey(StrToInt(RightStr(strBuffer,Length(strBuffer)-7)));
        if (AnsiStartsStr('Command:',strBuffer)) then
        begin
          Command:=RightStr(strBuffer,Length(strBuffer)-8);
          ExitApp:=AnsiSameText(Command,'exit');
        end;
      end;

    finally
      FlushFileBuffers(GetPipe);
      DisconnectNamedPipe(GetPipe);
    end;
  until ExitApp=true;
  CloseHandle(GetPipe);
  CloseHandle(Ovl.hEvent);
end.