pro detrend_spm, reihe, skala, factor=factor, dtreihe, sreihe=sreihe, bad_min

;+
; NAME:
;       DETREND_SPM
; PURPOSE:
;       Detrending The level 1 data and removing outliers
; EXPLANATION:
;
;
;
; CALLING SEQUENCE:
;       DETREND_SPM, time_series, scale, factor, detrended_ts, [sreihe=], bad_minutes
; INPUTS:
;       time_series: level1 time series
;       scale: Time scale of removed running mean (in minutes)
;       factor: any value with a square > factor*variance is rejected
; OUTPUTS:
;       detrended_ts: detrended time series
;       bad_minutes: list of invalid points
;
; OPTIONAL OUTPUT:
;       sreihe: time series with trend and removed outliers
; PROCEDURES USED:
;
;       Procedures:  WO
;
; MODIFICATION HISTORY:
;       Package written between 2000 and 2003, Richard Wachter, PMOD/WRC
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

 siz=size(reihe)

 sreihe=reihe

 sreihe[where(sreihe eq 99.99 or sreihe eq 0.0)]=!values.f_nan

 og=1.2*mean(sreihe[0:1000], /nan)
 ug=0.8*mean(sreihe[siz[1]-1000:siz[1]-1],/nan)

 if not keyword_set(factor) then factor=7.

 for i=0L, siz[1]-1L do begin

  if reihe[i] le ug or reihe[i] ge og  then sreihe[i]=!values.f_nan

 endfor

 smo=smooth(sreihe, 2*skala, /nan, /edge_truncate)

 stsmo=(sreihe-smo)/smo

 stab=min(smooth(stsmo^2, 4*skala, /nan,  /edge_truncate),mi)


;for optical check of outlier removal


;plot, stsmo, max_value=0.001, min_value=-0.001
;oplot, replicate(factor*sqrt(stab), siz[1]), color=2
;oplot, -replicate(factor*sqrt(stab), siz[1]), color=2

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

 for i=0L, siz[1]-1L do begin

  if abs(stsmo[i]) ge factor*sqrt(stab) then sreihe[i]=!values.f_nan

 endfor



 st=smooth(smooth(sreihe,skala, /nan, /edge_truncate),skala, /nan, /edge_truncate)
 dtreihe=1.e6*(sreihe-st)/st             ;Mittelwert=0

 wo, dtreihe, nullen

 ln=(size(nullen))[2]



 for i=0, ln-2 do begin

  if nullen[0,i+1]-nullen[1,i] lt 20 then begin
   dtreihe[nullen[1,i]:nullen[0,i+1]]=!values.f_nan
  endif

 endfor


 bad_min=fltarr(siz[1])
 bad_min[where(finite(sreihe) ne 0)]=1.0


end