;+
; Generate E spinfit for 12 and 34 pairs, based on the calibrated E UVW.
;-

pro rbsp_efw_phasef_read_e_spinfit_gen_file, time, probe=probe, filename=file, keep_e_model=keep_e_model

;---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

    pairs = ['12','34']
    sun2sensor_info = dictionary($
        'v12', 0d, $
        'v34', 90d )



;---Do spinfit.
    ; Get the time range.
    secofday = 86400d
    date = time-(time mod secofday)
    tr = date+[0,secofday]
    rbspx = 'rbsp'+probe
    prefix = 'rbsp'+probe+'_'
    timespan, tr[0], total(tr*[-1,1]), /seconds

    rbsp_read_spice_var, tr, probe=probe
    rbsp_efw_phasef_read_sunpulse_time, tr, probe=probe
    get_data, prefix+'sunpulse_times', common_times

    ; Restore the calibrated E UVW data.
    rbsp_efw_phasef_read_e_uvw, tr, probe=probe
    spin_axis_var = rbspx+'_wsc_gse'
    e_spinfit_vars = prefix+'e_spinfit_mgse_v'+pairs

    e_uvw_var = rbspx+'_e_uvw'
    ; Add UVW to dlim to tell spinfit the coord.
    data_att = {coord_sys:'uvw'}
    dlim = {data_att:data_att}
    store_data, e_uvw_var, dlimits=dlim

    spinfit_var = e_uvw_var+'_spinfit'
    foreach pair, pairs, pair_id do begin
        rbsp_efw_phasef_spinfit, e_uvw_var, plane_dim=pair_id;, sheng_test=1
        dsc_var = prefix+'e_spinfit_v'+pair+'_dsc'
        the_var = prefix+'e_spinfit_mgse_v'+pair
        ; DSC to MGSE.
        copy_data, spinfit_var, dsc_var
        rbsp_efw_dsc_to_mgse, probe, dsc_var, spin_axis_var
        mgse_var = dsc_var+'_mgse'
        copy_data, mgse_var, the_var
        interp_time, the_var, common_times
    endforeach


;---Remove E_model.
    if ~keyword_set(keep_e_model) then begin
        rbsp_read_e_model, tr, probe=probe
        e_model_var = rbspx+'_emod_mgse'
        interp_time, e_model_var, common_times
        ; Clear MGSE x.
        get_data, e_model_var, uts, data
        data[*,0] = 0
        store_data, e_model_var, uts, data

        foreach e_var, e_spinfit_vars do begin
            dif_data, e_var, e_model_var, newname=e_var
        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 E spinfit for opposite boom pairs', $
        '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 = prefix+'e_spinfit_mgse_v'+pairs
    get_data, save_vars[0], common_times
    foreach save_var, save_vars do begin
        interp_time, save_var, common_times
        get_data, save_var, times, e_uvw
        store_data, save_var, times, float(e_uvw), limits={units:'mV/m', coord:'mgse'}
    endforeach
    stplot2cdf, save_vars, istp=1, filename=file, time_var='epoch'

end


;stop
;probes = ['b']
;root_dir = join_path([homedir(),'data','rbsp'])
;foreach probe, probes do begin
;    prefix = 'rbsp'+probe+'_'
;    rbspx = 'rbsp'+probe
;    time_range = rbsp_efw_phasef_get_valid_range('spinfit', probe=probe)
;    days = make_bins(time_range, constant('secofday'))
;    foreach day, days do begin
;        str_year = time_string(day,tformat='YYYY')
;        path = join_path([root_dir,rbspx,'e_spinfit',str_year])
;        base = prefix+'efw_e_spinfit_mgse_'+time_string(day,tformat='YYYY_MMDD')+'_v02.cdf'
;        file = join_path([path,base])
;        if file_test(file) eq 1 then continue
;        rbsp_efw_phasef_read_e_spinfit_gen_file, day, probe=probe, filename=file
;    endforeach
;endforeach
;
;stop



time = time_double('2014-08-01')
probe = 'a'

; Jump around 14:23 UT.
time = time_double('2018-09-18')
probe = 'a'

; Data gap in spin phase.
time = time_double('2016-01-12')
probe = 'a'

time = time_double('2016-01-13')
probe = 'a'

time = time_double('2013-06-07')
probe = 'a'

; E from different combo do not have the same # of record.
time = time_double('2012-11-29')
probe = 'a'

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