;+
; Use E UVW -> E MGSE to fit the perigee residue.
;-

pro rbsp_efw_phasef_read_e_fit_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

    prefix = 'rbsp'+probe+'_'

;---Load all fit coef.
    fit_list = rbsp_efw_phasef_read_e_fit_param(probe=probe)
    nsection = fit_list.length
    section_times = dblarr(nsection,2)
    foreach fit_info, fit_list, fit_id do section_times[fit_id,*] = fit_info.time_range
    section_times[1:nsection-1,0] = section_times[0:nsection-2,1]

;---Filter the ones overlap with the current day.
    secofday = constant('secofday')
    date = time-(time mod secofday)
    time_range = date+[0,secofday]
    section_index = []
    for ii=0,nsection-1 do begin
        if section_times[ii,1] lt time_range[0] then continue
        if section_times[ii,0] gt time_range[1] then continue
        section_index = [section_index,ii]
    endfor

    fit_list = fit_list[section_index]
    section_times = section_times[section_index,*]
    nsection = n_elements(section_index)
    for ii=0,nsection-1 do fit_list[ii].time_range = reform(section_times[ii,*])

;---Load data to prepare the fit.
    rbsp_efw_phasef_read_wobble_free_var, time_range, probe=probe
    rbsp_read_e_model, time_range, probe=probe, datatype='e_model_related'
    b_mgse = get_var_data(prefix+'b_mgse', times=common_times)
    v_mgse = get_var_data(prefix+'v_mgse')
    vcoro_mgse = get_var_data(prefix+'vcoro_mgse')
    u_mgse = (v_mgse-vcoro_mgse)*1e-3

    ndim = 3
    ncommon_time = n_elements(common_times)
    xxs = fltarr(ndim,ncommon_time,ndim)
    ; For Ey.
    xxs[0,*,1] =  u_mgse[*,0]*b_mgse[*,1]
    xxs[1,*,1] = -u_mgse[*,0]*b_mgse[*,0]-u_mgse[*,2]*b_mgse[*,2]
    xxs[2,*,1] =  u_mgse[*,2]*b_mgse[*,1]
    ; For Ez.
    xxs[0,*,2] =  u_mgse[*,0]*b_mgse[*,2]
    xxs[1,*,2] =  u_mgse[*,1]*b_mgse[*,0]
    xxs[2,*,2] = -u_mgse[*,0]*b_mgse[*,0]-u_mgse[*,1]*b_mgse[*,1]

    efit_mgse = fltarr(ncommon_time,ndim)
    fit_index = [1,2]
    foreach fit_info, fit_list do begin
        fit_coef = fltarr(ndim+1,ndim)
        fit_coef[*,1] = fit_info.y
        fit_coef[*,2] = fit_info.z
        section_time_range = fit_info.time_range
        time_index = lazy_where(common_times,'[]',section_time_range)
        foreach jj, fit_index do begin
            res = fit_coef[0:2,jj]
            efit_mgse[time_index,jj] = reform(xxs[*,time_index,jj] ## res)
        endforeach
    endforeach
    efit_var = prefix+'efit_mgse'
    store_data, efit_var, common_times, float(efit_mgse), limits={$
        units: 'mV/m', $
        coord: 'MGSE' }


;---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 fit MGSE in the corotation frame', $
        'TEXT', 'Generated by Sheng Tian at the University of Minnesota' )
    cdf_save_setting, ginfo, filename=file
    stplot2cdf, efit_var, istp=1, filename=file, time_var='epoch'

end


probes = ['b']
root_dir = join_path([rbsp_efw_phasef_local_root()])
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_fit',str_year])
        base = prefix+'efw_efit_'+time_string(day,tformat='YYYY_MMDD')+'_v01.cdf'
        file = join_path([path,base])
        rbsp_efw_phasef_read_e_fit_gen_file, day, probe=probe, filename=file
    endforeach
endforeach


stop
time = time_double('2013-06-07')
;time = time_double('2013-06-06')
probe = 'a'
file = join_path([homedir(),'test.cdf'])
if file_test(file) eq 1 then file_delete, file
rbsp_efw_phasef_read_e_fit_gen_file, time, probe=probe, filename=file
end
