;function subtract_cm
;
;PURPOSE:
;	To eliminate the common mode signal present during the 
;	observing run at KPNO.
;	
;	The signal is not easily extracted from Channel 0 as a simple 
;	subtraction does not seem to work.
;
;NOTES:
;	This noise was present during the KPNO run of 4/24/07-5/1/07)
;INPUTS:
;	InArr - The full 4006x4096 array from the H4RG detector
;KEYWORDS:
;	MaxBackground:
;	   Set this keyword to a number for the maximum
;	   value of the background to avoid contamination from sources.
;	
;	SMOOTHB:
;	   If set, the median of the rows will be smoothed with a 
;	   savgol filter

function subtract_cm, InArr, MaxBackground=MaxBackground, SmoothB = SmoothB,$
	fwindow=fwindow, order=order, degree = degree

If N_Elements(SmoothB) eq 0 then SmoothB = 0
If N_Elements(FWindow) eq 0 then FWindow = 64
If N_Elements(Order)   eq 0 then Order   = 0
If N_Elements(Degreee) eq 0 then Degree  = 1

Common KeyParams, KeyStr

;Try to estimate the background by assuming that there are not a ton of 
;background sources
Background = InArr
MaskInds = where(InArr eq 0)

If N_Elements(MaxBackground) eq 0 then begin
  MeanArr    = Mean(InArr(KeyStr.Ch0W-1:KeyStr.Naxis1-KeyStr.Ref/2-1,$
			KeyStr.Ref/2 :KeyStr.Naxis2-KeyStr.Ref/2-1),/nan)
  StdDevArr  = StdDev(InArr(KeyStr.Ch0W-1:KeyStr.Naxis1-KeyStr.Ref/2-1,$
                        KeyStr.Ref/2 :KeyStr.Naxis2-KeyStr.Ref/2-1),/nan)
  MaxBackground = MeanArr+StdDevArr
EndIf

If (where(finite(Background) eq 0))[0] ne -1 then $
Background(where(finite(Background) eq 0)) = 2*MaxBackground
Background(where(Background gt MaxBackground)) = 0
RowMed = Median(Background(KeyStr.Ch0W :KeyStr.Naxis1-KeyStr.Ref/2-1,$
			   KeyStr.Ref/2:KeyStr.Naxis2-KeyStr.Ref/2-1),$
			   Dimension = 1)

;Allow for a smoothing
If SmoothB then begin 
  savgol_filter = savgol(fwindow, fwindow, order, degree)
  RowMed = convol(RowMed, savgol_filter, /EDGE_TRUNCATE)
EndIf

For Row = KeyStr.Ref/2, KeyStr.Naxis2-KeyStr.Ref/2-1 do begin
  InArr(KeyStr.Ch0W:KeyStr.Naxis2-KeyStr.Ref/2-1, Row) = $
	float(InArr(KeyStr.Ch0W:KeyStr.Naxis2-KeyStr.Ref/2-1,Row)) - $
	RowMed(Row-KeyStr.Ref/2)+max(RowMed)
EndFor

InArr(MaskInds) = 0

return, InArr

end 
