typedef struct {double x, y, mag;} Vector;
#define dot(i,j)	(i.x*j.x + i.y*j.y )

void bounce(int i, int j )
	{
	double	temp;
	Vector	vi, vj,		// velocity of objs i, j		
		ij,		// vector from center of i to center of j 
		vi_ij, vj_ij,	// velocity of obj along vector ij	
		vipij, vjpij,	// velocity perpendicular to ij		
		vi_ijf, vj_ijf;	// post-collision velocity along ij	

	vi.x = obj[i]->xvel(); vi.y = obj[i]->yvel();
	vj.x = obj[j]->xvel(); vj.y = obj[j]->yvel();
	ij.x = obj[j]->x() - obj[i]->x(); ij.y = obj[j]->y() - obj[i]->y();
	ij.mag = sqrt(ij.x*ij.x + ij.y*ij.y);

/*
Calculate velocities projected onto ij;
vi_ij = vi*cos(a) = (vi dot ij) / |ij|		
*/

	vi_ij.mag = dot(vi, ij) / ij.mag;
	vi_ij.x = (ij.x * vi_ij.mag) / ij.mag;
	vi_ij.y = (ij.y * vi_ij.mag) / ij.mag;
	vj_ij.mag = dot(vj, ij) / ij.mag;
	vj_ij.x = (ij.x * vj_ij.mag) / ij.mag;
	vj_ij.y = (ij.y * vj_ij.mag) / ij.mag;

	if (vi_ij.mag - vj_ij.mag < 0)	
		return;
/* 
Objs moving away from each other -
Since objs are round (at least when bouncing), this means
they are moving away from each other already.
*/

/*
Calculate component of velocities perpendicular to ij:
	|vipij| = |vi|*sin(a) = |vi x ij| / |ij|
Same as
	|vipij| = |vi|*cos(M_PI/2 - a) = (vi dot (perp. to ij)) / |ij|
*/

	temp = vi.y*ij.x - vi.x*ij.y;	// - (X-product when 3rd coord is 0)
	temp /= (ij.mag*ij.mag);
	vipij.x = -ij.y*temp; vipij.y = ij.x*temp;
	temp = (vj.x*ij.y - vj.y*ij.x) / (ij.mag*ij.mag);
	vjpij.x = -ij.y*temp; vjpij.y = ij.x*temp;

/*
Calculate the linear elastic collision along ij:
	Fmass(i)*vi_ij + mass(j)*vj_ij = mass(i)*vi_ijf + mass(j)*vj_ijf
	vi_ij + vi_ijf = vj_ij + vj_ijf	(derived by dividing equation
	for conservation of kinetic energy
	 by eq. for cons. of momentum)
*/

	temp = obj[i]->mass/obj[j]->mass;
	vj_ijf.x = (temp * (2*vi_ij.x - vj_ij.x) + vj_ij.x) / (1 + temp);
	vj_ijf.y = (temp * (2*vi_ij.y - vj_ij.y) + vj_ij.y) / (1 + temp);
	vi_ijf.x = vj_ijf.x + vj_ij.x - vi_ij.x;
	vi_ijf.y = vj_ijf.y + vj_ij.y - vi_ij.y;

/*
Now, given vi_ijf and vj_ijf, add them to the perpendicular
	components to get final velocity vectors
*/

	obj[i]->setFvel( FLOAT2FP(vi_ijf.x + vipij.x), FLOAT2FP(vi_ijf.y + vipij.y) );
	obj[j]->setFvel( FLOAT2FP(vj_ijf.x + vjpij.x), FLOAT2FP(vj_ijf.y + vjpij.y) );

	}
