function out = findclosestdaily_n(X, IND, n)
% findclosest
% supposed to find the closest n values of X elements in search index IND
% inputs should be vectors (indexing X to IND)
% This assumes that the inputs are matlab dates and that we are searching
% for closest indicies on a daily basis

% test values
% X = (0:1:100);
% IND = (0:1.2:100*1.1);
% n = 5;
% X = TCCON_other_time_1970;
% IND = TCCON_time_1970;
% max_dist = .5;
% IND = IND1(randperm(length(IND1)));
% X = X1(randperm(length(X1)));

% timer1 = cputime;

% data input check
if (size(X,1) ~=1 && size(X,2)~=1) || (size(IND,1)~=1 && size(IND,2)~=1) || length(n) ~=1;
    error('Mis-sized inputs. X and IND are vectors, n is a scalar')
end

% [IND_ordered, IND_original_ind] = sort(IND); %puts IND into ascending order if it isn't already
start_day = min(floor(X));
end_day = max(floor(X));

n = min(n, length(IND)); %if n is larger than the size of the index, this scales n back
closest_indx = zeros(length(X), n); %preallocated for speed
closest_indx_value = zeros(length(X),n); %preallocated for speed
closest_indx_diff = zeros(length(X),n); %preallocated for speed

se_i2 = [1 0];
warn_emptyday=0;
for i2=start_day:end_day;
    Xday = X(floor(X) == i2); %x values for day
    ind_INDday = find(floor(IND) == i2); %index of index for day
    INDday = IND(ind_INDday); %index values for day
    
    if ~isempty(Xday);
        if ~isempty(INDday);
            day_indx = NaN*zeros(length(Xday), n); %pafs
            day_indx_value = NaN*zeros(length(Xday),n); %pafs
            day_indx_diff = NaN*zeros(length(Xday),n); %pafs
            
            day_n = min([n, length(INDday)]);
            for i1=1:length(Xday)
                diff_vals = Xday(i1) - INDday;
                [sortB, sortIND] = sort(abs(diff_vals));
                day_indx_diff(i1,1:day_n) = diff_vals(sortIND(1:day_n)); %input and output should be 1:n
                day_indx(i1, 1:day_n) = ind_INDday( sortIND(1:day_n) ); %references back to original index
                day_indx_value(i1, 1:day_n) = INDday(sortIND(1:day_n));
            end
            
        elseif ~isempty(Xday); %data for Xday, but no index data
            if warn_emptyday ~=1;
                warning('Warning: Some of the input X days do not have matching index days. Look for NaNs, setting to 1')
                warn_emptyday=1;
            end
            day_indx_diff = NaN(length(Xday), n); % Nan or (max(X)-min(X))*100 to represent bad value
            day_indx = ones(length(Xday), n); %setting all to 1
            day_indx_value = NaN(length(Xday), n); % Nan or (max(X))*10 to represent bad value
            
        end
            
        se_i2(2) = se_i2(2) + length(Xday);
        closest_indx_diff(se_i2(1):se_i2(2),:) = day_indx_diff;
        closest_indx(se_i2(1):se_i2(2), :)     = day_indx; 
        closest_indx_value(se_i2(1):se_i2(2), :) = day_indx_value;
        se_i2(1) = se_i2(1) + length(Xday);
        
    end
end

%     search_start = 1;
%     search_end = length(IND);
%     while search_start<=search_end
%         mid = round((search_start+search_end)/2); %indexes mid-point since last search
%         diff = X(i1) - IND_ordered(mid); %difference between mid-point value of index and of search values
%             if diff == 0; %if there is an exact match
%                 closest_indx(i1) = IND_original_ind(mid); %indexes where X(i) would be in original IND vector
%                 closest_indx_value(i1) = IND_ordered(mid); %indexes the nearest index value of X(i)
%                 closest_indx_diff(i1) = 0; %indexes difference to nearest index value of X(i)
%                 search_end = mid; %to break out of while loop
%                 search_start = mid+1; %to break out of while loop
%             elseif diff>0; %x value is greater than value at current midpoint
%                 search_start = mid + 1;
%             elseif diff<0; %X value is less than value at current midpoint
%                 search_end = mid-1;
%             end
%     end
%     if search_end<search_start && diff~=0; %didnt find exact match
%         search_end = search_start;
%         search_start = search_end-1;
%         if search_end>length(IND); %if data are outside of range on upper end
%             mid = length(IND);
%         elseif search_start<1; %if data are outside of range on lower end
%             mid = 1;
%         elseif abs(X(i1) - IND_ordered(search_end)) < abs(X(i1) - IND_ordered(search_start)) %decides which end the value (X(i)) is closest to
%             mid = search_end;
%         else
%             mid = search_start; %goes with lower number if the difference is the same
%         end
% 
%         closest_indx(i1) = IND_original_ind(mid); %indexes where X(i) would be in original IND vector
%         closest_indx_value(i1) = IND_ordered(mid); %indexes the nearest index value of X(i)
%         closest_indx_diff(i1) = X(i1) - IND_ordered(mid); %indexes difference to nearest index value of X(i)
% %         if abs(closest_indx_diff(i))>max_dist; %too far away for value to be meaningful
% %             closest_indx(i) = NaN; %indexes where X(i) would be in original IND vector
% %             closest_indx_value(i) = NaN; %indexes the nearest index value of X(i)
% %             closest_indx_diff(i) = NaN;
% %         end
%     end
% end

% A = [X', closest_indx', closest_indx_value', closest_indx_diff', IND'];
out.closest_indx = closest_indx;
out.closest_indx_value = closest_indx_value;
out.closest_indx_diff = closest_indx_diff;
       