function [beta, theta1, theta2, delta, Q_all] = lyngby_lzit_algo(T, n, ...
    deltainit, stop, maxIterations, fhats, xi, Yi, theta1, theta2);

% lyngby_lzit_algo     - Lange-Zeger, optimization of model
%
%	function [beta, theta1,theta2, delta, Q_all] = ...
%		lyngby_lzit_algo(T, n, deltainit, stop, iter, fhats,
%		xi, Yi, theta1, theta2);
%
%	Input:	T
%               n
%	
%	Output: Q   last value of costfuntion
%
%       This function will optimized the beta and theta parameters of
%       the Lange-Zeger model for one voxel.
%
%	See also: lyngby_lzit_main, lyngby_lzit_thopt,
%	          lyngby_lzit_ftlamb, lyngby_lzit_beta 

% cvs : $Id: lyngby_lzit_algo.m,v 1.4 1999/02/18 14:05:16 fnielsen Exp $
%       $Revision: 1.4 $

    dLi = lyngby_lzit_ftlamb(T, n, theta1, theta2);
    Xi = dLi .* xi;
    beta = lyngby_lzit_beta(Yi, Xi, 1);
    diff = realmax;
    e = 0;

    Q = realmax;
    DIF = zeros(1, maxIterations);
    DELTA = zeros(1, maxIterations);
    Q_all = zeros(1, maxIterations);

    while (e < maxIterations)
      e = e+1;
      fhatvek = lyngby_lzit_noise(T, n, beta, fhats, Yi, Xi);
      beta = lyngby_lzit_beta(Yi, Xi, fhatvek);
      delta = deltainit;
      Qlast = Q;
      [theta1,theta2,delta,Xi,Q] = lyngby_lzit_thopt(T, n, delta, ...
	  beta, theta1, theta2, Yi, xi, fhatvek);
      if (abs(Qlast-Q) < stop)
	e = maxIterations;
      end
      Q_all(e) = Q;
      DELTA(e) = delta;
    end;















