program frantic_test

  ! execute a standalone frantic calculation
  ! this works by reading a NetCDF file containing the starting state
  ! of a frantic calculation, and proceding.

  ! this program accepts exactly one argument:  the NetCDF filename.

  ! mod DMC Dec 2008 -- the 2nd argument can contain optionally the wall source
  ! toroidal velocity in cm/sec
  !
  use iso_c_binding, only: fp => c_double
  implicit none

  integer :: nargs
  character(len=100) :: filename,zvel_str
  character(len=20) :: zvel_str0
  real(fp) :: zveloc

  integer :: izones,ierr,istat,ilen

  !-------------------------------
  !  use portlib routines to get command line argument

  call get_arg_count(nargs)
  if((nargs.lt.1).or.(nargs.gt.2)) call frantic_err_exit

  filename=' '
  call get_arg(1,filename)

  if(nargs.eq.2) then

    zvel_str=' '
    call get_arg(2,zvel_str)

    ilen=len(trim(zvel_str))
    if(ilen.gt.20) then
      write(6,*) ' argument too long: '//trim(zvel_str)
      call frantic_err_exit
    end if

    zvel_str0=' '
    zvel_str0(20-ilen+1:20)=zvel_str(1:ilen)

    read(zvel_str0,fmt='(G20.0)',iostat=istat) zveloc
    if(istat.ne.0) then
      write(6,*) ' could not parse as floating point: '//trim(zvel_str)
      call frantic_err_exit
    end if

    write(6,'(1x,a,1pe12.5,a)') ' *** resetting edge v_phi to ',zveloc, &
         ' cm/sec (per 2nd command argument).'

    zveloc = 0.01_fp*zveloc   ! -> m/sec
  end if

  !-------------------------------
  !  re-initialize state of frantic
  !  and re-calculate frantic neutral density, etc...
  !
  !  in the loop, allocate more and more x until there is enough.
  !

  call frantic_input_restore(filename,izones,ierr)
  write(6,*) ' %frantic_test: number of zones in output grid: ',izones


  if(nargs.eq.2) call frantic_edge_vphi(zveloc)


  if(ierr.eq.0) then

    !  now redo calculation

    call frantic_neuts(ierr)

    !  and print results summary

    if(ierr.eq.0) then
      call frantic_prinsum(6)
    end if

  end if

  if(ierr.ne.0) then
    call frantic_errmsg_exit(' ?? frantic_test: error reading NetCDF file: '// &
         filename(1:len_trim(filename)))
  end if

CONTAINS

  subroutine frantic_err_exit
    write(6,*) ' '
    write(6,*) ' ?? syntax:  frantic_test <NetCDF-filename>'
    write(6,*) '    alternate syntax: frantic_test <NetCDF-filename> <vphi_edge_sce(cm/sec)>'
    write(6,*) ' '
    stop
  end subroutine frantic_err_exit

  subroutine frantic_errmsg_exit(msg)
    implicit none
    character(len=*), intent(in) :: msg
    write(6,*) ' '
    write(6,*) trim(msg)
    write(6,*) ' '
    stop
  end subroutine frantic_errmsg_exit

end program frantic_test
