% 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: This function loads in a .mat file and writes and tab dlimited text 
% 			file .txt containing a table of information for use in R plotting functions
% 
%
% Inputs: 	folderReadStr - A string contianing the folder path from which file is to be read.
%			fileString -  A string contianing the name of the file to be read.
%			fileSaveStr - A string with the path to and name of the .txt file where output is to be saved
%			viralConcentrations - This function does not automatically write all viral concentration varables, 
% 								  they must be specified in this cell array of strings variable with strin cmatching their viral itentifier 
%			simFields - The simulatoin variables to save in the table, likely used for error messages, 
% 						or flags about whether or not the host or viral output is present at a given timestep
%
% Outputs: text format table saved in <fileSaveStr>
%
%
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
%
% Notes: > Only intended for use with a single host organism FBA siulation, first organism in list is used.
% 		 > This function writes from one inefficienctly stored format to another ineifficent file format, 
%			for the number of simulations handled typically optimization to a sparse format was not a priority.
%
%
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

function [] = FORMAT_EB_mat2textFluxes( folderReadStr, fileString, fileSaveStr, viralConcentrations, simFields)

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

% General preparation for output
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

load( fullfile(folderReadStr,fileString ) )

idxUnderscores = strfind( fileString, '_' );

modelString = simulation.organismList{1};

% prepare to output viral timescale varibles


% prepare to output host timescale variables
timeHost = simulation.t';
if simulation.(modelString).infectionFlag
    time = simulation.(modelString).simulation.tViralSubStep';
    idxHostData = 1 : simulation.(modelString).simulation.nViralSubSteps : length(time) ;
    % check host/virus time lineup
    idxCheck1 = length( idxHostData ) == simulation.nTimesteps;
    if idxCheck1
        idxCheck2 = all((timeHost - time( idxHostData )) < 1e-6) ;
    else
        idxCheck2 = false;
    end
    hostReactions = simulation.(modelString).modelInfected.rxnList;
    model2use = 'modelInfected';
else
    time = simulation.t';
    idxHostData = 1 : 1 : length(time) ;
    hostReactions = simulation.(modelString).model.rxnList;
    model2use = 'model';
end

% time
timeHeaderString = 't';
timeTableValues = time;
timeFormatString = '%1.3e';

% hostFlag
hostFlagHeaderString = '\t hostFlag';
hostFlagTableValues = zeros( size(time) );
hostFlagTableValues(idxHostData) = ones( size(idxHostData) );
hostFlagFormatString = '\t%1.0f';
 
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 



% output simulation
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

simFormatString = '';
simHeaderString = '';

simTableValues = zeros(length(time),0);

nSimOut = 0;
for iSimOut = 1: length(simFields)
	fieldString = simFields{iSimOut};
    if isfield( simulation.(modelString).simulation, fieldString)
		fieldData = simulation.(modelString).simulation.(fieldString);
		sizeFieldData = size(fieldData);
		skipField = false;
		if sizeFieldData == [length(idxHostData),1]
		elseif sizeFieldData == [1,length(idxHostData)]
			fieldData = fieldData';
		else
			skipField = true;
		end
		if ~ skipField
            nSimOut  = nSimOut  + 1;
			simTableValues(idxHostData,nSimOut) = fieldData;
			simHeaderString = [ simHeaderString, '\t ',fieldString];
	        simFormatString = [ simFormatString, '\t %1.3e'];
		end
		
    end
end % for iSimOut

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



% output viral
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

viralFormatString = '';
viralHeaderString = '';
viralRefFormatString = '';
viralRefHeaderString = '';
viralTableValues = zeros(length(time),0);
viralRefTableValues = zeros(length(time),0);

if simulation.(modelString).infectionFlag
	nVirPlot = 0;
	for iVirPlot = 1: length(viralConcentrations)
	   viralString = viralConcentrations{iVirPlot};
	   viralID = strrep([viralString(1),upper( viralString(2:end))], '-','_');
	   if isfield(  simulation.(modelString).modelInfected.metabolites, viralID)
	       idxMet = simulation.(modelString).modelInfected.metabolites.(viralID).idxMetabolite;
	       idxTrans = find( idxMet == simulation.(modelString).modelInfected.viralMetaboliteODETranslation(:,1), 1, 'first');
	       if ~isempty( idxTrans )
	           nVirPlot  = nVirPlot  + 1;
	           viralOutputIndicies( nVirPlot ) = idxTrans;
	           viralHeaderString = [ viralHeaderString, '\t ',['CONC',viralID]];
	           viralFormatString = [ viralFormatString, '\t %1.3e'];
               viralRefHeaderString = [ viralRefHeaderString, '\t ',['CONC',viralID],'Ref'];
	           viralRefFormatString = [ viralRefFormatString, '\t %1.3e'];
	       end
	   end
	end % for iVirPlot
	
	viralTableValues = simulation.(modelString).simulation.viralSubSteps(viralOutputIndicies,:)';
	viralRefTableValues = simulation.(modelString).simulation.viralReferenceRun(viralOutputIndicies,:)';
	
end % if infection flag

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



% output host
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

hostFormatString = '';
hostHeaderString = '';
hostTableValues = zeros(length(time),0);
hostOutputIndicies = [];

nHostOut = 0;
for iHostOut = 1: length(hostReactions)
    rxnString = hostReactions{iHostOut};
    rxnID = strrep([rxnString(1),upper( rxnString(2:end))], '-','_');
    if isfield(  simulation.(modelString).(model2use).rxns, rxnID)
        idxRxn = simulation.(modelString).(model2use).rxns.(rxnID).idxRxn;
        nHostOut  = nHostOut  + 1;
        hostOutputIndicies( nHostOut ) = idxRxn;
        hostHeaderString = [ hostHeaderString, '\t ',rxnID];
        hostFormatString = [ hostFormatString, '\t %1.3e'];

    end
end % for iHostOut

hostTableValues(idxHostData,1:nHostOut) = simulation.(modelString).simulation.fluxes(hostOutputIndicies,:)';

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



% combine & output
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

headerString = [timeHeaderString, hostFlagHeaderString, viralHeaderString, viralRefHeaderString, hostHeaderString, simHeaderString, '\n'];
formatString = [timeFormatString, hostFlagFormatString, viralFormatString, viralRefFormatString, hostFormatString, simFormatString,'\n'];
tableValues = [timeTableValues, hostFlagTableValues, viralTableValues,viralRefTableValues, hostTableValues, simTableValues];

fid = fopen([fullfile(fileSaveStr,fileString),'.txt'],'w');
fprintf(fid, headerString);
fprintf(fid, formatString, tableValues');
fclose(fid);