% Author: Elsa W. Birch, ewbirch@stanford.edu, Covert Lab - Stanford Bioengineering
% Date: July 27th 2012
% Version: associated with production of the figures for Birch et al. 2012
%
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
%
% Summary: Function sets up and coordinates the media componenets, loading in from file
% 
%
% Inputs: simulation - simulation structure
%
% Outputs: simulationWithMedia  - simulation including the media setup for the environment
%
%
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
%
% Notes: > multiple organisms ok
%
%
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
%
function simulationWithMedia = FBA_EB_simulationMedia(simulation)
%
mediaErrors = {};

% Media File
fileIdMedia = fopen( [simulation.setup.media, '.txt' ]);
% read in contents, assuming format columns: metaboliteID, concentration, freeExchangeFlag,
% (comment(discard))
headerRowsMedia = 1; % # ignored header rows
rawTextReadMedia = textscan(fileIdMedia, '%s %f %d %*s', 'Delimiter', '\t','HeaderLines', headerRowsMedia);
fclose(fileIdMedia); % close file

simulation.mediaID = simulation.setup.media;

% 
mediaComponents = rawTextReadMedia{ 1 };
mediaComponentsConc = rawTextReadMedia{ 2 };
freeExchangeFlags = rawTextReadMedia{ 3 };
nMediaFreeExchange = sum( freeExchangeFlags );
nMediaComponents = size( mediaComponents, 1 ); % temp variables, for number user entered
simulation.initialMedia = zeros( simulation.nMedia, 1 );
simulation.freeExchangeMedia = zeros(nMediaFreeExchange,1);
simulation.freeExchangeMediaIdx = zeros(nMediaFreeExchange,1);
iFreeExch = 0;

% loop through adding media componenets
for iMediaComp = 1 : nMediaComponents
    mediaMetName = upper( strrep(mediaComponents{iMediaComp}, '-', '_') );
    idxMediaComp = find(strcmp(['e',mediaMetName],simulation.mediaList), 1, 'first');
    if ~isempty(idxMediaComp)
        if freeExchangeFlags( iMediaComp ) == 0
            simulation.initialMedia( idxMediaComp ) = mediaComponentsConc( iMediaComp );
        elseif freeExchangeFlags( iMediaComp ) == 1
            iFreeExch = iFreeExch + 1;
            simulation.freeExchangeMedia( iFreeExch ) = mediaComponentsConc( iMediaComp );
            simulation.freeExchangeMediaIdx( iFreeExch ) = idxMediaComp;
        else
            mediaErrors = [ mediaErrors ,... 
            {(['free exchange flag ''', num2str(freeExchangeFlags( iMediaComp )),...
            ''', (associated with media component, ',['e',mediaMetName],...
            ')'])} ];
        end % uf freeExchangeFlags
    else
        mediaErrors = [ mediaErrors ,... 
            {(['media component, ',['e',mediaMetName],...
            ', not defined as organism exchange metabolite'])} ];
    end % if component in model
end % for iMediaComp

% media parse errors
if ~isempty(mediaErrors)
    for iEr = 1 : length(mediaErrors)
        disp(sprintf('%s', mediaErrors{iEr} ))
    end % iEr
    error( 'failure in media parsing, see above for detail' )
end % throw error if any have been found so far

% initialize media storage for whole simualtion
simulation.media = zeros(simulation.nMedia, simulation.nTimesteps);

% initialize media
simulation.media(:,1) = simulation.initialMedia ; 
simulation.media(simulation.freeExchangeMediaIdx,1) = simulation.freeExchangeMedia;

simulationWithMedia = simulation;
