// -*- ASCII:EDT -*-
//
// Run Compiler: Source -> dvi, pdf, ps, html, etc...
//
// This is a universal console application launching macro for applications
// that are defined in the execution modes.
//
// Input Parameters:
// -----------------
// %$('ExitCode-OK'): - the value that indicates OK Exit Code
//     Usually 0 (except for some applications when 1 indicates OK status
//     Only used when Detect Exit Code Option is enabled in the Execution Modes
// %$('Compile-Flag'):
//     0  - normal
//     1+ - don't reset show or hide WinEdt Console (inside multiple compilation)
//     2  - No Further Checks after successfully launching the compiler...
//     3  - Iterating: Check if more iterations are required
//                     before Starting Viewer and Checking for Warnings...
// %$('TeXify-Iterations') - How many iterations (including this one)
//                           (Only used if Compile-Flag is 3)
// %!9 contains the compiler declared and defined in the Execution Modes:
//     [PDF]TeXify, [PDF]TeX, [PDF]LaTeX, AMSTeX, ...
// %!8 empty or the extension of the produced Log File (log, blg, etc...)
// %!7 must contain the type of the compiled document / output (dvi, ps, pdf, bbl, etc...)
// %!6 Startup Folder (MUST Exist!) -- Usually %P or %O
// %!5 Command Line with Parameters and Switches
//
// Output Parameters:
// ------------------
// Return: %!3..%!9 - Preserved Values
// Return: %!0..%!2 - WinExe Flags
// Return: %$('Compile Status') - OK or Short Error / Event Description String
// Return: %$('Edit-Flag') - Empty unless WinEdt was called during
//                           the compilation (responses to e)
// Return: %$('Compile-Flag') - Always Reset to Empty (Zero)
// Return: %$('TeXify-Iterations') - The same or Zero if no Further Iterations are required
//                                   (Only used / changed if Compile-Flag is 3)
//
// ==================================================================

  Requires(20160131); // Requires this build of WinEdt to work properly

  IfConsoleRunning("Relax;","JMP('not_Running');");
  ShowConsole(1);
  Prompt("Another Application is already running in WinEdt's Console.>
 Terminate the application or wait for the execution to finish!");
  FocusConsole(1);
  Exit;

:not_Running:: ======================================================
  PushTagsandRegisters;
  Exe("%b\Exec\PushEnvVars.edt");

  SetErrorFlag(0);
  SetOK(1);  // Just in case ...
  Assign(!"Compile Status");
  SetExitHandler('Exit_Handler');
  JMP('Start');

:Exit_Handler:: =====================================================
  Assign(!'Compile-Flag');
  PopTagsandRegisters(0,0001111111);
  Exe("%b\Exec\PopEnvVars.edt");
  StopWorking;
  UpdateStatus;
  SetExitHandler;
Return;

:Start:: ============================================================
  IfStr("%$('%!9-WinEdt_Console');",'1','=',!'JMP(!"Test_Exit_OK");');
  IfStr("%$('%!9-Hidden_Window');", "1","=",!'JMP(!"Test_Exit_OK");');
  SetFocus('%!9 ...');
  IfOK(!"Assign(!'Compile Status',!'Focus %!9 ...');JMP(!'Exit');");  // Already Running: focus it and exit...

:Test_Exit_OK:: =====================================================
  IfStr('%!7',!'pdf','<>',!'JMP(!"not_PDF_Preview");');
  // Close the current Document in Acrobat (Reader) using DDE
  // Avoid the error message because Acrobat locks the ".pdf" file for writing...
  // The same for PDF-XChange
  Exe('%b\Exec\PDF\PDFCloseDoc.edt');

:not_PDF_Preview:: ==================================================
  IfStr("%$('%!9-Wait');","1","=",!|StartWorking("%!9 %N");|);

  // Execute tasks before compiling...
  Exe("%b\Exec\ExeCompilerPre.edt");

  // Delete the working output files...
  IfFileExists("%b\_Run.log",!"DeleteFile('%b\_Run.log')");
  IfFileExists("%b\_Err.log",!"DeleteFile('%b\_Err.log')");
  IfFileExists("%b\_Out.log",!"DeleteFile('%b\_Out.log')");
  IfFileExists("%P\%N.%!7",!"DeleteFile('%P\%N.%!7')");
  IfFileExists("%O\%N.%!7",!"DeleteFile('%O\%N.%!7')");
  IfStr('%!8','','>',>
    !|IfFileExists("%O\%N.%!8",!"DeleteFile('%O\%N.%!8')");>
      SetLogFilename("%%O\%%N.%!8");|);
  UpdateStatus;

  LetReg(0, !"0");
  LetReg(1, !"0");
  LetReg(2, !"0");
  IfStr("%$('%!9-Wait');",             "1","=",!|LetRegNum(0,"%!0+00100");|);
  IfStr("%$('%!9-Background_Window');","1","=",!|LetRegNum(0,"%!0+10000");|);
  IfStr("%$('%!9-STD_IO');",           "1","=",!|LetRegNum(0,"%!0+00010");|);
  // If hidden do not create console Window at all in order to avoid problems
  // with MiKTeX's packages on demand installation (new in WinEdt 10)!
  IfStr("%$('%!9-Hidden_Window');",    "1","=",!|LetRegNum(0,"%!0+1100000000");|);
  IfStr("%$('%!9-Pause');",            "1","=",!|LetRegNum(1,"%!1+111");|);
  IfStr("%$('%!9-High_Priority');",    "1","=",!|LetReg(2,'1');|);

  // %!5 contains the Command Line...
  TrimCommandLine(@@'%!5',5); // Expand Command Line (twice!) and Remove Extra Spaces
  // Prompt("|%!5|");         // For Debugging purposes
  Assign('Edit-Flag','');     // Response with e?

  IfStr("%$('%!9-WinEdt_Console');",'1','<>',!'JMP(!"Windows_Console");');

:WinEdt_Console:: ===================================================
  // Running from TeXify / Compile Macro?
  IfStr("%$('Compile-Flag');",'','=',>
   !|>
      IfStr("%$('%!9-Hidden_Window');",'1','=',!"ResetConsole;",!"ResetConsole;ShowConsole(1);");>
      IfStr("%$('%!9-Background_Window');",'1','=',!"FocusConsole(-1);",!"FocusConsole(1);");>
    |);
  GetConsoleText(3);
  IfStr('%!3','','<>',!'LetReg(3,"%!3%\");');

  // *** Execute it!!!
  SetConsoleText('%!3Command Line:   %!5%\Startup Folder: %!6%\%\',1);
  RunConsole('%!5','%!6','%!9 ...',1,1,0,0,0,0,0);
  IfOK(!"Assign(!'Compile Status',!'OK');",>
       !"ShowConsole(1);Assign('Force-Focus','1');Assign(!'Compile Status',!'Run Error');JMP(!'Exit');");

  // Execute tasks after compiling...
  Exe('%b\Exec\ExeCompilerPost.edt');
  UpdateStatus;
  JMP(!'no_LOG');

:Windows_Console:: ==================================================
  IfStr("%$('Compile-Flag');",'','=',>
    !|IfStr("%$('%!9-STD_IO');","1","=",!"ResetConsole;");|);

  // *** Execute it!!!
  SetOK(1); // Just in case
  WinExe('','%!5','%!6','%!9 ...', %!0, %!2,>
         '', '%b\_Out.log', '%b\_Err.log',%!1);
  IfOK(!"Assign(!'Compile Status',!'OK');",>
       !"Assign(!'Compile Status',!'Run Error');StopWorking;UpdateStatus;>
         Prompt('Error starting %!9!%\See WinEdt''s  Configuration Wizard%\for detailed diagnosis of your system.');>
         IfStr('%!8','','>',!'ErrorLogUpdate;');JMP(!'Exit');");

  // Execute tasks after compiling...
  Exe('%b\Exec\ExeCompilerPost.edt');
  UpdateStatus;

  IfStr("%$('%!9-Wait');","1","=",!|Relax;|,!|JMP(!'Exit');|);

  IfStr("%$('%!9-STD_IO');","1","<>",!"JMP(!'no_LOG');");

  // Create a log file!!!
  OpenOutput('%b\_Run.log');  // Open Run's Log File
  // Insert the general information ...
  WrL("Compiler: %!9 [TeX: %$('TeX System');]");
  WrL;
  WrL('Command Line:   %!5');
  WrL('Startup Folder: %!6');
  GetExitCode(3);
  WrL('Exit Code:      %!3');
  WrL;
  GetDate(3, 'dddd, mmmm d, yyyy "at" hh:nn'); // Date Stamp
  WrL('Output captured by WinEdt on %!3');
  WrL(|>
------------------------------------------------------------------%\>
%\>
WinEdt has successfully executed %$('TeX System'); %!9 accessory.%\>
%\>
If %!9 encountered and reported errors the resulting %!7 file%\>
may not appear properly displayed or in some cases may not be%\>
created at all. For your convenience WinEdt captured output and%\>
error files produced by the %!9 accessory.%\>
%\>
If there are problems (eg. if WinEdt displayed this file) read%\>
this output carefully, fix any offending errors in your documents%\>
and recompile your sources. If you are having troubles locating%\>
and fixing errors please consult the extensive documentation%\>
pertaining to %!9 in %$('TeX System'); Doc folder.%\>
%\>
  Hint: WinEdt is almost certainly irrelevant to this situation!%\>
%\>
WinEdt may be able to assist you with locating the most common%\>
%!9's errors and warnings based on the information in TeX's log%\>
file. If any such errors were detected you'll see the Error Log%\>
panel displayed at the bottom of your screen.%\>
%\>
  Hint: use the Ctrl+E shortcut to "walk" through Errors and%\>
  Warnings in your documents (as reported by TeX)...%\>
%\>
------------------------------------------------------------------%\|);
  IfFileExists('%b\_Err.log',!'ReadFile("%b\_Err.log", 3);',!'LetReg(3);');
  IfStr("%!3","","=",>
    !"Relax;>
      WrL('No errors were reported during the execution of %!9.');>
      WrL('*** Error File is empty!');>
      IfFileExists('%b\_Out.log',!'ReadFile(''%b\_Out.log'', 3);',!'LetReg(3);');>
      IfStr('%!3','','=',>
        !|WrL;>
          WrL('*** External application did not produce any console output!');>
          Relax;|,>
        !|WrL;>
          WrL('*** WinEdt captured the following console output:');>
          WrL;>
          WrL('%!3');>
          Relax;|);",>
    !"Relax;>
      WrL('Errors were reported during the execution of %!9.');>
      WrL('*** WinEdt captured the following error file:');>
      WrL;>
      WrL('%!3');>
      IfFileExists('%b\_Out.log',!'ReadFile(''%b\_Out.log'', 3);',!'LetReg(3);');>
      IfStr('%!3','','=',>
        !|WrL;>
          WrL('*** External application did not produce any console output!');>
          Relax;|,>
        !|WrL;>
          WrL('*** WinEdt captured the following console output:');>
          WrL;>
          WrL('%!3');>
          Relax;|);>
      Relax;");
  WrL(|%\------------------------------------------------------------------%\|);
  CloseOutput;    // Close Log file
  //Console Info!
  GetExitCode(3);
  SetConsoleInfo('%!9... (Exit Code=%!3)');
  ReadFile('%b\_Run.log',3);
  SetConsoleText('%!3',1,1);

:no_LOG:: ===========================================================
  IfFileExists("%b\_Err.log",!"DeleteFile('%b\_Err.log');");
  IfFileExists("%b\_Out.log",!"DeleteFile('%b\_Out.log');");

  // Update Log file...
  IfFileExists("%E",!"UpdateFile('%E');");
  ErrorLogUpdate;
  UpdateStatus;

  IfStr("%$('Post-Process');","","<>",>
    !"IfStr(`%$('%!9-Report');`,`1`,`=`,!`Exe('%b\Exec\ShowReport.edt');`);");
  IfStr("%$('Compile-Flag');","2","=",!"JMP(!'Exit');");
  // No Log File?
  IfStr('%!8','','=',!'IfStr("%$(`Compile-Flag`);","1","<",!"FocusConsole(-1);");JMP(!"no_Warnings");');

  // Iterating through TeXify ?
  IfStr("%$('Compile Status');","OK","<>",!"JMP(!'no_Iteration');");
  IfStr("%$('Compile-Flag');","3","<>",!"JMP(!'no_Iteration');");
  IfNum("%$('TeXify-Iterations');","1","<=",!"JMP(!'Done');");
  IfFileExists('%E',!'Relax;',!'JMP(!"no_Iteration");');
  ReadFile("%E",3);
  FindInString("%!3",!"<No file",-1,-1, 11);
  IfOK(!"JMP(!'Again');");
  FindInString("%!3",!"Rerun LaTeX",-1,-1, 0);
  IfOK(!"JMP(!'Again');");
  FindInString("%!3",!"Rerun to get",-1,-1, 10);
  IfOK(!"JMP(!'Again');");
  IfNum("%$('TeXify-Iterations');","2","<=",!"JMP(!'Done');");
  FindInString("%!3",!"LaTeX Warning: Citation",-1,-1, 10);
  IfOK(!"JMP(!'Again');");
  FindInString("%!3",!"Package natbib Warning: Citation",-1,-1, 10);
  IfOK(!"JMP(!'Again');");
  FindInString("%!3",!"Package glossaries Warning: Glossary entry",-1,-1, 10);
  IfOK(!"JMP(!'Again');");
:Done:: =============================================================
  Assign(!"TeXify-Iterations",!"0");
  Assign(!"Compile-Flag",!"1");
  JMP(!'no_Iteration');

:Again:: ============================================================
  Relax; // [PDF]TeXify will call you again if necessary!

:no_Iteration:: =====================================================
  IfStr("%$('External-Call');",!"1",!"<>",>
    !"IfStr(`%$('Compile-Flag');`,`2`,`<`,>
        !`IfStr(|%$('%!9-Report');|,|1|,|=|,>
            !|Exe('%b\Exec\ShowReport.edt');Assign('Report-Shown','1');|);`);");
  IfStr("%$('Compile-Flag');","1","<",!"FocusConsole(-1);");

  // Wait to receive "e" response
  ProcessMessages;
  LetRegNum(3,0);
:Wait_for_Edit-Flag:: ===============================================
  LetRegNum(3,%!3+1);
  Wait(66); // Wait for Edit-Flag?
  ProcessMessages;
  IfStr("%$(!'Edit-Flag');",!"",!"<>",!"Assign(!'Compile Status',!'Edit');JMP(!'Exit');");
  IfNum(%!3,4,!'<',!'JMP(!"Wait_for_Edit-Flag");');

  // Only "real / serious" Errors (not Warnings)
  IfStr("%$('%!9-Errors');","1","=",>
   !|>
      IfLogErrors(!"FindError(0,1,0,-1,2);Assign(!'Compile Status',!'Error');JMP(!'Exit');",>
        !`IfStr("%$('%!9-Warnings');","1","<>",!"ShowErrorLog(-1);");`,0,-1,2);>
    |);

:no_Errors:: ========================================================
  IfStr("%$('Compile-Flag');","3","=",>
   !|>
      GetExitCode(3);>
      IfNum('%!3','%$("ExitCode-OK");','=',!"JMP(!'no_Warnings');");>
    |);
  // All Enabled Errors and Warnings
  IfStr("%$('%!9-Warnings');","1","=",>
   !|>
      IfLogErrors(!"ShowErrorLog(1);",!"ShowErrorLog(-1);",0,-1,0);>
    |);

:no_Warnings:: ======================================================
  // Exit Code: Errors (non-zero return)?
  IfStr("%$('%!9-ExitCode');","1","=",>
   !|>
      GetExitCode(3);>
      IfNum('%!3','%$("ExitCode-OK");','=',>
        !"Relax;",>
        !"StopWorking;UpdateStatus;Assign(!'Compile Status',!'Exit Code');>
          // Comment the next line out if you don't want a prompt!<>
          Prompt('%!9 returned Exit Code (%!3) indicating that some problems might have occurred during the compilation...');>
          JMP(!'Exit');");>
    |);

// Check if the Output was Generated ...

  IfStr('%!9',!'NSIS',!'=',!'JMP(!"Preview");');
  IfStr("%!7","","=",!"JMP('Hide_Console');"); // No Output
  IfFileExists("%P\%N.%!7",!"JMP('Preview');");
  IfFileExists("%O\%N.%!7",!"JMP('Hide_Console');");

  GetExitCode(3);
  IfNum('%!3','%$("ExitCode-OK");','<>',>
    !"Assign(!'Compile Status',!'Exit Code');",>
    !"Assign(!'Compile Status',!'Output');JMP(!'Hide_Console');");

  LetReg(3, "%!9 failed to create a %!7 file.%\");
  LetReg(3, "%!3For possible explanations start the command from the Command Prompt...");
  StopWorking;
  UpdateStatus;

  IfStr("%$('%!9-WinEdt_Console');","1","=",!"JMP(!'no_Output');");
  IfFileExists("%b\_Run.log", !"Relax;",!"JMP(!'no_Console_Info');");

:no_Output:: ========================================================
  ShowConsole(1);
  IfStr("%$('%!9-Report');","1","<>",>
    !"SetConsoleText('%!3%\',1,1);FocusConsole(1);Assign('Force-Focus','1');");
  JMP(!'Exit');

:no_Console_Info:: ==================================================
  IfStr("%$('%!9-Report');","1","<>",!"Prompt('%!3');");
  JMP(!'Exit');

:Preview:: ==========================================================
  GetExitCode(3);
  IfNum('%!3','%$("ExitCode-OK");','<>',!"Assign(!'Compile Status',!'Exit Code');JMP(!'Exit');");
  IfStr("%$('Compile-Flag');","3","=",!"JMP(!'Exit');");
  // Hide WinEdt Console (if so configured)...
  IfStr("%$('%!9-WinEdt_Console');",'1','=',>
    !|IfStr("%$('%!9-Pause');",'1','<>',!"ShowConsole(-1);");|);
  IfStr("%$('%!9-Viewer');",!"1",!"<>",!"JMP(!'Exit');");
  IfStr("%!8","","<>",!|IfLogErrors(!"JMP(!'Exit');",!"Relax;",0,-1,2);|);
  FocusConsole(-1);
  IfStr('%!9',!'NSIS',!'=',!'JMP(!"NSIS_Preview");');
  IfStr('%!7',!'dvi',!'=',!'JMP(!"DVI_Preview");');
  IfStr('%!7',!'pdf',!'=',!'JMP(!"PDF_Preview");');
  IfStr('%!7',!'ps',!'=',!'JMP(!"PS_Preview");');
  IfStr('%!7',!'html',!'=',!'JMP(!"HTML_Preview");');
  IfStr('%!7',!'htm',!'=',!'JMP(!"HTM_Preview");');
  IfStr('%!7',!'chm',!'=',!'JMP(!"CHM_Preview");');
  Prompt('No Viewer for ".%!7" files is currently defined!');
  JMP(!'Exit');
:NSIS_Preview:: =====================================================
  Exe('%b\Exec\NSIS\Preview.edt');
  JMP(!'Exit');
:DVI_Preview:: ======================================================
  IfStr("%$('%!9-View_Search');",!"1",!"=",>
   !|Exe('%b\Exec\TeX\DVI Search.edt');|,>
   !|Exe('%b\Exec\TeX\DVI Preview.edt');|);
  JMP(!'Exit');
:PDF_Preview:: ======================================================
  IfStr("%$('%!9-View_Search');","1","=",>
   !|Exe('%b\Exec\PDF\PDF Search.edt');|,>
   !|Exe('%b\Exec\PDF\PDF Preview.edt');|);
  JMP(!'Exit');
:PS_Preview:: =======================================================
  Run('%$("GSView"); "%P\%N.ps"','%P',0,0,'%N.ps - GSview',1,1);
  JMP(!'Exit');
:HTML_Preview:: =====================================================
  ShellExecute(!"Open", "%N.html","","%P",1);
  JMP(!'Exit');
:HTM_Preview:: ======================================================
  ShellExecute(!"Open", "%N.htm","","%P",1);
  JMP(!'Exit');
:CHM_Preview:: ======================================================
  HTMLHelp("%P\%N.chm",1,1);
  JMP(!'Exit');

:Hide_Console:: =====================================================
  GetExitCode(3);
  IfNum('%!3','%$("ExitCode-OK");','<>',!"Assign(!'Compile Status',!'Exit Code');JMP(!'Exit');");
  IfStr("%$('%!9-WinEdt_Console');",'1','=',>
    !|IfStr("%$('%!9-Pause');",'1','<>',!"ShowConsole(-1);");|);

:Exit:: =============================================================
  // Reset the Compile-Flag: Not inside a (multiple conversion) compile...
  SetExitHandler;
  Assign(!'Compile-Flag');
  PopTagsandRegisters(0,0001111111);
  Exe("%b\Exec\PopEnvVars.edt");
  StopWorking;
  UpdateStatus;
End;
