% 
% function [rangebin, databin] = rangeBin_(target_range, fftData, cplxData, param)
% 
%     %range resolution calculation
%     rng = target_range;
%     indexx = zeros(1,param.numChirps);
% 
%     
%     if param.rangeresol >= param.peak2peakChest
%         %resolution is bigger than one rangebin
%         index = floor(rng(1)/param.rangeresol);
%         for i=1:param.numChirps
%            % index = floor(rng(i)/param.rangeresol);
%             rangebin(1,i) = fftData(i,index);
%             databin(1,i) = cplxData(i,index);
%         end
% 
%     else
% 
%         %resolution is not bigger than one rangebin
%         for i=1:param.numChirps
%             indexx(1,i) = floor(rng(i)/param.rangeresol);
%         end
% 
%         minIndex = min(indexx);
% 
%         coveredBins = ceil(param.peak2peakChest/param.rangeresol);
%         index = minIndex + coveredBins;
%         
%         %rangebin from minIndex-index from up to down into the opposite
% 
%         for i=1:param.numChirps
% 
%             for j=minIndex:indexx
%                 rangebin(j-(minIndex-1),i) = fftData(i,j);
%                 databin(j-(minIndex-1),i) = cplxData(i,j);
%             end
%         end
%         
%     end
% 
% end
% 


function [rangebin, databin] = rangeBin_(target_range, fftData, cplxData, param)

    %range resolution calculation
    rng = target_range;
    indexx = zeros(1,param.numChirps);

    
    if param.rangeresol >= param.peak2peakChest
        %resolution is bigger than one rangebin
        for i=1:param.numChirps
            index_(i) = floor(rng(i)/param.rangeresol);
        end

        index = 11; %mode(index_(param.startsample:param.endsample));

        for i=1:param.numChirps
            rangebin(1,i) = fftData(i,index);
            databin(1,i) = cplxData(i,index);
        end

    else

        %resolution is not bigger than one rangebin
        for i=1:param.numChirps
            indexx(1,i) = floor(rng(i)/param.rangeresol);
        end

        minIndex = min(indexx);

        coveredBins = ceil(param.peak2peakChest/param.rangeresol);
        index = minIndex + coveredBins;
        
        %rangebin from minIndex-index from up to down into the opposite

        for i=1:param.numChirps

            for j=minIndex:indexx
                rangebin(j-(minIndex-1),i) = fftData(i,j);
                databin(j-(minIndex-1),i) = cplxData(i,j);
            end
        end
        
    end

end