function Glossy_MDS(varargin)

Screen('Preference', 'SkipSyncTests', 1);
% glossy_MDS
%
% Experiment to demonstrate MDS to recover two dimensions (roughness and transmittance, two layers subsurface rendering using MaxwellRender) of a glossy space.
% Stimuli are pre-rendered frames, loaded on each trial.  The objects are from a 4x4 grid .  
% Subjects rate perceived (dis)similarity of pairs of stimuli
%
% originally coded by Roland Fleming
% example stimuli rendered by Eugen Prokott
%
% DEPENDECIES: Psychtoolbox
% 
% FZ 2016


%%%%%%%%%%%%%%%%
% Parameters
disp('Setting Parameters ...')

if nargin < 1
    num_reps = 2;
else
    num_reps = varargin{1};
end

rand('state',sum(100*clock)); % Sets random seed to be different for each subject

% Shape parameters and trial organization(dim1, dim2)
dim1_rough = (1:4);
dim2_transmit = (1:4);
num_stims = length(dim1_rough) .* length(dim2_transmit);
stimLookup = zeros(num_stims, 2);
% dim1 x dim2
[dim1Perms, dim2Perms] = meshgrid(dim1_rough, dim2_transmit);
stimLookup(:, 1) = dim1Perms(:);
stimLookup(:, 2) = dim2Perms(:);

pairs = nchoosek(1:16, 2);
As = pairs(:, 1);
Bs = pairs(:, 2);
num_trials = size(pairs, 1);
trialLookup = zeros(num_trials, 7);
trialLookup(:, 1) = 1:num_trials;
trialLookup(:, 2:3) = pairs;
trialLookup(:, 4) = stimLookup(As, 1);
trialLookup(:, 5) = stimLookup(As, 2);
trialLookup(:, 6) = stimLookup(Bs, 1);
trialLookup(:, 7) = stimLookup(Bs, 2);

% Response Keys
escape = KbName('ESCAPE');

% RESULTS:
results_path = 'Results';
columns = {'condOrder', 'condID', 'stimA_ID', 'stimB_ID', 'stimA_dim1', 'stimA_dim2', 'stimB_dim1', 'stimB_dim2', 'similarity rating'};
num_columns = length(columns);
results = zeros(num_trials, num_columns, num_reps);
sorted = results;
DissimMatrix = zeros(num_stims, num_stims, num_reps);

% Images
sliderRad = 300;
imWidth = 400;
imHeight = 400;
ovalrad = 4;
disp('Loading images ...')
% imblock = zeros(imHeight, imWidth, 3, num_stims, 'uint8');
imblock = zeros(imHeight, imWidth, 3, num_stims);
for cnt=1:num_stims
    dim1=stimLookup(cnt, 1);
    dim2=stimLookup(cnt, 2);
%     filename = sprintf('Stimuli/Stimulus-%d-%d.png', dim2, dim1);
    filename = sprintf('newStimuli/Stimulus-%d-%d.png', dim2, dim1);
    imblock(:, :, :, cnt) = imread(filename);
end
disp('done')

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%  Subject enters initials
initials = inputdlg('Enter Subject Number or Initials', 'Subject');

try
    %%%%%%%%%%%%%%%%%%%%%%
    % initialize screen
    disp('Initializing Screen ...')
    screens = Screen('Screens');
    [window, screenRect]=Screen('OpenWindow', max(screens(:)));
    
    sX = screenRect(3) ./ 2;
    sY = screenRect(4) ./ 2;
    lX = sX ./ 2;
    rX = sX + lX;
    leftrect = [lX-(imWidth./2) sY-(imHeight./2) lX+(imWidth./2)-1 sY+(imHeight./2)-1];
    rightrect = [rX-(imWidth./2) sY-(imHeight./2) rX+(imWidth./2)-1 sY+(imHeight./2)-1];

    sliderMin = sX - sliderRad;
    sliderMax = sX + sliderRad;
    sliderLength = sliderMax - sliderMin;
    sliderY = round(leftrect(4) + ((screenRect(4) - leftrect(4))./2));

    white=WhiteIndex(window);
    black=BlackIndex(window);
    grey=(white+black)/2;
    Screen(window,'FillRect', black);
    Screen('Flip', window);
    HideCursor;
    Screen(window,'TextSize', 24);
    [screenXpixels, screenYpixels] = Screen('WindowSize', window);
    Screen('BlendFunction', window, 'GL_SRC_ALPHA', 'GL_ONE_MINUS_SRC_ALPHA');

    for rep = 1:num_reps
        disp(sprintf('Rep %d', rep));
        %%%%%%%%%%%%%%%%%%%%%%
        % Trial structure
        trialOrder = randperm(num_trials)'; % creates random sequence of conds, scrambled across factors
        trials = [trialOrder, trialLookup];
        trials = sortrows(trials, 1);
        % Put conditions in results table
        results(:, 1:8, rep) = trials;

        for trial = 1:num_trials

            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            % Get conditions for current trial
            stimA = trials(trial, 3);
            stimB = trials(trial, 4);
            Screen('TextSize', window, 30);
            Screen('TextFont', window, 'Courier');
            DrawFormattedText(window, 'Similar', screenXpixels * 0.15, screenYpixels * 0.85, white);   
            Screen('TextSize', window, 30);
            Screen('TextFont', window, 'Courier');
            DrawFormattedText(window, 'Dissimlar', screenXpixels * 0.75, screenYpixels * 0.85, white);  
            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            % Load Image
            disp('Preparing image for current trial...');
            imAdata = imblock(:, :, :, stimA);
            imBdata = imblock(:, :, :, stimB);
            imA = Screen('MakeTexture', window, imAdata);
            imB = Screen('MakeTexture', window, imBdata);

            %%%%%%%%%%%%%%%%%%%%%
            % Present stimulus
            disp('Presenting stimulus ...')    
            theX = round((rand(1) .* sliderLength) + sliderMin);  % Set initial position to random location along slider
            theY = sliderY;
            SetMouse(theX, theY, window);
            ovalRect = [theX-ovalrad, theY-ovalrad, theX+ovalrad, theY+ovalrad];
            coinflip = round(rand(1));
            if coinflip
                Screen('DrawTexture', window, imA, [], leftrect);
                Screen('DrawTexture', window, imB, [], rightrect);
            else
                Screen('DrawTexture', window, imB, [], leftrect);
                Screen('DrawTexture', window, imA, [], rightrect);
            end
            Screen('DrawLine', window, [255 0 0], sliderMin, sliderY, sliderMax, sliderY);
            Screen('FillOval', window, [255 0 0], ovalRect);
            Screen('Flip', window);

            %%%%%%%%%%%%%%%%%%%%%%
            % Waiting for response
            disp('Waiting for response ...')
            % Wait for subject to release mouse button
            [dummy1,dummy2,buttons] = GetMouse;
            while any(buttons) % if already down, wait for release
                [dummy1,dummy2,buttons] = GetMouse;
            end
            while (1)
                [key_pressed, dummy, key_code] = KbCheck;  % check keyboard
                if key_pressed
                    key = find(key_code);
                    if length(key) == 1     % Ensures only one key is pressed
                        if(key == escape)
                            error('Experiment Aborted by Subject!')
                        end
                    end
                end

                [x,dummy,buttons] = GetMouse(window);  % Get mouse location
                if buttons(1)
                    break;
                end
                if (x ~= theX)
                    if x < sliderMin; x = sliderMin; end
                    if x > sliderMax; x = sliderMax; end
                    theX = x; % theY = sliderY;  % still set from previously
                    ovalRect = [theX-ovalrad, theY-ovalrad, theX+ovalrad, theY+ovalrad];
                    if coinflip
                        Screen('DrawTexture', window, imA, [], leftrect);
                        Screen('DrawTexture', window, imB, [], rightrect);
                        Screen('TextSize', window, 30);
                        Screen('TextFont', window, 'Courier');
                        DrawFormattedText(window, 'Similar', screenXpixels * 0.15, screenYpixels * 0.85, white);   
                        Screen('TextSize', window, 30);
                        Screen('TextFont', window, 'Courier');
                        DrawFormattedText(window, 'Dissimlar', screenXpixels * 0.75, screenYpixels * 0.85, white);  
                    else
                        Screen('DrawTexture', window, imB, [], leftrect);
                        Screen('DrawTexture', window, imA, [], rightrect);
                        Screen('TextSize', window, 30);
                        Screen('TextFont', window, 'Courier');
                        DrawFormattedText(window, 'Similar', screenXpixels * 0.15, screenYpixels * 0.85, white);   
                        Screen('TextSize', window, 30);
                        Screen('TextFont', window, 'Courier');
                        DrawFormattedText(window, 'Dissimlar', screenXpixels * 0.75, screenYpixels * 0.85, white);  
                    end
                    Screen('DrawLine', window, [255 0 0], sliderMin, sliderY, sliderMax, sliderY);
                    Screen('FillOval', window, [255 0 0], ovalRect);
                    Screen('Flip', window);
                end
            end

            % convert from slider position to dissimilarity scale (0:1)
            rating = (theX - sliderMin) ./ sliderLength;
            results(trial, 9, rep) = rating;
            DissimMatrix(stimA, stimB, rep) = rating;
            DissimMatrix(stimB, stimA, rep) = rating;

            Screen('Close');  % wipe the texture buffer containing images to save texture memory !!
        end
        sorted(:, :, rep) = sortrows(results(:, :, rep), 2);
    end % repetitions

    disp('Saving data ...')
    save(sprintf('Results/MDS_glossy_%s_%s.mat', char(initials), date), 'results', 'columns', 'stimLookup', 'DissimMatrix');

    % tidy up
    Priority(0);
    ShowCursor;
    Screen('CloseAll');
catch
    Screen('CloseAll');
    ShowCursor;
    Priority(0);
    rethrow(lasterror);
    disp('Saving raw data backup following error ...')
    save(sprintf('Results/%s_%s_backup.mat', char(initials), date), 'results', 'columns');
end

