function [Resp, RT] = showInstruction(slidenum,PTBParams,varargin)
% function showInstruction(slidenum, PTBParams, [options])
%
% DESCRIPTION: Shows image file of instruction, and waits for user to press
% a key to continue.
%
% slidenum: The number identifier of the slide/image to display
% PTBParams: structure containing useful info for PTB
%
% Option 1: 'SlidePrefix': Name of image file before the number identifier,
% e.g. Slide01.png, Instruction01.jpg
% Example: showInstruction(1,PTBParams,'SlidePrefix','InstructionImage')
% default prefix = 'Slide'
%
% Option 2: 'SlideType': 'PNG','JPG','BMP'
% Example: showInstruction(1,PTBParams,'SlideType','BMP')
% default = 'PNG'
%
% Option 3: 'SlidePath': location of instruction slides
% Example: showInstruction(1,PTBParams,'SlidePath','../NewInstructions/')
% default = homepath of the calling function
%
% Option 4: 'RequiredKeys': keys accepted by the slide to move on
% default = any key
%
% Author: Cendri Hutcherson
% Date: 9.16.08
%

% set defaults
slide_prefix = 'Slide';
slide_type = 'PNG';
required_keys = {};

% overwrite defaults if specified
if nargin > 1
    options_used = varargin(1:2:end);
    option_specification = varargin(2:2:end);

    for i = 1:length(options_used)
        switch options_used{i}
            case 'SlidePrefix'
                slide_prefix = option_specification{i};
            case 'SlideType'
                slide_type = option_specification{i};
            case 'SlidePath'
                homepath = option_specification{i};
            case 'RequiredKeys'
                required_keys = option_specification{i};

        end
    end
end

% read the image (assumes all images have number identifiers that are
% zero-padded to a minimum of two digits (i.e. Slide01.png, Slide02.png,
% Slide10.png)
InsrxScreen = imread([PTBParams.homepath 'Instructions/' slide_prefix ...
    sprintf('%02.0f',slidenum) '.' lower(slide_type)], slide_type);
textureIndex=Screen('MakeTexture',PTBParams.win,InsrxScreen);

% resize instruction screen to minimize distortion in the image
imageDims = size(InsrxScreen);
minResizeFactor = min([PTBParams.rect(4)/imageDims(1),PTBParams.rect(3)/...
    imageDims(2)]);

xOffset = floor((PTBParams.rect(3) - imageDims(2) * minResizeFactor)/2);
yOffset = floor((PTBParams.rect(4) - imageDims(1) * minResizeFactor)/2);
destRect = [xOffset, ...
            yOffset, ...
            xOffset + imageDims(2) * minResizeFactor,...
            yOffset + imageDims(1) * minResizeFactor];

        % draw the image
Screen('DrawTexture',PTBParams.win,textureIndex,[],destRect);
Screen(PTBParams.win,'Flip');
Screen('Close',textureIndex);

[Resp, RT] = collectResponse([],[],required_keys);