%% loads subject-specific data files, extracts trialinfo from encoding and recognition, cuts to same trials in same order

function DNNpredictorMatrices(subject,dnnType,corr_type,rsa_tag,roi_tag,stiminfo)

    %load folder names of subjects
    load('..\subject_list.mat'); %subNames for easier folder accessing
    
    %set directories
    dataDir = '..\Data';
    fs = '\';
    fileName = subNames{subject};

    %% DNN specifics
    switch dnnType
        case 'AlexNet_avg'
            dnnDir = '..\PlacesNet\AlexNet_Averages';
            layerNum = 8;
            layerNames = {'conv1','conv2','conv3','conv4','conv5','fc6','fc7','fc8'};
    end
    
    %% load BtwItem Info
    load([dataDir fs fileName fs 'stats' fs 'BtwItem' fs rsa_tag fs roi_tag fs 'BtwInfo.mat']);
    trials = info.trialinfo(:,3); %retNum order (from encodingtrialinfo) 
    
    %% loop over layers, load full RDM, cut to respective trials in correct order
    for layer = 1:layerNum
        switch dnnType
            case 'AlexNet_avg'
                if layer < 6
                    name = ['average_' corr_type '_conv' num2str(layer) '_corrMat.xlsx'];
                else
                    name = ['average_' corr_type '_fc' num2str(layer) '_corrMat.xlsx'];
                end
                raw = xlsread([dnnDir fs name]);
                behead = 1;
        end
        if behead
            RSM = raw(2:end,2:end); %get rid of header and index!   
        end

        %% load STIMULI information to match current trialorder to DNN Mat order which are currently in pythonic indexing
        %at this point, dnns are in order from pythonic data indexing!!!!
        stiminfo = sortrows(stiminfo,'retNum');

        %cut order to subjects-trials
        stiminfo_subjtrials = stiminfo(trials,:); %trials is retNum of trials in encRSA and retRSA
        dnn_sortidx = stiminfo_subjtrials.trialnum;
        
        %sort raw dnn mat to trials and order from brain data!
        RSM = RSM(dnn_sortidx,dnn_sortidx);

        %only half for normalization and storing!
        temp_r_mem = zeros(size(RSM));
        lower_idx = find(tril(RSM,-1));
        temp_r_mem(lower_idx) = RSM(lower_idx);

        RSM_vec = temp_r_mem(find(temp_r_mem));   

        %Fisher Z Normalize across vector without diagonal!
        RSM = 0.5 .* log((1 + RSM_vec) ./(1 - RSM_vec)); %complex values!

        %reshape to matrix
        temp_r_mem = zeros(size(temp_r_mem));
        temp_r_mem(lower_idx) = RSM;
        RSM = temp_r_mem;

        %% get proper save Dir and save
        saveDir = [dataDir fs fileName fs 'stats' fs 'BtwItem' fs 'DNN' fs dnnType];
        
        %save cut DNNs for encoding and retrieval to disk
        status = mkdir(saveDir);

        %safe one file --> same for encoding and retrieval!!!
        save([saveDir fs name(1:end-4) '.mat'], 'RSM');

    end
    disp(['created ' fileName ' ' dnnType ' ' corr_type ' matrices'])
end

    