function matrixout=clip(matrixin,percentile)
% matrixout=clip(matrixin,percentile)
% matrixin = vector or matrix with data to be clipped
% percentile = percentile of data to be kept 
% Ex: if percentile = 99, the biggest 0.5 percent of the data and the smallest 0.5 % will be set to the closest value. 
% percentile needs not be an integer

%H=sread('helocut.H');
%matrixin=normalize(H.data);
%lung=prod(size(H.data));
%percentile=100-0.2;

sm=size(matrixin);
[n,xout]=hist(reshape(matrixin,1,prod(sm)),1000);
threshold=round(0.5*(percentile/100+1)*prod(sm));

causal_integral=cumsum(n);
pointer=min(find(causal_integral>=threshold));
maxval=xout(pointer);

anticausal_integral=fliplr(cumsum(fliplr(n)));
pointer=min(find(anticausal_integral<=threshold));
minval=xout(pointer);

matrixin(find(matrixin>=maxval))=maxval;
matrixin(find(matrixin<=minval))=minval;

matrixout=matrixin;
