pro hsi_rebinner, specin, edgesin, specout, edgesout
edge_products, edgesin, edges_2 = edgesin2, width=widthin
edge_products, edgesout, edges_2 = edgesout2, width=widthout
ea1 = edgesin2[0,*]
ea2 = edgesin2[1,*]
eb1 = edgesout2[0,*]
eb2 = edgesout2[1,*]

specout = dblarr(n_elements(edgesout)-1)

;This loops over each bin of the OUTPUT spectrum and sees which bins of
;the the INPUT spectrum overlap it:

for i=0, n_elements(edgesout)-2 do begin

  ;There are four kinds of overlap: new channel completely covers old,
  ;old completely covers new, and offsets to both sides.  Find all four
  ;subsets and transfer the counts appropriately for each one:
  ;
  ;Old bins completely contain new bins [exclude specific case
  ; where they are identical, but keep cases where one side matches]:
  ;
  a = where(  (eb1[i] GE ea1 AND eb2[i] LE ea2) AND $
          NOT (eb1[i] EQ ea1 AND eb2[i] EQ ea2) ,act)
  ;
  ;New bins completely contain old bins
  ;
  b = where(eb1[i] LE ea1 AND eb2[i] GE ea2,bct)
  ;
  ; new bin overlaps lower edge
  ;
  c = where(eb2[i] lt ea2 and eb2[i] gt ea1 and eb1[i] lt ea1,cct)
  ;
  ; new bin overlaps upper edge
  ;
  d = where(eb1[i] GT ea1 AND eb1[i] lt ea2 and eb2[i] GT ea2,dct)

  if (act GT 0) then $
    specout[i] = specout[i] + total(widthout[i]/widthin[a]*specin[a])
  if (bct GT 0) then $
    specout[i] = specout[i] + total(specin[b])
  if (cct GT 0) then $
    specout[i] = specout[i] + total((eb2[i]-ea1[c])/widthin[c]*specin[c])
  if (dct GT 0) then $
    specout[i] = specout[i] + total((ea2[d]-eb1[i])/widthin[d]*specin[d])
;
endfor

end