;+
;
; Project   : s3drs reconstruction software
;                   
; Name      : fsigfig
;               
; Purpose   : part of the s3drs GUI
;               
; Explanation: formatting tool to truncate a float to approp. number
; of digigs
;               
; Use       : only called from 's3drs.pro' 
;    
; Inputs    : number, sigfig
;               
; Outputs   : 
;
; Keywords  : debug=debug
;               
; Common    : common s3drs, s3drs (a structure)
;               
; Restrictions: none
;               
; Side effects: 
;               
; Category    : 
;               
; Prev. Hist. : None.
;
; Written     : Sandy Antunes, NRC, March-April 2009
;               
;-            
; absolute idiocy, truncating a float but keeping it as a float.
; returns a float made to the appropriate sig figs

PRO testfsigfig
  values=[0,1,2,10,11,20,1.5,1.5E-1,1.5E10,1.5E-4,1.5E4,1.5E-10,0.9,-0.9,$
          2.5E-11,2.5E-1,2.5E-4,12431.12312,1.2433323E4,1.242132E-4]
  values=[values,0-values]

  print,'to 1 sig fig'
  for i=0,n_elements(values)-1 do ignore=fsigfig(values[i],/debug)
  print,'to 2 sig fig'
  for i=0,n_elements(values)-1 do ignore=fsigfig(values[i],2,/debug)

END

FUNCTION fsigfig,number,sigfig,debug=debug

  debug=KEYWORD_SET(debug)
  if (n_elements(sigfig) eq 0) then sigfig=1

  if (number eq 0) then begin
      final=0.0
  end else if (abs(number) ge 1 and abs(number) lt 1E5) then begin
      ; easy case, just truncate to 1 sig fig
      final = long(number*10^sigfig)/(10.0^sigfig)
  end else begin
      ; harder case, is an E-?
      myexp=fix(alog10(abs(number)))-1
      if (myexp ne 0) then base=abs(number) /(10.0^myexp) else base=0
      mytop = long(base*10^sigfig)
      final=mytop * 10.0^(myexp-sigfig)
      if (number lt 0) then final=0-final
  end

  if (number ne 0) then diff = abs(1.0-ratio(number,final)) else diff=0.0
  ; nice failsafe here
  if (diff gt 0.05) then final=number; if conversion is bad, ditch it
  if (debug) then print,number,final,diff

  return,final

END
