aiUnit* BuildHandler::UnitCreated (int id)
{
	float bestDis;
	aiTask *best=0, *t;
	aiUnit *unit = 0;

	float3 pos = ai->cb->GetUnitPos (id);
	const UnitDef* def = ai->cb->GetUnitDef (id);

	for (int a=0;a<tasks.size();a++)
		if (!tasks[a]->unit && tasks[a]->lead && tasks[a]->def == def)
		{
			float d = pos.distance2D (tasks[a]->pos);
			if (!best || d < bestDis) {
				best = tasks[a];
				bestDis = d;
			}
		}

	if (!best || bestDis > 200)
	{
		// TODO: Find a way to deal with these outcasts...
		return new aiUnit;
	}

	t = best;
	if (t->IsBuilder())
	{
		BuildUnit *bu = new BuildUnit;
		bu->owner = this;
		t->unit = bu;
		bu->UpdateTimeout(ai->cb);

		t->unit = bu;
		logPrintf ("New builder created. %s\n", t->def->name.c_str());
		return bu;
	}

	assert (t->destHandler);
	unit = t->destHandler->CreateUnit (id);
	unit->owner = this;
	t->AddDeathDependence (unit);
	t->unit = unit;
	return unit;
}