function str=tablab(A,s,rlabel,clabel1,clabel2);
%TABLAB creates a table of the form:
%
%      -----------------------------------------------------
%      |       |                  clabel1                  |
%      |       |--------------------------------------------
%      | rows  | clabel21 | clabel22 | clabel23 | clabel24 |   ...
%      -----------------------------------------------------
%      |rlabel1|  A(1,1)  |  A(1,2)  |  A(1,3)  |  A(1,4)  | 
%      -----------------------------------------------------
%      |rlabel2|  A(2,1)  |  A(2,2)  |  A(2,3)  |  A(2,4)  |
%      -----------------------------------------------------   ...
%      |rlabel3|  A(3,1)  |  A(3,2)  |  A(3,3)  |  A(3,4)  |
%      -----------------------------------------------------
%          :                    :                     :
%
%  INPUTS: 
%    (i) A = mxn matrix for table
%   (ii) s = number of spaces padding the number in the table (which has
%            converted to a 10-space string)
%  (iii) rlabel= (m+1) x max(row label) string matrix with labels for rows.
%            For example, rlabel=[' rows  ';'rlabel1';'rlabel2';'rlabel3']
%   (iv) clabel1= string row vector with the first labels for the columns
%    (v) clabel2= n x max(2nd col. labels) string matrix with labels for
%            columns.  For example, clabel2='clabel21';'clabel22'; ..
%            'clabel23';'clabel24']
%
%  OUTPUTS: str= a string matrix giving the table of the form above.
%
[m,n]=size(A);
[rr,rc]=size(rlabel);
[cr1,cc1]=size(clabel1);
[cr2,cc2]=size(clabel2);
if m~=rr-1; 
  error('no. of rows in matrix ~= no. of rows in row-labels matrix minus 1');
end;
if n~=cr2; 
  error('no. of columns in matrix ~= no. of rows in column-labels matrix ');
end;
p=2*s+10;
if cc2>2*s+10; 
  error('Make your column titles shorter or the space between columns longer.')
end;
for i=1:s; pad1(1,i)=' '; end;
for i=1:m;
  for j=1:n;
    snum=num2str(A(i,j));
    if length(snum)<10; 
      for k=1:s+10-length(snum); pad2(1,k)=' '; end;
    else;
      pad2=pad1;
    end;
    str(2*i-1,(j-1)*(p+1)+1:j*(p+1))=[pad2,snum,pad1,'|'];
    clear pad2
  end;
  for j=1:n*(p+1);
    str(2*i,j)='-';
  end;
end;
for i=1:rc;
  pad3(1,i)=' ';
end;
for i=1:rr;
  rstr(2*i-1,:)=['|',rlabel(i,:),'|'];
  for j=1:rc+2;
    rstr(2*i,j)='-';
  end;
end;
rstr=['|',pad3,'|';'|',pad3,'|';rstr];
if ((rem(n,2)==0 & rem(cc1,2)==0) | (rem(n,2)==1 & rem(cc1,2)==1));
  tl=(n*(p+1)-2-cc1)/2;
  title1=[clabel1,' '];
else;
  tl=(n*(p+1)-1-cc1)/2;
  title1=clabel1;
end;
for i=1:tl;
  pad4(1,i)=' ';
end;
title1=[pad4,title1,pad4,'|'];
for i=1:cr2;
  pad5(i,1)=' ';
end;
if rem(cc2,2)==1; clabel2=[clabel2,pad5]; cc2=cc2+1; end;
for i=1:(p-cc2)/2;
  pad6(1,i)=' ';
end;
for i=1:n;
  title2(1,(i-1)*(p+1)+1:i*(p+1))=[pad6,clabel2(i,:),pad6,'|'];
end;
str=[rstr(4,:) str(2,:);rstr [title1;str(2,:);title2;str(2,:);str]];

