function [STIM,imgRect] = loadOffscreen(win,images,varargin);
% Usage:
% [STIM,imgRect] = loadOffscreen(win,images,[options]);
%
% Takes a set of images, either as pixel arrays or as strings indicating
% file locations, and loads them into a series of off-screen windows.
% 
% Inputs:
%	win: Pointer to an existing onscreen window. Since the movie is stored in offscreen
% 	windows, this must already be opened.
%	
%	images: a cell containing images or image paths (or a mixture of both).
%
% Options:
%
%	stimSize: Put each image into a square of a set size. By default, it won't
%	do this, and will put different-sized images as their respective sizes onscreen
%
%	contrast: (optional) proportion to adjust contrast of image. E.g., contrast = 0.5
% 	will scale each image around the gray value to be half as much contrast. Default = 1, don't 
%	scale contrast
%
%	scale: size to rescale the images. Can also enter this argument as
%	a 2-entry vector specifying a range of scales, in which case it will
%	randomly scale each image within this range.
%
%	randPos: flag to randomize position of images anywhere on the screen.
%
%
% Outputs:
%
%	STIM: array of offscreen pointers to images.
%
%
% 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.
% 03/12/03 by ras: revised from loadImagesFromScript.
% 03/15/03 ras: revised again from loadScriptIntoMovie into loadOffscreen. Now accepts
% images directly.
% 11/25/03 ras: much improved. Now foregoes the imgNum crap, and has 
% options to randomly scale and position images on screen.
if nargin < 2		
	help loadOffscreen;
	return
end
	
%%%%% params
gray = 127;
imgType = 'jpg';
stimSize = [];
contrast = 1;
scale = 1;
randPos = 0;
setClut = [];
fixationFlag = 1;

%%%%% Parse the option flags
for i = 1:2:length(varargin)
	if isequal(varargin{i},'stimSize');
		stimSize = varargin{i+1};
	elseif ischar(varargin{i}) & i < length(varargin)
		a1 = varargin{i};
		a2 = varargin{i+1};
		cmd = sprintf('%s = %s;',a1,a2);
		eval(cmd);
	end
end

%%%%% For all strings in images, assume the string specifies a file
%%%%% path and load the images
for i = 1:length(images)
	if ischar(images{i})
		pth = images{i};

		% be flexible: sometimes I may specify a path relative
		% to imageDB
		if ~exist(pth,'file')
			pth = fullfile(imageDB,pth);
			
			if ~exist(pth,'file')
				msg = sprintf('Couldn''t find file %s.\n',images{i});
				error(msg);
			end
		end
	
		images{i} = imread(pth,imgType);
	end
end

% get info about the onscreen window for the movie
rect = screen(win,'Rect');
X = rect(3); Y = rect(4);

% if stimSize was assigned, set a standard rect to use for 
% all images (otherwise, images may be different sizes, use scale
% information to scale images uniformly but don't force same size)
if ~isempty(stimSize)
	stdRect = [X-stimSize Y-stimSize X+stimSize Y+stimSize]/2;
end

%%%%% calculate img Rect, taking into account prefs
if isempty(stimSize) 
	if length(scale) > 1  % randomize scale
		scl = RandSample(linspace(scale(1),scale(2),100));
		szX = scl * size(images{i},2);
		szY = scl * size(images{i},1);			
	else
		szX = scale * size(images{i},2);
		szY = scale * size(images{i},1);
	end

	imgRect = [X-szX Y-szY X+szX Y+szY]/2;
else	
	imgRect = stdRect;
end

% randomize position if selected
if randPos		
	rngX = X/2 - (imgRect(3)-imgRect(1));
	rngY = Y/2 - (imgRect(4)-imgRect(2));
	cornerX = randi(rngX);
	cornerY = randi(rngY);
	imgRect = [cornerX cornerY cornerX+rngX cornerY+rngY];
end

%%%%% load each image into STIM series of windows
fprintf('Loading %i images.',length(images));
for i = 1:length(images)

	STIM(i) = screen(win,'OpenOffScreenWindow',gray);

	% set clut if passed in
	if ~isempty(setClut)
		screen(STIM(i),'SetClut',setClut);
	end

	if contrast ~= 1
		images{i} = scaleContrast(images{i});
	end

	screen(STIM(i),'PutImage',images{i},imgRect,'srcCopyQuickly');

	fprintf('.');
end
fprintf('done. \n');

%%%%% add blank (other reserved images) at end of 'images'
i = length(STIM)+1;
STIM(i) = screen(win,'OpenOffScreenWindow',gray);

if fixationFlag==1
	for i = 1:length(STIM)	
		putFixation(STIM(i),255);
	end
end


return
