function y = percentile(x, p, ponder)
% x - numeric data, matrix (n,x) [values, frequencies], or matrix (n,1) - raw data
% p - percentile
y=NaN; %ovo da bi i ako je suma pondera, frekveci manja od 1 dao nista :)

if p>100 | p<0
	error("Percentile must be in range 0 to 100")
end

p = p/100;

if isnum(x)
	if size(x,2)==1
		if def(ponder)
			[d,l]=freq(x,ponder);
		else
			[d,l]=freq(x);
		end

		x = [d,l];
	end
	n = size(x,1);
	if x(n,1)==NaN
		x(n,:) = [];
		n = n-1;
	end
	if n>1
		W = csum(x);
		W = W(2);
		tp = (W+1)*p/W;
		cc1 = 0;
		cc2 = 0;
		cp1 = 0;
		cp2 = 0;
		i=1;
		while i<=n
			cc1 = cc2;
			cp1 = cp2;
			cc2 = cc2 + x(i,2);
			cp2 = cc2 / W;
			if cp2>tp %tu je zeljeni percentil
				if (tp-cp1)>=(1/W)
					y = x(i,1);
				else
					y = (1-((W+1)*p - cc1))*x(i-1,1) + ((W+1)*p-cc1)*x(i,1);
					%y = x(i,1);
				end
				i=n;
			end
			i = i+1;
		end
	else
		if n==1
			y=x(n,1);
		else
			y=[];
		end
	end
else
	error("Arg for PERCENTILE must be numeric.")
end

end