function color_hist=build_hist(B,K,LABmap,CC,X,bins,min_dist);

color_hist=zeros(B+1,K);

for blob=1:B
   on2=bwmorph(bwmorph(CC==blob,'fill'),'erode');
   member{blob}=find(on2);
end
   
for i=1:size(LABmap,1)
   for blob=1:B
      count(blob)=sum(X(member{blob})==i);
   end
   count(B+1)=sum(X(:)==i);
   if sum(count)>0
      bin_scores=zeros(1,K);
      d=ones(K,1)*LABmap(i,:)-bins;
      dist=sqrt(sum(d.^2,2));
      %[junk,close_bins]=min(dist); % these two lines do closest bin only
      %bin_scores(close_bins)=1;
      close_bins=find(dist<3*min_dist/4)';
      close_score=dist(close_bins)';
      bin_scores(close_bins)=(close_score<=min_dist/4) + ...
	  (close_score>min_dist/4 & close_score<3*min_dist/4).* ...
	  (1.5-close_score*2/min_dist);
      bin_scores(close_bins)=bin_scores(close_bins)/sum(bin_scores);
      for blob=1:B
	 color_hist(blob,:)=color_hist(blob,:)+bin_scores*count(blob);
      end
      color_hist(B+1,:)=color_hist(B+1,:)+bin_scores*count(B+1);
   end
end

color_hist=color_hist./(sum(color_hist,2)*ones(1,K));



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright (c) 1997-1999. The Regents of the University
% of California (Regents). All Rights Reserved.
% 
% Permission to use, copy, modify, and distribute this software and its
% documentation for educational, research, and not-for-profit purposes,
% without fee and without a signed licensing agreement, is hereby
% granted, provided that the above copyright notice, this paragraph and
% the following two paragraphs appear in all copies, modifications, and
% distributions. Contact The Office of Technology Licensing, UC Berkeley,
% 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620, (510)
% 643-7201, for commercial licensing opportunities. Created by
% Chad Carson, Serge Belongie, and Jitendra Malik, Department of Electrical
% Engineering and Computer Sciences, University of California, Berkeley.
% For technical information, contact carson@eecs.berkeley.edu.
% 
% IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
% SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
% ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
% REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
% 
% REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
% PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF
% ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION
% TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
% MODIFICATIONS.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

