************************************************************************
*
*   WBEND   version 1.0
*
*
*  Perform all necessary operations to shut down a Fortran program which
*  was started from Workbench.  For use with Amiga AbSoft Fortran v 2.3,
*  the module STDOPEN.ASM, and the Fortran-Workbench startup module
*  WBINIT.ASM (INIT.SC).  Compatible with normal CLI startup.
*
*  Author:  Jim Locker, SofTech Inc.  Published in Amazing Computing
*
*  This program is placed in the public domain, but the Author accepts no
*  responsibility whatsoever for anything that anyone does with it.
*
*  USAGE:
*
*      CALL WBEND
*
*        This call must be the last statement in the program, except for the
*        normal END statement.  If you call this from anywhere else in the 
*        program, you will crash.
*
*  This program must be linked into your executable using F77L.  It will 
*  crash if run unlinked.
*
*************************************************************************

AEXEC   EQU     -16                     * "exec_lib" pointer
DOS     EQU     AEXEC-4                 * "dos.library" pointer
STDIN   EQU     DOS-4                   * file handle for STDIN
STDOUT  EQU     STDIN-4                 * file handle for STDOUT
H.BASE  EQU     STDOUT-4                * base of heap
H.SIZE  EQU     H.BASE-4                * size of heap
WBSTAT  EQU     H.SIZE-2                * running from workbench?
WBMSG   EQU     WBSTAT-4                * loc of WB message
OURTSK  EQU     WBMSG-4                 * loc of our TCB
AMIGA   EQU     -OURTSK                 * size of Amiga global storage

* - from "exec.library"

_LVOForbid        EQU     -132
_LVOFreeMem       EQU     -210
_LVOReplyMsg      EQU     -378
_LVOCloseLibrary  EQU     -414
_LVODebug         EQU     -114

* - from "dos.library"

_LVOClose         EQU     -36

WBEND:
         tst.w WBSTAT(A0)                   * did we start from workbench?
         bne.s contnu                       * no.
         rts
contnu:
         MOVE.L  A0,-(A7)
         MOVE.L  WBMSG(A0),D2               * grab the WB message pointer
         MOVE.L  DOS(A0),A6                 * move in DOS lib pointer
         MOVE.L  STDIN(A0),D1               * move in STDIO pointer
         beq.s   skip                       * if no STDIO, skip
         jsr     _LVOClose(A6)              * close STDIO
skip:
         MOVEA.L A6,A1                      * prepare to close DOS lib
         MOVEA.L (A7)+,A0
         MOVE.L  AEXEC(A0),A6               * move in EXEC lib pointer
         jsr     _LVOCloseLibrary(A6)       * close DOS lib
         jsr     _LVOForbid(A6)             * so workbench can't unloadseg()
*                                               us until we're done
         MOVEA.L  D2,A1                     * reply to the workbench msg
         jsr     _LVOReplyMsg(A6)
         rts
