function [GMT,V_Gf_Gr,M_An_Be]=gmt(TD,TB,ToI)
%GMT  [GMT (,V_Gf_Gr) (,M_An_Be)]=gmt(TD,TB,ToI)
%     determination of general weighted mean dead times (GMT) 
%     for bus data transfer inside single control loops.
%Preconditions: bus data transfer within forward path after controller output,
%	  and within reverse path after actual value measurement; controller, 
%     control output processing and measurement synchronously via f_d=1/TD;
%	  bus data transfer asynchronously to this via f_b=1/TB;
%	  consideration of additional constant dead times in both paths;
%	  !!! all time values in ms with maximum 3 decimal places !!!
%Inputs:TD	sampling time for control / output processing / measurement
%	    TB	sampling time of bus data transfer
%	    ToI	vector containing constant dead times in forward and reverse path
%Outputs:  GMT  total dead time = GMT_forward + GMT_reverse in ms
%	   V_Gf_Gr  vector containing GMT_forward and GMT_reverse in ms
%	   M_An_Be  quantity and value matrix for dead times (resolution 0.1ms)
%			    row 1 and 3 - quantity;	row 2 and 4 - value (*TD)
%			    row 1 and 2 forward path, row 3 and 4 reverse path

% KEY WORDS: weighted mean dead time, running phase shift

% Copyright (c) 2012 Dr. Gert-Helge Geitner; TU Dresden, Fak. ET,
%                    Elektrotechnisches Institut (ETI); Mommsenstr. 13;
%                    D-01062 Dresden, Germany; Gert-Helge.Geitner@tu-dresden.de
%                    http://eeiwzg.et.tu-dresden.de/ae2_files/ae_0e.htm

if nargin<2       error('Inappropriate number of input arguments!'); end
if TB>TD          error('Inappropriate relation TD<TB!'); end
if nargin==2 ToI=[0 0]; end % no additional constant dead times
if length(ToI)~=2 error('Inappropriate vector ToI!'); end
TD=TD*1000; TB=TB*1000; ToI=ToI*1000; %algorithm usage for whole numbers!!!
M_An_Be=[];
for z=1:2
    i=0; s1=0; Tu=ToI(z)+TB;
    while s1==0
	  i=i+1; Ku=i*TD-Tu; if Ku>0 s1=1; end
    end
    if Ku<TB
       j=i+1; To=ToI(z)+2*TB-1;
       if (j*TD-To)>0	Km=TB-Ku; k=0; Ko=0;
       else	Km=TD;
			k=j+1;
			if (k*TD-To>0)  Ko=TB-Ku-Km;
            else error('GMT determination for no more as 3 parts prepared!')
			end
       end
    else  Ku=TB; j=0; Km=0; k=0; Ko=0;
    end
M_An_Be=[M_An_Be [Ku/100 i;Km/100 j;Ko/100 k]];
			      %quantity and value for resolution 0.1ms
V_Gf_Gr(z)=sum([Ku*i Km*j Ko*k])*TD/(TB*1000);
end
GMT=sum(V_Gf_Gr); %determination for forward and reverse path necessary
