pro FINDATTRACT, reihe, maxhist, kl

;+
; NAME:
;       FINDATTRACT
; PURPOSE:
;       Finding attractors from level 0 time series
; EXPLANATION:
;       readme.txt
;
;
; CALLING SEQUENCE:
;       FINDATTRACT, reihe, maxhist, kl
; INPUTS:
;       level_0: level 0 time series in the format (n vector)
; OUTPUTS:
;       maxhist: time series with maximum of histograms of overlapping time series of 2 hours (n/5 vector)
;                usually not needed
;       kl: ((3,m) vector) location and classification of attractors. First and second element correspond to begin
;           and end of attractor sequence. Third element contains a number, classifying the strength of the attractors.
;           Values > 400 are usually regarded as attractors, which has to be removed.
; PROCEDURES USED:
;       None
;
; MODIFICATION HISTORY:
;       Package 'SPM level 1.5' written between 2000 and 2003, Richard Wachter, PMOD/WRC
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

 siz=size(reihe)
 laenge=siz[1]/5L
 maxhist=intarr(laenge)


 reihe[where(reihe eq 0L)]=!values.f_nan

 for i=0L, laenge-24L do begin

  hhour=reihe[i*5L:(i+24L)*5L-1L]
  if total(finite(hhour)) ne 0 then begin

    hist=histogram(hhour, binsize=3L, /nan)
    maxhist[i]=max(hist)

  endif

 endfor


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

 att1=bytarr(laenge)

 for i=0L, laenge-24L do begin

  if maxhist[i] ge 6  then att1[i]=1

 endfor

 att2=bytarr(laenge)
 for i=25L, laenge-26L do begin


  sl=total(att1[i-25L:i-1L])
  sr=total(att1[i+1L:i+25L])

  if sl ge 1 and sr ge 1 then att2[i]=1 else  att2[i]=att1[i]

 endfor


 zz=0L & tt=0L

 for i=0L, laenge-2L do begin
  zz=zz+long(maxhist[i])*long(att2[i])

  if abs(att2[i+1L]-att2[i]) then begin

    tt=[tt,i,zz]
    zz=0L

  endif

 endfor

 siz=size(tt)
 kl=lonarr(3,siz[1]/4)

 for i=1, siz[1]-1, 4 do begin

  kl[0,i/4]=(tt[i]+10)*5
  kl[1,i/4]=(tt[i+2]+20)*5
  kl[2,i/4]=tt[i+3]

 endfor

end