!-------------------------------------- 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 minimize(lcolumng,lobsSpaceData,isControlAnalysis) 1,18
  use minimization_mod
  use obsSpaceData_mod
  use columnData_mod
  use timeCoord_mod
  use rmatrix_mod
  implicit none
  !
  !Purpose:
  ! Set the CMA for a minimization, pickup the appropriate minimizer
  ! and reset the CMA for post processing
  !
  !Author  : S. Pellerin *ARMA/MSC  Sept, 2005
  !                                    in 1-Obs case.
  !Local declarations
  type(struct_obs) :: lobsSpaceData
  type(struct_columnData) :: lcolumn,lcolumng
  logical :: isControlAnalysis
  integer :: indic,ierr

  write(*,*) '--------------------------------'
  write(*,*) '--Starting subroutine minimize--'
  write(*,*) '--------------------------------'
  call tmg_start(2,'MIN')

  call col_setVco(lcolumn,col_getVco(lcolumng))
  call col_allocate(lcolumn,col_getNumCol(lcolumng),mpi_local=.true.)
  call col_copyLatLon(lcolumng,lcolumn)

  write(*,*) 'PRDATABIN: For 4D increment'
  call prdatabin(lobsSpaceData,tim_nstepobsinc)
  call tim_sutimeinterp(lobsSpaceData)

  call min_minvar(lcolumn,lcolumng,lobsSpaceData,isControlAnalysis)

  DO INDIC =1,1
     if(obs_numHeader(lobsSpaceData).ge.indic) then 
        CALL obs_prnthdr(lobsSpaceData,indic)
        CALL obs_prntbdy(lobsSpaceData,indic)
     endif
  END DO

  call col_deallocate(lcolumn)
  call tmg_stop(2)

! Memory deallocations for non diagonal R matrices for radiances
  call rmat_cleanup()

end subroutine minimize