!
      PROGRAM FOGCM
      implicit none
!
! Main entry point for tgcm13mt:
!
      include "params.h"
      include "blnk.h"
      include "buff.h"
      include "vscr.h"
      include "rfft.h"
      include "cons.h"
      include "index.h"
      include "strt.h"
      include "unit.h"
      include "sechis.h"
      include "amie.h"
      include "fgcom.h"

      call opngks
!
      CALL START
      ixtimec = ixtimep
C     ****
      GO TO 20
C     ****                   ADVANCE THE MODEL IN TIME
   10 CALL ADVNCE
C     ****     CHECK FOR HISTORY FILE WRITE
 20   if (ihis.ne.0.and.ihissech.ne.0) goto 30
      if (ihis.eq.0) call output(0)           ! write a full restart history
      if (ihissech.eq.0) call output(1)       ! write a secondary history
      if (ixtimec==ixtimep) ixtimec = ixtimep+1 ! reset after source hist
C     ****     CHECK FOR ERROR IN OUTPUT
      IF(NERR.EQ.0)GO TO 30
      NERR=0
      if (isav.eq.0) call wtsave(0)
      if (isavsech.eq.0) call wtsave(1)
C     ****
      IF(IAMIE.EQ.1) CLOSE(UNIT=16,STATUS='DELETE')
      STOP
C     ****     CHECK FOR SAVE TAPE WRITE
 30   if (isav.ne.0.and.isavsech.ne.0) goto 40
      if (isav.eq.0) call wtsave(0)
      if (isavsech.eq.0) call wtsave(1)
 40   if (iter.lt.nstp) goto 10                 ! do another advnce call
      if (iend.eq.2) then
        nstp = nnstp(2)
        mhis = mmhis(2)
        ihis = mhis
        ihissech = mhissech
        iend = 1
        goto 10
      endif
c
c 5/98: secondary histories do not check for iend==2.
      IF(IEND.EQ.2) THEN
          NSTP=NNSTP(2)
          MHIS=MMHIS(2)
          IHIS=MHIS
          IEND=1
          GO TO 10
      END IF
      IF (IAMIE.EQ.1) CLOSE(UNIT=16,STATUS='DELETE')
      write(6,"('Normal exit at iter = ',i6)") iter

      call clsgks 

      STOP
      END
C
