function histogram1=preprocessing(histogram,CsSurvey)

%
% histogram1=preprocessing(histogram,CsSurvey)
%
% Implement the three-step pre-processing procedure introduced in Section
% 8.2.3 of
%
% J. M. Mendel and Dongrui Wu, Perceptual Computing: Aiding People in
% Making Subjective Judgments, Wiley-IEEE Press, 2010.
%
% Dongrui WU (dongruiw@usc.edu), 5/12/2008
%

histogram1=zeros(size(histogram));

for i=1:length(histogram)
    %% step 1
    left=find(histogram(i,:)>0,1,'first');
    right=find(histogram(i,:)>0,1,'last');
    zero=find(histogram(i,left:right)==0);
    k=length(zero);
    if k>0
        zero=[max(left-1,1) zero min(right+1,size(histogram,2))];
        for j=1:k+1
            temp(j)=sum(histogram(i,zero(j):zero(j+1)));
        end
        J=find(temp==max(temp));
        if mod(length(J),2)==1 %% J has an odd number of elements
            histogram1(i,zero(median(J)):zero(median(J)+1))=histogram(i,zero(median(J)):zero(median(J)+1));
        elseif length(J)>0 %% J has an even number of elements
            if sum(histogram1(i,1:zero(J/2+1)))>=sum(histogram1(i,zero(J/2+1):size(histogram,2)))
                histogram1(i,zero(J/2):zero(J/2+1))=histogram(i,zero(J/2):zero(J/2+1));
            else
                histogram1(i,zero(J/2+1):zero(J/2+2))=histogram(i,zero(J/2+1):zero(J/2+2));
            end
        end
    else
        histogram1(i,:)=histogram(i,:);
    end
    %% step 2 & 3
    I=find(histogram1(i,:)>0);
    temp2(1:histogram1(i,I(1)))=CsSurvey(I(1))*ones(1,histogram1(i,I(1)));
    for j=2:length(I)
        temp2(sum(histogram1(i,I(1:j-1)))+1:sum(histogram1(i,I(1:j))))=CsSurvey(I(j))*ones(1,histogram1(i,I(j)));
    end
    I2=BWTL(temp2,.95);
    outliers=unique(temp2(I2));
    for j=1:length(outliers)
        histogram1(i,find(CsSurvey==outliers(j)))=0;
    end
end