function export_eigen_data(pdm)
% function export_eigen_data(pdm)
%
% A function that takes a pdm structure and saves the eigenvectors and
% eigenvalues to an excel sheet. In the excel file the sheets that contain
% the eigenvectors, each column is a vector. 
%
% Dr. A. I. Hanna (2007)

% First get the name of the excel file to write the data to.
[xlsfilename, xlspathname] = uiputfile('*.xls', 'Save as...');
if isequal(xlsfilename,0) || isequal(xlspathname,0)
    disp('User pressed cancel')
    return;
end

% check that the fields we need are there
if ~isfield(pdm, 'pca')
    fprintf('cannot find field pca in pdm structure\n');
    return;
end
pcadata = pdm.pca;
if ~isfield(pcadata, 'P')
    fprintf('cannot find field P in pdm.pca structure\n');
    return;
end
P = pcadata.P;
if isempty(P)
    fprintf('matrix P is empty, nothing to save\n');
    return;
end
if ~isfield(pcadata, 'b')
    fprintf('cannot find field pca in pdm.pca structure\n');
    return;
end
b = pcadata.b;
if isempty(b)
    fprintf('vector b is empty, nothing to save\n');
    return;
end
P_sheets = matrix2cellarray(P);
b_sheets = matrix2cellarray(b);

for i=1:length(P_sheets)
    sheet = P_sheets{i};
    [success, message] = xlswrite([xlspathname, filesep, xlsfilename], sheet, ['Eigenvectors ', num2str(i)]);
end
for i=1:length(b_sheets)
    sheet = b_sheets{i};
    [success, message] = xlswrite([xlspathname, filesep, xlsfilename], sheet, ['Eigenvalues ', num2str(i)]);
end
return
%%%
%
%%%
function pmsheets = matrix2cellarray(P)
[N, M] = size(P);
P_cell  = mat2cell(P, ones(1, N), ones(1, M));
max_columns_in_excel_file = 250;
if size(P_cell,2)>max_columns_in_excel_file
    numsheets = ceil(M/max_columns_in_excel_file);
    pmsheets = cell(1, numsheets);
    indx = 1;
    for i=1:max_columns_in_excel_file:M
        start_ind = i;
        end_ind = min(i+max_columns_in_excel_file-1, M);
        pmsheets{indx} = P_cell(:, start_ind:end_ind);
        indx = indx +1;
    end
else
    pmsheets = {};
    pmsheets{1} = P_cell;
end
return