function [dist4] = size_wound(wnd,num_images,res)
%Function calculating the size of the wound
%   returns the mean size, minimum size, maximum
%   size & 50th percentile (dist4) of te scratch

%Calculate number of "wound pixels" for each line in the segmented image
L=size(wnd,1);
dist1=zeros(num_images,L);
for k=1:num_images
    for p=1:L
        it=1;
        spot1=[];
        nbr1=[];
        for i=1:L
            if it>=L
                break
            else
                switch wnd(p,it,k)
                    case 2
                        it=it+1;
                        continue
                    case 1
                        cunt=0;
                        spot1=[spot1 it];
                        j=it;
                        while wnd(p,j,k)==1
                            cunt=cunt+1;
                            j=j+1;
                            if (cunt>L) || (j>L)
                                break
                            end
                        end
                        nbr1=[nbr1 cunt*res];
                        it=it+cunt;
                    otherwise
                        disp('problem')
                        break
                end
            end
        end
        diff=[];
        for l=1:length(spot1)-1
            diff(l)=spot1(l+1)-(spot1(l)+nbr1(l)/res);
        end
        nbr11=[];
        for ll=1:length(diff)
            switch diff(ll)
                case {1, 2}
                    cunt1=nbr1(ll);
                    alpha=ll;
                    while diff(alpha)<=2
                        cunt1=cunt1+diff(alpha)*res+nbr1(alpha+1);
                        alpha=alpha+1;
                        if (cunt1>L*res) || (alpha>length(diff))
                            break
                        end
                    end
                    nbr11=[nbr11 cunt1];
                otherwise
                    nbr11=[nbr11 nbr1(ll)];
            end
        end
        if length(nbr11)>1
            Max=max(nbr11);
        elseif length(nbr11)==1
            Max=nbr11;
        else
            Max=0;
        end
        dist1(k,p)=Max;
    end
end

%To ease analysis, zeros are not taken into account
dist2=zeros(1,num_images);
for k7=1:num_images
    c=L;
    for r=1:L
        if dist1(k7,r)==0
            c=c-1;
        end
    end
    dist2(1,k7)=c;
end

dist4=zeros(4,num_images);
for k8=1:num_images
    dist3=zeros(1,dist2(1,k8));
    d=1;
    for s=1:L
        if dist1(k8,s)~=0
            dist3(1,d)=dist1(k8,s);
            d=d+1;
        end
    end
    dist4(1,k8)=max(dist3);
    dist4(2,k8)=min(dist3);
    dist4(3,k8)=(prctile(dist3,50));
    dist4(4,k8)=mean(dist3);
end
end

