/* Polynomial.cp */

#include <stdlib.h>
#include "Polynomial.h"
#include "Complex.h"

// initializes memory for polynomial of degree n and zeroes coeffs.
void CreateP(Polynomial& z, int n)
{
	long		i;
	
	if(n<0)
		return;
	
	z.n = n;
	z.coeff = (Complex* )malloc(((z.n)+1)*sizeof(Complex));
	
	for(i=0;i<=z.n;i++)
		assignZeroC(z.coeff[i]);
	
}/* CreateP */


void FreeP(Polynomial& z)
{
	if(z.coeff!=NULL)
		free(z.coeff);

}/* FreeP */


void EquateP_P(Polynomial& z, Polynomial& x)
{
	long	i;
	
	if(z.coeff==NULL || x.coeff==NULL || x.n!=z.n)
		return;
		
	for(i=0;i<=z.n;i++)
		EquateC_C(z.coeff[i], x.coeff[i]);

}/* EquateP_P */


// z = x*y, all polynomials must be precreated
void MulP_P(Polynomial& z, Polynomial& x,  Polynomial& y)
{
	long		i, j, k;
	Complex		temp;
	Polynomial	P;
	
	if(z.coeff==NULL || x.coeff==NULL || y.coeff==NULL)
		return;
		
	CreateP(P, z.n); // P is created as a zero polynomial
	
	for(k=0;k<=P.n;k++)
	{
		for(i=0;i<=x.n;i++)
			for(j=0;j<=y.n;j++)
				if(i+j==k)
				{
					Mul(temp, x.coeff[i], y.coeff[j]);
					Add(P.coeff[k], P.coeff[k], temp);
				}
	}
	
	EquateP_P(z, P);
	
	FreeP(P);
	
}/* MulP_P */

