# include "runsim.h"

void find_next_reaction_erg(
    double *tnext_ptr, 
    int *rxnnum_ptr, 
    double *ai_sum_ptr, 
    struct rxn *rxn_ptr, 
    int stoch_algor, 
    int refresh, 
    struct array_sizes *arsz_ptr, 
    double cur_time)
{
	
	double tnext;
        double ai_sum, checktime, random_num, a_subtotal, rand_ai;
	int i, rxnnum = 0;
	
	ai_sum = *ai_sum_ptr;
	if (stoch_algor != 2) 
      {
		tnext = DBL_MAX;
		for (i = 0; i < arsz_ptr -> num_rxns; i++) 
        {
			checktime = rxn_ptr[i].rxn_time;
			if (checktime < tnext) 
            {
				tnext = checktime;
				rxnnum = i;
			 } 
		 }
	}
	else 
    {
		if (refresh == 1)
        {
			ai_sum = 0;
			for (i = 0; i < arsz_ptr -> num_rxns; i++) 
			        	ai_sum = ai_sum + rxn_ptr[i].ai;	
		}

		random_num = ranf();   
/* 		random_num = (double) (rand()/RAND_MAX);   */
		tnext = cur_time + (1 / ai_sum) * log(1/random_num);
		
		a_subtotal = 0;
		random_num = ranf();   
/*		random_num = (double) (rand()/RAND_MAX);    */
		rand_ai = random_num * ai_sum;
		for (i = 0; i < arsz_ptr -> num_rxns; i++) 
        {
			a_subtotal = a_subtotal + rxn_ptr[i].ai;
			if (rand_ai < a_subtotal) 
            {
				rxnnum = i;
				break;
			}
		}
	}

	*tnext_ptr = tnext;
	*rxnnum_ptr = rxnnum;
	*ai_sum_ptr = ai_sum;
}
