    

!=======================================================================
!      account for static instabilities
!=======================================================================

 subroutine convection(ierr)
   use pyOM_module   
   implicit none
   integer, intent(out) :: ierr
   integer :: i,j,k,js,je

   ierr = 0
   js=max(2,js_pe); je = min(je_pe,ny-1)
   K_b(:,js:je,:) = 0.0

   if (enable_back_state) then
    do j=js,je
      do k=1,nz-1
        do i=2,nx
           if ( b(i,j,k+1,taum1)+back(i,j,k+1,taum1) >  &
                b(i,j,k   ,taum1) +back(i,j,k,taum1) )   K_b(i,j,k)=1000.*maskW(i,j,k)
        enddo
      enddo
    enddo
    b(:,js:je,:,taup1) = b(:,js:je,:,taup1) + back(:,js:je,:,taup1)
    call implicit_tracer_mix(nx,ny,nz,b,K_b)
    b(:,js:je,:,taup1) = b(:,js:je,:,taup1) - back(:,js:je,:,taup1)
   else
    do j=js,je
      do k=1,nz-1
        do i=2,nx
         if (b(i,j,k+1,taum1) > b(i,j,k,taum1)) K_b(i,j,k)=1000.*maskW(i,j,k)
        enddo
      enddo
    enddo
    call implicit_tracer_mix(nx,ny,nz,b,K_b)
   endif

 end subroutine convection


 subroutine implicit_tracer_mix(nx_,ny_,nz_,var,K_vert)
   !   T_n+1 = T_n+1(1 + c2dt* (K (T_n+1)_z )_z )
   use pyOM_module   
   implicit none
   integer :: nx_,ny_,nz_
   integer :: j,k,js,je
   real*8 :: var(nx_,ny_,nz_,3),K_vert(nx_,ny_,nz_)
   real*8 :: a(nx,nz),bb(nx,nz),c(nx,nz),bet(nx)
   real*8 :: pu(nx,nz),gam(nx,nz),fxa, r(nx,nz)

      js=max(2,js_pe); je = min(je_pe,ny-1)
      fxa = c2dt/dz**2

      do j=js,je
       bb(:,1) = 1+fxa*K_vert(:,j,1)
       c(:,1)  =  -fxa*K_vert(:,j,1)
       do k=2,nz-1
        a(:,k)  =  -fxa *   K_vert(:,j,k-1)
        bb(:,k) = 1+fxa * ( K_vert(:,j,k)+K_vert(:,j,k-1) )
        c(:,k)  =  -fxa *   K_vert(:,j,k)
       enddo
       a(:,nz)  =  -fxa * K_vert(:,j,nz-1)
       bb(:,nz) = 1+fxa * K_vert(:,j,nz-1) 

       pu=0.0;gam=0.0
       r=var(:,j,:,taup1)
       r(:,nz-1)=r(:,nz-1) !  +aidif_tracer*surface_flux(:,j)*c2dt/dz
       bet=bb(:,1)
       where (bet/=0.0) pu(:,1)=r(:,1)/bet
       do k=2,nz
        where (bet/=0.0) gam(:,k)=c(:,k-1)/bet
        bet=bb(:,k)-a(:,k)*gam(:,k)
        where(bet/=0.0) pu(:,k)=(r(:,k)-a(:,k)*pu(:,k-1))/bet
       enddo
       do k=nz-1,1,-1
        pu(:,k)=pu(:,k)-gam(:,k+1)*pu(:,k+1)
       enddo
       var(:,j,:,taup1)=pu
      enddo
  end subroutine implicit_tracer_mix


