%FacesExperiment_DAI
%Presents 92 images randomly
%
%abort the experiment by pressing any key
%if experiment crashes for whatever reason press ctrl+c to get keyboard
%function back
%mv02 19/03 
%Back to original timings, 2 secs pic, 4 sec rest and null events 

clear all;
KbName('UnifyKeyNames');

%% SCANNERSYNC
TR=1000; % TR in ms
numdummies=20;

% Create & initialise scanner sync object
objSS=actxserver('MRISync.ScannerSync');  %Create a scanner object
invoke(objSS,'Initialize','') %Initialise the Keithley board and object
invoke(objSS,'SetMSPerSample',2); %Set “StartExperiment” routines’ sampling

%Create subject files
subjectNum = input('please enter the subject number:', 's');
sessionNum = input('please enter the session number:', 's');
fid=fopen('Results.txt','a');
fprintf(fid,['***New session at ' datestr(now) '\n']);
fprintf(fid, '%s\n', 'subjectNum sessionNum whichpicture');
fclose('all');

%ListenChar(2);   %prevents writing into the command window during the experiment

%open screen
try %embedded in try-catch in case something goes wrong
    whichScreen = 0;
    window = Screen(whichScreen, 'OpenWindow');

    white = WhiteIndex(window); % pixel value for white
    black = 128; % pixel value for grey
    Screen(window,'FillRect', black);
    HideCursor;
    WaitSecs(0.5);

    % onscreen instructions
    info =  ['You will be presented with a series of pictures' ...
        '\n\nPlease pay attention to the pictures' ...
        '\n\nThe experiment will begin after a countdown'];

    DrawFormattedText(window, info, 'center', 'center', white);
    Screen(window, 'Flip');
    %WaitSecs(10);  % now, wait below until first pulse


    % ScannerSync - waits for the first pulse, resets timer to 0, sets TR
    invoke(objSS,'StartExperiment', double(TR));


    %SCANNER PULSE IMPUT HERE%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    for countdown=(numdummies-1):-1:2 % two less as StartExperiment command above will already have heard a pulse and first trial waits for a pulse
        %cd_adjust=-2*countdown+6;
        %cd=countdown+cd_adjust;
        count_text=sprintf('%d', countdown);
        DrawFormattedText(window, count_text, 'center', 'center', white);
        Screen(window, 'Flip');
        WaitSecs(1.0);
    end;

    DrawFormattedText(window, '+', 'center', 'center', white);
    Screen(window, 'Flip');
    WaitSecs(1.5);  % a little less as will synchronise to next pulse below

    trialnum=1; % this includes the nulls
    while(1)
        while(1)

            %load picture
            parmfile=sprintf('c:\\temp\\parm%d.txt',trialnum);
            trialnum=trialnum+1;
            fprintf('Parameter file is %s\n',parmfile);
            dirfile=dir(parmfile);
            modtime=datestr(dirfile.date);
            accesstime=datestr(now);
            fid=fopen(parmfile,'r');
            whichpicture=str2num(fgetl(fid));
            fclose(fid);

            % -1 means end of session
            % -99 means end of experiment
            if (whichpicture==-1)
                break;
            end;
            if (whichpicture==-99)

                done = ['Thank you!'];
                DrawFormattedText(window, done, 'center', 'center', white);
                Screen(window, 'Flip');
                WaitSecs(20);

                Screen('CloseAll');
                ShowCursor
                return;
            end;

            % 0 means null trial
            if (whichpicture==0)
                % SCANNERSYNC
                invoke(objSS,'SynchroniseExperiment',1,0); %Set “StartExperiment” routines’ sampling
                %null events (fixation screen)
                WaitSecs(3.5); % A little less as will synchronise at start of next trial
            else

                fprintf('File %s value of whichpicture %d\n',parmfile, whichpicture);


                %    whichpicture=pics_shuffled(1,pics);
                picture_name=sprintf('stimulus_big%d.TIF',whichpicture);
                trialpicture=imread(picture_name, 'TIF');
                % SCANNERSYNC
                invoke(objSS,'SynchroniseExperiment',1,0); %Set “StartExperiment” routines’ sampling

                %                 scaleby=2;
                %
                %                 trialpicture=double(trialpicture);
                %                 for colourplane=1:3
                %                     t(:,:,colourplane)=interp2(squeeze(trialpicture(:,:,colourplane)),scaleby);
                %                 end;

                %present picture for two seconds
                tex=Screen('MakeTexture', window, trialpicture);
                Screen('DrawTexture', window, tex); %needs to be adjusted depending on the size of the picture!
                Screen(window, 'Flip');             %left, top, right, bottom; to make a square the difference between left-right and bottom-top must be the same!

                % SCANNERSYNC
                picstarttime=invoke(objSS,'SSGetTimer')
                WaitSecs(2);

                %present fixation cross for two seconds
                DrawFormattedText(window, '+', 'center', 'center', white);
                Screen(window, 'Flip');

                % Unload the texture or it complains when there are lots
                % loaded up
                Screen('Close', tex);

                WaitSecs(1.5); % A little less as will synchronise at start of next trial

                %write to file
                fid = fopen('Results.txt','a');
                fprintf(fid, '%2s\t%1s\t%d\t%f\t%s\t%s\n', subjectNum, sessionNum, whichpicture, picstarttime,modtime,accesstime);
                fclose(fid);

                %terminate as per real-time instructions


                %abort experiment
                %abort=CharAvail;
                %if abort==1
                %      error('aborted by user');
                %end;
            end;
        end;

        %end

        %KbWait;
        %while KbCheck; end;
        done = ['Brief pause,'...
            '\n\nplease remain fixated on the cross.'];
        DrawFormattedText(window, done, 'center', 'center', white);
        Screen(window, 'Flip');
        WaitSecs(3);
        % ...3 s here...
        %pause for real-time catch and wait for instructions
        DrawFormattedText(window, '+', 'center', 'center', white);
        Screen(window, 'Flip');
        % ...20.25 s here...
        WaitSecs(8.25);
        for waiti=1:36
            WaitSecs(1.0);
        end;
       % ...then the pulse, and we'll get a nice round 24 s                ...
        invoke(objSS,'SynchroniseExperiment',1,0); %Set “StartExperiment” routines’ sampling

    end
    %close
    Screen('CloseAll');
    ShowCursor

catch
    % This "catch" section executes in case of an error in the "try" section
    % above.  Importantly, it closes the onscreen window if it's open.
    Screen('CloseAll');
    psychrethrow(psychlasterror);
    ShowCursor
    %ListenChar(0);
end %end of try-catch

%ListenChar(0);













