function convertLegacyModel(RXNFile, ParamFile, InitFile, name)
%CONVERTLEGACYMODEL converts the old index style model to the new format
% 
% This function can be used to convert the old style model files that use
% the index notatation for species and rate parameters to the new format.
% Three new files will be generated.
%
%       <name>_reactions.txt
%       <name>_parameters.txt
%       <name>_species.txt
%   
%  If any of these files already exist then the function will throw an error

% This work is licensed under the Creative Commons Attribution-Noncommercial-No Derivative 
% Works 3.0 United States License. To view a copy of this license, visit 
% http://creativecommons.org/licenses/by-nc-nd/3.0/us/ or send a letter to Creative Commons,
% 171 Second Street, Suite 300, San Francisco, California, 94105, USA.

% Read in the reactions
[Rxn.Num, Rxn.Fwd, Rxn.R1, Rxn.R2, Rxn.Rev, Rxn.P, Rxn.Step, Rxn.Include, ...
    Rxn.ProcessDescription, Rnx.RxnDescription] ...
    = textread(RXNFile, '%d%d%d%d%d%d%d%d%s%s',  'delimiter', '\t',  'headerlines', 1);
    
% Read in the parameters
[Rate.Name,	Rate.Num, Rate.Fwd, Rate.Value,	Rate.Max, Rate.Min,	Rate.Fixed] ...
    = textread(ParamFile, '%s%d%d%f%f%f%d',  'delimiter', '\t',  'headerlines', 1);

% Read in the initial conditions
[Init.Num,	Init.Conc, Init.Scale, Init.Input, Init.Name, NotUsed] ...
    = textread(InitFile, '%d%f%f%d%s%[^\n]',  'delimiter', '\t',  'headerlines', 1);

% Read in the output variables
OutputVarStart = 6;
headerline     = textread(InitFile, '%s', 1, 'delimiter', '\n');
matches        = regexp(headerline, '[^(\t)]*', 'match');
matches        = matches{:}; % I don't understand why I have to do this
Output.Names   = {matches{OutputVarStart:end}};

% Need the -1 because dlmread is 0 based
Output.Values  = dlmread(InitFile, '\t', 1, (OutputVarStart-1));

% print the parameter file
if(nargin == 4)
    path = '.';
end



rxn = [path, filesep, name, '_reactions.txt'];
prm = [path, filesep, name, '_parameters.txt'];
spc = [path, filesep, name, '_species.txt'];

assert(~exist(rxn, 'file'), 'Kronecker:FileExists', '%s already exists', rxn);
assert(~exist(prm, 'file'), 'Kronecker:FileExists', '%s already exists', prm);
assert(~exist(spc, 'file'), 'Kronecker:FileExists', '%s already exists', spc);


% Write out the reaction file
fid = fopen(rxn, 'w');
fprintf(fid, 'Reactant1\tReactant2\tProduct\tkForward\tkReverse\tComment\n');
for i = 1:length(Rxn.Num)
    r1  = findSpeciesName(Rxn.R1(i));
    r2  = findSpeciesName(Rxn.R2(i)); 
    p   = findSpeciesName(Rxn.P(i)); 
    fwd = findRateName(Rxn.Fwd(i), 1);
    rev = findRateName(Rxn.Rev(i), 0);
    
    fprintf(fid,'%s\t%s\t%s\t%s\t%s\t%s\n', r1, r2, p, fwd, rev, '');
end
fclose(fid);


% Write out the species file
fid = fopen(prm, 'w');

% Write the fixed part of the header
fprintf(fid, 'Name\tValue\tComment\n');
for i = 1:length(Rate.Name);
    fprintf(fid, '%s\t%e\t%s\n', Rate.Name{i}, Rate.Value(i), '');
end
fclose(fid);

% Write the output variables header
fid = fopen(spc, 'w');
fprintf(fid, 'Name\tInitial\tInput');
for i = 1:length(Output.Names)
    fprintf(fid, '\t%s', Output.Names{i});
end

% Finish off the header
fprintf(fid, '\tComment\n');

% Print the table values
for i = 1:length(Init.Name)
    name    = Init.Name{i};
    isInput = Init.Input(i);
    conc    = Init.Conc(i);

    fprintf(fid,'%s\t%e\t%d', name,  conc, isInput);
    
    for j = 1:length(Output.Names)
        fprintf(fid, '\t%d', Output.Values(i,j));
    end

    fprintf(fid, '\t \n');    
end
fclose(fid);


    function name = findRateName(num, fwd)
        if(num == 0)
            name = '0';
        else
            ind = find((Rate.Num == num) & (Rate.Fwd == fwd));
            assert(length(ind)== 1, 'parameter #%d(fwd=%d) appears %d times in the parameter file', ...
                num, fwd, length(ind));
            
            name = Rate.Name{ind};
        end
    end
            
    function name = findSpeciesName(num)
        if(num == 0)
            name = '0';
        else
            ind = find(Init.Num == num);
            assert(length(ind)== 1, 'kronecker:modelerror', 'species %d appears %d times in the species file', ...
                num, length(ind));
            name = Init.Name{ind};
        end
    end
end
