/*
    mmorph, MULTEXT morphology tool
    Version 2.3, October 1995
    Copyright (c) 1994,1995 ISSCO/SUISSETRA, Geneva, Switzerland
    Dominique Petitpierre, <petitp@divsun.unige.ch>
*/
/*
    combine.c

    handle combination of affix and binary rules

    Dominique Petitpierre, ISSCO Summer 1994
*/

#include "user.h"

s_bitmap   *rule_maps[_last_rule_kind];
static int  combined_rule_card;
int         rule_instance_card;
s_rule_instance **rule_instance_ref;

/*
   for every binary rule, for every affix try to combine the affix on
   the right and on the left of the rule.
   Each combined rule is put in the applicable rule list.
   TODO: involve unary rules in the process (chain of unary rules).
*/

static s_var_map *
new_var_map(local_index, foreign_index)
t_index     local_index;
t_index     foreign_index;

{
    s_var_map  *var_map;

    MY_MALLOC(var_map, s_var_map);
    var_map->local_index = local_index;
    var_map->foreign_index = foreign_index;
    return (var_map);
}

void
fill_rule_maps(rule_ref)
s_symbol  **rule_ref;

{
    s_symbol  **ref;

    for (ref = rule_ref; *ref != NULL; ref++) {
	set_bit(rule_maps[(*ref)->data->rule.instance->rule_kind],
		(long) (ref - rule_ref));
    }
}

/*
    perform the unification of two tfs that have been checked to match
*/
static s_tfs *
unify_tfs(rule_tfs, lex_tfs)
s_tfs      *rule_tfs;
s_tfs      *lex_tfs;

{
    s_tfs      *result_tfs;
    register t_value *t;
    register t_value *r;
    register t_value *l;

    result_tfs = new_tfs(rule_tfs->type);
    t = result_tfs->att_list;
    r = rule_tfs->att_list;
    l = lex_tfs->att_list;
    while ((*t++ = *r++ & *l++) != NO_BITS) {
    }
    return (result_tfs);
}

static s_tfs *
copy_tfs(result_tfs, master_tfs, var_source_tfs, variable_ref,
	 master_index, var_source_index)
s_tfs      *result_tfs;
s_tfs      *master_tfs;
s_tfs      *var_source_tfs;
s_symbol  **variable_ref;
int         master_index;
int         var_source_index;

{
    register t_value *val_result;
    register t_value *val_master;
    register t_value *val_source;
    t_value     v;
    s_var_map **var_map;
    int         var_map_size;
    s_symbol  **var;
    t_index    *tfs_index;
    t_boolean   is_new;

    is_new = (result_tfs == NULL);
    if (is_new) {
	result_tfs = new_tfs(master_tfs->type);
    }
    val_result = result_tfs->att_list;
    val_master = master_tfs->att_list;
    while ((*val_result++ = *val_master++) != NO_BITS) {
    }
    var_map = NULL;
    var_map_size = 0;
    val_result = result_tfs->att_list;
    val_source = var_source_tfs->att_list;
    for (var = variable_ref; *var != NULL; var++) {
	tfs_index = (*var)->data->variable.tfs_index;
	if (tfs_index[master_index] != NO_INDEX
	    && tfs_index[var_source_index] != NO_INDEX) {
	    /*
	       copy the possibly new corresponding value. no need to unify
	       since all variable positions have already been unified in
	       check_var_map()
	    */
	    v = val_result[tfs_index[master_index]] =
		val_source[tfs_index[var_source_index]];
	    if (!has_unique_bit(v)) {
		if (var_map_size == 0) {
		    MY_CALLOC(var_map, 2, s_var_map *);
		}
		else {
		    MY_REALLOC(var_map, var_map_size + 2, s_var_map *);
		}
		var_map[var_map_size + 1] = NULL;	/* sentinel */
		if (is_new)
		    var_map[var_map_size] =
			new_var_map(tfs_index[master_index],	/* local_index */
				    tfs_index[var_source_index]);	/* foreign */
		else
		    /*
		       affix branch will never provide values again but might
		       want to receive some at percolate down time
		    */
		    var_map[var_map_size] =
			new_var_map(tfs_index[var_source_index],	/* local */
				    tfs_index[master_index]);	/* foreign */
		var_map_size++;
	    }
	}
    }
    if (is_new)
	result_tfs->var_map = var_map;
    else
	var_source_tfs->var_map = var_map;
    return (result_tfs);
}

static      t_str
concat_3_strings(string1, string2, string3)
t_str       string1;
t_str       string2;
t_str       string3;

{
    int         length1;
    int         length1_2;
    t_str       string_new;

    length1 = strlen(string1);
    length1_2 = length1 + strlen(string2);
    MY_STRALLOC(string_new, length1_2 + strlen(string3) + 1);
    (void) strcpy(string_new, string1);
    (void) strcpy(string_new + length1, string2);
    (void) strcpy(string_new + length1_2, string3);
    return (string_new);
}

static s_rule_instance *
combine_rule(binary_index, lexical_index, rule_ref, rule_kind)
long        binary_index;
long        lexical_index;
s_symbol  **rule_ref;
e_rule_kind rule_kind;

{
    s_rule_instance *result;
    s_rule_instance *binary_rule;
    s_rule_instance *lexical_rule;
    s_tfs      *affix_tfs;
    s_tfs      *arg_tfs;
    int         affix_side;
    int         arg_side;
    s_symbol  **variable_ref;
    s_symbol   *new_rule_sym;

    binary_rule = rule_ref[binary_index]->data->rule.instance;
    lexical_rule = rule_ref[lexical_index]->data->rule.instance;
    if (rule_kind == Prefix) {
	affix_tfs = binary_rule->first;
	arg_tfs = binary_rule->second;
	affix_side = 1;
	arg_side = 2;
    }
    else {	/* suffix */
	affix_tfs = binary_rule->second;
	arg_tfs = binary_rule->first;
	affix_side = 2;
	arg_side = 1;
    }
    if (match_tfs(affix_tfs, lexical_rule->lhs)) {
	MY_MALLOC(result, s_rule_instance);
	result->rule_kind = rule_kind;
	result->second = unify_tfs(affix_tfs, lexical_rule->lhs);
	variable_ref = rule_ref[binary_index]->data->rule.variable_set.ref;
	result->first =	/* NULL indicate that creation is necessary */
	    copy_tfs((s_tfs *) NULL, arg_tfs, result->second,
		     variable_ref, arg_side, affix_side);
	result->lhs =	/* NULL indicate that creation is necessary */
	    copy_tfs((s_tfs *) NULL, binary_rule->lhs, arg_tfs,
		     variable_ref, 0, arg_side);
	result->lhs =
	    copy_tfs(result->lhs, binary_rule->lhs, result->second,
		     variable_ref, 0, affix_side);
	result->lex = lexical_rule->lex;	/* watchout when freeing */
	result->lex_length = lexical_rule->lex_length;


	MY_MALLOC(new_rule_sym, s_symbol);
	new_rule_sym->kind = Rule;
	new_rule_sym->name =
	    concat_3_strings(rule_ref[binary_index]->name,
			     (rule_kind == Prefix ? "<" : ">"),
			     rule_ref[lexical_index]->name);
	if (debug & DEBUG_COMBINE)
	    print_out("combined rule: %s\n", new_rule_sym->name);
	new_rule_sym->ordinal = combined_rule_card++;	/* no used ?? */
	/* the data part is not filled */
	result->rule_link = new_rule_sym;
	return (result);
    }
    else
	return (NULL);
}

t_ptr      *current_ref;	/* extra argument passed to ref_is_item() */

/* action passed to map_chain */
static void
ref_is_arg(item)
t_ptr       item;

{
    *current_ref = item;
    current_ref++;
}

static void
warn_for_each_member(rule_map, rule_ref, format)
s_bitmap   *rule_map;
s_symbol  **rule_ref;
char       *format;

{
    int         rule_index;

    for (rule_index = next_bit(rule_map, 0L);
	 rule_index >= 0L;
	 rule_index = next_bit(rule_map, rule_index + 1L)) {
	print_warning(format, rule_ref[rule_index]->name);
    }
}

void
combine_all(binary_map, lexical_map, rule_ref)
s_bitmap   *binary_map;
s_bitmap   *lexical_map;
s_symbol  **rule_ref;

{
    long        binary_index;
    long        lexical_index;
    s_rule_instance *result_suffix;
    s_rule_instance *result_prefix;
    s_chain    *rule_chain;
    int         binary_count;
    int         lexical_count;
    int         suffix_count;
    int         prefix_count;
    s_bitmap   *suffix_map;
    s_bitmap   *prefix_map;
    s_bitmap   *temp_bitmap;

    rule_chain = NULL;
    combined_rule_card = 0;
    binary_count = 0;
    lexical_count = 0;	/* in case there is no binary rules */
    prefix_map = new_bitmap(lexical_map->size);
    suffix_map = new_bitmap(lexical_map->size);
    for (binary_index = next_bit(binary_map, 0L);
	 binary_index >= 0L;
	 binary_index = next_bit(binary_map, binary_index + 1L)) {
	binary_count++;
	lexical_count = 0;
	suffix_count = 0;
	prefix_count = 0;
	for (lexical_index = next_bit(lexical_map, 0L);
	     lexical_index >= 0L;
	     lexical_index = next_bit(lexical_map, lexical_index + 1L)) {
	    lexical_count++;	/* count many times but who cares */
	    result_prefix =
		combine_rule(binary_index, lexical_index, rule_ref, Prefix);
	    if (result_prefix != NULL) {
		rule_chain =
		    insert_chain_link(rule_chain, (t_ptr) result_prefix);
		prefix_count++;
		set_bit(prefix_map, lexical_index);
	    }
	    result_suffix =
		combine_rule(binary_index, lexical_index, rule_ref, Suffix);
	    if (result_suffix != NULL) {
		rule_chain =
		    insert_chain_link(rule_chain, (t_ptr) result_suffix);
		suffix_count++;
		set_bit(suffix_map, lexical_index);
	    }
	}
	if (suffix_count > 0 && prefix_count > 0)
	    print_warning("binary rule \"%s\" %s",
			  rule_ref[binary_index]->name,
			  "combines both with prefixes and suffixes");
	else if (suffix_count == 0 && prefix_count == 0)
	    print_warning("binary rule \"%s\" %s",
			  rule_ref[binary_index]->name,
			  "does not combine with any affix");
    }
    temp_bitmap = new_bitmap(lexical_map->size);
    assign_or(temp_bitmap, suffix_map);
    assign_and(temp_bitmap, prefix_map);
    warn_for_each_member(temp_bitmap, rule_ref,
		    "affix rule \"%s\" combines both as prefix and suffix");
    assign_or(prefix_map, suffix_map);
    negate_bitmap(prefix_map);
    assign_and(prefix_map, lexical_map);
    warn_for_each_member(prefix_map, rule_ref,
		 "affix rule \"%s\" does not combine with any binary rule");
    free_bitmap(temp_bitmap);
    free_bitmap(suffix_map);
    free_bitmap(prefix_map);
    /*
       put all interesting rule instances in an array new ones and old ones
       that are neither binary nor affix (Lexical).
    */
    rule_instance_card = symbol_set[Rule].card - lexical_count
	- binary_count + combined_rule_card;
    MY_CALLOC(rule_instance_ref, rule_instance_card + 1, s_rule_instance *);
    rule_instance_ref[rule_instance_card] = NULL;	/* sentinel */
    current_ref = (t_ptr *) rule_instance_ref;	/* global argument */
    map_chain(rule_chain, ref_is_arg);	/* TODO preserve rule order */
    assign_or(binary_map, lexical_map);
    negate_bitmap(binary_map);	/* binary_map is now non_binary_map! */
    for (binary_index = next_bit(binary_map, 0L);
	 binary_index >= 0L;
	 binary_index = next_bit(binary_map, binary_index + 1L)) {
	*current_ref++ = (t_ptr) rule_ref[binary_index]->data->rule.instance;
    }
    free_chain(rule_chain);
}
