;+
; Adopted from rbsp_efw_spinfit_vxb_subtract_crib
;
;-

pro rbsp_efw_phasef_read_e_uvw_diagonal_gen_file, time, probe=probe, filename=file

;---Check inputs.
    if n_elements(file) eq 0 then begin
        errmsg = handle_error('No output file ...')
        return
    endif

    if n_elements(probe) eq 0 then begin
        errmsg = handle_error('No input probe ...')
        return
    endif

    if n_elements(time) eq 0 then begin
        errmsg = handle_error('No input time ...')
        return
    endif


;---Constants and settings.
    secofday = 86400d
    errmsg = ''


;---Load E UVW.
    rbspx = 'rbsp'+probe
    prefix = 'rbsp'+probe+'_'
    date = time[0]-(time[0] mod secofday)
    time_range = date+[0,secofday]
    tr = time_range+[-1,1]*60d
    timespan, tr[0], total(tr*[-1,1]), /seconds
    ; Time tag corrections have been applied in this phasef vsvy data.
    rbsp_efw_phasef_read_vsvy, time_range, probe=probe
    l1_var = prefix+'efw_vsvy'
    get_data, l1_var, times, vsvy
    if n_elements(times) le 2 then return

;---Construct E combo.
    ; Get boom length.
    cp0 = rbsp_efw_get_cal_params(tr[0])
    cp = (probe eq 'a')? cp0.a: cp0.b
    boom_length = cp.boom_length
    boom_shorting_factor = cp.boom_shorting_factor

    boom_length_adj = sqrt(2)*boom_length[0]*0.5
    pairs = ['13','14','23','24']
    foreach pair, pairs do begin
        idx = [strmid(pair,0,1),strmid(pair,1,1)]-1
        edata = (vsvy[*,idx[0]]-vsvy[*,idx[1]])*(1000./boom_length_adj)
        e_var = prefix+'efw_esvy_'+pair
        store_data, e_var, times, edata, $
            limits={units:'mV/m', coord:'uvw', labels:pair}
    endforeach


;---Remove DC offset.
    spin_period = 11d   ; the rough number works fine, no need to get the accurate number
    dt = median(times[1:-1]-times[0:-2])
    width = spin_period/dt
    e_vars = prefix+'efw_esvy_'+pairs
    foreach e_var, e_vars do begin
        get_data, e_var, times, edata
        offset1 = smooth(edata, width, /nan, /edge_zero)
        offset2 = smooth(offset1, width, /nan, /edge_zero)
        edata -= offset2
        store_data, e_var, times, float(edata)
    endforeach
    ; Trim data to the wanted time range.
    index = where(times ge time_range[0] and times lt time_range[1], count)
    if count ne 0 then begin
        foreach e_var, e_vars do begin
            get_data, e_var, times, edata
            store_data, e_var, times[index], edata[index]
        endforeach
    endif


;---Save data.
    path = fgetpath(file)
    if file_test(path,/directory) eq 0 then file_mkdir, path
    data_file = file
    if file_test(data_file) eq 1 then file_delete, data_file  ; overwrite old files.

    ginfo = dictionary($
        'TITLE', 'RBSP EFW calibrated E combo in the spacecraft frame', $
        'TEXT', 'Generated by Sheng Tian at the University of Minnesota, adopted from rbsp_efw_spinfit_vxb_crib' )
    cdf_save_setting, ginfo, filename=file
    save_vars = e_vars
    stplot2cdf, save_vars, istp=1, filename=file, time_var='epoch'

end


;stop
;probes = ['a','b']
;root_dir = join_path([diskdir('data'),'rbsp'])
;foreach probe, probes do begin
;    prefix = 'rbsp'+probe+'_'
;    rbspx = 'rbsp'+probe
;    time_range = rbsp_efw_phasef_get_valid_range('e_uvw', probe=probe)
;;time_range = time_range>time_double('2016-01-01')
;    days = make_bins(time_range, constant('secofday'))
;    foreach day, days do begin
;        str_year = time_string(day,tformat='YYYY')
;        path = join_path([root_dir,'efw_phasef','e_uvw_diagonal',rbspx,str_year])
;        base = prefix+'efw_e_uvw_diagonal_'+time_string(day,tformat='YYYY_MMDD')+'_v01.cdf'
;        file = join_path([path,base])
;        rbsp_efw_phasef_read_e_uvw_diagonal_gen_file, day, probe=probe, filename=file
;    endforeach
;endforeach
;stop

probe = 'a'
time = time_double(['2016-01-01'])
;time = time_double(['2013-01-01'])
probe = 'b'
time = time_double('2015-07-01')

; Beyond the last day.
probe = 'b'
time = time_double('2019-07-17')

file = join_path([homedir(),'test.cdf'])
if file_test(file) eq 1 then file_delete, file
rbsp_efw_phasef_read_e_uvw_diagonal_gen_file, time, probe=probe, filename=file
end
