// a database of bodypart definitions

public class bodypartDB
{
public  static bodypart    bodyparts[];    // all bodyparts in existance
private static bodypartDEF bodypartdefs[];
private static int         size;
private static int         num;
public  static int         allocated;
    
//--------- optimization ---------
public  static void init_static(int dim) // dim = max number of bodypart definitions
    {
	size         = dim;
	num          = 0;
	allocated    = 0;
	bodyparts    = new bodypart[size*4]; // assume each part won't be allocated more than 4 times
	bodypartdefs = new bodypartDEF[size];
    }
//--------------------------------
    
public static boolean insert(bodypartDEF bodypartdef)
    {
	for(int i=0; i<num; i++)
	    {
		if(bodypartdefs[i].name.equals(bodypartdef.name))
		    {
			System.err.println("bodypart definition "+ bodypartdef.name +" already exists in the database");
			return false;
		    }
	    }
	bodypartdefs[num++] = bodypartdef;
	return true;
    }

public static bodypartDEF find(String name)
    {
	for(int i=0; i<num; i++)
	    {
		if(bodypartdefs[i].name.equals(name))
		    return bodypartdefs[i];
	    }
	System.err.println("bodypart definition "+ name +" does not exists in the database");
	return null;
    }

public static bodypart find(String name, int count)
    {
	for(int i=0; i<allocated; i++)
	    {
		if(bodyparts[i].name.equals(name))
		    if(count == 0)
			return bodyparts[i];
		    else
			count--;
	    }
	System.err.println("bodypart "+ name +" does not exists in the database");
	return null;
    }

public static bodypart makebodypart(String name)
    {
	bodypartDEF p = find(name);
	if(p == null)
	    {
		System.err.println("cannot create undefined bodypart "+ name);
		return null;
	    }
	int index = allocated;
        bodyparts[allocated++] = p.makebodypart();
	return bodyparts[index];
    }
}

