module wemva_basfnc_mod
  use  sep
  use  base_spline_mod
  use  wemva_struct_mod
  implicit none
  type(axis)                     , private :: axd, ayd, azd
  type(axis)                     , private :: axk, ayk, azk
  real, dimension(:), allocatable, private :: modl, data
contains

  integer function wemva_basfnc_init(axd_in,ayd_in,azd_in,axk_in,ayk_in,azk_in) result(stat)
    type(axis) :: axd_in, ayd_in, azd_in
    type(axis) :: axk_in, ayk_in, azk_in
    axd = axd_in; ayd = ayd_in; azd = azd_in
    axk = axk_in; ayk = ayk_in; azk = azk_in
    if(.not.allocated(modl))allocate(modl(axk%n*ayk%n*azk%n))
    if(.not.allocated(data))allocate(data(axd%n*ayd%n*azd%n))
    stat = base_spln3d_init(axd,ayd,azd,axk,ayk,azk)
    stat = 0
  end function

  integer function wemva_basfnc_clos() result(stat)
    deallocate(modl, data)
    stat = 0
  end function

  integer function wemva_basfnc_oper(adj, add, modl_, data_) result(stat)
    logical          :: adj, add
    character(len=*) :: modl_, data_
    if (.not.add) then
       if (adj) then
          modl = 0.
          call sseek(modl_, 0, 0)
          call sep_write(modl, modl_)
       else
          data = 0.
          call sseek(data_, 0, 0)
          call sep_write(data, data_)
       end if  
    end if 

    call sseek(modl_, 0, 0); call sep_read(modl, modl_)
    call sseek(data_, 0, 0); call sep_read(data, data_)
    if (adj) then
       stat = base_spln3d_oper(adj, add, modl, data)
       call sseek(modl_, 0, 0); call sep_write(modl, modl_)
    else
       stat = base_spln3d_oper(adj, add, modl, data)
       call sseek(data_, 0, 0); call sep_write(data, data_) 
    end if 

  end function

end module
