!--------------------------------------------------------!
! $BI=Bj(B: $B=i4|CM:n@.%W%m%0%i%`(B
! $BMzNr(B: 2003/09/17
!--------------------------------------------------------!
program make_init
  use prm, only : IMAX,   &   ! x $B3J;R?t(B
&                 JMAX,   &   ! y $B3J;R?t(B
&                 KMAX,   &   ! z $B3J;R?t(B
&                 DX          ! $B3J;R4V3V(B (km)
  use file_switch, only : rswt_UID
  implicit none

   character(LEN=100) :: HEAD
   integer            :: IDATE
   integer            :: KT                        

   integer            ::  k 

   real(8)            :: H(1:IMAX, 1:JMAX)
   real(8)            :: B(1:IMAX, 1:JMAX)
   real(8)            :: T(1:IMAX, 1:JMAX, 1:KMAX)

   character(LEN=3)    :: IMAXC
   character(LEN=3)    :: JMAXC
   character(LEN=3)    :: KMAXC
   character(LEN=6)    :: TIME
    character(LEN=80)   :: rs_file_in
   HEAD = '2DICE-SHEET_test'
   TIME = '000000'

    write(IMAXC, '(I3.3)')IMAX
    write(JMAXC, '(I3.3)')JMAX
    write(KMAXC, '(I3.3)')KMAX

   IDATE = -1
   KT = 0 
   
   H(1:10  , 1:JMAX)   = 0.D0
   H(22:IMAX,1:JMAX)   = 0.D0
   H(11: 21, 1:JMAX)   = 3000.D0
   
!   H =0.0D0

   B = 0.D0
!   T = 273.D0
   call mktemp(H, B, T)
   
   rs_file_in = TRIM(HEAD)//IMAXC//'_'//JMAXC//'_'//KMAXC//'_'//TIME
   open(unit=rswt_UID , file=TRIM(rs_file_in), access='sequential', form='unformatted', status='NEW')


   call rs_write(HEAD, IDATE, KT, H, B, T)


   write(6, *)'write GRADS file'
   open(10, file='GRADS.init_ICE-SHEET', form='unformatted', &
        & access='direct', recl=4*IMAX*JMAX)
   
   write(10, rec=1)REAL(H)
   write(10, rec=2)REAL(B)
   do k = 1, KMAX
      write(10, rec=k+2)REAL(T(:, :, k))
   end do
   

   close(10)

end program make_init


subroutine mktemp(Hsfc, Hbnd, Temp)
  use prm,     only : IMAX, JMAX, KMAX
  use prmphys, only : gamma, k_ice
  use com_var,  only : get_frame, zk
  use Tbound, only  : get_Ts_con, Ts
  implicit none
  
  real(8), intent(IN) :: Hsfc(1:IMAX, 1:JMAX)
  real(8), intent(IN) :: Hbnd(1:IMAX, 1:JMAX)
  real(8),intent(OUT) :: Temp(1:IMAX, 1:JMAX, 1:KMAX)
  integer    :: i, j, k 
  call get_frame
  call get_Ts_con

  do i=1,  IMAX
     do j =1, JMAX
        if((Hsfc(i, j)-Hbnd(i, j)) > 0.0D0)then
           do k = 1, KMAX
              Temp(i, j, k) = -gamma/k_ice * (Hsfc(i, j) - Hbnd(i, j)) * (zk(k) - 1) + Ts(i, j)
           end do
           write(6, *)'temp', temp(i, j, :)
                                    
        else
           Temp(i, j, :) = Ts(i, j)
        end if
     end do
  end do


  
end subroutine mktemp
