function A=thickness_automatic(start,finish)
%function A=thickness_automatic(start,finish)
%
%   COPYRIGHT:  George D. Tsibidis(1) and Nektarios Tavernarakis(2)
%               (1) Institute of Electronic Structure and Laser 
%               (2) Institute of Molecular Biology and Biotechnology 
%               Foundation for Research and Technology-Hellas (FORTH)
%               January 2007
%
%
% This helps to compute automatically the thickness of the animal with a
% minor intervention from the user by defining the circle around which the
% thicjkness will be computed.

cd ('DATA_SAVED')

pieces_number=load('number_of_time_points.txt');

for n=start:finish
    n=n
    A=load(['skeleton_' int2str(n)]);

    [skelr,skelc]=find(A==1);
%figure;imshow(A);

cd ..
cd ('DATA_SAVED')
    B=load(['mask_' int2str(n)]);
%figure;imshow(B);

perim=bwperim(B,8);

A=zeros(size(perim,1),size(perim,2));
if n==start
figure;
imshow(perim);hold on;
plot(skelc,skelr,'.');
end

        cd ..
    cd ('DATA_SAVED')
         K=[];DISTANCES=[];
        for i=2:pieces_number-1   
         K=load(['skeleton_' int2str(n) '_point=' int2str(i) '.txt']);  
        
        % hold on;plot(K(2), K(1),'r*');
         Xo=K(2);Yo=K(1);  %coordinates of CM of segment i
         %define radius of circle
                             if i==2 & n==start
                                  hold on;plot(K(2), K(1),'r*');
                                  [C,R,P] = impixel;

                                  X_p=C(1);Y_p=R(1);
                                     %%%%%plot([X_p,Xo],[Y_p,Yo],'m');
                                  R_n=sqrt((X_p-Xo)^2+(Y_p-Yo)^2);
                                       tic
                             end
                        
          theta=0.01:.1:2*pi;
          Y_r=round(Yo+R_n*sin(theta));
          X_c=round(Xo+R_n*cos(theta));hold on;
         % plot(X_c,Y_r,'y.');
          for t=1:length(Y_r)
          A(Y_r(t),X_c(t))=1;
          end
       %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% figure;imshow(perim);hold on;  plot(X_c,Y_r,'y.');
        
        BW=bwfill(A,Xo,Yo,8);
        BW=im2double(BW);
        %hold on;
       %figure; imshow(BW)
        NEW=perim./BW;
        la=find(NEW==1);
        A=zeros(size(perim,1),size(perim,2));
        A(la)=1;
     %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%   figure;imshow(A);hold on;plot(Xo,Yo,'ro');
    [r,c]=find(NEW==1);
    DISTANCE_a=sqrt((Xo-c).^2+(Yo-r).^2);
    
    DISTANCE_a=sort(DISTANCE_a);
    
   R_a=mean(DISTANCE_a(1:13)) ;
Y_r=(Yo+R_a*sin(theta));
          X_c=(Xo+R_a*cos(theta));
          %plot(Xo,Yo,'r*');hold on;
         %plot(X_c,Y_r,'y.');
    
      aq=['thickeness_image=' int2str(n) '_segment=' int2str(i) '.txt'];
    save(aq,'R_a','-ascii'); 
   
     
     
     
A=zeros(size(perim,1),size(perim,2));
      

         end
        
toc
    
end


cd ..

msgbox('Calculations have Finished')