function [meanuewktmat,distout]=calcdist(reihe,uewktmat,meanuewktmat,weight,functionstatus)

%   calcdist

%   This software is protected by german copyright and international treaties.             
%   Copyright 2004 Markus Junghöfer & Peter Peyk. All Rights Reserved.                     
%                                                                                          
%   THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE        
%   NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO,    
%   WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE    
%   OF THE SOFTWARE OR DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS,
%   TRADEMARKS OR OTHER RIGHTS. COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT,       
%   INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE      
%   OR DOCUMENTATION.      

global distmat kriterium verteilungsniveau

%averaging
%------------
if isempty(meanuewktmat)
    meanuewktmat=uewktmat;
else
    meanuewktmat=(meanuewktmat*weight+uewktmat)/(weight+1);
end

%distanz zu average
%------------------
if weight<40*verteilungsniveau
    distout=9999999999;
elseif weight<=40+40*verteilungsniveau
    distout=9999999999;
    dist=sum(sum(abs(uewktmat-meanuewktmat)));
elseif weight>40+40*verteilungsniveau
    distout=sum(sum(abs(uewktmat-meanuewktmat)));
    dist=sum(sum(abs(uewktmat-meanuewktmat)));
end

%distmat
%---------
if weight>40
    distmat(weight-40)=dist;
end

if weight<40+40*verteilungsniveau
    kriterium=0; 
elseif weight==40+40*verteilungsniveau
    if functionstatus ~= 1
		figurehandle = figure('tag','kriteriumsplot','Name','Kriteriumsbestimmung nach Verteilung der Distanzen:','NumberTitle','off','menubar','none','units','normalized','position',[0.1 0.2 0.3 0.3]);
        hold on
		haeufigkeiten=hist(distmat,20);
        binzaehler=1;
        hist(distmat,20);
        set(gca,'DataAspectRatioMode','auto');
        set(gca,'PlotBoxAspectRatioMode','auto');
        set(gca,'CameraViewAngleMode','auto');
        set(gca,'position',[0.1 0.1 0.8 0.7]);
        title({'Kriterium festlegen (return für mehr Reihen)';['bisher: ',num2str(length(distmat)),' Reihen']});
        [x,y]=ginput(1);
        if isempty(x)
            verteilungsniveau=verteilungsniveau+1;
            close(gcf);
        else
            line([x x],[0,max(haeufigkeiten)+2]);
		    hold off
            kriterium = x
        end
    else
        [haeufigkeiten,bincenters]=hist(distmat,20);
        total=sum(haeufigkeiten);
        binzaehler=1;
        cumhfgkt=0;
        while cumhfgkt/total<0.01
            cumhfgkt=cumhfgkt+haeufigkeiten(binzaehler);
            binzaehler=binzaehler+1;
        end
        kriterium=bincenters(binzaehler-1);
    end   
end



return