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

pro rbsp_efw_phasef_read_e_spinfit_diagonal_gen_file, time, probe=probe, filename=file, pairs=pairs, 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

    if n_elements(pairs) eq 0 then pairs = ['13','14','23','24']
    ; New values, Sheng, 2021-01-08.
    sun2sensor_info = dictionary($
        'v13', 45d, $
        'v14', -45d, $
        'v23', 135d, $
        'v24', -135d )


;---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 combo data.
    rbsp_efw_phasef_read_e_uvw_diagonal, tr, probe=probe, pairs=pairs
    spin_axis_var = rbspx+'_wsc_gse'
    e_spinfit_vars = rbspx+'_efw_esvy_'+pairs

    foreach pair, pairs, pair_id do begin
        sun2sensor = sun2sensor_info['v'+pair]

        ; Expand the wanted pair to 3D, because spinfit needs 3D inputs.
        e_combo_var = e_spinfit_vars[pair_id]
        e_uvw_var = prefix+'e_combo_'+pair
        get_data, e_combo_var, times, edata
        ntime = n_elements(times)
        tmp = fltarr(ntime)
        edata = [[edata],[tmp],[tmp]]
        data_att = {coord_sys:'uvw'}
        dlim = {data_att:data_att}
        store_data, e_uvw_var, times, edata, dlimits=dlim

        spinfit_var = e_uvw_var+'_spinfit'
        rbsp_efw_phasef_spinfit, e_uvw_var, plane_dim=0, sun2sensor=sun2sensor, force=1
        ;rbsp_spinfit, e_uvw_var, plane_dim=0, sun2sensor=sun2sensor, force=1
        dsc_var = prefix+'e_spinfit_v'+pair+'_dsc'
        the_var = prefix+'e_spinfit_mgse_v'+pair

        ; Transform the spinfit data from DSC to MGSE (AARON'S UPDATED VERSION which is very fast and gives same result as old method)
        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.
    e_combo_spinfit_vars = prefix+'e_spinfit_mgse_v'+pairs
    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

        ;
        ;    test_pair = '24'
        ;    vars = prefix+['e_spinfit_mgse_v'+test_pair,'emod_mgse']
        ;    foreach var, vars do begin
        ;        get_data, var, times, data
        ;        store_data, var+'_mag', times, snorm(data)
        ;    endforeach
        ;    dif_data, vars[0], vars[1], newname=prefix+'de_mgse_v'+test_pair
        ;    dif_data, vars[0]+'_mag', vars[1]+'_mag', newname=prefix+'de_mag_v'+test_pair
        ;
        ;    get_data, vars[0], times, epair, limits=lim
        ;    emod = get_var_data(vars[1], at=times)
        ;    store_data, 'angle', times, sang(epair, emod, /deg), limits={constant:10, yrange:[0,20]}
        ;    store_data, 'de_before', times, epair-emod, limits=lim
        ;    srotate, epair, -10, /deg, 0
        ;    store_data, 'de_after', times, epair-emod, limits=lim
        ;    tplot, ['de_before','angle','de_after']
        ;
        ;    stop


        foreach e_var, e_combo_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 diagonal 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 = e_combo_spinfit_vars
    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 = (probe eq 'a')? time_double(['2012-09-08','2019-10-14']): time_double(['2012-09-08','2019-07-16'])
    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_diagonal_spinfit',str_year])
        base = prefix+'efw_e_diagonal_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_diagonal_gen_file, day, probe=probe, filename=file
    endforeach
endforeach


stop



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

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

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

;; Data gap in spin phase.
;time = time_double('2016-01-12')
;probe = 'a'
;
;; Test a random day.
;time = time_double('2013-06-07')
;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_diagonal_gen_file, time, probe=probe, filename=file
toc
end
