#include "config.h"

/*
 * Every skill datum consists of a triplet:
 *   The name of the skill (a string).
 *   The value of the skill (number of successful uses).
 *   Optionally an array of subskills.
 * The skill structure is an array of skill data.
 */
private mixed *skill_structure;

private mixed *find_add_skill_points(mixed *node, string *path, int pos,
				     int amount);
void dump_value(mixed val);
private int summarize_skill(mixed *node, string *path, int pos);

private mixed *find_add_skill_points(mixed *node, string *path, int pos,
				     int amount) {
    int i;
    mixed *sub_node;

    if (pos == sizeof(path))
	return ({});
    for (i=0; i < sizeof(node); i++) {
	if (node[i][0] == path[pos])
	    break;
    }
    if (i == sizeof(node)) {
	/* New skill type */
	mixed *tmp;
	tmp = find_add_skill_points( ({}), path, pos+1, amount);
	if (sizeof(tmp) > 0)
	    return node +
		({ ({ path[pos], amount }) +
		   ({ find_add_skill_points( ({}), path, pos+1, amount) }) });
	else
	    return node +
		({ ({ path[pos], amount }) });
    }
    if (sizeof(node[i]) == 3)
	sub_node = node[i][2];
    else
	sub_node = ({});
    node[i] = ({ path[pos], node[i][1] + amount }) +
	({ find_add_skill_points(sub_node, path, pos+1, amount) });
    return node;
}

/*
 * Add 'amount' skill points to the skill defined by the path 'path'.
 */
void add_skill_points(string *path, int amount) {
    if (skill_structure == 0)
	skill_structure = ({});
    skill_structure = find_add_skill_points(skill_structure, path, 0, amount);
}

mixed *query_skills() {
    return skill_structure;
}

private int summarize_skill(mixed *node, string *path, int pos) {
    int i;
    mixed *sub_node;

    if (pos == sizeof(path))
	return 0;
    for (i=0; i < sizeof(node); i++) {
	if (node[i][0] == path[pos])
	    break;
    }
    if (i == sizeof(node)) {
	/* New skill type */
	return 0;
    }
    if (sizeof(node[i]) == 3)
	sub_node = node[i][2];
    else
	return node[i][1];
    return EXP_TO_PERCENT(node[i][1])
	+ summarize_skill(sub_node, path, pos+1);
}

int compute_total_skill(string *path) {
    return summarize_skill(skill_structure, path, 0) / sizeof(path);
}
