function [images,imgNum,imgNames] = loadImagesFromScript(scriptName,stimSize,contrastScale);
% [images,imgNum,imgNames] = loadImagesFromScript(Trials,[stimSize,contrastScale]);
%
% Load/Resize/Contrast-scale images specified in script, into 'images' (cell-of-matrices).
% 
% Inputs:
%	Trials: struct with the field 'image'; Trials.image should be an array of strings specifying
% 	the location of .jpg images to load (with some other key text words like 'blank' or 'end of run'). 
%	Trials is generally obtained by using fmra_er_readscript, varyISI_readscript, or some other
% 	*_readscript file used for Rory's expts.
%
%	stimSize: (optional) size to reshape stimuli (square). If empty, the matrices will all be the
% 	size of the first image specified. Default = 240.
%.
%	contrastScale: (optional) proportion to adjust contrast of image. E.g., contrastScale = 0.5
% 	will scale each image around the gray value to be half as much contrast. Default = 1, don't 
%	scale
%
% Outputs:
%
%	images: cell-of-matrices; each matrix is a different unique image specified in 
%	Trials.image. Each matrix is square, sized stimSize x stimSize.
%
%	imgNum: array the same length as Trials.image, specifying the index in 'images' for each image.
%     So, for instance, if the first 10 entries in Trials.image all point to the same file, imgNum(1:10)
% 	will equal [1 1 1 1 1 1 1 1 1 1 ...], and that image will be found in images{1}.
%
%	imgNames: cell array the same length as images; each entry is a string specifying the 
%	full file name (+ path) of the image that was loaded to produce the image.
%
% NOTE: To prevent redundant loading of repeated images, the cell-array 'images' contains
% each unique image only once; so 'images' is not going have as many entries as there are in
% 'Trials.image'. The imgNum array needs to be used to reference where each image has been 
% load in 'images'. 
%
% A blank (gray-color) matrix is appended as the last entry in 'images'. Trials labeled 'blank' in
% Trials.image are referred to this entry in imgNum.
%
% Written 1/17/03 by ras.
% 10/15/03 ras: updated for exp4, now works with paths relative to imageDB. Unfortunately, not 
% backward compatible with old scripts. Renaming old version as 'old_loadImagesFromScript'.

if ~exist('stimSize','var') 		stimSize = [];         			end
if ~exist('contrastScale','var') 	contrastScale = 1;         		end

%%%%% if a string has been passed (name of script), load script; if a struct has 
%%%%% been passed, check that it has an images field, if a cell has been passed,
%%%%% assume this is a set of image names directly
if ischar(scriptName)
	Trials = exp4_readscript(scriptName);
elseif iscell(scriptName) & ischar(scriptName{1})
	Trials.image = scriptName;
elseif isstruct(scriptName) & isfield(scriptName,'image')
	Trials = scriptName;
end

%%%%% params
gray = 127;

%%%%% assign an image number to each distinct image (repeated images numbered the same)
imgNum = zeros(1,length(Trials.image));
% first assigned reserved names, specifying null trials etc., to negative imgNums
for i = 1:length(Trials.image)
	if strncmp('blank',Trials.image{i},5)
		imgNum(i) = -1;
	elseif strncmp('end',Trials.image{i},3)
		imgNum(i) = -2;
	end
end
% assign remaining names, specifying image files, to positive imgNums
imgcnt = 1;
while ~all(imgNum)
	nextimg = find(imgNum==0);
	nextimg = nextimg(1);
	imgname = Trials.image{nextimg};
	for i = 1:length(Trials.image)
		if isequal(Trials.image{i}, imgname)
			imgNum(i) = imgcnt;
		end
	end
	imgcnt = imgcnt + 1;	
end

% if no stimSize assigned, set stimSize to size of first image
if isempty(stimSize)
	firstimg = find(imgNum==1);
	firstimg = firstimg(1);
	firstfile = strtok(Trials.image{firstimg});
	testfile = fullfile(imageDB,firstfile);
	if ~exist(testfile,'file')
		testfile = fullfile(machinename,firstfile);
	end
	test = imread(testfile,'jpg');
	stimSize = length(test);
	resize = 0;
else resize = 1;
end

%%%%% load each image into 'images' cell-of-matrices
fprintf('Loading %i images.',max(imgNum));
for imgcnt = 1:max(imgNum)
	nextimg = find(imgNum==imgcnt);
	nextimg = nextimg(1);
% 	imgname = strtok(Trials.image{nextimg});
	imgname = removeSpaces(Trials.image{nextimg}); % different from strtok
	imgfile = fullfile(imageDB,imgname);

	% an attempt at backwards compatibility: if file doesn't exist relative
	% to imageDB, see if it's relative to machinename
	if ~exist(imgfile,'file')
		imgfile = fullfile(machinename,imgname);
	end

	img = imread(imgfile,'jpg');					% load the image
	img = uint8(floor( (double(img) - gray) *contrastScale ) + gray);   % scale the color
	if resize
		img = imresize(img,[stimSize stimSize]);		% resize image
	end
	images{imgcnt} = img;
	imgNames{imgcnt} = imgname;
	fprintf('.');
end
fprintf('done. \n');

%%%%% add blank (other reserved images) at end of 'images'
imgcnt = length(images)+1;
images{imgcnt} = gray*ones([stimSize,stimSize]);
imgNum(find(imgNum==-1)) = imgcnt;	

return
  



function str = removeSpaces(str);
% removes leading and trailing, but not internal, spaces in a string.
while str(1)==' '
	str = str(2:end);
end
while str(end)==' '
	str = str(1:end-1);
end
return
