program BinData

  use sep
  use normlint2_mod

  use dottest

  implicit none

  integer                               :: m12, m1, m2, npts
  integer                               :: stat, niter
  real                                  :: dot1(2), dot2(2)
  real,    dimension (:)  , pointer     :: gridded, z, w, zfold, fold, bad
  real,    dimension (:,:), pointer     :: xy, raw, sigma, tmp1, tmp2, tmp0
  real	                                :: xmin1, xmin2, d1, d2

  call sep_init(SOURCE)
  call from_history( "n1", npts)

  call from_param( "m_ns", m1);      call from_param( "m_ew", m2)
  call from_param( "min_ns", xmin1); call from_param( "min_ew", xmin2)
  call from_param( "d_ns", d1);      call from_param( "d_ew", d2)
  call to_history( "n1", m1)    ; call to_history( "n2", m2)
  call to_history( "o1", xmin1) ; call to_history( "d1", d1)
  call to_history( "o2", xmin2) ; call to_history( "d2", d2)
  call to_history( "esize", 4)
  if( exist_file("fold") ) then
     call to_history( "n1", m1, "fold")    ; call to_history( "n2", m2, "fold")
     call to_history( "o1", xmin1, "fold") ; call to_history( "d1", d1, "fold")
     call to_history( "o2", xmin2, "fold") ; call to_history( "d2", d2, "fold")
     call to_history( "esize", 4, "fold")
  end if
  call sep_close()

  m12 = m1*m2

  allocate( raw(npts,4), w(npts), z(npts), xy(npts,2), gridded(m12) )

  call sep_read( raw)

  xy = raw(:,1:2);  z = raw(:,3);  w = raw(:,4)

  deallocate( raw)
  call normlint2_init( m1, m2, npts, xmin1, xmin2, d1, d2, xy ) 
  stat = normlint2_lop( .true., .false., gridded, z )

  if( exist_file("fold") ) then
     allocate( fold(m12) )
     call get_fold( fold )
     call sep_write( fold, "fold" )
  end if

  call sep_write( gridded)

  call normlint2_close()
  deallocate( xy, z, w, gridded)

  call exit(0)

end program BinData
