program Ernst_OLX_Editor_Caller;

{$M $4000,$0,$0 }   { 16K stack, no heap }

uses
    Crt, Dos, Ernst;

var
    Buffer        : string;       {Buffer tempor rio para leitura de arquivos}
    C             : byte;         {Contador tempor rio}
    F             : text;         {Arquivo Texto Tempor rio}
    hdr           : text;         {Arquivo HEADER.DAT}
    ori           : text;         {Arquivo ORIGINAL}
    rep           : text;         {Arquivo REPLY}
    reeditflag    : boolean;      {Reedi‡„o de mensagem, Reeditflag = TRUE}
    newflag       : boolean;      {Mensagem nova, Neflag = TRUE}
    work          : string[38];   {Diret¢rio de trabalho}
    reply         : string[49];   {Arquivo REPLY, com PATH}
    original      : string[49];   {Arquivo ORIGINAL, com PATH}
    header        : string[49];   {Arquivo HEADER.DAT, com PATH}
    reg           : boolean;      {Flag de registro}

    SeuDir        : string[38];   {do EOEC.INI: Diret¢rio dos arquivos}
    SeuEditor     : string[50];   {do EOEC.INI: Editor de textos}
    SeuEditorParam: string[50];   {do EOEC.INI: Parƒmetros para o editor}
    SeuHeader     : string[50];   {do EOEC.INI: Arquivo com HEADER}
    SeuHeaderArea : string[50];   {do EOEC.INI: Arquivo com HEADER}
    SeuLogo       : string[50];   {do EOEC.INI: Arquivo com assinatura}
    SeuTaglines   : string[50];   {do EOEC.INI: Arquivo com taglines}
    QuoteFix      : boolean;      {do EOEC.INI: Corrige os QUOTES?}

    OMsgDate      : string[8];    {Mensagem original: Data}
    OMsgTime      : string[5];    {Mensagem original: Hora}
    OMsgPacket    : string[8];    {Mensagem original: Pacote onde foi encontrada}

    OMsgArea      : string[3];    {Mensagem original: N£mero da  rea}
    OMsgAreaName  : string[25];   {Mensagem original: Nome da  rea}

    OMsgFrom      : string[25];   {Mensagem original: From}
    OMsgFFrom     : string[25];   {Mensagem original: Primeiro nome do From}
    OMsgLFrom     : string[25];   {Mensagem original: Ultimo nome do From}

    OMsgTo        : string[25];   {Mensagem original: To}
    OMsgFTo       : string[25];   {Mensagem original: Primeiro nome do To}
    OMsgLTo       : string[25];   {Mensagem original: Ultimo nome do To}

    OMsgSubj      : string[25];   {Mensagem original: Subject}

    RMsgArea      : string[3];    {Mensagem reply: N£mero da  rea}
    RMsgAreaName  : string[25];   {Mensagem reply: Nome da  rea}

    RMsgFrom      : string[25];   {Mensagem reply: From}
    RMsgFFrom     : string[25];   {Mensagem reply: Primeiro nome do From}
    RMsgLFrom     : string[25];   {Mensagem reply: Ultimo nome do From}

    RMsgTo        : string[25];   {Mensagem reply: To}
    RMsgFTo       : string[25];   {Mensagem reply: Primeiro nome do To}
    RMsgLTo       : string[25];   {Mensagem reply: Ultimo nome do To}

    RMsgSubj      : string[25];   {Mensagem reply: Subject}


(* ---------------------------------------------------------------------- *)
procedure Logo;
    (* Logo de programado por Ernesto Baschny *)

begin

    HighVideo;
    writeln('EOEC v1.3a - Ernst OLX Editor Caller');
    LowVideo;
    writeln('(c) 1994,95 por Ernesto Baschny');
    writeln;

end; {Logo}

(* ---------------------------------------------------------------------- *)
procedure ErrorMsg(Errorlevel: Byte; Error1, Error2: String);
    (* Apresenta mensagem de erro e sai com errorlevel especificado *)

begin

     textcolor(lightred);
     writeln('ERRO: ',Error1);
     textcolor(lightgray);
     writeln;
     if Error2 <> '' then
        writeln('þ ',Error2);
     CursorOff;
     readkey;
     CursorOn;
     halt(Errorlevel);

end;


(* ---------------------------------------------------------------------- *)
procedure Verify_Param;
    (* Verifica os parƒmetros passados ao programa *)

begin

    if (paramstr(1) = '/?') or (paramstr(1) = '-?') or (paramstr(1) = '?') then
    begin
         writeln('Sintaxe: EOEC <EOEC.INI> <REPLY>');
         writeln;
         writeln('Verifique o manual para conhecer o formato do arquivo <EOEC.INI>');
         writeln('<REPLY> ‚ o arquivo de resposta passado pelo OLX');
         CursorOff;
         readkey;
         CursorOn;
         halt(1);
    end;

    if paramcount<>2 then
    begin
         writeln('Sintaxe: EOEC <EOEC.INI> <REPLY>');
         CursorOff;
         readkey;
         CursorOn;
         halt(1);
    end;

    if not FileExists(paramstr(1)) then
         ErrorMsg(1,'N„o existe o arquivo de configura‡„o '+paramstr(1),'');

    if not FileExists(GetPathName(paramstr(2))+'NUL') then
         ErrorMsg(1,'N„o existe o diret¢rio '+GetPathName(paramstr(2)),'');

end; {Verify_Param}


(* ---------------------------------------------------------------------- *)
procedure CreateVars;
    (* Cria as vari veis de acordo com os arquivos *)

begin

    reply    := GetFileName(paramstr(2));
    work     := GetPathName(paramstr(2));
    reply    := work + reply;
    original := work + 'ORIGINAL';
    header   := work + 'HEADER.DAT';

    reeditflag := False;
    newflag    := False;
    reg        := False;
    QuoteFix   := False;

end; {CreateVars}

(* ------------------------------------------------------------------ *)
procedure CfgLineRead(var item, valor: string; var cfgfile: text);
    (* Lˆ uma linha do arquivo de configura‡„o, devolvendo o item e o valor *)

var Index : byte;

begin {CfgLineRead}

    item  := '';
    valor := '';

    readln(cfgfile, Buffer);
    while ((Buffer = '') or
          (Buffer[1] = ' ') or
          (Buffer[1] = ';') or
          (Buffer[1] = '#') or
          (Buffer[1] = '%')) and
          (not Eof(cfgfile)) do

    begin
        readln(cfgfile,Buffer);
{        if Eof(cfgfile) then
        begin
            item := '** EOF **';
            valor := '';
        end; }
    end;

    if (Buffer[1]) = '[' then
    begin
        item := copy(Buffer, 2, length(Buffer)-2);
        valor := 'INI_SESSAO';
    end;

    if (item = '') and (not Eof(cfgfile)) then
    begin

        Index := pos('=',Buffer);

        if Index = 0 then
             ErrorMsg(1,'Verifique se o arquivo '+paramstr(1)+' est  correto.','');

        Item := RTrim(copy(Buffer,1,Index-1));
        Valor := LTrim(copy(Buffer,Index+1,length(Buffer)-Index));

    end;

end; {CfgLineRead}


(* ---------------------------------------------------------------------- *)
procedure CfgRead;
    (* Lˆ configura‡„o do arquivo *)

var cfgfile : Text;   {arquivo de configura‡„o, parƒmetro 1}
    I       : Byte;   {contador para separar editor do parƒmetro}
    item, valor : String;  {item e valor da pr¢xima linha do EOEC.INI}


begin {Main - CfgRead}

    assign(cfgfile, paramstr(1));
    reset(cfgfile);

    CfgLineRead(Item, Valor, cfgfile);

    if (Item <> 'EOEC') and (Valor <> 'INI_SESSAO') then
         ErrorMsg(1,'A primeira sess„o do arquivo '+paramstr(1)+' deve ser'+Chr(13)+Chr(10)+
                    '      a sess„o [EOEC]. Verifique o EOEC.DOC para maiores detalhes','');

    Valor := '';

    while (Valor <> 'INI_SESSAO') and (not Eof(cfgfile)) do
    begin
        CfgLineRead(Item, Valor, cfgfile);

        if Item = 'Editor' then
        begin
            I := 0;
            for C := Length(Valor) downto 0 do
            begin
                 if (C = 0) and (I = 0) then I := Length(Valor)+1;
                 if (C > 0) and (Copy(Valor,C,1) = ' ') then I := C;
            end;

            SeuEditor := Copy(Valor,1,I-1);
            SeuEditorParam := Copy(Valor,I+1,Length(Valor)-I);
        end;

        if Item = 'ApagaDuploQuote' then
           if (Upper(Valor) = 'YES') or (Upper(Valor) = 'SIM') then
               QuoteFix := True
           else
               QuoteFix := False;

        if Upper(Item) = 'DIRETORIO'     then SeuDir        := ClearPath(Upper(Valor));
        if Upper(Item) = 'CABECALHO'     then SeuHeader     := Upper(Valor);
        if Upper(Item) = 'CABECALHOAREA' then SeuHeaderArea := Upper(Valor);
        if Upper(Item) = 'ASSINATURA'    then SeuLogo       := Upper(Valor);
        if Upper(Item) = 'TAGLINES'      then SeuTaglines   := Upper(Valor);
        if (Upper(Item) = 'REGISTER') and (Valor = 'EOEC13') then Reg := true;

    end;

        {verifica se os arquivos existem}

    Buffer := GetPathName(SeuHeader);

    if GetPathName(SeuHeader)     = '' then SeuHeader     := SeuDir+SeuHeader;
    if GetPathName(SeuHeaderArea) = '' then SeuHeaderArea := SeuDir+SeuHeaderArea;
    if GetPathName(SeuLogo)       = '' then SeuLogo       := SeuDir+SeuLogo;
    if GetPathName(SeuTaglines)   = '' then SeuTaglines   := SeuDir+SeuTaglines;

    if not FileExists(SeuEditor) then
         ErrorMsg(1,'N„o foi achado o editor de textos '+SeuEditor+'.',
                    'Verifique o item Editor do arquivo '+paramstr(1)+'.');

    if not FileExists(SeuDir+'NUL') then
         ErrorMsg(1,'N„o foi achado o diret¢rio '+SeuDir+'.',
                    'Verifique o item Diretorio do arquivo '+paramstr(1)+'.');

    if not FileExists(SeuHeader) then
         ErrorMsg(1,'N„o foi achado o arquivo com o header especificado como'+Chr(13)+Chr(10)+SeuHeader,
                    'Verifique o item Cabecalho do arquivo'+paramstr(1)+'.');

    if not FileExists(SeuHeaderArea) then
         ErrorMsg(1,'N„o foi achado o arquivo com o header para  rea especificado como'+Chr(13)+Chr(10)+SeuHeaderArea,
                    'Verifique o item CabecalhoArea do arquivo'+paramstr(1)+'.');

    if not FileExists(SeuLogo) then
         ErrorMsg(1,'N„o foi achado o arquivo com sua assinatura especificado como'+Chr(13)+Chr(10)+SeuLogo,
                    'Verifique o item Assinatura do arquivo'+paramstr(1)+'.');

    if not FileExists(SeuTaglines) then
         ErrorMsg(1,'N„o foi achado o arquivo com TAGLINES especificado como'+Chr(13)+Chr(10)+SeuTaglines,
                    'Verifique o item Taglines do arquivo'+paramstr(1)+'.');

end; {CfgRead}


(* ---------------------------------------------------------------------- *)
procedure WriteMacroLine(var DestFile: Text; Level: Byte; Line: String);
    (* Lˆ linha especificada e grava ela no arquivo DestFile, usando *)
    (* vari veis, se necess rio                                      *)

var TempLine : String;
    Macro    : String[10];
    I        : Byte;
    flag     : Boolean;

begin

     TempLine := '';
     Macro := '';
     I := 1;

     while I <= Length(Line) do
     begin
          if Line[I] <> '@' then TempLine := TempLine + Line[I];
          if Line[I] = '@' then
          begin
               flag := false;
               inc(I);

               while flag = false do
               begin
                    if (Line[I] <> '@') and (Line[I] <> ' ') then Macro := Macro + Line[I];
                    if (Line[I] = '@') or (Line[I] = ' ') then flag := true;
                    inc(I);
               end;

               dec(I);
               Macro := Upper(Macro);

               if level >= 1 then
               begin

                   if Macro = 'OPACKET' then TempLine := TempLine + Upper(OMsgPacket);
                   if Macro = 'OANAME' then TempLine := TempLine + OMsgAreaName;
                   if Macro = 'OANUMBER' then TempLine := TempLine + OMsgArea;
                   if Macro = 'ODATE' then TempLine := TempLine + OMsgDate;
                   if Macro = 'OTIME' then TempLine := TempLine + OMsgTime;
                   if Macro = 'OFROM' then TempLine := TempLine + Capitalize(OMsgFrom);
                   if Macro = 'OFFROM' then TempLine := TempLine + Capitalize(OMsgFFrom);
                   if Macro = 'OLFROM' then TempLine := TempLine + Capitalize(OMsgLFrom);
                   if Macro = 'OTO' then TempLine := TempLine + Capitalize(OMsgTo);
                   if Macro = 'OFTO' then TempLine := TempLine + Capitalize(OMsgFTo);
                   if Macro = 'OLTO' then TempLine := TempLine + Capitalize(OMsgLTo);
                   if Macro = 'OSUBJ' then TempLine := TempLine + OMsgSubj;

               end;

               if level >= 2 then
               begin

                   if Macro = 'RANAME' then TempLine := TempLine + RMsgAreaName;
                   if Macro = 'RANUMBER' then TempLine := TempLine + RMsgArea;
                   if Macro = 'RFROM' then TempLine := TempLine + Capitalize(RMsgFrom);
                   if Macro = 'RFFROM' then TempLine := TempLine + Capitalize(RMsgFFrom);
                   if Macro = 'RLFROM' then TempLine := TempLine + Capitalize(RMsgLFrom);
                   if Macro = 'RTO' then TempLine := TempLine + Capitalize(RMsgTo);
                   if Macro = 'RFTO' then TempLine := TempLine + Capitalize(RMsgFTo);
                   if Macro = 'RLTO' then TempLine := TempLine + Capitalize(RMsgLTo);
                   if Macro = 'RSUBJ' then TempLine := TempLine + RMsgSubj;
                   if Macro = 'CURDATE' then TempLine := TempLine + Current_Date;
                   if Macro = 'CURTIME' then TempLine := TempLine + Current_Time;
                   if Macro = 'CURDOW' then TempLine := TempLine + Current_DOW;

               end;

               if Macro = '' then TempLine := TempLine + '@';
               Macro := '';
               flag := false;

          end;
          inc(I);

     end;

     if I <= Length(Line) then
          TempLine := TempLine + Buffer[I];

     if Line <> '' then
         writeln(DestFile,TempLine)
     else
         writeln(DestFile);

end; {WriteMacroLine}


(* ---------------------------------------------------------------------- *)
function LimpaLinha (linha: string): string;
    (* LimpaLinha(l) tira ocorrencias de  l  do  tipo 'ENY>EB>' ficando  *)
    (* apenas com 'EB>'                                                  *)

var  temp, I, C, I2 : byte;
     pos : array[0..10] of byte;

begin

    temp   := 1;
    I2     := 0;
    C      := 1;
    I      := 1;
    pos[0] := 1;

        {tenta a cada 6 caracteres, ou at‚ chegar no fim da linha}

    while (I2 < 5) and (C < length(linha)) do

    begin

        inc(C);
        inc(I2);
        if linha[C]='>' then
        begin
            temp := C;
            inc(C);

            while (linha[C] = ' ') do
                inc(C);

            if linha[C] = '>' then
            begin
                pos[I] := temp + 1;
                C := temp + 1;
            end
            else
                pos[I] := C;

            I2 := 0;
            inc(I);
        end;

    end;

    LimpaLinha := copy(linha,pos[I-2],length(linha)-pos[I-2]+1);

end;  {LimpaLinha}


(* ---------------------------------------------------------------------- *)
procedure DoVars;
    (* produz as vari veis para uso no HEADER *)

begin

        {lˆ arquivo HEADER.DAT e guarda resultados}

    reset(hdr);
    readln(hdr,Buffer);

    if Buffer <> 'Reply Header File' then
         ErrorMsg(2,'Problemas no arquivo HEADER.DAT do OLX.'+Chr(13)+Chr(10)+
                    'Tente sair do OLX e entrar de novo.','');

    readln(hdr,RMsgFrom);                     {Reply message: From}
    RMsgFFrom := FirstName(RMsgFrom);         {First name of From}
    RMsgLFrom := LastName(RMsgFrom);          {Last name of From}

    readln(hdr,RMsgTo);                       {Reply message: To}
    RMsgFTo   := FirstName(RMsgTo);           {First name of To}
    RMsgLTo   := LastName(RMsgTo);            {Last name of To}

    readln(hdr,RMsgSubj);                     {Reply message: Subject}
    readln(hdr,RMsgArea);                     {Reply message: Area number}
    readln(hdr,RMsgAreaName);                 {Reply message: Area Name}

    close(hdr);

        {se for o caso, lˆ vari veis do ORIGINAL (header do OLX)}

    if (NewFlag <> true) and (Reeditflag <> true) then
    begin
         reset(ori);
         readln(ori);
         readln(ori, Buffer);

         OMsgPacket := RTrim(Copy(Buffer,9,8));     {Pacote: 'STIBBS'}

         readln(ori, Buffer);
         OMsgDate   := RTrim(Copy(Buffer,7,8));     {Data: 'DD-MM-AA'}
         OMsgTime   := Copy(Buffer,17,5);          {Hora: 'HH:MM'}

         readln(ori, Buffer);
         OMsgFrom   := RTrim(Copy(Buffer,7,25));    {From: 'xxxxxxxx'}
         OMsgFFrom  := FirstName(OMsgFrom);        {First name of From}
         OMsgLFrom  := LastName(OMsgFrom);         {Last name of From}

         readln(ori, Buffer);
         OMsgTo     := RTrim(Copy(Buffer,7,25));    {To: 'xxxxxxxxx'}
         OMsgFTo    := FirstName(OMsgTo);          {First name of To}
         OMsgLTo    := LastName(OMsgTo);           {Last name of To}

         readln(ori, Buffer);
         OMsgSubj   := RTrim(Copy(Buffer,7,25));    {Subj: 'xxxxxxxxx'}
         OMsgArea   := Copy(Buffer,45,3);

         close(ori);

            {ajuste do nome da  rea}

         if Copy(OMsgArea,2,1) = ')' then OMsgArea := Copy(OMsgArea,1,1);
         if Copy(OMsgArea,3,1) = ')' then OMsgArea := Copy(OMsgArea,1,2);

         if Length(OMsgArea) = 1 then OMsgAreaName := RTrim(FileString(ori,6,48,25));
         if Length(OMsgArea) = 2 then OMsgAreaName := RTrim(FileString(ori,6,49,25));
         if Length(OMsgArea) = 3 then OMsgAreaName := RTrim(FileString(ori,6,50,25));

    end;

end; {DoVars}


(* ---------------------------------------------------------------------- *)
procedure DoHeader;
    (* Coloca um HEADER na mensagem *)

begin

        {Recria o arquivo de resposta}

    Rewrite(rep);

        {Caso tenha havido mudan‡a de  rea da mensagem, inclui essa informa‡„o}

    if (RMsgArea <> OMsgArea) then
    begin

        assign(F,SeuHeaderArea);
        reset(F);

        while not Eof(F) do
        begin
             readln(F,Buffer);
             WriteMacroLine(rep,2,Buffer);
        end;

        close(F);

    end;

    { if (Upper(OMsgTo) = Upper(SeuNome)) or (Upper(OMsgTo) = Upper(SeuHandle)) then
       OMsgTo := 'mim';
    if (Upper(OMsgFrom) = Upper(RMsgTo)) then
       OMsgFrom := 'vocˆ'; }

        {Cria‡„o do HEADER conforme arquivo indicado no EOEC.CFG}

    assign(F,SeuHeader);
    reset(F);

    { Buffer := ''; }

        {lˆ cada linha do arquivo de header e aplica macros correspondentes}

    while not Eof(F) do
    begin
         readln(F,Buffer);
         WriteMacroLine(rep,2,Buffer);
    end;

        {mais uma linha depois do header}

    writeln(rep);

end; {DoHeader}


(* ---------------------------------------------------------------------- *)
procedure ShareDelay(Tempo: Byte);
    (* D  um delay de "tempo" segundos, com mensagem de pausa *)

begin

    CursorOff;
    while Tempo > 0 do
    begin
         write('Pausa por ',Tempo,' segundos...   ',Chr(13));
         delay(1000);
         dec(Tempo);
    end;
    writeln('Ok. Pausa encerrada.                          ');
    CursorOn;

end; {ShareDelay}


(* ---------------------------------------------------------------------- *)
procedure DoBottom;
    (* Coloca assinatura e tagline *)

Var Taglines : Word;  {quantidade de taglines no arquivo de tags}

begin

    assign(F,SeuLogo);
    reset(F);

    append(rep);

    while not Eof(F) do
    begin
         Readln(F, Buffer);
         WriteMacroLine(rep,2,Buffer);
    end;

    close(F);

    writeln(rep);

    Taglines := 0;

    assign(F,SeuTaglines);
    reset(F);

    while not Eof(F) do
    begin
         Readln(F);
         Inc(Taglines);
    end;

    randomize;
    append(rep);
    WriteMacroLine(rep,2,'... '+GetLine(F,Random(Taglines)+1));
    if reg = true then writeln(rep,'~~~ EOEC/OLX v1.3a [REG] - God save the OLX!');
    if reg = false then writeln(rep,'~~~ EOEC/OLX v1.3a [NR] - God save the OLX!');

    close(rep);

end;



(* ====================================================================== *)
begin {Main Program}

    Logo;                     {Logotipo inicial do programa}
    Verify_Param;             {Verifica a entrada de um parƒmetro (REPLY)}
    CreateVars;               {Cria vari veis work, reply, original e header}
    CfgRead;                  {Lˆ configura‡„o do arquivo EOEC.INI}

    assign(rep,reply);        {Arquivo REPLY = rep}
    assign(hdr,header);       {Arquivo HEADER.DAT = hdr}
    assign(ori,original);     {Arquivo ORIGINAL = ori}

    if FileExists(reply) then   {Verifica se a mensagem ‚ reedi‡„o de mensagem}
        Reeditflag := True      {pr¢pria ou n„o      1a edi‡„o    Reedi‡„o}
    else                                   {           Ori Rep     Ori Rep}
        if not FileExists(original) then   {  New       n   n       n   s }
            Newflag := True;               {  Reply     s   n       s   s }
                                           {  Mensagem minha        s   s }

    DoVars;

    if (not Reeditflag) and (not Newflag) then
    begin
         DoHeader;
         Append(rep);
         Reset(ori);
         for C := 1 to 7 do readln(ori);
         while not Eof(ori) do
         begin
               readln(ori,Buffer);
               if QuoteFix = true then
                   writeln(rep,LimpaLinha(Buffer))
               else
                   writeln(rep,Buffer);
         end;
         close(rep);
         close(ori);
    end;


    { debug procedures
    writeln('EOEC est  para entrar no editor, chamando:');
    writeln(SeuEditor,' '+SeuEditorParam+' '+reply);
    readkey;
     end debug }

    SwapVectors;
    Exec(SeuEditor,SeuEditorParam+' '+reply);
    SwapVectors;

    if DosError <> 0 then
         ErrorMsg(2,'Erro de execu‡„o no EOEC:','Contate Ernesto Baschny, informando erro #001-'+IntToStr(DosError));

    if not FileExists(reply) then
         ErrorMsg(2,'N„o foi criado um arquivo de resposta: '+reply,'Pressione alguma tecla para retornar ao OLX.');

    if not Reeditflag then DoBottom;

    clrscr;
    writeln('Obrigado por usar o EOEC v1.3a.');
    CheckBreak := False;

    if reg = false then
    begin
        writeln;
        writeln('Contate ERNESTO BASCHNY para retirar essa mensagem. N„o ‚ necess rio nenhum');
        write('pagamento. ');
        TextColor(White);
        writeln('Este programa ‚ Freeware.');
        TextColor(LightGray);
        writeln;
        writeln('O contato s¢ precisa ser feito para que eu possa manter o controle de quem');
        writeln('o usa.');
        writeln;
        writeln('Obrigado pela compreens„o,');
        writeln('       Ernesto Baschny');
        writeln;
        writeln('  E VIVA O OLX!');
        writeln;
        ShareDelay(5);
    end;

end. {Main Program}
