function [ structure ] = imdirectbil( numberofimages,cropper,varargin )
% IMDIRECTBIL:
% [ S ] = imdirectbil( N,C,varargin ) outputs to structure S the results of
% an image PCA of N multispectral data images present in the current
% folder. C is the cropping matrix [topleftx toplefty bottomrightx
% bottomrighty] which will crop the image before analysis. VARARGIN is the
% transformtype to use to register images after a pre-registration step
% (translation).
%
%   TRANSFORMTYPE         TYPES OF DISTORTION
%       -------------         -----------------------
%       'translation'         Translation
%       'rigid'               Translation, Rotation
%       'similarity'          Translation, Rotation, Scale
%       'affine'              Translation, Rotation, Scale, Shear

cropper=cropper+(mod(cropper,2));
fc=cropper(1);
fr=cropper(2);
lc=cropper(3);
lr=cropper(4);
bil=imget(numberofimages);
fprintf('Pre-registering images (translation)... ');
bil=bil(fr/2:lr+(end-lr)/2,fc/2:lc+(end-lc)/2,:);
bil=registerbil(bil,'translation');
if size(varargin,1)>0 && strcmp(varargin{1},'translation')~=1
disp(sprintf('re-registering images (%s)... ',varargin{1}));
bil=registerbil(bil,varargin{1});
end
disp(sprintf('cropping, decorrelating and standardising... '));
bil=bil(fr/2:lr-fr/2,fc/2:lc-fc/2,:);
% bil=bil(fr:lr,fc:lc,:);
sbil=decorrstretch(bil);
[bil]=pixelrange2(bil);
[sbil]=pixelrange2(sbil);
fprintf('principal components analysis... ');
[d,p,s,l,e]=makepcabil(bil);
[ds,ps,ss,ls,es]=makepcabil(sbil);
fprintf('creating images, writing variables to data structure... ');
nrows=cropper(4)-cropper(2)+1;
for w=1:numberofimages;
scoreimages(:,:,w)=imadjust(mat2gray(reshape(s(:,w),nrows,[])),stretchlim(mat2gray(reshape(s(:,w),nrows,[]))),[]);
end
for w=1:numberofimages;
sscoreimages(:,:,w)=imadjust(mat2gray(reshape(ss(:,w),nrows,[])),stretchlim(mat2gray(reshape(ss(:,w),nrows,[]))),[]);
end
structure(1).name='Regular';
structure(2).name='Decorrelated';
structure(1).bil=bil;
structure(2).bil=sbil;
structure(1).images=scoreimages;
structure(2).images=sscoreimages;
structure(1).data=d;
structure(2).data=d;
structure(1).ddata=[];
structure(2).ddata=ds;
structure(1).pc=p;
structure(2).pc=ps;
structure(1).score=s;
structure(2).score=ss;
structure(1).normscore=s./repmat(std(s),length(s),1);
structure(2).normscore=ss./repmat(std(ss),length(ss),1);
structure(1).latent=l;
structure(2).latent=ls;
structure(1).variance=e;
structure(2).variance=es;
structure(1).cropmatrix=cropper;
structure(2).cropmatrix=cropper;

structure(1).map=[];
structure(2).map=[];
structure(1).findk=[];
structure(2).findk=[];
disp('complete. ');
end