% ASSIGNMENT 4: Electrical/Bioengineering Case Study - Fear Analysis using GSR data
% Author: Mahfuz
% Date Created: December 19, 2023
%
% This script analyzes galvanic skin response (GSR) data collected in
% baseline and fear conditions. It applies a signal-processing pipeline,
% extracts features, computes a weighted fear index, and visualizes each
% stage of the workflow.

clc;
clearvars;
close all;

projectRoot = fileparts(mfilename('fullpath'));

conditionConfigs = [
    struct('name', 'Baseline', 'filename', 'GSR_Baseline.csv', 'color', 'b')
    struct('name', 'Fear', 'filename', 'GSR_FEAR.csv', 'color', 'r')
];

results = repmat(struct( ...
    'name', '', ...
    'color', '', ...
    'timeMillis', [], ...
    'raw', [], ...
    'medianFiltered', [], ...
    'lowPassFiltered', [], ...
    'movingAverageFiltered', [], ...
    'normalized', [], ...
    'features', struct(), ...
    'fearIndex', 0), size(conditionConfigs));

for idx = 1:numel(conditionConfigs)
    results(idx) = runConditionAnalysis(projectRoot, conditionConfigs(idx));
    printConditionSummary(results(idx));
end

plotProcessingStages(results);

function result = runConditionAnalysis(projectRoot, config)
    dataFile = resolveDataFile(projectRoot, config.filename);
    [timeMillis, rawValues] = loadAndProcessCSV(dataFile);

    medianFiltered = applyThirdOrderMedianFilter(rawValues);
    lowPassFiltered = applyLowPassFilter(medianFiltered);
    movingAverageFiltered = applyMovingAverageFilter(lowPassFiltered, 10);
    normalizedSignal = normalizeGSR(movingAverageFiltered);

    features = calculateGSRFeatures(normalizedSignal, timeMillis);
    fearIndex = calculateFearIndex(features);

    result = struct( ...
        'name', config.name, ...
        'color', config.color, ...
        'timeMillis', timeMillis, ...
        'raw', rawValues, ...
        'medianFiltered', medianFiltered, ...
        'lowPassFiltered', lowPassFiltered, ...
        'movingAverageFiltered', movingAverageFiltered, ...
        'normalized', normalizedSignal, ...
        'features', features, ...
        'fearIndex', fearIndex);
end

function printConditionSummary(result)
    fprintf('%s Features:\n', result.name);
    disp(result.features);
    fprintf('%s Fear Index: %.4f\n\n', result.name, result.fearIndex);
end

function plotProcessingStages(results)
    stageDefinitions = {
        'Original Data', 'raw', 'GSR (uS)', 1
        '3rd Order Median Filter', 'medianFiltered', 'GSR (uS)', 2
        'Low Pass Filter', 'lowPassFiltered', 'GSR (uS)', 3
        'N-Point Moving Average', 'movingAverageFiltered', 'GSR (uS)', 4
        'Normalized Data', 'normalized', 'Normalized GSR', 5
    };

    for stageIdx = 1:size(stageDefinitions, 1) - 1
        figure(stageDefinitions{stageIdx, 4});
        for conditionIdx = 1:numel(results)
            subplot(2, 2, conditionIdx);
            plotSignal(results(conditionIdx), stageDefinitions{stageIdx, 2}, ...
                stageDefinitions{stageIdx, 1}, stageDefinitions{stageIdx, 3});

            subplot(2, 2, conditionIdx + 2);
            plotSignal(results(conditionIdx), stageDefinitions{stageIdx + 1, 2}, ...
                stageDefinitions{stageIdx + 1, 1}, stageDefinitions{stageIdx + 1, 3});
        end
    end

    figure(stageDefinitions{end, 4});
    for conditionIdx = 1:numel(results)
        subplot(1, numel(results), conditionIdx);
        plotSignal(results(conditionIdx), stageDefinitions{end, 2}, ...
            stageDefinitions{end, 1}, stageDefinitions{end, 3});
        legend(results(conditionIdx).name, 'Location', 'best');
    end
end

function plotSignal(result, fieldName, stageName, yLabelText)
    plot(result.timeMillis, result.(fieldName), result.color, 'LineWidth', 1.25);
    title(sprintf('%s: %s', result.name, stageName));
    xlabel('Time (ms)');
    ylabel(yLabelText);
    grid on;
end

function resolvedPath = resolveDataFile(projectRoot, filename)
    candidatePaths = {
        fullfile(projectRoot, filename)
        fullfile(projectRoot, 'data', filename)
    };

    for idx = 1:numel(candidatePaths)
        if isfile(candidatePaths{idx})
            resolvedPath = candidatePaths{idx};
            return;
        end
    end

    error(['Required data file not found: ', filename, ...
        '. Place it in the project root or in a data/ directory.']);
end
