PRO s3drs_hist
;+
;
; Project   : s3drs reconstruction software
;                   
; Name      : s3drs_hist
;               
; Purpose   : part of the s3drs GUI
;               
; Explanation: plots histograms of the S/N data
;               
; Use       : only called from 's3drs.pro' 
;    
; Inputs    : none (uses existing data in s3drs structure)
;               
; Outputs   : none (plots to GUI)
;
; Keywords  : 
;               
; Common    : common s3drs, s3drs (a structure)
;               
; Restrictions: none
;               
; Side effects: 
;               
; Category    : GUI
;               
; Prev. Hist. : None.
;
; Written     : Sandy Antunes, NRC, March-April 2009
;               
;-            

  common s3drs,s3drs

  if (n_elements(uname) eq 0) then uname='SNHist1'; main histogram window

  if (s3drs.choice eq 'synthetic') then dsptr=s3drs.syn else dsptr=s3drs.diff
  if (PTR_VALID(dsptr) eq 0 or PTR_VALID(s3drs.ndiff) eq 0) then return

  win1 = WIDGET_INFO(s3drs.wTLB, FIND_BY_UNAME=uname)
  if (win1 eq 0) then return

  ; resize appropriately
  n2=floor(s3drs.Nframes/2) + (s3drs.Nframes mod 2)

  ;print,'drawing to ',n2,' ',n2*120
  WIDGET_CONTROL,win1,draw_ysize=n2*120

  WIDGET_CONTROL,win1,GET_VALUE=index1
  wset,index1

  !P.MULTI=[0,2,n2]

  for i=0,s3drs.Nframes-1 do begin
      sn =  ratio( (*dsptr)[*,*,i], $
                   (*s3drs.ndiff)[*,*,i]/((*s3drs.snratio)[i]) )

      ; histogram sometimes blows up with bad data, so we catch here

      Nf=FLOAT(s3drs.Nd^2.)
      Nsub=s3drs.Nd

      CATCH, Error_status
      IF Error_status NE 0 THEN BEGIN
          ; avoids memory errors with ill-formed data
          ; put at a smaller binned size
          Nsub=Nsub/2
          if (Nsub le 1) then begin
              ; give up
              !P.MULTI=0
              return
          end
          ;print,'Bad histogram, retrying at size ',Nsub,Nsub
          myhist=histogram(congrid(sn,Nsub,Nsub))
      END

      myhist=histogram(sn) / Nf


      if (n_elements(myhist) eq 1) then guessatmax=1 else $
        guessatmax = max(myhist[1:*])*1.5
      xmax=MIN([s3drs.Nd,n_elements(myhist)])
      plot,myhist,title=(*s3drs.names)[i],yticks=2,$
        ystyle=1,yrange=[0,guessatmax],xrange=[0,xmax],xstyle=1
  end

  !P.MULTI=0

END
