function [knnMedian, mre, kEffort] = nnkForKernel(myRow,dataset,kValue)
% this function finds the closes k neighbors to a row within a dataset
% and returns the median of those k projects' effort values
% and also the mre value

featureSize = size(dataset,2);

% % firstly normalize the row and data
trainActualCostValues = dataset(:,size(dataset,2));
actualRowCost = myRow(:,size(dataset,2));
myTempToNormalize = [myRow;dataset];
for i =1:size(myTempToNormalize,1)
    myTempToNormalize(i,:) = (myTempToNormalize(i,:) - min(myTempToNormalize))./(max(myTempToNormalize) - min(myTempToNormalize));
end

% get normalized row and replace cost with actual cost
myRow = myTempToNormalize(1,:);
myRow(:,featureSize) = actualRowCost;

% get normalized train data and replace cost with actual cost
myTempToNormalize(1,:) = []; % delete test data
dataset = myTempToNormalize;
dataset(:,featureSize) = trainActualCostValues;

% below array keeps the kNN effort values
kEffort = zeros(kValue,1);

% below array keeps the distance values
kDistances = zeros(kValue,1);

for counter = 1:kValue
    
   % initially let the first instance have the best distance
   bestDist = sqrt(sum(abs(myRow(1,1:(featureSize-1)).^2 - dataset(1,1:1:(featureSize-1)).^2))); 
   bestIndex = 1; 
   
   for i=2:size(dataset,1)
       tempDist = sqrt(sum(abs(myRow(1,1:1:(featureSize-1)).^2 - dataset(i,1:1:(featureSize-1)).^2)));
       if tempDist < bestDist
          bestDist = tempDist;
          bestIndex = i;
       end
   end
   
   % save the effort value of the closest neighbor
   kEffort(counter,1) = dataset(bestIndex,featureSize);
   kDistances(counter,1) = bestDist;
   
   % delete the closest neighbor for the next run (if there is any)
   dataset(bestIndex,:) = [];
   
end

% return the median of the kNN
knnMedian = median(kEffort);
[kDistances, IX] =sort(kDistances);
kEffort = kEffort(IX);

mre = abs(knnMedian - myRow(1,featureSize))/myRow(1,featureSize);

end

