# -*- coding: utf-8 -*-
"""
Created on Sat Aug  1 17:10:16 2015

@author: Jacob Hedelius
"""

__author__ = 'Jacob Hedelius'

def read_top_params(filename):

    # This function is meant to read in the 2014 version of .top files, and save
    # them into a structure/dictionary
    # example data
    #ex_filename = 'C:\\Users\\Jacob Hedelius\\Documents\\Research\\python\\example_data\\cn20140613opus-ipp.top'
    #filename = ex_filename
    
    # import packages
    import numpy as np
    #import re
    import egi_subs as egs
    
    # read in file
    fobj = open(filename, 'r') # gets file object for reading
    file_lines = fobj.readlines() #reads in entire file all at once, line by line
    fobj.close() #closes open file
    
    param_lines = np.zeros([len(file_lines),1]) #pre-allocates
    i1=0
    for line_i1 in file_lines:
        semicolontest = line_i1.find(':') #searches for FIRST semicolon in string
        if (semicolontest != 0 and not line_i1.isspace()):
            param_lines[i1] = 1;
        
        i1 += 1 #adds one to iterate
    
    param_lines2 = np.nonzero(param_lines) #makes an index of the lines useful parameters are on
    param_lines3 = param_lines2[0]
    
    parameters_list = ['ifgs_loc_1', 'spec_loc_2', 'save_new_ifgs_3', 'save_new_ifgs_loc_4',
        'save_phasecurves_5', 'save_phasecurves_loc_6', 'channels_7', 'freq_lims_8',
        'naming_conv_9', 'light_source_ind_10', 'channel_ind_ifg_11', 'channel_ind_spec_12',
        'output_form_13', 'ascii_field_sep_14', 'ascii_minmax_pairs_15', 'qc_suntracker_16',
        'qc_min_zpd_peaks_17', 'qc_cross_corr_18', 'add_get_utc_19', 'max_scans_20',
        'max_ifg_points_21', 'freq_lim_siv_corr_22', 'type_lse_23', 'length_phase_op_24',
        'frac_int_use_spec_pt_pco_25', 'amount_processing_26', 'verbosity_27'];
    
    if len(parameters_list) != ( len(param_lines2[0]) ):
        raise ValueError('unrecognized .top file format')
    
    i1 = 0
    out = {parameters_list[0]: ''} #preparing dictionary for writing
    for param_i1 in parameters_list:
        pi1_ds = egs.is_number(file_lines[param_lines3[i1]])
        if pi1_ds == 1: #is a number
            out[parameters_list[i1]] = float(file_lines[param_lines3[i1]])
        else:
            out[parameters_list[i1]] = file_lines[param_lines3[i1]]
        
        i1 +=1
    
    return out
    
