program Ernst_OLX_Editor_Caller;

{$M $4000,$0,$0 }   { 16K stack, no heap }
{$B-}

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}
    cfgfile       : text;
    reeditflag    : boolean;      {Reedi‡„o de mensagem, Reeditflag = TRUE}
    newflag       : boolean;      {Mensagem nova, Neflag = TRUE}
    forwardtype   : byte;         {0=no forward; 1=newarea; 2=samearea}
    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}
    ReplyCRC      : word;

    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?}
    Saudacao      : boolean;      {do EOEC.INI: Coloca sauda‡„o autom tica?}
    SeuRegLine    : string[50];   {do EOEC.INI: O que aprece depois do [REG]}
    SeuQuoteSigns : string[20];   {do EOEC.INI: Caracteres de quote}
    SeuTagSign    : string[10];   {do EOEC.INI: Prefixo de taglines}

    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}
    OMsgFromHandle: string[25];   {Mensagem original: Handle 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}
    OMsgToHandle  : string[25];   {Mensagem original: Handle 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}
    RMsgToHandle  : string[25];   {Mensagem reply: Handle do To}

    RMsgSubj      : string[25];   {Mensagem reply: Subject}

    MsgPacket     : string[11];   {Pacote de mensagens}

(* ---------------------------------------------------------------------- *)
procedure Logo;
    (* Logo de programado por Ernesto Baschny *)

begin

    HighVideo;
    writeln('EOEC v1.4 - 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 DirExists(GetPathName(paramstr(2))) 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;
    forwardtype:= 0;
    reg        := False;
    QuoteFix   := False;
    Saudacao   := False;

end; {CreateVars}

(* ------------------------------------------------------------------ *)
procedure INISectionFind(var cfgfile: text; sessao: string; var flag: boolean);
    (* Acha uma determinada sess„o no arquivo de configura‡„o           *)
    (* Se for encontrada, ele deixa o ponteiro na posi‡„o e FLAG = TRUE *)
    (* Se n„o for encontrado, retorna FLAG = FALSE                      *)

var done : boolean;

begin

    flag := true;
    done := false;

    reset(cfgfile);

    Buffer := 'A';

    while (Buffer[1] <> '[') and (flag = true) do
    begin

        readln(cfgfile,Buffer);

        while (flag = true) and (done = false) do
        begin

            if Upper(copy(Buffer, 2, length(Buffer)-2)) = Upper(sessao) then
                done := true;

            if Eof(cfgfile) then
                flag := false;

            if done <> true then
                readln(cfgfile,Buffer);

        end;

    end;

end; {INISectionFind}

(* ------------------------------------------------------------------ *)
procedure INILineRead(var item, valor: string; var cfgfile: text);
    (* Lˆ uma linha do arquivo de configura‡„o, devolvendo o item e o valor *)
    (* Se n„o houver mais itens, retorna ENDSECTION em item, valor ''       *)

var Index : byte;

begin {INILineRead}

    item  := '';
    valor := '';
    Buffer := '';

    readln(cfgfile, Buffer);
    while ((Buffer = '') or
          (Buffer[1] = ' ') or
          (Buffer[1] = ';') or
          (Buffer[1] = '#') or
          (Buffer[1] = '%')) and
          (not Eof(cfgfile)) do
              readln(cfgfile,Buffer);

    if (Buffer[1] = '[') or ((Eof(cfgfile)) and (Buffer = '')) then
    begin
        item := 'ENDSECTION';
        valor := '';
    end;

    if (item = '') 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; {INILineRead}


(* ---------------------------------------------------------------------- *)
procedure CfgRead;
    (* Lˆ configura‡„o do arquivo *)

var I       : Byte;   {contador para separar editor do parƒmetro}
    item, valor : String;  {item e valor da pr¢xima linha do EOEC.INI}
    flag    : boolean;

begin {Main - CfgRead}

    INISectionFind(cfgfile,'EOEC',flag);

    if flag = false then
         ErrorMsg(1,'N„o foi encontrada a sess„o [EOEC] no arquivo '+paramstr(1)+Chr(13)+Chr(10)+
                    '      Verifique o EOEC.DOC para maiores detalhes','');

    item := '';

    while (item <> 'ENDSECTION') do
    begin
        INILineRead(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 Item = 'Saudacao' then
           if (Upper(Valor) = 'YES') or (Upper(Valor) = 'SIM') then
               Saudacao := True
           else
               Saudacao := 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) = 'QUOTES'        then SeuQuoteSigns := Strip(Valor,true);
        if Upper(Item) = 'TAGSIGN'       then SeuTagSign    := Valor;
        if (Upper(Item) = 'REGISTER') and (Valor = 'EOEC14') then Reg := true;
        if (Upper(Item) = 'REGISTERLINE') and (Reg = true) then SeuRegLine := Valor;

    end;

        {verifica se os arquivos existem}

    Buffer := GetPathName(SeuHeader);

        {Se n„o tiver PATH especificado, usa o do SeuDir}

    if SeuDir <> '' then
    begin

        if (GetPathName(SeuHeader) = '') and
           (SeuHeader <> '') then SeuHeader := SeuDir+SeuHeader;

        if (GetPathName(SeuHeaderArea) = '') and
           (SeuHeaderArea <> '') then SeuHeaderArea := SeuDir+SeuHeaderArea;

        if (GetPathName(SeuLogo) = '') and
           (SeuLogo <> '') then SeuLogo := SeuDir+SeuLogo;

        if (GetPathName(SeuTaglines) = '') and
           (SeuTaglines <> '') then SeuTaglines := SeuDir+SeuTaglines;

        if not DirExists(SeuDir) then
             ErrorMsg(1,'N„o foi achado o diret¢rio '+SeuDir+'.',
                        'Verifique o item Diretorio do arquivo '+paramstr(1)+'.');

    end;

    if SeuTagSign = '' then SeuTagSign := '...';

    if SeuQuoteSigns = '' then SeuQuoteSigns := '>';

    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 SeuHeader <> '' then
        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 SeuHeaderArea <> '' then
        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 SeuLogo <> '' then
        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 SeuTaglines <> '' then
        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                                      *)
    (* Level >= 1 para os itens @O...@                               *)
    (* Level >= 2 para os itens @R...@                               *)

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 = 'OFROMHANDLE' then TempLine := TempLine + Capitalize(OMsgFromHandle);
                   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 = 'OTOHANDLE' then TempLine := TempLine + Capitalize(OMsgToHandle);
                   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 = 'RTOHANDLE' then TempLine := TempLine + RMsgToHandle;
                   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;
     posi : array[0..10] of byte;

begin

    temp   := 1;     {para se o quote for "EB>   > texto"               }
    I2     := 0;     {contador para ver se n„o passa dos 6 caracteres   }
    C      := 1;     {contador para verificador de caracter por caracter}
    I      := 1;     {indice para as posi‡”es                           }
    posi[0] := 1;    {posi‡”es para os quotes                           }

        {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 pos(linha[C],SeuQuoteSigns) > 0 then
        begin
            temp := C;
            inc(C);

            while (linha[C] = ' ') do
                inc(C);

            if pos(linha[C],SeuQuoteSigns) > 0 then
            begin
                posi[I] := temp + 1;
                C := temp + 1;
            end
            else
                posi[I] := C;

            I2 := 0;
            inc(I);
        end;

    end;

    LimpaLinha := copy(linha,posi[I-2],length(linha)-posi[I-2]+1);

end;  {LimpaLinha}


(* ---------------------------------------------------------------------- *)
procedure DoVars;
    (* produz as vari veis para uso nos arquivos *)

    (* ------------------------------------------------------------------ *)
    function DoHandle(Nome: string): string;
            (* retorna Handle do Nome, caso exista                *)
            (* para nomes com mais handles, faz sorteio aleat¢rio *)

    var Flag       : boolean;
        Item, Valor: String;  {item e valor da pr¢xima linha do EOEC.INI}
        TempHandle : array [1..10] of string;
                              {array com os poss¡veis 10 handles para posterior
                               sorteio aleat¢rio}
        Counter    : byte;    {contador para os handles}

    begin {DoHandle}

        Flag := false;
        Item := '';
        Counter := 0;


            {acha sess„o APELIDOS, posiciona o ponteiro na primeira linha}

        INISectionFind(cfgfile,'APELIDOS',flag);

        if flag <> false then                   {se achou a sess„o, ent„o}
        begin

            while item <> 'ENDSECTION' do       {lˆ do arquivo as linhas v lidas}
            begin                               {at‚ chegar ao final do arquivo}

                INILineRead(item, valor, cfgfile);

                if Upper(item) = Upper(Nome) then  {caso v  encontrando nomes}
                begin                              {correspondentes ao handle}
                    inc(Counter);                  {os vai guardando na array}
                    TempHandle[Counter] := valor;
                end;

            end;

            if Counter = 0 then               {se ele n„o achou nenhum handle}
                DoHandle := Capitalize(FirstName(Nome))
            else                              {se ele achou handles, ele faz}
            begin                             {sorteio entre os existentes}
                randomize;
                DoHandle := TempHandle[random(Counter)+1];
            end;

        end;

    end; {DoHandle}
    (* ------------------------------------------------------------------ *)

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}

    RMsgToHandle := DoHandle(RMsgTo);

    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}

        OMsgFromHandle := DoHandle(OMsgFrom);

        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}

        OMsgToHandle := DoHandle(OMsgTo);

        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) and (SeuHeaderArea <> '') 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.INI}

    if SeuHeader <> '' then
    begin

        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;

end; {DoHeader}

(* ---------------------------------------------------------------------- *)
procedure DoSaudacao;
    (* Coloca uma sauda‡„o aleat¢ria na mensagem *)

var Saudacoes : word;
    Aleatorio : word;
    flag      : boolean;

begin

    if Saudacao = true then
    begin

        INISectionFind(cfgfile,'SAUDACOES',flag);

        if flag <> false then
        begin

            Saudacoes := 0;
            Buffer := 'A';

            while (Buffer[1] <> '[') and (not Eof(cfgfile)) do
            begin

                readln(cfgfile, Buffer);
                if (Buffer <> '') and
                   (Buffer[1] <> ' ') and
                   (Buffer[1] <> ';') and
                   (Buffer[1] <> '#') and
                   (Buffer[1] <> '%') and
                   (Buffer[1] <> '[') then
                        inc(Saudacoes);

            end;

            randomize;
            Aleatorio := Random(Saudacoes)+1;

            INISectionFind(cfgfile,'SAUDACOES',flag);

            Saudacoes := 0;
            Buffer := '';

            while Saudacoes < Aleatorio do
            begin
                inc(Saudacoes);

                readln(cfgfile, Buffer);

                while ((Buffer = '') or
                       (Buffer[1] = ' ') or
                       (Buffer[1] = ';') or
                       (Buffer[1] = '#') or
                       (Buffer[1] = '%')) do
                            readln(cfgfile, Buffer);

            end;

            WriteMacroLine(rep,2,Buffer);
            writeln(rep);

        end
        else
            writeln(rep,'Oi ',RMsgToHandle,'.');
            writeln(rep);

    end;

end;

(* ---------------------------------------------------------------------- *)
procedure DoQuotes(lines: byte; Quote: boolean);
    (* "Appenda" os quotes na mensagem *)
    (* Se QUOTE for TRUE, ele utiliza o Limpalinha, se necess rio *)

begin

    append(rep);
    reset(ori);

    if lines > 1 then
        for C := 1 to (lines-1) do readln(ori);

    while not Eof(ori) do
    begin
          readln(ori,Buffer);
          if (QuoteFix = true) and (Quote = true) then
              writeln(rep,LimpaLinha(Buffer))
          else
              writeln(rep,Buffer);
    end;

    close(ori);

end;


(* ---------------------------------------------------------------------- *)
procedure DoBottom;
    (* Coloca assinatura e tagline *)

Var Taglines : Word;  {quantidade de taglines no arquivo de tags}

begin

    if SeuLogo <> '' then
    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);

    end;

    if SeuTaglines <> '' then
    begin

        Taglines := 0;

        assign(F,SeuTaglines);
        reset(F);

        while not Eof(F) do
        begin
             Readln(F);
             Inc(Taglines);
        end;

        randomize;
        append(rep);
        WriteMacroLine(rep,2,SeuTagSign+' '+GetLine(F,Random(Taglines)+1));

    end;

    if SeuRegLine <> '' then SeuRegLine := ' - '+SeuRegLine;

    if reg = true then writeln(rep,'~~~ EOEC/OLX v1.4 [REG]',SeuRegLine);
    if reg = false then writeln(rep,'~~~ EOEC/OLX v1.4 [NR] - God save the OLX!');

    close(rep);

end;


(* ---------------------------------------------------------------------- *)
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}


(* ====================================================================== *)
begin {Main Program}

    Logo;                     {Logotipo inicial do programa}
    Verify_Param;             {Verifica a entrada de um parƒmetro (REPLY)}

    assign(cfgfile, paramstr(1));
    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 }

    if (Reeditflag) and (not Newflag) then
    begin
        reset(rep);
        readln(rep,Buffer);

        if copy(Buffer,1,21) = 'This message was from' then
        begin

            readln(rep,Buffer);

            if copy(Buffer,1,24) = 'originally in conference' then
                Forwardtype := 2
            else
                Forwardtype := 1;

            Reeditflag := False;

        end;

        close(rep);
    end;

{    INISectionFind(cfgfile,'AREACONFIG',flag);

    if flag := true then Reconfig; }

    DoVars;

    if (not Reeditflag) and (not Newflag) then
    begin
        DoHeader;
        DoSaudacao;
        DoQuotes(8,true);     {P”e quotes a partir da linha 9}
        close(rep);
    end;

    if Forwardtype > 0 then
    begin
        rewrite(rep);
        DoSaudacao;
        writeln(rep,'                    ---------- Forwarded message -----------');
        DoQuotes(1,false);   {P”e texto a partir da linha 1, sem LimpaLinha}
        writeln(rep,'                    ---------------[EOEC 1.4]---------------');
        close(rep);
    end;

    if (not Reeditflag) and (Newflag) then
    begin
        rewrite(rep);
        DoSaudacao;
        close(rep);
    end;

    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 uma resposta no arquivo '+reply,'Pressione alguma tecla para retornar ao OLX.');

    if not Reeditflag then
        DoBottom;

    clrscr;
    writeln('Obrigado por usar o EOEC v1.4.');
    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('Leia a documenta‡„o do EOEC para maiores detalhes.');
        writeln;
        writeln('Obrigado pela compreens„o,');
        writeln('       Ernesto Baschny');
        writeln;
        writeln('  E VIVA O OLX!');
        writeln;
        ShareDelay(5);
    end;

end. {Main Program}
