# 1 "<stdin>"
# 1 "<built-in>"
# 1 "<command line>"
# 1 "<stdin>"
!<
!
!
!
!
!
! MODULE CONTAINING CONVERSION FROM DEPTH
! TO WHAT EVER SPACE TOMOGRAPHY WILL BE PERFORMED IN
! TO ADD TYPE MAKE SURE TO INCLUDE IN CONV_TYPE
! AND ALL ACCESSING FUNCTIONS.
!
!
!>
module update_vel_mod
  use tomo_space_conv_mod
  use model_des_mod
  implicit none
  integer, private,save :: n(3)
  real, private, save :: o(3),d(3)
  contains
  logical function calc_write_new_vel()
    type(sep3d) :: tomo_s,vel_s
    real, pointer :: update(:)
    real, pointer :: vel(:,:,:)
    calc_write_new_vel=.false.
!GRAB TOMO STRUCTURE
    if (.not. vel_tomo_structure(tomo_s)) then
      write(0,*) "trouble getting tomo structure"
      return
    end if
    call set_n_o_d_3d(tomo_s,n,o,d)
!GRAB DS
    allocate(update(product(n)))
    if (.not. return_change(update)) then
      write(0,*) "trouble grabbing update"
      return
    end if
!WRITE OUT IF REQUESTED
    if (.not. check_write_change(update)) then
      write(0,*) "trouble writing out update"
      return
    end if
    deallocate(update)
    if (.not. update_vel()) then
      write(0,*) "trouble updating velocity"
      return
    end if
!GRAB AND UPDATE VELOCITY
    allocate(vel(n(1),n(2),n(3)))
    if (.not. vel_tomo_3d(myvel=vel)) then
      write(0,*) "trouble grabbing slowness"
      return
    end if
!DO FINAL CLEAN UP IN TOMO_SPACE
    if (.not. model_tomo_space_clean(vel)) then
      write(0,*) "    ERROR: cleaning up model in tomo space"
      return
    end if
    deallocate(vel)
    if (.not. transform_vel_orig_space(vel)) then
      write(0,*) "    ERROR: transfering back to original space"
      return
    end if
    if (.not. vel_structure(vel_s)) then
      write(0,*) "    ERROR: grabbing velocity structure"
      return
    end if
!WRITE OUT
    if (.not. write_out_field("out",vel_s,vel)) then
      write(0,*) "    ERROR: writing out velocity"
      return
    end if
    deallocate(vel)
    calc_write_new_vel=.true.
  end function
  logical function check_write_change(change)
    real :: change(:)
    integer, external :: srite
    check_write_change=.false.
    if (check_write("change")) then
      call setup_reg_file("change",n,o,d,1)
      if (4*size(change) .ne. srite("change",change,size(change)*4))&
        & then
        write(0,*) "trouble setting up change"
        return
      end if
    end if
    check_write_change=.true.
  end function
end module
