;+
; Scan L2 esvy data for irregular time tags.
;-

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
    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 = times-pre_times
        index = where(dtimes lt 0, 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

time_range = time_double('2014'+['-01-01','-12-31'])
time_range = time_double('2017'+['-04-13','-04-15'])
;time_range = time_double('2014'+['-05-07','-05-08'])
probe = 'a'
file = join_path([homedir(),'test.cdf'])
rbsp_efw_read_l1_time_tag_irregularity_gen_file, time_range, probe=probe, filename=file, errmsg=errmsg
end