/*
**  $VER: TeX-Server_start.ged 0.004 (02 May 1996)
**
**  © 1995 Stefan Berendes
**
**  PROGRAMNAME:  TeX-Server_start.ged
**
**  FUNCTION:     Create Arexx port as TeX server, named "Start_TeX",
**                waiting for the following commands
**
**      - compile <format-file> <TeX-file including-absolute-path>
**              - the filename *must* have an extension.
**              - if <format-file>=='&', use tex'es default format.
**      - quit
**              exits the server.
**
**  ARGUMENT:   The name of the screen the window resides on
**
**  NEEDS FILES:
**
**      Rexx:namestruc
**      <path>/PToFront
**      TeX:bin/virtex*
**      <path>/SetActiveWin
**
**      output window named "TeX System#?"
**
**  $HISTORY:
**
**  02 May 1996 : 000.004 : done some cleanup
**  19 Feb 1996 : 000.003 : ASK args to control popup of requesters
**  10 Dec 1995 : 000.002 : fixed some minor bugs
**   08 Dec 1995 : 000.001 : initial release
**
**  Based on TeX-server.rexx by Jörg Höhle and Georg Hessmann (-1991)
*/

portname = "Start_TeX"          /* PortName */

/* Failat 10 */
OPTIONS RESULTS

PARSE ARG PubScreen EditReq FormatReq
IF PubScreen = "" THEN PubScreen = "Workbench"

IF ~show('L','rexxsupport.library') THEN
        IF ~addlib('rexxsupport.library',0,-30,0) THEN DO
                say "Can't open 'rexxsupport.library'!"
                EXIT 20
                END

SIGNAL ON break_C
SIGNAL ON break_D

if (LEFT(ADDRESS(), 6) ~= "GOLDED") then    /* not started by GoldEd ? */
    address 'GOLDED.1'

'LOCK CURRENT'                              /* lock GUI, gain access   */
OPTIONS FAILAT 6                            /* ignore warnings         */
SIGNAL ON SYNTAX                            /* ensure clean exit       */


/* ------------------------ INSERT YOUR CODE HERE: ------------------- */

oldedit = upper(mygetenv(TEXREXX))
IF UPPER(EditReq) = "ASK" THEN DO
    /* default is no change, logical ? */
    IF "EDIT" = oldedit THEN DO
        'REQUEST TITLE="TeX-Server" BODY="Call GoldED automatically on first error?" BUTTON="_Yes|_No"'
        if (result = 1) then newedit = "edit"
        else newedit = "e"
        END
    ELSE DO
        'REQUEST TITLE="TeX-Server" BODY="Call GoldED automatically on first error?" BUTTON="_No|_Yes"'
        if (result = 1) then newedit = "e"
        else newedit = "edit"
        END
    END
ELSE DO
    IF (oldedit ~= "EDIT") & (oldedit ~= "E") THEN DO
        'REQUEST TITLE="TeX-Server" BODY="Call GoldED automatically on first error?" BUTTON="_No|_Yes"'
        if (result = 1) then newedit = "e"
        else newedit = "edit"
        END
    ELSE DO
        newedit = oldedit
        'REQUEST STATUS="Errormode is «'|| newedit ||'»"'
    END
IF UPPER(newedit) ~= oldedit THEN CALL mysetenv(TEXREXX,newedit)
/* if it were undefined, virtex would call ENV:EDITOR.
         We want Rexx scripts to be used (TeXEdit.rexx). */
DROP newedit oldedit

IF UPPER(FormatReq) = "ASK" THEN DO
    'REQUEST TITLE="TeX-Server" BODY="Ask for format when default is requested?" BUTTON="_No|_Yes"'
    if (result = 1) THEN CALL SETCLIP("TEXQUERY")
    else CALL SETCLIP("TEXQUERY","TRUE")
    END

/* ---------------------------- END OF YOUR CODE --------------------- */

'UNLOCK' /* VERY important: unlock GUI */


FALSE = 0
TRUE = 1

ADDRESS COMMAND PToFront PubScreen

say
say "*******************************************************"
say "*                                                     *"
say "*    Welcome to the GoldED - PasTeX Interface         *"
say "*                                                     *"
say "*******************************************************"
say "Modified version Dec 95 by Stefan Berendes"
say
OPTIONS PROMPT "? >"
say
say "- Opening port "portname"."

IF ~openport(portname) THEN DO
  say
  say "- Can't open port !"
  EXIT 20
END


empty = FALSE

mainloop:
DO UNTIL com = 'quit'

  IF ~empty THEN DO
        CALL SETCLIP("TEXTIME")
        say "- Waiting for command (compile/quit) on port "portname"."
  END

  CALL waitpkt(portname)
  packet = getpkt(portname)
  IF (packet = NULL()) THEN empty = TRUE
      /* say "- Received NULL packet." */
  ELSE DO

    empty = FALSE

    PARSE VALUE getarg(packet) WITH com format fullname texname

    CALL REPLY(packet, 0)

    IF (com = 'compile') THEN DO

        /* and now, Server-to-front */
        ADDRESS COMMAND 'PToFront' PubScreen
        ADDRESS COMMAND 'wait 1'
        ADDRESS COMMAND 'SetActiveWin "TeX System#?" pspat #? tofront'

        IF '&' ~= left(format,1) THEN format = '&'||format
        ELSE IF '&' = format THEN format = "" /* use virtex default format */

        fullname = STRIP(fullname)      /* beware of blanks (eg RAM DISK:) */

        /* make RAM DISK: a special case */
        IF "RAM DISK:" = UPPER(LEFT(fullname,9)) THEN
           fullname="RAM:"||SUBSTR(fullname,10)

/* KLUDGE: Do NOT accept names with blanks, I could do a better job here */
        IF 0 ~= INDEX(fullname," ") THEN
           say "- Sorry, no spaces in filenames :"fullname
        ELSE DO

         PARSE VALUE namestruc(fullname) WITH ivol idir iname .

         texdir = LEFT(fullname, ivol+idir)  /*(TeX:doc/sample.tex-> TeX:doc/)*/
         nameonly = SUBSTR(fullname, 1+ivol+idir)               /*(sample.tex)*/
         baseonly = SUBSTR(fullname, 1+ivol+idir, iname)        /*(sample)*/
         fullbase = LEFT(fullname, ivol+idir+iname)     /*(TeX:doc/sample)*/

         IF 0=ivol THEN DO
           say "- An absolute path must be used (eg. <device|volumename>:...) !"
           END
         ELSE IF (SUBSTR(fullname, 1+ivol+idir+iname,1) ~= ".") THEN DO
           say "- Sorry, filename must have a .<extension> :"fullname
           END
         ELSE DO

          IF ~EXISTS(fullname) THEN DO
           say "- Couldn't locate "fullname" ! Missing a path ?"
           END
          ELSE DO

           CALL DELETE(fullbase||".log")
           /* I feel there's no need to delete the .dvi file. */

            if (texname = "") then do
                virtex = GETCLIP("virtex")   /* get TeX or bigTeX */
                IF ("" = virtex) THEN virtex = 'virtex'
                end
            else
                virtex = texname

           say '- Start command: 'virtex format nameonly
           say '   in directory 'texdir
           CALL PRAGMA('directory',texdir)

           CALL SETCLIP("TEXFILE",fullname)
           now = TIME('s')
           CALL SETCLIP("TEXTIME",now)

/* The "< *" is a hack, no ? */
           ADDRESS COMMAND virtex' < * 'format nameonly

           IF rc == 0 THEN DO
                say
                say "- Compiled file "fullname" without errors."
                IF (SHOW('P','showdvi')) THEN DO
                   ADDRESS "showdvi"
                   OPTIONS RESULTS
                   getfile
                   loadedfile = RESULT
                   getdir
                   loadeddir = RESULT
                   IF RIGHT(loadeddir,1)~=':' & RIGHT(loadeddir,1)~='/' THEN
                        loadeddir = loadeddir||'/'
                   IF texdir = loadeddir & 1 = INDEX(UPPER(loadedfile||".dvi"),UPPER(baseonly||".dvi")) THEN DO
                        say "- Updating file in ShowDVI."
                        loadagain
                        activate
                        END
                   ELSE DO
                        say "- Loading file "fullbase".dvi into ShowDVI."
                        loadnew fullbase||".dvi"
                        activate
                        END
                   tofront
                   END
                ELSE DO
                   say "- ShowDVI is not running."
                   END
                END
           ELSE DO
                say
                say "- Compilation not successful, error level "errorcode"."
                IF getclip("TEXTIME") == now & EXISTS(fullbase||".log") THEN DO
                    /* TeXEdit sets TEXTIME, so we don't run the editor twice */
                  editscript = WORD(mygetenv("TEXREXXEDIT"),1)
                  IF "" = editscript THEN editscript = 'Tex:rexx/TeXedit.rexx'
                  say "- Calling editor for file "fullname" via "editscript"."
                  ADDRESS COMMAND ""rx editscript fullname 0""
                  IF 0~=RESULT THEN SAY "Error callin ed"
                  END
                END
           END  /* exists */
          END   /* !ivol, "." */
         END    /* !index */
        END     /* compile */
    END         /* !NULL() */
  END           /* do */

finish:

ADDRESS COMMAND PToFront PubScreen
/* Result: 5: not OS 2.0, 10: PubScreen not found, 15: no Intuition.library */

say "- Closing down port "portname
CALL CLOSEPORT portname

IF PubScreen ~= "Workbench" THEN
        say "  Type CTRL-\ or hit the CLOSE Gadget to close the window."
        /* das koennte man im Prinzip immer (unter 2.0) ausgeben */

SIGNAL cleanup

break_C:
break_D:
say
say "- Break received."

cleanup:
CALL SETCLIP("TEXFILE")
CALL SETCLIP("TEXTIME")
CALL SETCLIP("TEXQUERY")
EXIT

SYNTAX:

SAY "Sorry, error line" SIGL ":" ERRORTEXT(RC) ":-("
'UNLOCK'
EXIT


mygetenv: PROCEDURE     /* when will ARexx supply GetEnv/SetEnv ? */
   PARSE ARG name

   IF open(TEMPFILE,"ENV:"||name,'r') THEN DO
        gives = readln(TEMPFILE)
        CALL close TEMPFILE
        END
   ELSE gives = ""

   RETURN gives

mysetenv: PROCEDURE
   PARSE ARG name,content

   ADDRESS COMMAND "SetEnv" name content

   RETURN

