;+
;PROCEDURE:	load_stb_l1_mag
;PURPOSE:	
;   loads STEREO/IMPACT MAG high resolution data for "tplot".
;
;INPUTS:	none, but will call "timespan" if time
;		range is not already set.
;KEYWORDS:
;  TIME_RANGE:  2 element vector specifying the time range
;  POLAR:       Also computes the B field in polar coordinates.
;  DATA:        Data returned in this named variable.
;  NODATA:	Returns 0 if data exists for time range, otherwise returns 1.
;  PREFIX:	(string) prefix for tplot variables.  Default is 'stb_'
;  NAME:	(string) name for tplot variables. Default is 'stb_B'
;  RESOLUTION:	Resolution to return in seconds.
;  MASTERFILE:	(string) full filename of master file.
;  RTN:         If set, return B field in RTN coordinates.
;SEE ALSO: 
;  "make_cdf_index","loadcdf","loadcdfstr","loadallcdf"
;
;CREATED BY:	Peter Schroeder
;LAST MODIFIED:	11/27/06
;-


pro load_stb_l1_mag,time_range=trange,polar=polar,data=d,  $
  nodata=nodat, $
  prefix = prefix, $
  resolution = res,  $
  name = bname, $
  masterfile=masterfile, rtn = rtn
  
if not keyword_set(masterfile) then masterfile = 'STB_L1U'
;if keyword_set(rtn) then cdfnames = ['B_RTN'] else cdfnames = ['B_SC']
cdfnames=['BFIELD']
if keyword_set(rtn) then ppx = 'B_RTN' else ppx = 'B'
if keyword_set(rtn) then dirpart = 'RTN' else dirpart='SC'
myformat = '/disks/stereodata/l1/behind/mag/'+dirpart+'/????/??/STB_L1_MAG_*.cdf'

d=0
nodat = 0

loadallcdf,myformat,time_range=trange, $
    cdfnames=cdfnames,data=d,res =res

if keyword_set(d) eq 0 then begin
   message,'No STB MAG data during this time.',/info
   nodat = 1
  return
endif


if data_type(prefix) eq 7 then px=prefix else px = 'stb_'
if data_type(bname) eq 7 then px = bname else px = px+ppx

if keyword_set(rtn) then labs=['B!dR!n','B!dT!n','B!dN!n'] else $
   labs=['B!dX!n','B!dY!n','B!dZ!n']

time  = reform(d.time)
str_element,d,cdfnames(0),bhgrtn
bhgrtn = bhgrtn[0:2,*]
bhgrtn = transpose(bhgrtn)

bmag=sqrt(total(bhgrtn*bhgrtn,2))
w =where(bmag gt 1000.,c)
if c ne 0 then bhgrtn[w,*] = !values.f_nan

store_data,px,data={x:time,y:bhgrtn},min= -1e30, dlim={labels:labs}

if keyword_set(polar) then begin
   xyz_to_polar,px,/ph_0_360

   options,px+'_mag','ytitle','|B|',/def
   options,px+'_th','ytitle','!19Q!X!DB!U',/def
   ylim,px+'_th',-90,90,0,/def
   options,px+'_phi','ytitle','!19F!X!DB!U',/def
   options,px+'_phi','psym',3,/def
   ylim,px+'_phi',0,360.,0,/def

endif

;if keyword_set(rtn) then begin
;   mycmat = get_stereo_cmat(unixtai2utc(time), 'A')
;   rtndata = matrix_multiply(mycmat,bhgrtn,/btranspose)
;   labs=['B!dR!n','B!dT!n','B!dN!n']
;   store_data,'sta_B_RTN',data={x:time,y:transpose(rtndata)},min= -1e30, $
;      dlim = {labels:labs}
;endif

end