SUBROUTINE SAVE_MERR_TEND(kstep)

!     Purpose.
!     --------
!       Save tendencies for model error statistics

!     Author.
!     -------
!       Y.Tremolet

!     Modifications.
!     --------------
!        Original : 01-Apr-2004
!     ------------------------------------------------------------------

USE PARKIND1, ONLY: JPIM, JPRB
USE YOMHOOK , ONLY: LHOOK, DR_HOOK
USE YOMDYN  , ONLY: TSTEP
USE YOMDIM  , ONLY: NSMAX
USE YOMLUN  , ONLY: NULOUT
USE YOMMODEL_ERROR, ONLY: NVE3D, NVE2D, NGRBMERRCTL, TSTEP_ERR, LSCALERR
USE SPECTRAL_FIELDS_MOD

IMPLICIT NONE

INTEGER(KIND=JPIM), INTENT(IN) :: kstep

TYPE(SPECTRAL_FIELD) , SAVE :: YLSP0
TYPE(SPECTRAL_FIELD) :: YLSP1
INTEGER(KIND=JPIM) :: istep,ifreq,ifrst,idelta,jf,js,jl
CHARACTER(LEN=12) :: clfile
REAL(KIND=JPRB) :: zz,zt
REAL(KIND=JPRB) :: ZHOOK_HANDLE

#include "abor1.intfb.h"
#include "state2spec.intfb.h"
#include "write_spec_grib.intfb.h"

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

IF (LHOOK) CALL DR_HOOK('SAVE_MERR_TEND',0,ZHOOK_HANDLE)

! Output every 6 hours
zt=6.0_JPRB*3600.0_JPRB/TSTEP   ! number of steps in 6 hours
ifreq=NINT(zt)
IF (ifreq<2) CALL ABOR1('SAVE_MERR_TEND: at least 2 steps between outputs')

! First output after 12 hours
zt=12.0_JPRB*3600.0_JPRB/TSTEP  ! number of steps in 12 hours
ifrst=NINT(zt)

! Interval for finite difference
IF (TSTEP_ERR/=0.0_JPRB) THEN
  idelta = NINT(TSTEP_ERR/TSTEP) ! number of steps in TSTEP_ERR
  zz = 3600.0_JPRB/TSTEP_ERR
ELSE
  idelta = 1
  zz = 3600.0_JPRB/TSTEP
ENDIF

istep=MOD(kstep,ifreq)
IF (kstep<ifrst) istep=-1

IF (kstep<=1) WRITE(NULOUT,*)'SAVE_MERR_TEND: ifreq=',ifreq,' ifrst=',ifrst

IF (istep==0) THEN
  write(NULOUT,*)'SAVE_MERR_TEND 0: kstep,istep=',kstep,istep
  CALL ALLOCATE_SPEC(YLSP0,NSMAX,0,NVE3D,NVE2D,0,NGRBMERRCTL)
  CALL state2spec(YLSP0)

ELSEIF (istep==idelta) THEN
  write(NULOUT,*)'SAVE_MERR_TEND 1: kstep,istep=',kstep,istep
  CALL ALLOCATE_SPEC(YLSP1,NSMAX,0,NVE3D,NVE2D,0,NGRBMERRCTL)
  CALL state2spec(YLSP1)

  DO jf=1,YLSP1%NS2D
  DO js=1,YLSP1%NSPEC2
    YLSP1%SP2D(js,jf)=YLSP1%SP2D(js,jf)-YLSP0%SP2D(js,jf)
  ENDDO
  ENDDO
  DO jf=1,YLSP1%NS3D
  DO js=1,YLSP1%NSPEC2
  DO jl=1,YLSP1%NFLEVL
    YLSP1%SP3D(jl,js,jf)=YLSP1%SP3D(jl,js,jf)-YLSP0%SP3D(jl,js,jf)
  ENDDO
  ENDDO
  ENDDO

  IF (LSCALERR) THEN
    write(NULOUT,*)'SAVE_MERR_TEND: Scaling=',zz
    CALL SELF_MUL(YLSP1,zz)
  ENDIF

  clfile(1:12)='merrtendYYYh'
  WRITE(clfile(9:11),'(I3.3)')NINT((kstep-1)*TSTEP/3600.)
  write(NULOUT,*)'SAVE_MERR_TEND: writing to ',clfile
  CALL WRITE_SPEC_GRIB(clfile,YLSP1)

  CALL SPECTRAL_NORM_LEVS(YLSP1,'MERR_TEND')

  CALL DEALLOCATE_SPEC(YLSP0)
  CALL DEALLOCATE_SPEC(YLSP1)
ENDIF

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