function y=magic(n)
% y=magic(n)
% generate a magic square for odd n

%       S.Halevy 7/31/92
%       Copyright (c) 1992 by the MathWizards

y=[];

% handle all simple cases
if n==1
  y=1;
elseif n==2
  y=[1 3;4 2];
elseif n==4
  y=[16 2 3 13;5 11 10 8;9 7 6 12;4 14 15 1];
elseif n==6   % needed for one of the demos
  A=magic(3); % recursive call
  y=[A A+18;A+27 A+9];
  t1=y(1,1); y(1,1)=y(4,1); y(4,1)=t1;
  t1=y(3,1); y(3,1)=y(6,1); y(6,1)=t1;
  t1=y(2,2); y(2,2)=y(5,2); y(5,2)=t1;
end

if ~isempty(y)
  return;
end

if rem(n,2)==0
   n
   error('MathViews does not support magic of that even number')
end

y=zeros(n);
n2=n*n;
i0=1;
j0=(n+1)/2;

for k=1:n2
  y(i0,j0)=k;
  if k<n2
     i1=rem(n+i0-2,n)+1;
     j1=rem(j0,n)+1;
     if y(i1,j1)>0
          i0=rem(i0,n)+1;
          % no change in j0
     else
          i0=i1;
          j0=j1;
     end
     while y(i0,j0)>0
        i0=rem(i0,n)+1;
        if y(i0,j0)>0
           i0=rem(n+i0-2,n)+1;
           j0=rem(j0,n)+1;
        end
     end
  end
end
