/* reduce.c */

#include "computorv1.h"

static double get_all_terms_with_exponent(s_term *terms, int exponent)
{
    int i;
    double coefficient;
    int sign;

    i = 0;
    coefficient = 0.0;
    while (terms[i].sign != TERM_SIGN_END)
    {
        if (terms[i].exponent != exponent)
        {
            i++;
            continue;
        }

        // sign
        sign = terms[i].sign == TERM_PLUS ? 1 : -1;
        if (terms[i].position == TERM_RIGHT)
            sign *= -1;

        // add coefficients
        coefficient += terms[i].coefficient * sign;
        i++;
    }

    return coefficient;
}

int reduce(s_term *terms, s_polynom *polynom, int max_exponent)
{
    int i;
    double tmp_coefficient;
    int degree;

    i = 0;
    degree = 0;
    while (max_exponent >= 0)
    {
        // if any terms contains this exponent, returns the addition of their coefficient
        tmp_coefficient = get_all_terms_with_exponent(terms, max_exponent);

        // skip if coefficient is null or no exponent
        if (tmp_coefficient == 0.0)
        {
            max_exponent--;
            continue;
        }

        // get degree
        if (max_exponent > degree)
            degree = max_exponent;

        // fill polynom
        polynom[i].coefficient = tmp_coefficient;
        polynom[i].exponent = max_exponent;
        polynom[i].sign = ft_fsign(tmp_coefficient) == 1 ? TERM_PLUS : TERM_MINUS;

        max_exponent--;
        i++;
    }

    return degree;
}