function convertDataToText
%-------------------------------------------------------------------------%
% function convertDataToText
%
% DESCRIPTION: This function is designed to take a Data.mat file (or files),
% and process them from .mat format into .csv (comma separated value)
% format, which is easily readable by other programs like R or SPSS.
%
% USAGE:
% 1) Edit the line defining the subjects you want to process below.
% 2) Edit the lines defining the .mat files you will load for processing
% 3) Edit the data file name to be saved
% 4) Define the column headers in the 'headers' variable
% 5) Define the actual variables to be printed

% Author: Cendri Hutcherson
% Last modified: 05-27-18

%-------------------------------------------------------------------------%

% First make this script path independent, based on the assumption that it
% resides in a directory called 'Analysis'
fileName = mfilename('fullpath');
dataPath = regexp(fileName,'.*Analysis','match');
dataPath = fullfile(dataPath{1}(1:(end - 8)), 'SubjectData');

% Define the subject identifiers. This program assumes they are identified
% by a simple numeric identifier. If this is not the case, you will have to
% edit the script to work with character strings.
subjects = [101];

% The following loop will iterate over all the subjects specified by the
% 'subjects' variable.
for s = 1:length(subjects)

    % Convert the subject number to a string so that it can be used to
    % specify file names
    subjID = num2str(subjects(s));

    % Display information about which subject is currently being processed
    fprintf('Processing data for subject %s...\n',subjID)

    % \ Get trial data for each part \
    % First make sure there's no prior data hanging around in the workspace
    clear Choice Ratings

    % Load the choice data
    load(fullfile(dataPath, subjID, ['Data.' subjID '.ChoiceTask.mat']))


    % Load the rating data
    Ratings = load(fullfile(dataPath, subjID, ...
        ['Data.' subjID '.AttributeRatings.mat']));

    % \ Print trial-by-trial variables to a .csv file \

    % First check to see if there's a previous version of this file
    % hanging around, and if there is, delete it.
    textFile = fullfile(dataPath,subjID,['ChoiceData_' subjID '.csv']);
    if exist(textFile,'file')
        delete(textFile)
    end

    % Next, open up a file with this name, using the "append" option, which
    % will allow you to write to the file one line at a time
    fid = fopen(textFile,'a');

    % Print a header line containing the names of the variables to be
    % printed
    headers = {'Subject','Trial','Instruction','Food','Liking', ...
            'Taste','Health','Amount','Choice','ChoiceRT'};

    for h = 1:length(headers)
        % Print each variable name followed by a comma, unless it's the
        % one, in which case, end the line with the 'newline' character
        if h < length(headers)
            fprintf(fid,'%s,',headers{h});
        else
            fprintf(fid,'%s\n',headers{h});
        end
    end


    % Now, we will run a loop for each trial, in which we will either
    % access the values of the variables out of one of our data structures
    % or manually calculate the variable on the fly for each trial. We will
    % then print one line per trial, using the variable specifications
    % contained in the columnVars cell defined below.
    % Note: Each entry here should correspond to the CODE YOU WOULD USE to
    % access that variable. For instance, if the data is contained in
    % the "Instruction" field of the Data structure, then you would have an
    % entry 'Data.Instruction{t}'. If you calculated a variable on the
    % fly in the trial loop, use the name of that variable. For example,
    % the loop below will calculate a "HealthRating" variable that matches
    % up the health rating for each food shown during the choice phase of
    % the task.
    % The length of the columnVars array should be exactly equal to the
    % length of the headers array calculated above.
    columnVars = {'Data.subjid','t','Data.Instruction{t}','FoodStem'...
               'LikingRating','TasteRating','HealthRating','FoodAmount',...
               'Data.Resp{t}','Data.ChoiceRT{t}'};


    for t = 1:length(Data.Resp) % loop over each trial completed

        % Identify the food shown and the numerical code for the portion
        % size (1-X). This can be extracted from the image file name for
        % the food, which has the format food_portionID_rawportion.jpg. To
        % extract the components, we use regexp.
        fullFoodName = Data.Food{t};
        FoodStem = fullFoodName(1:(regexp(fullFoodName,'_','once') - 1));
        FoodAmount = fullFoodName(regexp(fullFoodName,'_','once') + 1);

        % Identify health, taste, and liking ratings made during the
        % rating task that correspond to the food seen during the choice
        % task on that trial
        foodMatches = strcmp(Ratings.Data.Food,Data.Food{t});

        ratingIsHealth = strcmp(Ratings.Data.Attribute,'Health');
        HealthRating = Ratings.Data.Resp{ratingIsHealth & foodMatches};

        ratingIsTaste = strcmp(Ratings.Data.Attribute,'Taste');
        TasteRating = Ratings.Data.Resp{ratingIsTaste & foodMatches};

        ratingIsLiking = strcmp(Ratings.Data.Attribute,'Liking');
        LikingRating = Ratings.Data.Resp{ratingIsLiking & foodMatches};


        % Finally, we will loop through each variable, assign a variable v
        % to temporarily hold the value for the relevant variable, and then
        % use the printvar function (see the end of this script for
        % details) to print it in the proper format to the data file
        % specified by fid
        for c = 1:length(columnVars)
            eval(['v = ' columnVars{c} ';']);
            if c < length(columnVars)
                printvar(v,fid,','); % variable, file, end character: ','
            else
                printvar(v,fid,'\n'); % variable, file, end character: '\n'
            end
        end % end of variable loop

    end % end of trial loop

end % end of subject loop


function printvar(var,fid,endChar)
% This function checks the data type of the variable to be printed (which
% can be NaN, character, logical, or numeric), and then prints the variable
% in the appropriate format, followed by the desired character endChar
% (which can be a comma, tab ('\t'), new line ('\n'), etc.)

% First deal with NaN values
if isempty(var) || any(isnan(var))
    var = 'NA';
end

% Now, get the variable type
varInfo = whos('var');

% Based on the variable type, print the variable appropriately, followed
% by the endChar
switch varInfo.class
    case 'char'
        fprintf(fid,['%s' endChar],var);
    case 'logical'
        fprintf(fid,['%d' endChar],var);
    otherwise
        fprintf(fid,['%.4f' endChar],var);
end