!--------------------------------------------------------!
!$BI=Bj(B: $B%U%!%$%k$N(B open/close
!$BMzNr(B: 2003/10/28
!--------------------------------------------------------!
module file_switch
  ! $B5!G=(B
  ! $B%U%!%$%k$N(B open/close $B4XO"$O$9$Y$F$3$3$G9T$&(B.
  !  - unit $BHV9f$NEPO?(B
  !  - $B%U%!%$%kL>$N7hDj(B
  ! 
  use prm, only  : imax, jmax, kmax, dt
  use prmphys, only : s_a
  implicit none

  integer, save  :: rsrd_UID     = 10 
  integer, save  :: rswt_UID     = 20

  integer, save  ::monit2D_UID = 30
  integer, save  ::monit3D_UID = 40


!--------------------------------------------------------!
contains
!--------------------------------------------------------!
  subroutine file_switch_on(loop_end)
    ! $B%U%!%$%k$N(B open 
    ! $B0z?t(B  loop_end $B$O=PNO%j%9%?!<%H%U%!%$%kL>$r7h$a$k(B
    ! $B=PNO%j%9%?!<%H%U%!%$%k$N;EMM$O(B, $B:#$N$H$3$m(B 1 job $B$KBP$7$F(B 1 $B$D(B

    implicit none

    integer, INTENT(IN) :: loop_end
    character(LEN=80)   :: rs_file_in
    character(LEN=80)   :: rs_file_out
    character(LEN=100)  :: HEAD
    character(LEN=3)    :: IMAXC
    character(LEN=3)    :: JMAXC
    character(LEN=3)    :: KMAXC
    character(LEN=6)    :: TIME
    integer             :: TIME_num

    namelist /NAM_FILE/ HEAD, TIME

    ! $B%G%U%)%k%H$O;~4V(B 0 $B$+$i(B
    HEAD = '2DICE-SHEET_pre'
    TIME = '000000'
!    rewind(5)
    read(5, NAM_FILE)
    write(6, NAM_FILE)

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

    ! $BFI$_9~$_%j%9%?!<%H%U%!%$%kL>$N7hDj(B
    rs_file_in = TRIM(HEAD)//IMAXC//'_'//JMAXC//'_'//KMAXC//'_'//TIME
    write(6, *)'restart file is ', rs_file_in

    open(unit=rsrd_UID , file=TRIM(rs_file_in), access='sequential', form='unformatted', status='OLD')

    ! $B?t;z$H$7$FFI$_$3$_(B
    read(TIME, '(I6.6)')TIME_num

    write(TIME, '(I6.6)')TIME_num+INT(loop_end * dt/s_a)
    ! $B=q$-9~$_%j%9%?!<%H%U%!%$%kL>$N7hDj(B
    rs_file_out = TRIM(HEAD)//IMAXC//'_'//JMAXC//'_'//KMAXC//'_'//TIME
    open(unit=rswt_UID , file=TRIM(rs_file_out), access='sequential', form='unformatted', status='NEW')

    open(unit=monit2D_UID, file='m2.dat', access='direct', &
         & form='unformatted', status='NEW', recl=4*imax*jmax )
    open(unit=monit3D_UID, file='m3.dat', access='direct', &
         & form='unformatted', status='NEW', recl=4*imax*jmax*kmax )
  end subroutine file_switch_on
!--------------------------------------------------------!


!--------------------------------------------------------!
  subroutine file_switch_off(UID)
    implicit none

    integer, INTENT(IN) :: UID
    
    close(UID)

  end subroutine file_switch_off


end module file_switch
