
c
c   program to convert an pflame restart file
c   to an spflame restart file
c


      program cv_rest
      implicit none
      integer :: io,nt=2,itt,ierr, io2,j,k,i
      integer (kind=8) :: itt2,ii,jj
      character (len=32) :: stamp
      character (len=40) :: tr_name

      integer :: imt,jmt,km ,n
      real, allocatable  :: dat4(:,:)
      real (kind=8) , allocatable :: dat8(:,:)
      real, allocatable  :: tr4(:,:,:)
      real (kind=8) , allocatable  :: tr8(:,:,:)

      print*,' Converting pflame to spflame'

      call get_commandline_arg_int(1,imt,ierr)
      if (ierr/=0) goto 99
      call get_commandline_arg_int(2,jmt,ierr)
      if (ierr/=0) goto 99
      call get_commandline_arg_int(3,km,ierr)
      if (ierr/=0) goto 99

      allocate(dat4(imt,jmt), tr4(imt,jmt,nt+2))
      allocate(dat8(imt,jmt), tr8(imt,km,nt+2))

      call get_free_iounit(io)
      open(io,file='restart_pflame.dta',form='unformatted',status='old')

      read(io) stamp
      read(io) itt2
      itt=itt2

      print*,' time stamp = ',stamp
      print*,' itt        = ',itt
      print*,' nt         = ',nt 

      call get_free_iounit(io2)
      open(io2,file='new_restart.dta',form='unformatted',status='new')

      write(io2) itt,stamp,nt
c
c     barotropic mode
c
      dat4=0.0  ! write guess fields
      write(io2)dat4
      write(io2)dat4
      read(io)   ! streamfct at tau
      read(io)  ii,jj,dat8; dat4=dat8
      print*, 'psi(,,2) min,max [Sv]:',
     &                  minval(dat4)/1.e12,maxval(dat4)/1.e12
      write(io2)dat4  ! psi(:,:,1)
      write(io2)dat4 ! psi(:,:,2)

      read(io)   ! streamfct at tau+1
      read(io)  

      read(io)   ! guess value 1 
      read(io)  
      read(io)   ! guess value 2
      read(io)  
      read(io)   ! kmt mask
      read(io)  

      tr4=0.0;tr8=0.0
      do k=1,km

       rewind(io)
       do n=1,12; read(io); enddo

       do j=1,jmt
        print*,' reading pflame data  ... k,j=',k,j
        read(io) 
        read(io) ii,tr8
        do i=1,imt
         do n=1,nt+2
           tr4(i,j,n)=tr8(i,k,n)
         enddo
        enddo
       enddo
       print*,' done reading pflame data'

       print*,' writing spflame data'
       do n=1,nt
        write(io2) ((tr4(i,j,n),i=1,imt),j=1,jmt)
        write(io2) ((tr4(i,j,n),i=1,imt),j=1,jmt)
       enddo
       do n=1,2
        write(io2) ((tr4(i,j,nt+n),i=1,imt),j=1,jmt)
        write(io2) ((tr4(i,j,nt+n),i=1,imt),j=1,jmt)
       enddo
       print*,' done writing spflame data'
      enddo

      do j=1,jmt ! read t,u at tau+1
        read(io)
        read(io)
      enddo

      ! read dml from ktmix 
      read(io)
      read(io) ii,jj,dat8; dat4=dat8
      write(io2) dat4

      ! tkemix ? no

      close(io)
      close(io2)

      stop
 99   print*,' program needs command line parameter:'
      print*,'<executable> imt jmt km nt'

      end program cv_rest



      subroutine halt_stop(s)
      character*(*) s
      print*,s
      stop
      end
