SUBROUTINE WRRESF

!**** *WRRESF*  - write restart files

!     Purpose.
!     --------
!     Write a set of restart files:
!       (1) spectral fields
!       (2) upper-air grid-point fields (t-dt)
!       (3) surface fields
!       (4) upper-air grid-point fields (t)
!       (5) cumulated fluxes
!       (6) instantaneous fluxes
!       (7) restart control file

!**   Interface.
!     ----------
!        *CALL* *WRRESF

!        Explicit arguments :      None.
!        --------------------

!        Implicit arguments :      None.
!        --------------------

!     Method.
!     -------
!        See documentation

!     Externals.
!     ----------

!     Reference.
!     ----------
!        ECMWF Research Department documentation of the IFS

!     Author.
!     -------
!        David Dent *ECMWF*

!     Modifications.
!     --------------
!        Original : 92-04-06
!        Modified : 92-06-04 V. Ducrocq and R. El Khatib (restart with physics)
!        Modified : 92-11-19 R. El Khatib (restart on cumulated fluxes)
!        Modified : 93-04-09 : time stamp controled by LSDHM
!        Modified : 93-09-06 R. El Khatib (restart on instantaneous fluxes)
!        Modified : 93-07-05 M.Hamrud (DDH restart)
!        Modified : 94-05-16 M.Hamrud (Add NSTEPLPP to NAMRCF)
!        Modified : 94-10-27 M.Hamrud (Restart for upper-air t grid-point)
!        Modified : 95-06-06 L. Isaksen (Reordering of spectral arrays)
!        Modified 98-08-10 by K. YESSAD: removal of LRPOLE option.
!          - removal of LRPOLE in YOMCT0.
!          - removal of code under LRPOLE.
!        Modified : 00-09-01 D.Dent: convert from MPE to MPL
!        Modified : 01-06-13 R. El Khatib ISP restart + fix
!        Modified : 01-08-07 by R. El Khatib - Pruning options
!        Modified 08-2002 C. Smith : use "w" as prognostic variable in the
!         semi-lag advection of vertical divergence in the NH model.
!        Modified : 02-06-10 by D.Dent - Additional file for GP fields
!                                        and  LFASTRES option
!        M.Hamrud      01-Oct-2003 CY28 Cleaning
!        M.Hamrud      10-Jan-2004 CY28R1 Cleaning
!        Modified : 04-08-12 R. El Khatib Bugfixes + COPY
!        Modified : 22-June-2005 R. El Khatib Fix LFASTRES for MF
!        JJMorcrette 20060721 PP of clear-sky PAR and TOA incident solar radiation
!        M.Hamrud      01-Jul-2006  Revised surface fields
!        JJMorcrette 20070321 Prognostic aerosols in rad and clouds
!        R. El Khatib  10-Apr-2007  Fix again LFASTRES for CFU/XFU
!        M.Hamrud      13-Oct-2008 Use IOSTREAM, one file per task, 
!                                  only FASTRES supported
!        JJMorcrette 20091201 Total and clear-sky direct SW radiation flux at surface 
!        M.Leutbecher  10-Nov-2009 Parametrization tendency perturbation pattern
!        M. Steinheimer Oct-2009  added output for stochastic physics options LSTOPH
!                                 and LSTOPH_SPBS
!     ------------------------------------------------------------------

USE PARKIND1  ,ONLY : JPIM     ,JPRB
USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK
USE YOMLUN   , ONLY : NULOUT   ,NULRCF   ,NPPPSH
USE YOMCT0   , ONLY : NPROC    ,NPRGPNS, NPRGPEW, NPRTRW   ,NPRTRV
USE YOMCT3   , ONLY : NSTEP
USE YOMDIM   , ONLY : NFLEVG   ,NPROMA   ,NGPBLKS
USE YOMSP    , ONLY : SPA3     ,SPA2
USE YOMDPHY  , ONLY : NTILES
USE YOMSPSDT , ONLY : LSPSDT, YSPSDT_AR1
USE SURFACE_FIELDS_MIX  , ONLY : GPOPER, NDIMSURFL
USE YOMIOS   , ONLY : CIOSPRF  ,CFRCF    ,CIOISPRF
USE YOMOP    , ONLY : LINC
USE YOMDYN   , ONLY : TSTEP
USE YOMGEM   , ONLY : NGPTOT
USE YOMRES   , ONLY : JPNRF    ,CRFTIME  ,CTIME    ,CSTEP    ,&
 & N1RFS    ,N2RFS    ,LSDHM, COPY     ,LDELRES
USE YOMCFU   , ONLY : NFDCFU   ,LCUMFU
USE YOMGFUB  , ONLY : GFUBUF
USE YOMXFU   , ONLY : NFDXFU   ,LXFU
USE YOMXFUB  , ONLY : XFUBUF
USE YOMLDDH  , ONLY : LSDDH
USE YOMTDDH  , ONLY : HDCVB0   ,HDCVB1   ,HDCS0    ,HDCS1
USE YOMGRB   , ONLY : NSTEPLPP
USE YOMGFL   , ONLY : GFL,GFLSLP
USE YOM_YGFL , ONLY : YGFL
USE YOMMP    , ONLY : MYPROC
USE YOMPPC   , ONLY : LMOVPH
USE YOMSLPHY , ONLY : SAVTEND, LSLPHY
USE YOMRADF  , ONLY : EMTD, TRSW, EMTC, TRSC, TAUAER, &
 & SRSWD    ,SRSWDCS ,EDRO  , SRSWPAR, SRSWUVB, SRSWPARC, SRSWTINC, &
 & SRFDIR   ,SRCDIR 
USE YOE_TILE_PROP , ONLY : RUSTRTI, RVSTRTI, RAHFSTI, REVAPTI, RTSKTI
USE YOEPHY   , ONLY : LEPHYS
USE YOEAERSRC, ONLY : LEPAERO
USE YOMGMV   , ONLY : GMV,GMVS,YT0,YT9
USE YOMMASS  , ONLY : GMASS0, GMASSI
USE YOMRIP   , ONLY: NYMLPPGP, NYMLPPSP
USE MPL_MODULE, ONLY : MPL_BARRIER
USE IOSTREAM_MIX , ONLY : SETUP_IOSTREAM, SETUP_IOREQUEST, IO_PUT, &
 & CLOSE_IOSTREAM, TYPE_IOSTREAM , TYPE_IOREQUEST,CLOSE_IOREQUEST
USE STOPH_MIX , ONLY : LSTOPH, LSTOPH_SPBS, SPSTREAM, SPSTREAM_FORC, GPTOTDISS, &
 & GPTOTDISS_SMOOTH, GPSTREAM, GPVORTGRAD, RSTOPHU, RSTOPHV, RSTOPHT, RSTOPHQ, &
 & LSTOPH_SPBS_T, SPTEMP, SPTEMP_FORC, GPTEMP
USE YOMRANDOM_STREAMS, ONLY  : YD_RANDOM_STREAM_STOCHPHYS, YD_RANDOM_STREAM_STOCHPHYS_SPBS, &
                             & YD_RANDOM_STREAM_STOCHPHYS_RVP, YD_RANDOM_STREAM_STOPH_SPBS_T, &
                             & YD_RANDOM_STREAM_STOPH_RVP_T
USE RANDOM_NUMBERS_MIX, ONLY : RANDOM_NUMBER_RESTARTFILE

!     ------------------------------------------------------------------

IMPLICIT NONE

#include "namrcf.h"

CHARACTER (LEN = 80)  ::  CLFN
CHARACTER (LEN = 5)   ::  CL_CMYPROC
CHARACTER (LEN = 80)  ::  CLFNISP
CHARACTER (LEN = 200) ::  CLSHELL

REAL(KIND=JPRB), ALLOCATABLE :: ZBUF(:),ZBUF2(:,:),ZBUF3(:,:,:)

INTEGER(KIND=JPIM) :: I1,IDAY,IEND,IFCTIM,IHOUR,IINC,IMIN,INUM, &
 & IST,IT,ITEMP,JLEV,JSTGLO,IBL,II,JBLK, &
 & ISIZE,JFLD,JROF,IBUF(1),IFLDS,IOFF,IBLSZ1,IBLSZ2,IBLSZ3,IBLSZ

LOGICAL :: LLEXIST
TYPE(TYPE_IOSTREAM) :: YL_IOSTREAM
TYPE(TYPE_IOREQUEST) :: YL_IOREQUEST
REAL(KIND=JPRB) :: ZHOOK_HANDLE

#include "ddhsnd.intfb.h"
#include "sc2rdg.intfb.h"

!     ------------------------------------------------------------------

!*       1.    PREAMBLE
!              --------

!        1.1   FIND TIME STAMP

IF (LHOOK) CALL DR_HOOK('WRRESF',0,ZHOOK_HANDLE)
CALL GSTATS(27,0)
IF (LSDHM) THEN
  IFCTIM=(NSTEP*TSTEP+0.5_JPRB)/60.0_JPRB
  IDAY =IFCTIM/24/60
  IHOUR=IFCTIM/60-IDAY*24
  IMIN =IFCTIM-IDAY*24*60-IHOUR*60
  WRITE(CTIME,'(I6.6,I2.2,I2.2)') IDAY,IHOUR,IMIN
ELSE
  IF (LINC) THEN
    IINC=NINT(REAL(NSTEP,JPRB)*TSTEP/3600._JPRB)
  ELSE
    IINC=NSTEP
  ENDIF
  WRITE(CTIME,'(''+'',I9.9,''   '')') IINC
ENDIF
IT=INDEX(CTIME,' ')-1

!     ------------------------------------------------------------------

!*       2.    WRITE SPECTRAL DATA
!              -------------------

I1=INDEX(CIOSPRF,' ')-1

WRITE(CL_CMYPROC,'(A1,I4.4)')'.',MYPROC
CLFN=CIOSPRF(1:I1)//CTIME(1:IT)//CL_CMYPROC
WRITE(UNIT=NULOUT,FMT='('' CREATE RESTART FILE '',A)') CLFN

CALL SETUP_IOSTREAM(YL_IOSTREAM,'CIO',TRIM(CLFN),CDMODE='w')
CALL SETUP_IOREQUEST(YL_IOREQUEST,'RAW')

IBUF(1)=88801
CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,KR1=IBUF)
CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,PR3=SPA3)
CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,PR2=SPA2)

IF (LSPSDT) THEN
  CALL IO_PUT(YL_IOSTREAM, YL_IOREQUEST,PR2=YSPSDT_AR1%SF%SP2D)
ENDIF

!     ------------------------------------------------------------------

!*       3.    WRITE UPPER-AIR AND SURFACE DATA
!              --------------------------------

IBUF(1)=88802
CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,KR1=IBUF)
IBLSZ1=NPROMA*NFLEVG*YT9%NDIM
IBLSZ2=NPROMA*YT9%NDIMS
IBLSZ3=NPROMA*NFLEVG*YGFL%NDIM9
IBLSZ =IBLSZ1+IBLSZ2+IBLSZ3
ALLOCATE(ZBUF(NGPBLKS*IBLSZ))
DO JSTGLO=1,NGPTOT,NPROMA
  IBL=(JSTGLO-1)/NPROMA+1
  IEND=MIN(NPROMA,NGPTOT-JSTGLO+1)
  DO JFLD=1,YT9%NDIM
    DO JLEV=1,NFLEVG
      DO JROF=1,IEND
        II=(IBL-1)*IBLSZ &
         & +(JFLD-1)*NPROMA*NFLEVG+(JLEV-1)*NPROMA+JROF
        ZBUF(II)=GMV(JROF,JLEV,YT0%NDIM+JFLD,IBL)
      ENDDO
    ENDDO
  ENDDO
  DO JFLD=1,YT9%NDIMS
    DO JROF=1,IEND
      II=IBLSZ1+(IBL-1)*IBLSZ &
       & +(JFLD-1)*NPROMA+JROF
      ZBUF(II)=GMVS(JROF,YT0%NDIMS+JFLD,IBL)
    ENDDO
  ENDDO
  DO JFLD=1,YGFL%NDIM9
    DO JLEV=1,NFLEVG
      DO JROF=1,IEND
        II=IBLSZ1+IBLSZ2+(IBL-1)*IBLSZ &
         & +(JFLD-1)*NPROMA*NFLEVG+(JLEV-1)*NPROMA+JROF
        ZBUF(II)=GFL(JROF,JLEV,YGFL%NDIM0+JFLD,IBL)
      ENDDO
    ENDDO
  ENDDO
ENDDO
CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,PR1=ZBUF)
DEALLOCATE(ZBUF)

!*       3.2   WRITE SURFACE GRID-POINT DATA


IBUF(1)=88803
CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,KR1=IBUF)
ALLOCATE(ZBUF3(NPROMA,NDIMSURFL,NGPBLKS))
DO JBLK=1,NGPBLKS
  CALL GPOPER('GETALLFLDS',KBL=JBLK,PFIELD=ZBUF3(:,:,JBLK))
ENDDO
CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,PR3=ZBUF3)
DEALLOCATE(ZBUF3)

!*       3.3   WRITE UPPER-AIR T GRID-POINT DATA

IF(YGFL%NUMGPFLDS > 0) THEN

  IBUF(1)=88804
  CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,KR1=IBUF)
  CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,PR4=GFL(:,:,1:YGFL%NUMGPFLDS,:))

ENDIF

!*       3.4  WRITE CUMULATED AND INSTANTANEOUS FLUXES GRID-POINT DATA

IF (LCUMFU) THEN
  IF (NFDCFU > 0) THEN
    IBUF(1)=88805
    CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,KR1=IBUF)
    ALLOCATE(ZBUF2(NPROMA,NFDCFU))
    DO JSTGLO=1,NGPTOT,NPROMA
      IST=1
      IEND=MIN(NPROMA,NGPTOT-JSTGLO+1)
      CALL SC2RDG(GFUBUF,JSTGLO,IST,IEND,ZBUF2)
      CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,PR2=ZBUF2)
    ENDDO
    DEALLOCATE(ZBUF2)
  ENDIF
ENDIF

IF (LXFU) THEN
  IF (NFDXFU > 0) THEN
    IBUF(1)=88806
    CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,KR1=IBUF)
    ALLOCATE(ZBUF2(NPROMA,NFDXFU))
    DO JSTGLO=1,NGPTOT,NPROMA
      IST=1
      IEND=MIN(NPROMA,NGPTOT-JSTGLO+1)
      CALL SC2RDG(XFUBUF,JSTGLO,IST,IEND,ZBUF2)
      CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,PR2=ZBUF2)
    ENDDO
    DEALLOCATE(ZBUF2)
  ENDIF
ENDIF

!*       3.41  WRITE ADDITIONAL TENDENCIES AND RADIATION FIELD DATA

IF (LEPHYS) THEN
  IF (LSLPHY) THEN
    IBUF(1)=88807
    CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,KR1=IBUF)
    CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,PR4=SAVTEND)
    IF(ALLOCATED(GFLSLP)) THEN
      IF(SIZE(GFLSLP) > 0) THEN
        CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,PR4=GFLSLP)
      ENDIF
    ENDIF
  ENDIF
  IBUF(1)=88808
  CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,KR1=IBUF)
  CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,PR3=EMTD)
  CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,PR3=TRSW)
  CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,PR3=EMTC)
  CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,PR3=TRSC)

  IF (LEPAERO) THEN
    CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,PR4=TAUAER)
  ENDIF

  IBUF(1)=88809
  CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,KR1=IBUF)
  IFLDS=9
  ISIZE=NPROMA*NGPBLKS
  ALLOCATE(ZBUF(ISIZE*IFLDS))
  IOFF=0
  ZBUF(IOFF+1:IOFF+ISIZE)=RESHAPE(SRSWDCS,(/ISIZE/))
  IOFF=IOFF+ISIZE
  ZBUF(IOFF+1:IOFF+ISIZE)=RESHAPE(SRSWD,(/ISIZE/))
  IOFF=IOFF+ISIZE
  ZBUF(IOFF+1:IOFF+ISIZE)=RESHAPE(EDRO,(/ISIZE/))
  IOFF=IOFF+ISIZE
  ZBUF(IOFF+1:IOFF+ISIZE)=RESHAPE(SRSWPAR,(/ISIZE/))
  IOFF=IOFF+ISIZE
  ZBUF(IOFF+1:IOFF+ISIZE)=RESHAPE(SRSWUVB,(/ISIZE/))
  IOFF=IOFF+ISIZE
  ZBUF(IOFF+1:IOFF+ISIZE)=RESHAPE(SRSWPARC,(/ISIZE/))
  IOFF=IOFF+ISIZE
  ZBUF(IOFF+1:IOFF+ISIZE)=RESHAPE(SRSWTINC,(/ISIZE/))
  IOFF=IOFF+ISIZE
  ZBUF(IOFF+1:IOFF+ISIZE)=RESHAPE(SRFDIR,(/ISIZE/))
  IOFF=IOFF+ISIZE
  ZBUF(IOFF+1:IOFF+ISIZE)=RESHAPE(SRCDIR,(/ISIZE/))
  CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,PR1=ZBUF)
  DEALLOCATE(ZBUF)
    
  IBUF(1)=88810
  CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,KR1=IBUF)
  IFLDS=5
  ISIZE=NPROMA*NGPBLKS*NTILES
  ALLOCATE(ZBUF(ISIZE*IFLDS))
  IOFF=0
  ZBUF(IOFF+1:IOFF+ISIZE)=RESHAPE(RUSTRTI,(/ISIZE/))
  IOFF=IOFF+ISIZE
  ZBUF(IOFF+1:IOFF+ISIZE)=RESHAPE(RVSTRTI,(/ISIZE/))
  IOFF=IOFF+ISIZE
  ZBUF(IOFF+1:IOFF+ISIZE)=RESHAPE(RAHFSTI,(/ISIZE/))
  IOFF=IOFF+ISIZE
  ZBUF(IOFF+1:IOFF+ISIZE)=RESHAPE(REVAPTI,(/ISIZE/))
  IOFF=IOFF+ISIZE
  ZBUF(IOFF+1:IOFF+ISIZE)=RESHAPE(RTSKTI ,(/ISIZE/))
  CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,PR1=ZBUF)
  DEALLOCATE(ZBUF)
ENDIF

!*       3.5  WRITE DDH DATA

IF (LSDDH ) THEN

  IBUF(1)=88811
  CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,KR1=IBUF)
  IBUF(1)=NPRTRW
  CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,KR1=IBUF)
  IBUF(1)=NPRTRV
  CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,KR1=IBUF)

  CALL DDHSND(HDCVB0,SIZE(HDCVB0),YL_IOSTREAM,YL_IOREQUEST)
  CALL DDHSND(HDCVB1,SIZE(HDCVB1),YL_IOSTREAM,YL_IOREQUEST)
  CALL DDHSND(HDCS0 ,SIZE(HDCS0 ),YL_IOSTREAM,YL_IOREQUEST)
  CALL DDHSND(HDCS1 ,SIZE(HDCS1 ),YL_IOSTREAM,YL_IOREQUEST)

ENDIF

CALL CLOSE_IOREQUEST(YL_IOREQUEST)
CALL CLOSE_IOSTREAM(YL_IOSTREAM)


!*       3.6 WRITE ISP DATA

IF (LMOVPH) THEN
  CLFN=TRIM(CIOISPRF)//TRIM(CTIME)
  WRITE(UNIT=NULOUT,FMT='('' CREATE RESTART FILE '',A)') CLFN
  IF( MYPROC == 1 )THEN
    INQUIRE(NPPPSH,OPENED=LLEXIST)
    IF (LLEXIST) THEN
      INQUIRE(NPPPSH,NAME=CLFNISP)
      CLOSE(NPPPSH)
      WRITE(CLSHELL,'(A,'' '',A,'' '',A)') TRIM(COPY),TRIM(CLFNISP),TRIM(CLFN)
      CALL SYSTEM(CLSHELL)
      OPEN(NPPPSH,FORM='UNFORMATTED',POSITION='APPEND')
    ENDIF
  ENDIF
  IF (NPROC > 1) THEN
    CALL MPL_BARRIER(CDSTRING='WRRESF:')
  ENDIF
ENDIF

!     ------------------------------------------------------------------

!*       4.    WRITE RESTART CONTROL FILE
!              --------------------------

IF( MYPROC == 1) THEN

!        4.1   MODIFY CONTENTS OF NAMELIST

  WRITE(CSTEP,'(I9)') NSTEP
  IPRGPNSRES=NPRGPNS
  IPRGPEWRES=NPRGPEW
  IPRTRWRES =NPRTRW 
  IPRTRVRES =NPRTRV 

!        4.2   WRITE FILE

  OPEN  (NULRCF,FILE=CFRCF,DELIM="QUOTE")
  WRITE (NULRCF,NAMRCF)
  CLOSE (NULRCF,STATUS='KEEP')
  WRITE(UNIT=NULOUT,FMT='('' CREATE RESTART CONTROL FILE '',A)')CFRCF
ENDIF

!     ---------------------------------------------------------------------
!*       4.3   WRITE STATE OF old stochastic physics
!              ------------------------------------------------------------
IF (LSTOPH) THEN
    CLFN='../stoph_old' // CTIME(1:IT) //CL_CMYPROC
    WRITE(UNIT=NULOUT,FMT='('' CREATE RESTART FILE FOR OLD STOPH'',A)') CLFN

    CALL SETUP_IOSTREAM(YL_IOSTREAM,'CIO',TRIM(CLFN),CDMODE='w')
    CALL SETUP_IOREQUEST(YL_IOREQUEST,'RAW')

    IBUF(1)=88801
    CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,KR1=IBUF)
    CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,PR1=RSTOPHU)

    IBUF(1)=88802
    CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,KR1=IBUF)
    CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,PR1=RSTOPHV)

    IBUF(1)=88803
    CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,KR1=IBUF)
    CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,PR1=RSTOPHT)

    IBUF(1)=88804
    CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,KR1=IBUF)
    CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,PR1=RSTOPHQ)

    CALL CLOSE_IOREQUEST(YL_IOREQUEST)
    CALL CLOSE_IOSTREAM(YL_IOSTREAM)
    !write state of the random number generator
    CLFN='../stoph_old_rand_nbrs' // CTIME(1:IT) //CL_CMYPROC
    WRITE(UNIT=NULOUT,FMT='('' WRITE RANDOM NUMBER STATE FOR OLD STOPH'',A)') CLFN
    CALL RANDOM_NUMBER_RESTARTFILE( CLFN, 'w',YD_RANDOM_STREAM_STOCHPHYS)
ENDIF


!     ---------------------------------------------------------------------
!*       4.4   WRITE STATE OF AUTOREGRESSIVE PROCESS FOR STOCHASTIC PHYSICS
!              ------------------------------------------------------------
IF (LSTOPH_SPBS) THEN
    CLFN='../stoph_spbs' // CTIME(1:IT) //CL_CMYPROC
    WRITE(UNIT=NULOUT,FMT='('' CREATE RESTART FILE FOR SPBS'',A)') CLFN

    CALL SETUP_IOSTREAM(YL_IOSTREAM,'CIO',TRIM(CLFN),CDMODE='w')
    CALL SETUP_IOREQUEST(YL_IOREQUEST,'RAW')

    IBUF(1)=88801
    CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,KR1=IBUF)
    CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,PR2=SPSTREAM)
    IBUF(1)=88802
    CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,KR1=IBUF)
    CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,PR2=SPSTREAM_FORC)
    IBUF(1)=88803
    CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,KR1=IBUF)
    CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,PR3=GPSTREAM)
    IBUF(1)=88804
    CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,KR1=IBUF)
    CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,PR3=GPTOTDISS)
    IBUF(1)=88805
    CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,KR1=IBUF)
    CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,PR3=GPTOTDISS_SMOOTH)
    IBUF(1)=88806
    CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,KR1=IBUF)
    CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,PR3=GPVORTGRAD)
    IF (LSTOPH_SPBS_T) THEN
      IBUF(1)=88807
      CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,KR1=IBUF)
      CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,PR2=SPTEMP)
      IBUF(1)=88808
      CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,KR1=IBUF)
      CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,PR2=SPTEMP_FORC)
      IBUF(1)=88809
      CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,KR1=IBUF)
      CALL IO_PUT(YL_IOSTREAM,YL_IOREQUEST,PR3=GPTEMP)
    ENDIF
    CALL CLOSE_IOREQUEST(YL_IOREQUEST)
    CALL CLOSE_IOSTREAM(YL_IOSTREAM)
    !write state of the random number generator
    CLFN='../stoph_spbs_rand_nbrs' // CTIME(1:IT) //CL_CMYPROC
    WRITE(UNIT=NULOUT,FMT='('' WRITE RANDOM NUMBER STATE FOR SPBS'',A)') CLFN
    CALL RANDOM_NUMBER_RESTARTFILE( CLFN, 'w',YD_RANDOM_STREAM_STOCHPHYS_SPBS)
    CLFN='../stoph_rvp_rand_nbrs' // CTIME(1:IT) //CL_CMYPROC
    WRITE(UNIT=NULOUT,FMT='('' WRITE RANDOM NUMBER STATE FOR RVP'',A)') CLFN
    CALL RANDOM_NUMBER_RESTARTFILE( CLFN, 'w',YD_RANDOM_STREAM_STOCHPHYS_RVP)
    IF (LSTOPH_SPBS_T) THEN
      CLFN='../stoph_spbs_T_rand_nbrs' // CTIME(1:IT) //CL_CMYPROC
      WRITE(UNIT=NULOUT,FMT='('' WRITE RANDOM NUMBER STATE FOR SPBS_T'',A)') CLFN
      CALL RANDOM_NUMBER_RESTARTFILE( CLFN, 'w',YD_RANDOM_STREAM_STOPH_SPBS_T)
      CLFN='../stoph_rvp_T_rand_nbrs' // CTIME(1:IT) //CL_CMYPROC
      WRITE(UNIT=NULOUT,FMT='('' WRITE RANDOM NUMBER STATE FOR RVP_T'',A)') CLFN
      CALL RANDOM_NUMBER_RESTARTFILE( CLFN, 'w',YD_RANDOM_STREAM_STOPH_RVP_T)
    ENDIF
ENDIF






!     ------------------------------------------------------------------

!*       5.    CONTROL NUMBER OF RESTART FILES
!              -------------------------------

!        5.1   HOW MANY EXIST NOW?

IF(N2RFS >= N1RFS) THEN
  INUM=N2RFS-N1RFS
ELSE
  INUM=JPNRF+N2RFS-N1RFS
ENDIF
IF(LDELRES .AND.INUM >= 1) THEN

!           5.2   TIME TO DELETE THE OLDEST SET

  ITEMP=99
  OPEN (ITEMP,FILE=CIOSPRF(1:I1)//CRFTIME(N1RFS)//CL_CMYPROC)
  CLOSE(ITEMP,STATUS='DELETE')
  IF(LMOVPH) THEN
    OPEN (ITEMP,FILE=TRIM(CIOISPRF)//CRFTIME(N1RFS)//CL_CMYPROC)
    CLOSE(ITEMP,STATUS='DELETE')
  ENDIF
  IF (LSTOPH) THEN
    OPEN (ITEMP,FILE='../stoph_old' //CRFTIME(N1RFS)//CL_CMYPROC)
    CLOSE(ITEMP,STATUS='DELETE')
    OPEN (ITEMP,FILE='../stoph_old_rand_nbrs' //CRFTIME(N1RFS)//CL_CMYPROC)
    CLOSE(ITEMP,STATUS='DELETE')
  ENDIF
  IF (LSTOPH_SPBS) THEN
    OPEN (ITEMP,FILE='../stoph_spbs' //CRFTIME(N1RFS)//CL_CMYPROC)
    CLOSE(ITEMP,STATUS='DELETE')
    OPEN (ITEMP,FILE='../stoph_spbs_rand_nbrs' //CRFTIME(N1RFS)//CL_CMYPROC)
    CLOSE(ITEMP,STATUS='DELETE')
    OPEN (ITEMP,FILE='../stoph_rvp_rand_nbrs' //CRFTIME(N1RFS)//CL_CMYPROC)
    CLOSE(ITEMP,STATUS='DELETE')
    IF (LSTOPH_SPBS_T) THEN
      OPEN (ITEMP,FILE='../stoph_spbs_T_rand_nbrs' //CRFTIME(N1RFS)//CL_CMYPROC)
      CLOSE(ITEMP,STATUS='DELETE')
      OPEN (ITEMP,FILE='../stoph_rvp_T_rand_nbrs' //CRFTIME(N1RFS)//CL_CMYPROC)
      CLOSE(ITEMP,STATUS='DELETE')
    ENDIF
  ENDIF
  IF(N1RFS == JPNRF) THEN
    N1RFS=1
  ELSE
    N1RFS=N1RFS+1
  ENDIF
  
ENDIF

!           5.3   ADJUST CIRCULAR BUFFER

CRFTIME(N2RFS)=CTIME
IF(N2RFS == JPNRF) THEN
  N2RFS=1
ELSE
  N2RFS=N2RFS+1
ENDIF

CALL GSTATS(27,1)
!     ------------------------------------------------------------------

IF (LHOOK) CALL DR_HOOK('WRRESF',1,ZHOOK_HANDLE)
END SUBROUTINE WRRESF
