% Demonstration of textscan useage. File contains comments starting with
% % symbols. Each data line contains space seperated values for cell line, 
% pO2, location, factor mix and 5 osteo ratios (in this order).
% Created by Dr. C. S. Tritt, 11/15/10 (v. 1.1)
%
clear; close all; clc; % Start clean.
%
% Open data file and check for errors.
fid = fopen('tissEng.dat', 'rt'); % Open the data file.
if fid == -1
    fprintf('File open error.\n');
    return;
else
    fprintf('File successfully opened.\n');
end

% Read data into cell array.
data = textscan(fid, '%s%u%s%u%f%f%f%f%f', ...
    'CommentStyle', '%'); % Read data, skipping comments.
Nexps = size(data{1,1}, 1); % Number of lines (experiments). Used in loops.
fprintf('%i data lines (experiments) read into cell array.\n', Nexps)

% Construct structure array.
exper(100) = struct('cells', [], 'pO2', [], 'loc', [], ...
    'fact_mix', [], 'ratio', [], 'ave', []);
fprintf('Structure created.\n')

% Transfer data from cell array to structure array for easier handling.
% Calculate and save experiment averages in the process.
for n = 1:Nexps % Process each line of data (i.e., experiment).
    exper(n).cells = data{1,1}(n);
    exper(n).pO2 = data{1,2}(n);
    exper(n).loc = data{1,3}(n);
    exper(n).fact_mix = data{1,4}(n);
    exper(n).ratio(1) = data{1,5}(n);
    exper(n).ratio(2) = data{1,6}(n);
    exper(n).ratio(3) = data{1,7}(n);
    exper(n).ratio(5) = data{1,8}(n);
    exper(n).ratio(6) = data{1,9}(n);
    exper(n).ave = mean(exper(n).ratio);
end
clear data; % Delete data as it is no longer needed.
fprintf('Structure populated.\n')

% Process data. Find average of by cell line for pO2s between 75 and 95.
count = [0 0 0]; % Initialize counts.
sum = [0 0 0]; % Initialize sums.
A = 1; B = 2; XY = 3; % Use symbolic (variable) indices for easier reading. 
for n = 1:Nexps
    if exper(n).pO2 >= 75 && exper(n).pO2 <= 95
        if (strcmpi(exper(n).cells, 'a'))
            count(A) = count(A) + 1;
            sum(A) = sum(A) + exper(n).ave;
        elseif (strcmpi(exper(n).cells, 'b'))
            count(B) = count(B) + 1;
            sum(B) = sum(B) + exper(n).ave;
        elseif (strcmpi(exper(n).cells, 'xy'))
            count(XY) = count(XY) + 1;
            sum(XY) = sum(XY) + exper(n).ave;
        else
            fprintf('Experiment %i: unrecognized cell line - %s\n', ...
                n, exper(n).cells{:}); % Note required dereference. 
        end
    end
end
ave = sum ./ count; % Vectorized calculation of average.
fprintf('Data processing complete.\n')

% Calculate averagesa and display results.
fprintf('Average osteo ratios for 75 <= pO2 <= 95 experiments --\n');
fprintf('Cell line a: %6.3f\n', ave(A));
fprintf('Cell line b: %6.3f\n', ave(B));
fprintf('Cell line xy: %6.3f\n', ave(XY));

% Close the open file before exiting.
fclose(fid);