;+
; Sun pulse time is used to do spinfit, save this to avoid recalc and to ensure all spinfit data are on the same times.
;-

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


;---Load spin related info.
    ; Get the time range.
    secofday = 86400d
    date = time-(time mod secofday)
    time_range = date+[0,secofday]
    rbspx = 'rbsp'+probe
    prefix = 'rbsp'+probe+'_'

    rbsp_read_spice_var, time_range, probe=probe
    tper = prefix+'spinper'
    tphase = prefix+'spinphase'
    if check_if_update(tper, time_range) eq 1 then begin
        errmsg = handle_error('No spin period data ...')
        return
    endif

;---New algorithm.
    full_circle = 360d
    get_data, tphase, phase_times, phase_data
    get_data, tper, phase_times, period_data
    period_range = [0d,15]   ; to work with commisional phase.
    index = lazy_where(period_data, ')(', period_range, count=count)
    fillval = !values.f_nan
    if count ne 0 then begin
        phase_data[index] = fillval
        period_data[index] = fillval
        store_data, tphase, phase_times, phase_data
        store_data, tper, phase_times, period_data
    endif
    index = where(finite(phase_data) and phase_data ge 0 and phase_data le full_circle, count)
    good_sections = phase_times[time_to_range(index,time_step=1)]
    ngood_section = n_elements(good_sections)*0.5

    sunpulse_times = []
    for section_id=0,ngood_section-1 do begin
        index = lazy_where(phase_times, '[]', good_sections[section_id,*], count=count)
        if count eq 0 then continue
        times = phase_times[index]
        phase = phase_data[index]

        ntime = n_elements(times)
        for ii=1,ntime-1 do begin
            if phase[ii] lt phase[ii-1] then phase[ii:*] += full_circle
        endfor
        max_phase = max(phase, min=min_phase)
        phase_range = [min_phase, max_phase]
        sunpulse_phases = make_bins(phase_range, full_circle, /inner)
        ncycle = n_elements(sunpulse_phases)
        if ncycle eq 0 then continue
        sunpulse_times = [sunpulse_times,interpol(times, phase, sunpulse_phases)]
    endfor
    tmp_var = tper+'_tmp'
    copy_data, tper, tmp_var
    interp_time, tmp_var, sunpulse_times
    sunpulse_periods = get_var_data(tmp_var)
    sunpulse_var = prefix+'sunpulse_times'
    store_data, sunpulse_var, sunpulse_times, float(sunpulse_periods)


;---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 sun pulse time for spinfit', $
        'TEXT', 'Generated by Sheng Tian at the University of Minnesota' )
    cdf_save_setting, ginfo, filename=file
    save_vars = sunpulse_var
    stplot2cdf, save_vars, istp=1, filename=file, time_var='epoch'

end

;stop
probes = ['a','b']
root_dir = join_path([rbsp_efw_phasef_local_root()])
foreach probe, probes do begin
    prefix = 'rbsp'+probe+'_'
    rbspx = 'rbsp'+probe
    time_range = rbsp_efw_phasef_get_valid_range('sunpulse_time', 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,'efw_phasef','sunpulse_time',rbspx,str_year])
        base = prefix+'efw_sunpulse_time_'+time_string(day,tformat='YYYY_MMDD')+'_v01.cdf'
        file = join_path([path,base])
if file_test(file) eq 1 then continue
        rbsp_efw_phasef_read_sunpulse_time_gen_file, day, probe=probe, filename=file
    endforeach
endforeach


stop




time = time_double('2018-06-07')
probe = 'a'
file = join_path([homedir(),'test.cdf'])
rbsp_efw_phasef_read_sunpulse_time_gen_file, time, probe=probe, filename=file
end
