SUBROUTINE MODELTOJBAD(YDSPJB)

!**** *MODELTOJBAD * - Routine to transfer model state fields tocontrol variable spectral fields
!                       - ADJOINT

!     Purpose.
!     --------
!           Transfer from SPA3JB, SPA2JB and SPA1JB
!           to SPA3, SPA2, SPA1 and possibly GFL
!           (Adjoint of MODELTOJB)

!**   Interface.
!     ----------
!        *CALL* *MODELTOJBAD*

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

!     Implicit arguments :
!     --------------------

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

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

!     Author.
!     -------
!        Gabor Radnoti *ECMWF*

!     Modifications.
!     --------------
!        Original : 2007-01-30

USE PARKIND1  ,ONLY : JPRB, JPIM
USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK
USE YOMLUN   , ONLY : NULOUT
USE YOMDIM   , ONLY : NPROMA
USE YOMSP    , ONLY : SPA3,   SPA2,   SPA1, SPGFL
USE YOMGFL   , ONLY : GFL
USE YOMMP    , ONLY : NBSETLEV, NPSP
USE YOMJG    , ONLY : N_SPJB_VARS, SPJB_VARS_INFO
USE YOMCT0   , ONLY : LELAM
USE SPECTRAL_FIELDS_MOD

IMPLICIT NONE

TYPE(SPECTRAL_FIELD), INTENT(INOUT) :: YDSPJB

INTEGER(KIND=JPIM) :: JFIELD, IPT, IPTJB
REAL(KIND=JPRB) :: ZHOOK_HANDLE

INTERFACE
#include "dir_transad.h"
END INTERFACE


#include "abor1.intfb.h"

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

!-- SPA1 is a special case!

IF (LELAM) SPA1(:,:) = YDSPJB%SP1D(:,:)

!--- Loop over Jb variables

DO JFIELD=1,N_SPJB_VARS
  IPTJB = SPJB_VARS_INFO(JFIELD)%IPTJB
  IPT   = SPJB_VARS_INFO(JFIELD)%IPT

  IF (SPJB_VARS_INFO(JFIELD)%L_IN_SPA2) THEN

    IF (NPSP>0) THEN
      SPA2(:,IPT)=YDSPJB%SP2D(:,IPTJB)
      YDSPJB%SP2D(:,IPTJB) = 0.0_JPRB
    ENDIF

  ELSEIF (SPJB_VARS_INFO(JFIELD)%L_IN_SPA3) THEN

    SPA3(:,:,IPT) = YDSPJB%SP3D(:,:,IPTJB)
    YDSPJB%SP3D(:,:,IPTJB) = 0.0_JPRB

  ELSEIF (SPJB_VARS_INFO(JFIELD)%L_IN_SPGFL) THEN

    SPGFL(:,:,IPT) = YDSPJB%SP3D(:,:,IPTJB)
    YDSPJB%SP3D(:,:,IPTJB) = 0.0_JPRB

  ELSEIF (SPJB_VARS_INFO(JFIELD)%L_IN_GPGFL) THEN
    GFL(:,:,IPT,:)= 0.0_JPRB 
    CALL DIR_TRANSAD (PSPSCALAR=YDSPJB%SP3D(:,:,IPTJB), PGP=GFL(:,:,IPT,:), &
                    & KVSETSC=NBSETLEV, KPROMA=NPROMA)
    YDSPJB%SP3D(:,:,IPTJB) = 0.0_JPRB

  ELSE

    WRITE (NULOUT,*) 'DON''T KNOW WHERE TO GET JB MODEL FIELD : ',JFIELD
    CALL ABOR1 ('DON''T KNOW WHERE TO GET JB MODEL FIELD')

  ENDIF
ENDDO

IF (LHOOK) CALL DR_HOOK('MODELTOJBAD',1,ZHOOK_HANDLE)

END SUBROUTINE MODELTOJBAD
