clear all;
clf;
global real_class_position class_position sigma number dimension class_index max_class
number=30;
max_class=4;
dimension=3;
number_of_bins=70;
min_number_of_bins=10;
tolerance=2;
file=fopen('dane4.kla');
Z=fscanf(file,'%f %f',[dimension max_class*number]); 
real_class_position=zeros(dimension,max_class*number);        
sigma=zeros(dimension,max_class*number);
class_position=zeros(dimension,max_class*number);
for d=1:dimension
clf;
 W=Z(d,:); 
 W=W/max(W);
 xmin=min(W); xmax=max(W);C=2^32 / (xmax-xmin);
 lv=length(W);
%
imax=32; 
imin=24;

  V=(W-xmin)*C;
  lv=length(V) ;
  i=imin;
  iv=(imax-i+1)*ones(lv,1);
  k=2^i;
  U=xmin+ (round(V/k)*k)/C; 
  if dimension==3
    plot3(Z(1,:),Z(2,:),Z(3,:),'.');      
  end;
  if dimension==2
    plot(Z(1,:),Z(2,:),'.');
  end;  

%for i=number_of_bins:-1:min_number_of_bins
      i=number_of_bins;
      bins_vectors=zeros(i+1); 
      step=1/i; 
      m=1;
      for j=step:step:1 
          number_of_vectors=0; 
          for k=1:max_class*number
              if U(k)<=j & U(k)>(j-step)
                 number_of_vectors=number_of_vectors+1; 
              end;
          end;
          if number_of_vectors>0
             bins_vectors(m)=number_of_vectors; 
          end;
      m=m+1;    
      end; 
      tmp_matrix=find(bins_vectors(1:m)>0);                     
      class_index=1;            
      z=1;
      while z<=(length(tmp_matrix)-1)
          remember_z=z;
          bin_length=0;
          claster_vectors=0;
          while z<=(length(tmp_matrix)-1) & (tmp_matrix(z+1)-tmp_matrix(z))<=tolerance
             z=z+1;
             bin_length=bin_length+1;
             if z>(length(tmp_matrix)-1)
                break;
             end;               
          end; 
%          if bin_length==0
%             bin_length=1;
%          end;   
          begin_bin=tmp_matrix(remember_z)*step*max(Z(d,:));
          end_bin=begin_bin+bin_length*step*max(Z(d,:));
          sum=0;
          cluster_vectors=0;
          class_position(d,class_index)=begin_bin+(end_bin-begin_bin)/2;
          sigma(d,class_index)=(end_bin-begin_bin)/2;                   
%          pause
          class_index=class_index+1;
          z=z+1; 
      end;    
end;  


d=1;
class_index=1;

search_c(Z,1);

hold on;
for i=1:max_class*number
        if real_class_position(1,i)>0
         hold on;
         if dimension==3
                  plot3(real_class_position(1,i),real_class_position(2,i),real_class_position(3,i),'w+');
         end;
         if dimension==2
                  plot(real_class_position(1,i),real_class_position(2,i),'w+');
         end;         
        end;
end; 












