;+
; Scan L2 esvy data for timg tag jump of +/-1 sec.
;-

pro rbsp_efw_read_l1_time_tag_irregularity_gen_file, time_range, probe=probe, filename=file, errmsg=errmsg


;---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_range) lt 2 then begin
        errmsg = handle_error('No input time range ...')
        return
    endif


;---Constants and settings.
    secofday = 86400d
    days = make_bins(time_range+[-1,0]*secofday, secofday)
    nday = n_elements(days)-1
    prefix = 'rbsp'+probe+'_'
    rbspx = 'rbsp'+probe

;---Locate L1 files.
    local_root = join_path([default_local_root(),'rbsp'])
    version = 'v*'
    cdf_files = strarr(n_elements(days))
    foreach day, days, day_id do begin
        base_name = rbspx+'_l1_esvy_%Y%m%d_'+version+'.cdf'
        local_path = [local_root,rbspx,'l1','esvy','%Y']
        remote_path = ['http://themis.ssl.berkeley.edu/data/rbsp', $
            rbspx,'l1','esvy','%Y']
        local_file = apply_time_to_pattern(join_path([local_path,base_name]), day)
        files = file_search(local_file)
        cdf_files[day_id] = files[-1]
    endforeach


;---Loop through each day.
    current_times = []
    previous_times = []
    common_time_step = 1d/32
    wanted_dtime = 1.
    foreach day, days, day_id do begin
        if day_id eq 0 then continue
        lprmsg, 'Processing '+time_string(day)+' ...'
        the_files = cdf_files[day_id-1:day_id]
        if file_test(the_files[1]) eq 0 then continue  ; no data for the current day.
        epochs = cdf_read_var('epoch', filename=the_files[1])
        times = convert_time(epochs, from='epoch16', to='unix')
        pre_times = [0,times[0:-2]]
        if file_test(the_files[0]) eq 1 then begin
            epochs = cdf_read_var('epoch', filename=the_files[0])
            pre_times[0] = convert_time(epochs[-1], from='epoch16', to='unix')
        endif
        dtimes = round(abs(times-pre_times))
        index = where(dtimes eq wanted_dtime, count)
        if count eq 0 then continue
        current_times = [current_times, times[index]]
        previous_times = [previous_times, pre_times[index]]
    endforeach


;---Init file.
    out_dir = fgetpath(file)
    if file_test(out_dir,/directory) eq 0 then file_mkdir, out_dir
    data_file = file
    if file_test(data_file) eq 1 then file_delete, data_file  ; overwrite old files.
    cdf_id = cdf_create(data_file)
    ginfo = dictionary($
        'TITLE', 'RBSP EFW times of potential time tag shift', $
        'TEXT', 'Generated by Sheng Tian at the University of Minnesota' )
    cdf_save_setting, ginfo, filename=cdf_id

    if n_elements(current_times) eq 0 then begin
        cdf_close, cdf_id
        return
    endif

    utname = 'epoch'
    data = convert_time(current_times, from='unix', to='epoch')
    settings = dictionary($
        'FIELDNAM', 'Epoch', $
        'UNITS', 'msec', $
        'VAR_TYPE', 'support_data' )
    cdf_save_var, utname, value=data, filename=cdf_id, cdf_type='CDF_EPOCH'
    cdf_save_setting, settings, var=utname, filename=cdf_id

    the_var = 'epoch_previous'
    data = convert_time(previous_times, from='unix', to='epoch')
    settings = dictionary($
        'DEPEND_0', utname, $
        'FIELDNAM', 'Epoch previous', $
        'UNITS', 'msec', $
        'VAR_TYPE', 'data' )
    cdf_save_var, the_var, value=data, filename=cdf_id, cdf_type='CDF_EPOCH'
    cdf_save_setting, settings, var=the_var, filename=cdf_id

    the_var = 'time_diff'
    data = current_times-previous_times
    settings = dictionary($
        'DEPEND_0', utname, $
        'FIELDNAM', 'current time - previous time', $
        'UNITS', 'sec', $
        'VAR_TYPE', 'data' )
    cdf_save_var, the_var, value=data, filename=cdf_id, cdf_type='CDF_EPOCH'
    cdf_save_setting, settings, var=the_var, filename=cdf_id

    cdf_close, cdf_id

end





log_file = join_path([homedir(),'rbsp_l1_time_tag_irregularity.txt'])
if file_test(log_file) eq 1 then file_delete, log_file
ftouch, log_file
tab = '    '
tformat = 'YYYY-MM-DD/hh:mm:ss.ffffff'
foreach probe, ['a','b'] do begin
    prefix = 'rbsp'+probe+'_'
    file = join_path([homedir(),'rbsp'+probe+'_l1_time_tag_irregularity.cdf'])
    times = convert_time(cdf_read_var('epoch', filename=file),from='epoch',to='unix')
    pre_times = convert_time(cdf_read_var('epoch_previous', filename=file),from='epoch',to='unix')
    rbx = 'RB-'+strupcase(probe)
    dtimes = times-pre_times
    foreach time, times, ii do begin
        msg = rbx+tab+time_string(time,tformat=tformat)+tab+time_string(pre_times[ii],tformat=tformat)+tab+string(dtimes[ii])
        lprmsg, msg, log_file
    endforeach
endforeach
stop


foreach probe, ['a','b'] do begin
    case probe of
        'a': time_range = time_double(['2012-09-09','2019-10-14'])
        'b': time_range = time_double(['2012-09-09','2019-07-16'])
    endcase
    file = join_path([homedir(),'rbsp'+probe+'_l1_time_tag_irregularity.cdf'])
    rbsp_efw_read_l1_time_tag_irregularity_gen_file, time_range, probe=probe, filename=file, errmsg=errmsg
endforeach
end



