# 1 "<stdin>"
# 1 "<built-in>"
# 1 "<command line>"
# 1 "<stdin>"
module reweight_mod
  use quantile_mod
  use sep
  implicit none
  character(len=30),private,save :: reweight_method
  integer,private,save :: nreweight
  logical, private, save :: verb
  real, private,save :: huber_pct
  contains
  integer function reweight_op(resid,wt)
    real :: resid(:),wt(:)
    real, pointer :: temp(:)
    real :: mya,eps,myp,myc
    integer :: ic,ismall,i
    write(0,*) "WHAT ALS 1",size(resid),size(wt)
    if (reweight_method(1:2).eq."L1") then
      myp=.02
      eps=0.
      wt=resid/wt
      do while (eps .eq.0)
        ic=myp*size(wt)
        eps=quantile(ic,wt)
        myp=myp*1.5
      end do
      mya=sum(1./wt+eps)/size(wt) !average of |1/r|
      wt=1./(wt+eps)
    else if (reweight_method(1:5).eq."huber") then
      wt=abs(resid/wt) !undo current weighting then abs(r)
      ic=huber_pct/100.*size(wt) !the x percentile location
      myc=quantile(ic,wt) !the value at that location
      do ic=1,size(wt)
        if (wt(ic) > myc) then
          wt(i)=1./wt(i)
        else
          wt(i)=1.
        end if
      end do
    else if (reweight_method(1:4).eq."NONE") then
      wt=1.
    else
      call seperr("unknown residual weighting method")
    end if
    write(0,*) "VJDJKdfs 1"
    reweight_op=0
  end function
  logical function check_reweight_params(niter,nre)
    integer :: niter,nre
    check_reweight_params=.false.
    call from_param("verb",verb,.false.)
    call from_param("niter",nreweight,niter+1)
    if (nreweight<niter+1) then
      call from_param("reweight_method",reweight_method,"NONE")
      if (reweight_method(1:2).eq."L1") then
        if (verb) then
          write(0,*) "reweighting  L1 residuals"
        end if
      else if (reweight_method(1:5).eq."huber") then
        if (verb) then
          write(0,*) "reweighting with huber"
        end if
        call from_param("huber_pct",huber_pct,90.)
      else
        write(0,*) "don't understand reweighting scheme",trim(reweight_method&
          &)
        return
      end if
    else
      reweight_method="NONE"
    end if
    nre=nreweight
    check_reweight_params=.true.
  end function
end module
