function [stru] = CNA2EFMtool(CNAmodel)

%When using CellNetAnalyzer (CNA), This function prepares the files for 
%standalone EFMtool execution.  You must have a folder called 'tmp' in your
%current directory, and the model should be opened in CNA. 
%Usage stru=CNA2EFMtool(CNAmodelfolder) where CNAmodelfolder is the name of
%the folder where your model is kept. Functions CalculateStoich, 
%writeText, and writeBool are from CalculateFluxModes.m

temp = CNAmodel.stoichMat;
stru.stoich=temp(CNAmodel.specInternal,:);
temp = cellstr(CNAmodel.specID)';
stru.metaboliteNames=temp(CNAmodel.specInternal);
stru.reactionNames = cellstr(CNAmodel.reacID)';
stru.reversibilities = CNAmodel.reacMin';
[R,C,V]=find(stru.reversibilities);
stru.reversibilities(C)=1;
CalculateStoich(stru.stoich, ...
                        stru.reversibilities, ...
                        stru.metaboliteNames, ...
                        stru.reactionNames);
end

function [mnet] = CalculateStoich(stoich, revs, mnames, rnames)

    save(fullfile('tmp', 'stoich.txt'), 'stoich', '-ASCII', '-TABS')
    writeBool(fullfile('tmp', 'revs.txt'),  revs);
    writeText(fullfile('tmp', 'mnames.txt'), mnames);
    writeText(fullfile('tmp', 'rnames.txt'), rnames);

end

%% writeText()
% 
% Writes a tab separated ascii file for text entries (one row)
function writeText(fileName, cellArr)
    fid = fopen(fileName, 'w');
    for i=1:length(cellArr);
        if (i>1), fprintf(fid, '\t'); end
        fprintf(fid, '"%s"', cellArr{i});
    end
    fprintf(fid, '\n');
    fclose(fid);
end

%% writeBool()
% 
% Writes a tab separated ascii file for boolean entries (one row)
function writeBool(fileName, arr)
    fid = fopen(fileName, 'w');
    for i=1:length(arr);
        if (i>1), fprintf(fid, '\t'); end
        fprintf(fid, '%1.0f', arr(i));
    end
    fprintf(fid, '\n');
    fclose(fid);
end