%MTIMES   Overloaded operator for a*b.

% (C) Copyright 1999-2008               Pattern Recognition Group
%     All rights reserved               Faculty of Applied Physics
%                                       Delft University of Technology
%                                       Lorentzweg 1
%                                       2628 CJ Delft
%                                       The Netherlands
%
% Bernd Rieger & Cris Luengo, July 2000.
% 18 December 2001: Color information is not as volitile anymore.
% 10 March 2008: Fixed 'undefined variable COL' error.

function out = mtimes(in1,in2)
try
   [in1,in2,arrayop] = doarrayinputs(in1,in2);
   if arrayop
      out = mtimes_array(in1,in2);
   else
      out = compute2('times',in1,in2);
   end
catch
   error(di_firsterr)
end

function out = mtimes_array(in1,in2)
% Matrix multiplication for dip_image_arrays.
% out(j,k) = in1(j,i) * in2(i,k)
s1 = imarsize(in1);
s2 = imarsize(in2);
if prod(s1)==1
   col = in2(1).color;
   out = dip_image('array',s2);
   for ii=1:prod(s2)
      out(ii) = in2(ii) .* in1;
      out(ii).color = col;
   end
elseif prod(s2)==1
   col = in1(1).color;
   out = dip_image('array',s1);
   for ii=1:prod(s1)
      out(ii) = in1(ii) .* in2;
      out(ii).color = col;
   end
elseif length(s1)~=2 | length(s2)~=2
   error('Matrix multiplication only defined for 2D tensors.');
elseif s1(2) == s2(1)
   col1 = in1(1).color;
   col2 = in2(1).color;
   if isempty(col1)
      if isempty(col2)
         col = '';
      else
         col = col2;
      end
   else
      if isempty(col2)
         col = col1;
      else
         if strcmp(col1.space,col2.space)
            col = col1;
         else
            warning('Color spaces do not match: removing color space information.')
            col = '';
         end
      end
   end
   I = s1(2);
   J = s1(1);
   K = s2(2);
   out = dip_image('array',[J,K]);
   for kk = 1:K
      for jj = 1:J
         out(jj,kk) = in1(jj,1) .* in2(1,kk);
         out(jj,kk).color = col;
         for ii = 2:I
            out(jj,kk) = out(jj,kk) + in1(jj,ii) .* in2(ii,kk);
            out(jj,kk).color = col;
         end
      end
   end
else
   error('Inner tensor dimensions must agree.')
end
