
function out = addlabels(mat,rowLabels,colLabels)
% function out = addlabels(mat,rowLabels,colLabels)
% Adds row and column labels to a matrix ahead of writing the matrix out
% Arguments
% 'mat': The matrix to add labels to, required
% 'colLabels': a vector of cells containing the column labels, required
% ie: colLabels={'Agricultural production';'Veterinary services';...}
% 'rowLabels': a vector of cells containing the row labels, required
% written and maintained by Kyle Matoba: kyle.matoba@frb.sf.org
% will hopefully be superceded if I can find a better way managing labels
% updated log.  August 7, 2008: written
%               May 11, 2009: made labels optional

    [m,n]=size(mat);
    
    if isempty(rowLabels) & isempty(colLabels)
        out = mat;
        return
    end

    outNrow = m;
    outNcol = n;    
    isRlab = ~isempty(rowLabels);
    isClab = ~isempty(colLabels);
    
    
    
    if isClab
        if(size(colLabels,1)~=1)
            colLabels=colLabels';
        end
        if(size(colLabels,1)~=1)
            error('Column labels should be a "vector" of cells (one dimensional)')
        end
        if(size(colLabels,2)~=n)
            error('Number of column labels should match the number of columns of input matrix')
        end
        outNrow = m+1;
    end
    
    if isRlab
        if(size(rowLabels,2)~=1)
            rowLabels=rowLabels';
        end
        if(size(rowLabels,2)~=1)
            error('Row labels should be a "vector" of cells (one dimensional)')
        end
        if(size(rowLabels,1)~=m)
            error('Number of row labels should match the number of rows of input matrix')
        end
        outNcol = n+1;
    end
    
    out=cell( outNrow, outNcol );
    
    rOffset = outNrow - m;
    cOffset = outNcol - n;
    
    for i =1:m
        for j = 1:n
            out(i+rOffset,j+cOffset)={mat(i,j)};
        end
    end

     if isRlab && ~isClab
        out(:,1)=deal(rowLabels);
    end
    
    if isClab && ~isRlab
        out(1,:)=deal(colLabels);
    end
    
    if isRlab && isClab
         out(2:end,1)=deal(rowLabels);
         out(1,2:end)=deal(colLabels);
    end
    
    
    
end
