function [ data,pc,score,latent,explain ] = makepcabil( bil )
%Function: Perform PCA on image matrices
%Compiles a data matrix from a bil type matrix and performs PCA.
%
%OUTPUTS: data matrix, pc matrix, scores matrix, latent variables,
%"explained" latent variables
%Inputs Required: (bil), where bil is a n*m*i matrix of i images.
%
%Notes the number of rows in the first image matrix as a global variable.
%All matrices are reshaped into single columns, and %concatenated into data 
%matrix "data". PCA on this yields the principal components matrix "pc", 
%scores matrix "score" and the absolute variance in each
%latent variable in the matrix "latent". Matrix "explain" is "latent"
%expressed as a percentage and a cumulative sum, which is printed to the 
%command window at completion of the function.
global nrows
nrows=size(bil,1);
ncols=size(bil,2);
images=size(bil,3);
if images < 7
    rows=2;
    columns=3;
else rows=3;
    columns=3;
end
if images > 9
    rows=3;
    columns=4;
else rows=rows;
    columns=columns;
end
if images > 12
    rows=4;
    columns=4;
else rows=rows;
    columns=columns;
end
[data]=reshape(bil,nrows*ncols,images);
[pc,score,latent]=pca(data);
explain=[latent.*100./sum(latent),cumsum(latent.*100./sum(latent))]
figure
plotmatrix(score(1:500:end,:));
title('Scores Plot Matrix')
makescoremaps(score,rows,columns);
end