%To anyone reading this, please be gentle in critiquing my code. I've only
%been doing this for about 6 months now...


%Reads in excel stim presentation and accuracy data, reads in fiff files(s) and 
%creates new trigger channel STI101 based on the data across the five sessions, calls mne_ex...
%to read in old fiff file, writes new trig channel and saves as new fiff file. 

clear all
close all

inlist{1,1} = 'cc101_nback_meg_mc_tsss.fif';
inlist{2,1} = 'cc101_nback_meg-1_mc_tsss.fif';

outlist{1,1} = 'testfile1.fif';
outlist{2,1} = 'testfile2.fif';



s1 = 83478;
s2 = 436777;
s3 = 774774;
s4 = 1116138;
s5 = 1472884;

%1. Read in old fiff files to be changed. 

%Read fiff file header
fh1 = fiff_setup_read_raw(inlist{1,1});
fh2 = fiff_setup_read_raw(inlist{2,1});

%Read fiff file info
f1 = fiff_read_raw_segment(fh1);
f2 = fiff_read_raw_segment(fh2);

flength(1,1) = length(f1);
flength(2,1) = length(f2);


%Finds STI101 channel 
trigloc = find(strcmpi('STI101', fh1.info.ch_names));

%Combines both files trigger channels into one large one. 
trigch = horzcat(f1(trigloc,:), f2(trigloc,:));

%Plots old triggers
plot(trigch, '-ob')
hold;

clear fh* f1 f2 %No longer needed. Can read values directly from trigchan. 

%2. Read excel data, create new trigger channel values.

%%%EXCEL SECTION%%%

sheets = {'Sheet1', 'Sheet2', 'Sheet3', 'Sheet4', 'Sheet5'};
hap = [110 210 111 211 112 212 113 213];
sad = [120 220 121 221 122 222 123 223];
neu = [130 230 131 231 132 232 133 233];
rest = 99;
all = [hap sad neu rest];

%Copies each worksheet to its own matrix within structural file. 
%Note: n is numbers, t is text

for i = 1:5; 
[n{i}, t{i}] = xlsread('MEG_n-back_c101.xlsx', sheets{1,i});
i = i + 1;
end

%Zeroes trigger channel, writes new values (k) at sample j, loops through i
%times to write all values per session. NOTE: REQUIRES STIM DURATION
%ERROR TO BE PRESENT IN EXCEL SPREADSHEET. IF NOT WILL GIVE NAN ERROR.  

trigch(1,:) = 0;

for i = 1:159;
for j = s1; %Start Session 1
for k = 1:1:159;
trigch(1,j) = n{1,1}(k,3); %Reads trigger value
j = j + 1800 + n{1,1}(k,4); %Moves 1800 samples + offset given in row k of n).
k = k + 1;
i = i + 1;
end
end
end

for i = 1:159;
for j = s2; %Start Session 2
for k = 1:1:159;
trigch(1,j) = n{1,2}(k,3);
j = j + 1800 + n{1,2}(k,4);
k = k + 1;
i = i + 1;
end
end
end

for i = 1:158;
for j = s3; %Start Session 3
for k = 1:1:158;
trigch(1,j) = n{1,3}(k,3);
j = j + 1800 + n{1,3}(k,4);
k = k + 1;
i = i + 1;
end
end
end

for i = 1:159;
for j = s4; %Start Session 4
for k = 1:1:159;
trigch(1,j) = n{1,4}(k,3);
j = j + 1800 + n{1,4}(k,4);
k = k + 1;
i = i + 1;
end
end
end

for i = 1:159;
for j = s5; %Start Session 5
for k = 1:1:159;
trigch(1,j) = n{1,5}(k,3);
j = j + 1800 + n{1,5}(k,4);
k = k + 1;
i = i + 1;
end
end
end

clear s1 s2 s3 s4 s5 %Session sample start info no longer required - the
%next step is direct writing using fxlength var. 

%Plots old values over new. 
plot(trigch, '--*r'); %Check to see if
%new channel is synched with old (eg, doesn't start too early, end too
%late).

q = input('Write condition trial lists? y / n:    ', 's');

if strcmpi(q, 'y') == 1
   
% function mne_ex_read_write_raw(infile,outfile);
%
% Read and write raw data in 60-sec blocks
%

%
%   Author : Matti Hamalainen, MGH Martinos Center
%   License : BSD 3-clause
%
    
    global FIFF;
if isempty(FIFF)
   FIFF = fiff_define_constants();
end
    
    raw = fiff_setup_read_raw(char(inlist(1,1)));
    
    %want_meg   = true;
    %want_eeg   = false;
    %want_stim  = false;
    %include{1} = 'STI101';
    
    %picks = fiff_pick_types(raw.info,want_meg,want_eeg,want_stim,include,raw.info.bads);
    
    [outfid,cals] = fiff_start_writing_raw(char(outlist(1,1)),raw.info);
    
    from        = raw.first_samp;
    to          = raw.last_samp;
    quantum_sec = 100;
    quantum     = ceil(quantum_sec*raw.info.sfreq);
    %
    %   To read the whole file at once set
    %
    % quantum     = to - from + 1;
    %
    %
    %   Read and write all the data
    %
    first_buffer = true;
    for first = from:quantum:to
        last = first+quantum-1;
        if last > to
            last = to;
        end
     
        [ data, times ] = fiff_read_raw_segment(raw,first,last);
        
        
    trigloc = find(strcmpi(raw.info.ch_names, 'STI101'));
    data(trigloc,:) = 0;
    data(trigloc,(from:to)) = trigch(1,(from:to));

    %
    %   You can add your own miracle here
    %
   

    fprintf(1,'Writing...');
    if first_buffer
       if first > 0
           fiff_write_int(outfid,FIFF.FIFF_FIRST_SAMPLE,first);
       end
       first_buffer = false;
    end
    fiff_write_raw_buffer(outfid,data,cals);
    fprintf(1,'[done]\n');
end

    
else disp('Exiting')
end

