;+
;*****************************************************************************************
;
;  PROCEDURE:   wi_tds_dustimpact_load.pro
;  PURPOSE  :   
;
;  CALLED BY:   
;               
;
;  INCLUDES:
;               
;
;  CALLS:
;               
;
;  REQUIRES:    
;               
;
;  INPUT:
;               
;
;  EXAMPLES:    
;               
;
;  KEYWORDS:    
;               
;
;   CHANGED:  1)  Continued to write routine
;                                                                   [08/24/2016   v1.0.0]
;             2)  Continued to write routine
;                                                                   [08/24/2016   v1.0.0]
;             3)  Continued to write routine
;                                                                   [08/25/2016   v1.0.0]
;
;   NOTES:      
;               
;
;  REFERENCES:  
;               
;
;   CREATED:  08/23/2016
;   CREATED BY:  Lynn B. Wilson III
;    LAST MODIFIED:  08/25/2016   v1.0.0
;    MODIFIED BY: Lynn B. Wilson III
; $LastChangedBy: $
; $LastChangedDate: $
; $LastChangedRevision: $
; $URL: $
;
;*****************************************************************************************
;-

PRO wi_tds_dustimpact_load,FILES=files,TRANGE=trange,VERBOSE=verbose,              $
                           DOWNLOADONLY=downloadonly,VARFORMAT=varformat,          $
                           DATATYPE=datatype, $
                           ADDMASTER=addmaster,TPLOTNAMES=tn,SOURCE_OPTIONS=source

ex_start       = SYSTIME(1)
;;----------------------------------------------------------------------------------------
;;  Constants
;;----------------------------------------------------------------------------------------
ver_str        = !VERSION
vern           = ver_str.RELEASE                             ;;  e.g., '8.5.1'
vernf          = FLOAT(vern[0])                              ;;  e.g., 8.5
f              = !VALUES.F_NAN
d              = !VALUES.D_NAN
slash          = get_os_slash()                              ;;  '/' for Unix, '\' for Windows
http_slash     = '/'                                         ;;  separator for URLs
R_Ea__m        = 6.3781366d06                                ;;  Earth's Mean Equatorial Radius [m, 2015 AA values]
R_E            = R_Ea__m[0]*1d-3                             ;;  m --> km
tdate0         = '1994-11-01'
t_current      = time_string(ex_start[0],PREC=3)
tdate1         = STRMID(t_current[0],0L,10L)                 ;;  Current date
yr_st_en       = STRMID([tdate0[0],tdate1[0]],0L,4L)
start_of_day   = '00:00:00.000'
end___of_day   = '23:59:59.999'
;;  Define the maximum possible time range
tr_tmax        = [tdate0[0]+'/'+start_of_day[0],tdate1[0]+'/'+end___of_day[0]]
tr_dmax        = time_double(t)
;t              = [tdate0[0]+'/'+start_of_day[0],tdate1[0]+'/'+end___of_day[0]]
;trange         = time_double(t)
;;  Define dummy angle bin arrays
nang           = 13L                                         ;;  30 deg angle bins
dang           = 36d1/(nang[0] - 1L)
dumb_angs      = DINDGEN(nang[0])*dang[0]
hist_parms     = [dang[0],0d0,36d1]
;;  Define all dates from start to end
all_tdates_gd  = fill_tdates_btwn_start_end(tdate0[0],tdate1[0])
all_unix_gd    = time_double(all_tdates_gd+'/'+start_of_day[0])
n_all_td       = N_ELEMENTS(all_unix_gd)
;;  Define local base data directory
local_base     = root_data_dir()           ;;  e.g., '/Users/lbwilson/data/'
;;  Define CDF file name formats
fname_format   = 'wi_l3-dustimpact_waves_YYYYMMDD_v???.cdf'
;;  Define SPDF base data directory
spdf_base_dir  = 'http://spdf.gsfc.nasa.gov/pub/data/'
;;  Define SPDF path format to data [*** this will change in the future ***]
pathformat     = 'wind'+http_slash[0]+'waves'+http_slash[0]+$
                 'dust_impact_level3'+http_slash[0]+'YYYY'+http_slash[0]+fname_format[0]
;pathformat     = spdf_base_dir[0]+'wind'+http_slash[0]+'waves'+http_slash[0]+$
;                 'dust_impact_level3'+http_slash[0]+'YYYY'+http_slash[0]+fname_format[0]
;;  Define SPDF Wind data directory
spdf_wind_dir  = spdf_base_dir[0]+'wind'+http_slash[0]
;;  Define SPDF Wind/WAVES data directory
spdf_wave_dir  = spdf_wind_dir[0]+'waves'+http_slash[0]
;;  Define SPDF dust impact data directory [*** this will change in the future ***]
spdf_dust_dir  = spdf_wind_dir[0]+'wav_dust'+http_slash[0]
;;----------------------------------------------------------------------------------------
;;  Stuff for TPLOT
;;----------------------------------------------------------------------------------------
sc             = 'Wind'
scpref         = sc[0]+'_'
all_types      = ['A','B','C','D','M']
val_sm_labs    = ['vals','smth']
loc_labs       = ['Clear','Magnetosph','Moon','Both']
typ_labs       = 'Type '+all_types
pos_neg_s      = ['+','-']
pos_neg_w      = ['pos','neg']
vec_str        = ['x','y','z']
ef_names       = 'E'+vec_str
channels       = 'Ch'+['1','2']
;;  LABFLAG settings:  defines lable positions
;;    2  :  locations at vertical location of last component data point shown
;;    1  :  equally spaced with zeroth component at bottom
;;    0  :  no labels shown
;;   -1  :  equally spaced with zeroth component at top
def_labflag    = -1
def__ystyle    = 1
def_pansize    = 2.0
def__xminor    = 5
def_xtcklen    = 0.04
def_ytcklen    = 0.01
;;  TPLOT name suffixes containing numeric data
good_suffx     = ['TDS_Event_'+['Number','Duration'],'Wind_Spin_'+['Rate','Period'],   $
                  'FLAG_'+['Location','XAnt_Cut'],                                     $
                  'Ch01___'+['Peak_amplitude','cc_'+['value','threshold']],            $
                  'MinCh1_threshold','Ch1ImpAnt_E_S_Angle',                            $
                  'Ch02___'+['Peak_amplitude','cc_'+['value','threshold']],            $
                  'MinCh2_threshold','Ch2ImpAnt_E_S_Angle',                            $
                  'Pos_A'+['x_SCS_Angle',['x','y']+'_E_S_Angle','x_E_S_Delta_Angle'],  $
                  'ImpAnt_E_S_Delta_Angle','n_TDS_per_day']
;;  TPLOT name suffixes containing strings
bad_suffx      = ['ImpactAntenna','MorphologicalType']
;;  Define min/max spin period [s] and rate [degrees/s]
mnmx_spperi    = [1d0,5d0]        ;;  min/max spin period [s]
mnmx_sprate    = 36d1/REVERSE(mnmx_spperi)
;;  Define TPLOT YTITLEs
evn_yttl       = 'TDS Event #'
dur_yttl       = 'TDS Duration'+'!C'+'[sec]'
wsr_yttl       = sc[0]+' Spin Rate'+'!C'+'[degrees/sec]'
wsp_yttl       = sc[0]+' Spin Period'+'!C'+'[sec]'
wlf_yttl       = sc[0]+' Location'+'!C'+'Flag'
wac_yttl       = sc[0]+' Ant. Cut'+'!C'+'Flag'
xpk_yttl       = ef_names[0]+' Peak Amp.'+'!C'+'[mV]'
xcv_yttl       = ef_names[0]+' CC Val.'+'!C'+'[unitless]'
xct_yttl       = ef_names[0]+' CC Thresh.'+'!C'+'[unitless]'
xmt_yttl       = ef_names[0]+' Min. Thresh.'+'!C'+'[mV]'
xia_yttl       = ef_names[0]+' Imp. Ant.'+'!C'+'Angle [E-S line vs '+ef_names[0]+', CW, degrees]'
ypk_yttl       = ef_names[1]+' Peak Amp.'+'!C'+'[mV]'
ycv_yttl       = ef_names[1]+' CC Val.'+'!C'+'[unitless]'
yct_yttl       = ef_names[1]+' CC Thresh.'+'!C'+'[unitless]'
ymt_yttl       = ef_names[1]+' Min. Thresh.'+'!C'+'[mV]'
yia_yttl       = ef_names[1]+' Imp. Ant.'+'!C'+'Angle [E-S line vs '+ef_names[1]+', CW, degrees]'
axs_yttl       = '+Ax Angle'+'!C'+'[SC-Sun line vs +Ax, CW, degrees]'
axe_yttl       = '+Ax Angle'+'!C'+'[E-S line vs +Ax, CW, degrees]'
aye_yttl       = '+Ay Angle'+'!C'+'[E-S line vs +Ay, CW, degrees]'
axd_yttl       = 'd(+Ax Angle)'+'!C'+'[Uncert., degrees]'
iad_yttl       = 'd(Imp. Ant.)'+'!C'+'[Uncert., degrees]'
ntd_yttl       = '# TDS'+'!C'+'Per Day'
all_yttls      = [evn_yttl[0],dur_yttl[0],wsr_yttl[0],wsp_yttl[0],wlf_yttl[0],wac_yttl[0],$
                  xpk_yttl[0],xcv_yttl[0],xct_yttl[0],xia_yttl[0],xmt_yttl[0],            $
                  ypk_yttl[0],ycv_yttl[0],yct_yttl[0],yia_yttl[0],ymt_yttl[0],            $
                  axs_yttl[0],axe_yttl[0],aye_yttl[0],axd_yttl[0],iad_yttl[0],            $
                  ntd_yttl[0]]
;;----------------------------------------------------------------------------------------
;;  Initialize external/remote directory locations
;;----------------------------------------------------------------------------------------
;;  Initialize Wind structure
wind_init
;;  Initialize ISTP structure
istp_init
test           = (N_ELEMENTS(source) EQ 0) OR (SIZE(source,/TYPE) NE 8)
IF (test[0]) THEN BEGIN
  ;;  Make sure SOURCE structure is defined
  source         = !istp
  source.LOCAL_DATA_DIR = local_base[0]
ENDIF
;;  Alter remote data directory
;old_remote_dir = !istp.REMOTE_DATA_DIR
;new_remote_dir = spdf_dust_dir[0]
;!istp.REMOTE_DATA_DIR = new_remote_dir[0]
;IF NOT KEYWORD_SET(source) THEN source = !istp
;;----------------------------------------------------------------------------------------
;;  Check keywords
;;----------------------------------------------------------------------------------------
;;  Check TDATE and TRANGE
time_ra        = get_valid_trange(TDATE=tdate,TRANGE=trange)
;;  Define dates and time ranges
tran           = time_ra.UNIX_TRANGE
tdates         = time_ra.DATE_TRANGE        ;;  'YYYY-MM-DD'  e.g., '2009-07-13'
tdate          = tdates[0]                  ;;  Redefine TDATE on output
tdate_st       = tdates[0]
tdate_en       = tdates[1]
;;  Check PREFIX
test           = (N_ELEMENTS(prefix) EQ 0) OR (SIZE(prefix,/TYPE) NE 7)
IF (test[0]) THEN prefix = scpref[0] ELSE prefix = prefix[0]
;;  Check SUFFIX
test           = (N_ELEMENTS(suffix) EQ 0) OR (SIZE(suffix,/TYPE) NE 7)
IF (test[0]) THEN suffix = '' ELSE suffix = suffix[0]

;;----------------------------------------------------------------------------------------
;;  Find files and download
;;----------------------------------------------------------------------------------------
;;  Define relative file paths/HTMLs
;;    base path/url contained within REMOTE_DATA_DIR tag of SOURCE structure
relpathnames   = file_dailynames(FILE_FORMAT=pathformat,TRANGE=tran,ADDMASTER=addmaster)
;;  Get files
test_v64       = (vernf[0] GE 6.4)       ;;  Check IDL version number
IF (test_v64[0]) THEN BEGIN
  ;;  User has ≥ v6.4
  ;;    --> Use IDLnetURL object to retrieve data files
  files          = spd_download(REMOTE_FILE=relpathnames,_EXTRA=source,/LAST_VERSION)
ENDIF ELSE BEGIN
  ;;  User has < v6.4
  ;;    --> Use SOCKET.PRO to retrieve data files
  files          = file_retrieve(relpathnames,_EXTRA=source,/LAST_VERSION)
ENDELSE
;;  Check if user wants only to get the data files
IF KEYWORD_SET(downloadonly) THEN RETURN
;;----------------------------------------------------------------------------------------
;;  Open window
;;----------------------------------------------------------------------------------------
;DEVICE,GET_SCREEN_SIZE=s_size
;wsz            = s_size*7d-1
;win_ttl        = 'Wind Plots ['+tdate_st[0]+' to '+tdate_en[0]+']'
;win_str        = {RETAIN:2,XSIZE:wsz[0],YSIZE:wsz[1],TITLE:win_ttl[0],XPOS:10,YPOS:10}
;WINDOW,0,_EXTRA=win_str
;;  Set TPLOT time span
timespan,tran[0],(tran[1] - tran[0]),/SECONDS
;;----------------------------------------------------------------------------------------
;;  Load all CDF data into TPLOT
;;----------------------------------------------------------------------------------------
prefix         = scpref[0]
n_cdf          = N_ELEMENTS(files)
cdf2tplot,files,PREFIX=prefix,MIDFIX=midfix,MIDPOS=midpos,SUFFIX=suffix,     $
                NEWNAME=newname,VARFORMAT='*',VARNAMES=varnames2,ALL=all,    $
                VERBOSE=verbose,/GET_SUPPORT_DATA,/CONVERT_INT1_TO_INT2,     $
                RECORD=record,TPLOTNAMES=tplotnames,LOAD_LABELS=load_labels
;;  Define TPLOT names containing numeric and string data
tpn_dat_tpns   = tnames('*_'+good_suffx)
tpn_str_tpns   = tnames('*_'+bad_suffx)
;;  Change options for good outputs
options,tpn_dat_tpns,'YTITLE'
options,tpn_dat_tpns,'YSUBTITLE'
options,tpn_dat_tpns,'YSUBTITLE',/DEF
options,tpn_dat_tpns,'PSYM'
options,tpn_dat_tpns,PSYM=2,COLORS=50,/DEF
options,tnames('*_Wind_Spin_Rate'),  'MAX_VALUE'
options,tnames('*_Wind_Spin_Rate'),  'MIN_VALUE'
options,tnames('*_Wind_Spin_Period'),'MAX_VALUE'
options,tnames('*_Wind_Spin_Period'),'MIN_VALUE'
;options,tnames('*_Wind_Spin_Period'),MAX_VALUE=5d0,MIN_VALUE=1d0,/DEF
;options,tnames('*_Wind_Spin_Rate'),  MAX_VALUE=36d1/1d0,MIN_VALUE=36d1/5d0,/DEF
options,tnames('*_Wind_Spin_Period'),MIN_VALUE=mnmx_spperi[0],MAX_VALUE=mnmx_spperi[1],/DEF
options,tnames('*_Wind_Spin_Rate'),  MIN_VALUE=mnmx_sprate[0],MAX_VALUE=mnmx_sprate[1],/DEF
;;  Set TPLOT YTITLEs
n_tpn          = N_ELEMENTS(all_yttls)
FOR j=0L, n_tpn[0] - 1L DO options,tpn_dat_tpns[j],YTITLE=all_yttls[j],/DEF
;;  Define TPLOT defaults
tplot_options,  'YMARGIN',[4,4]
tplot_options,  'XMARGIN',[20,20]
tplot_options,  'LABFLAG',def_labflag[0]
nnw            = tnames()
options,nnw,YSTYLE=def__ystyle[0],YSTYLE=def__ystyle[0],PANEL_SIZE=def_pansize[0],$
            XMINOR=def__xminor[0],XTICKLEN=def_xtcklen[0],YTICKLEN=def_ytcklen[0],$
            LABFLAG=def_labflag[0],/DEF
;;  Remove any remnant options
nna            = [tpn_dat_tpns,tpn_str_tpns]
options,nna,       'YLOG'
options,nna,'X_NO_INTERP'
options,nna,'X_NO_INTERP'
options,nna,  'NO_INTERP'








RETURN
END