% This function output a matrix of data to a Latex file
% mat - the matrix to be written
% tex - the name of the latex file 
% lab_row - the labels for each row
% lab_col - the labels for each column

function cm2tex(mat, tex, lab_row, lab_col, SNR)

[nRow, nCol] = size(mat);
L=mat==0; %indices where count is zero
mat(L)=NaN;  %replace zeros with NaN


fid = fopen(tex, 'wt'); %open tex file in write mode

  %fprintf(fid, '\\begin{table} \n');
  %fprintf(fid, '\\centering \n');

  %fprintf(fid, '\\caption{%s}',tex(5:end-4)); fprintf(fid, '\n');

% print \begin{tabular{c c c c c ... }
ctrl_line = '\\begin{tabular}{|c|';
for i=1:nCol-1
  if mod(i,3)==0 S='c |';else S=' c ';end
    ctrl_line = [ctrl_line S];
    if i == nRow;ctrl_line = [ctrl_line '||'];end
end
ctrl_line = [ctrl_line '|| c '];
ctrl_line = [ctrl_line '|} \n'];
fprintf(fid, ctrl_line);

% print double line
fprintf(fid, '\\hline');
fprintf(fid, '\n');

% print the first line, pa ta ka ...
first_line = SNR{1};
for j=1:nCol-1
    first_line = [first_line ' & \\makeatletter ' lab_col{j} ' \\makeatother' ];
end
first_line = [first_line '& $\' lab_col{nCol} '$']; %This is the first row (row header)
fprintf(fid, first_line); 
fprintf(fid, ' \\'); fprintf(fid, '\\'); % print '\\'  
fprintf(fid, '\n'); 

% print double line
fprintf(fid, '\\hline');
fprintf(fid, '\n');

% print the data lines
for i=1:nRow
  if mod(i,3)==0 S=' \\hline';else S='';end
  
    cur_line = ['{\\makeatletter ' lab_row{i} ' \\makeatother }'];
    for j=1:nCol
        if ~isnan(mat(i, j))
            cur_line = [cur_line, ' & ' num2str(round(mat(i,j)))];
        else
            cur_line = [cur_line, ' & ' ];            
        end
    end 
    fprintf(fid, cur_line);  
    fprintf(fid, ' \\'); fprintf(fid, ['\\' S]); % print '\\'      
    fprintf(fid,'\n');     
end

fprintf(fid, '\\hline');
fprintf(fid,'\n');
fprintf(fid, '\\end{tabular} \n');
  %fprintf(fid, '\\end{table} \n');
fclose(fid);
