function info=GetPackage(PackName,iver,packdir)
% Get local copy of standard lab analysis package.
% Usage: info=GetPackage(PackName,[ver],[PackageDir]);
% PackName is NOT case sensitive.  info returns structured list of available
% packages. ver is optional 3-digit version number (default: none or
% highest). Package name is determined by directory name in PackageDir
% (default: C:\Matlab\work\packages).  If PackName is a number then
% info(PackName).name is used.  A script UpdatePackage.m is created
% which will update the original package.
%
% (run GetPackage(); to see a list of Packages.)
%
% See also: AddToPackage

% revision history:
% 05/04/10 Mark D. Shattuck <mds> GetFiles.m  

if(~exist('packdir','var') || isempty(packdir))
	packdir='C:\Matlab\work\packages';
end

% Build info

pack=dir(packdir);
pack=pack([pack(:).isdir]);
pack=pack(3:end);
Npack=length(pack);
info=struct('name',{pack.name}');
for np=1:Npack
	files=dir([packdir '/' pack(np).name]);
	files=files(3:end);
	ver.num={files([files.isdir]).name};
	if(isempty(ver.num)); ver.num={''}; end;
	Nv=max([1 length(ver.num)]);
	for nv=1:Nv
		files=dir([packdir '/' pack(np).name '/' ver.num{nv}]);
		files=files(3:end);
		ver.files{nv}={files(~[files.isdir]).name};
		descfn=[packdir '/' pack(np).name '/' ver.num{nv} '/PackageDescription.m'];
		ver.ShortDesc{nv}='';
		ver.LongDesc{nv}='';
		ver.RevHist{nv}='';
		if(exist(descfn,'file'))
			clear('ShortDesc','LongDesc','RevHist');
			run(descfn);
			if(exist('ShortDesc','var'))
				ver.ShortDesc{nv}=ShortDesc;
			end
			if(exist('LongDesc','var'))
				ver.LongDesc{nv}=LongDesc;
			end
			if(exist('RevHist','var'))
				ver.RevHist{nv}=RevHist;
			end
		end
	end
	info(np).ver=ver;
end

% Process PackName

if(~exist('PackName','var') || isempty(PackName))
	ShowPackageInfo(info);
	return;
else
	if(isnumeric(PackName))
		PackNum=PackName;
	elseif(ischar(PackName))
		PackNum=find(strcmpi(PackName,{info.name}));
		if(isempty(PackNum))
			PackNum=0;
		end
	else
		PackNum=0;
	end
end

if(PackNum>=1 && PackNum<=Npack);
	% Process iver
	if(~exist('iver','var') || isempty(iver))
		iver=length(info(PackNum).ver.num);
	else
		iver=find(strcmpi(iver,{info(PackNum).name}));
	end
	srcdir=[packdir '/' info(PackNum).name '/' info(PackNum).ver.num{iver}];
	[status,message,messageId]=copyfile(srcdir,'.'); 
	if(~status)
		fprintf('Copy Failed: %s:: %s.\n',messageId,message);
	end
	if(exist('UpdatePackage.m','file'))
		delete('UpdatePackage.m');
	end
	fid=fopen('UpdatePackage.m','w');
	fprintf(fid,'%%%%Set Directory\nsyncdir=''%s'';\n\n',srcdir);
	Nf=length(info(PackNum).ver.files{iver});
	fprintf(fid,'%%%%Copy Files\n\n');
	for nf=1:Nf
		fn=info(PackNum).ver.files{iver}{nf};
		fprintf(fid,'s=copyfile(''%s'',syncdir);\n',fn);
		fprintf(fid,'if(~s);fprintf(''Copy Failed for: %s\\n'');end;\n\n',fn);
	end
	fclose(fid);
else
	fprintf('Package ''%s'' does not exist\n',num2str(PackName));
	return;
end

		
	