%tableproducer
%tabtex(header,caption,dig,varargin)
% header=string
% caption=string
% dig(digits)=number
% varargin=vectors of strings (e.g. first column of labels) or number
% (data)
% this function prints on screen a LaTeX table which entries are
% (column-wise) the vectors in varargin. The input varargin are entries
% (e.g. vectors) separated by commas. At this point the vectors must have
% equal numbers of rows.
% G.L.

function tabl=tabtex(header,caption,dig,varargin)
%global ta
% keyboard
doheader=1;
if isempty(header)
    doheader=0;
else
    tmp=header(:)';
    head=tmp{1};
    
    for kk=2:length(tmp);
        head=[head,'&',tmp{kk}];
    end
end
if isempty(dig)
    dig=15;
end
ta=[];

hum=['& '
     '\\'];
%   semc=[,
%         ;];
   sepc1=[];
   sepc2=[];
   for uu=1:size(varargin{1},1)
       sepc1=[sepc1;hum(1,:)];
       sepc2=[sepc2;hum(2,:)];
   end
if ischar(varargin{1})
   ta=[strvcat(varargin{1}),repmat('&',size(varargin{1},1),1)];
elseif size(varargin{1},2)==1
    ta=[num2str(approx(varargin{1},dig)),sepc1];
else
    ta=[];
    for i=1:size(varargin{1},2)-1
        ta=[ta,[num2str(approx(varargin{1}(:,i),dig)),sepc1]];
    end
    ta=[ta,num2str(approx(varargin{1}(:,end),dig))];
end


if length(varargin)>1 
for i=2:length(varargin)
    if size(varargin{i},2)==1
        
        ta=[ta,[num2str(approx(varargin{i},dig))]];%,sepc1
      
    else
        for j=1:size(varargin{i},2)-1
           
            ta=[ta,[num2str((varargin{i}(:,j)),dig),sepc1]];%approx
      
        end
         ta=[ta,num2str((varargin{i}(:,end)),dig)];%approx
    end
    
end
end

ta=[ta(:,1:end),sepc2];
ta1=ta(1,:);

nc=size(ta1(ta1=='&'),2);
cl=['l'];
for ii=1:nc
cl=[cl,'r'];
end
cl=[cl,''];
dis=(strvcat('\begin{table}[h]',...
          '\begin{center}'));
 
dis=strvcat(dis,(strvcat([' \caption{',caption,'}\label{}'],' ',['\begin{tabular}{', cl, '} '])));

if doheader==1
dis=strvcat(dis,'\hline',char(head),'\\ \hline');
end

dis=strvcat(dis,'%\hline\endhead',...
'%\hline',...
[repmat('%&',1,size(header,1)-1),'%(continues...)\\'],...
'%\hline',...
'%\endfoot',...
'%\hline',...
'%\endlastfoot');
tao=[];
for jj=1:size(ta,1);
    tao=strvcat(tao,regexprep(ta(jj,:),'\& \\','\\'));
end
dis=strvcat(dis,(tao));
dis=strvcat(dis,' \hline');
dis=strvcat(dis,(' \end{tabular}'));
dis=strvcat(dis,(' \end{center}'));
dis=strvcat(dis,(' \end{table}'));
tabl=dis;
%disp(dis);