!-------------------------------------- LICENCE BEGIN ------------------------------------
!Environment Canada - Atmospheric Science and Technology License/Disclaimer,
!                     version 3; Last Modified: May 7, 2008.
!This is free but copyrighted software; you can use/redistribute/modify it under the terms
!of the Environment Canada - Atmospheric Science and Technology License/Disclaimer
!version 3 or (at your option) any later version that should be found at:
!http://collaboration.cmc.ec.gc.ca/science/rpn.comm/license.html
!
!This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
!without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
!See the above mentioned License/Disclaimer for more details.
!You should have received a copy of the License/Disclaimer along with this software;
!if not, you can write to: EC-RPN COMM Group, 2121 TransCanada, suite 500, Dorval (Quebec),
!CANADA, H9P 1J3; or send e-mail to service.rpn@ec.gc.ca
!-------------------------------------- LICENCE END --------------------------------------
!

      SUBROUTINE CAINGDAD(KDIM,PX) 2,3
#if defined (DOC)
*
***s/r CAINGDAD  Adjoint of the canonical injection:
*     .          transfer of the model state from COMGD into
*     .          the control variable (with optional spectral filter)
*
*Author  : M. Buehner, August 2002
*Revision:
*
*    -------------------
*Arguments
*     i : KDIM = dimension of the control variable
*     i : PX   = control variable
#endif
      IMPLICIT NONE
*implicits
#include "pardim.cdk"
#include "comdim.cdk"
#include "comlun.cdk"
#include "comgd0.cdk"
#include "comsp.cdk"
#include "comleg.cdk"
#include "comgem.cdk"
*
      INTEGER KDIM, JDIM, JLEV, JLAT, JLON
      LOGICAL LFILTER
      REAL*8 PX(KDIM)
      EXTERNAL ABORT3D
c
      LFILTER=.true.
c
      IF(LFILTER) THEN
        CALL REESPE(NKSDIM,SP,GD
     S             ,NLA,NIBEG,NIEND,NJBEG,NJEND,NKSDIM)
        CALL SPEREE(NKSDIM,SP,GD
     S             ,NLA,NIBEG,NIEND,NJBEG,NJEND,NKSDIM)
      ENDIF
c
      do jlat = 1, nj
        do jlev = 1, nkgdim
          do jlon = 1, ni
            gd(jlon,jlev,jlat) = gd(jlon,jlev,jlat) *
     +             rwt(jlat) / nilon(jlat)
          enddo
        enddo
      enddo
C
C*    1. Transfer of the model spcetral state
C
      JDIM=0
C
      DO JLEV = 1, NKGDIM
        DO JLAT = 1, NJ
          DO JLON = 1, NI
            JDIM = JDIM + 1
            PX(JDIM) = PX(JDIM) + GD(JLON,JLEV,JLAT)
          ENDDO
        ENDDO
      ENDDO
C
C     2. Verify the dimension of the control variable
C
      IF(JDIM.NE.KDIM) THEN
         WRITE(NULOUT,FMT='(//,10X,''Error in CAINGDAD. Wrong dimension'',
     S        '' for the control variable. KDIM = '',I8,4X,''JDIM ='',
     S        I8)')KDIM, JDIM
         CALL ABORT3D(NULOUT,'ERROR IN CAINGDAD ')
      END IF
C
      RETURN
      END