#!/bin/python
# Filename findclosest_n.py

__author__ = 'Jacob Hedelius'  # oh yeah!

def findclosest_n(x_vec, ind, n):
    
    # This function finds the closest n values of x_vec elements in search index ind
    # inputs should be vectors (single column arrays/lists, of numbers)
    # the outputs are quite similar to the matlab version, except if the absolute difference is the same
    # for example, if we're looking for the closest numbers to 2 out of 1 & 3, matlab will choose the 1
    # this python function will choose the 3
    
    # # Sub-functions to include/import
    #    from egi_subs import *  # import in my common library
    #    import egi_subs as egs
    import numpy as np
    
    
    #    # test values
    #    x_vec = range(101)  # range of 0 to 100
    #    ind = egs.frange(0, 110, 1.2)
    #n = 5
    #ind = zeno_date
    #x_vec = filedates
    
    # ind_length = len(ind);
    # print(ind[ind_length-1])
    
    # convert IND and x_vec to np arrays
    x_vec_np = np.array(x_vec)
    ind_np = np.array(ind)
    
    if type(n).__name__ != 'int':  # quick check to see that n is an integer
        print('n is NOT int')
    
    n = np.min([n, len(ind_np)])  # if n is larger than the size of the index, n is set to the index length
    closest_indx = np.zeros([len(x_vec), n])  # pre-allocation for speed
    closest_indx_value = np.zeros([len(x_vec), n])  # pafs
    closest_indx_diff = np.zeros([len(x_vec), n])   # pafs
    
    i1 = -1
    for x_val in x_vec_np:
        i1 += 1  # increase iteration by 1
        diff_vals = x_val - ind_np
        abs_diffs = np.absolute(diff_vals)
        sortIND = np.argsort(abs_diffs,0)
        closest_indx[i1, :] = np.squeeze(sortIND[0:n])
        closest_indx_diff[i1, :] = np.squeeze(diff_vals[sortIND[0:n]])
        closest_indx_value[i1, :] = np.squeeze(ind_np[sortIND[0:n]])
        
        
    # print(closest_indx_value)
    
    
    out = []
    out.append({'closest_ind': closest_indx, 'closest_ind_diff': closest_indx_diff, 'closest_ind_val': closest_indx_value})
    #return closest_indx, closest_indx_diff, closest_indx_value
    return out
