%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%  Run stand-alone bns_c
%%  Value of use_batch defines number of 
%%     processors
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

tic

clear_stuff
other_constants
collect_rundata

if isempty(randseed)
    temclock = sum(fix(clock));
    randseed = temclock;
end

run_info.randseed = randseed; 

partname = [output_filename];
delete(fullfile(output_dir, [partname '_*']));

sbml_check

if use_sbml ~= 1
        read_cmpds
        read_reactions
        read_reaction_constants
        prepare_rxn_grps  
        StoP = [];
else
    % Save initial kinetic constants
              for i_rxn = 1: num_rxns
               rxn = rxn_grp{1}.rxn{i_rxn};
               StoP{i_rxn} = rxn.StoP;
              end
end
  
num_cmpds = cmpd_info.num_cmpds;
orig_cmpd_vals = cmpd_info.orig_cmpd_vals;

        rxn_grp{1}.cmpd_nums = create_cmpd_matrix(rxn_grp{1}.global_comp_gid, cmpd_info);
        [modrxn, moddepend, mod_monitor] = prepare_matlab_indices_for_c(rxn_grp{1}.rxn, rxn_grp{1}.rxn_dependency_matrix, rxn_grp{1}.monitor_comps);
        write_bns_textfile(modrxn,rxn_grp{1}.cmpd_nums(:,1), mod_monitor, run_info, plot_info, dir_info, numsets);
        movefile([output_filename '_constants.txt'], output_dir);

  save_rundata(output_dir, output_filename, plot_info, 'plot_info', run_info, 'run_info', dir_info, 'dir_info', cmpd_info, 'cmpd_info', rxn_grp, 'rxn_grp');
        
        if use_batch == 1
           curr_dir = pwd;
           cd ('bns_mat_c'); 
           if ispc
            !make_lcc > out.out
           else
            !make unix_gcc C=gcc >out.out
            !make clean  > out.out
           end
           delete('out.out');
            cd (curr_dir);
            !bns_c.exe            
        else
            curr_dir = pwd;
            cd ('bns_mat_c');
             !make mpi  C=mpicc >out.out 
             !make clean > out.out
            delete('out.out');
            cd (curr_dir);
        end
        
real_time_elapsed = toc      
  
