
repeat = 6;
ns = unique(floor(exp(log(1):0.3:log(1000000))));
max_time = 0.4;
max_error = 1e-6;

time_abgabe = zeros(1, length(ns));
time_lapack = zeros(1, length(ns));
diff        = zeros(1, length(ns));
max_diff    = zeros(1, length(ns));

act_pos = 0;

for i=1:length(ns)
   act_pos = act_pos+1;

   n = ns(i)

   sumtime_abgabe = 0;
   sumtime_lapack = 0;
   sumdiff        = 0;

   for j=1:repeat
      a = randn(n,1);
      b = randn(n,1);
      b(end) = inf;
      c = randn(n,1);
      c(1) = inf;
      y = randn(n,1);

      % run Abgabe
      tic;
      [alpha, beta, gamma] = tridiag_factor(a, b, c);
      x_abgabe = tridiag_solve(alpha, beta, gamma, y);
      sumtime_abgabe = sumtime_abgabe + toc;

      % run LAPACK
      A = spdiags([[c(2:end); inf] a [inf; b(1:end-1)]], -1:1, n, n);
      tic;
      x_lapack = A\y;
      sumtime_lapack = sumtime_lapack + toc;

      fehler = norm(x_abgabe-x_lapack);
      if( fehler > n*n*max_error )
         fehler
         save('fehler_beispiel.mat', 'a', 'b', 'c', 'y');
         disp('Die von "tridiag_factor" und "tridiag_solve" Ausgerechnete Loesung ist fehlerhaft!');
         disp(' Geben sie "load(''fehler_beispiel.mat'')" ein um a, b, c, y zu laden, welche auf das Problem gefuehrt haben.');
         error('Fehler!');
      end

      sumdiff = sumdiff + fehler;

   end

   time_abgabe(i) = sumtime_abgabe/repeat;
   time_lapack(i) = sumtime_lapack/repeat;
   diff(i)        = sumdiff/repeat;
   max_diff(i)    = n*n*max_error;

   if( (sumtime_abgabe+sumtime_lapack)>max_time )
      break;
   end
end

time_abgabe = time_abgabe(1:act_pos);
time_lapack = time_lapack(1:act_pos);
diff        = diff(1:act_pos);
max_diff    = max_diff(1:act_pos);
ns = ns(1:act_pos);

subplot(2,1,1);
loglog(ns, time_abgabe, 'b-', ns, time_lapack, 'r--');
legend('Mittlere Laufzeit Abgabe', 'Mittlere Laufzeit LAPACK', ...
         'Location', 'NorthWest');

subplot(2,1,2);
loglog(ns, diff, 'b-', ns, max_diff, 'k--');
legend('Fehler Abgabe<->LAPACK', 'Maximal erlaubter Fehler', ...
         'Location', 'NorthWest');
