/*
 *  fpComplexConv.cpp
 *  fp
 *
 *  Created by Robert Delaney on 11/7/09.
 *  Copyright 2009 __MyCompanyName__. All rights reserved.
 *
 */

#include "fpComplex.h"

bool init(fpComplex& x)
{
	init(x.re);
	init(x.im);
	return true;
	
}/* init */

void equate(fpComplex& z, const fpComplex& x)
{
	z.re = x.re;
	z.im = x.im;
	
}/* equate */


void equate(fpComplex& z, const fp& x, const fp& y)
{
	
	z.re = x;
	z.im = y;
	
}/* equate */


void equate(fpComplex& z, const mb& x, const mb& y)
{
	
	z.re = x;
	z.im = y;
	
}/* equate */


void equate(fpComplex& z, double x, double y)
{
	
	z.re = x;
	z.im = y;
	
}/* equate */


void equate(fpComplex& z, const fp& x)
{
	z.re = x;
	z.im = 0.;
	
}/* equate */


void equate(fpComplex& z, const mb& x)
{
	z.re = x;
	z.im = 0.;
	
}/* equate */


void equate(fpComplex& z, double x)
{
	z.re = x;
	z.im = 0.;
	
}/* equate */



bool fpConvFromString(fpComplex& z, const char* inStringRe, const char* inStringIm)
{
	if(fpConvFromString(z.re, inStringRe) && fpConvFromString(z.im, inStringIm))
		return true;
	
	return false;
	
}/* fpConvFromString */



bool fpConvFromString(fpComplex& z, const char* inString)
{
	INT32		i, j, len, commaIndex;
	char		*tempStr, *tempStr1, ch;
	bool		isGood;
	
	commaIndex = -1;
	
	len = strlen(inString);
	if(!len)
	{
		z.re = z.im = 0;
		return false;
	}
	
	// remove parentheses
	tempStr1 = (char*)malloc((len+1)*sizeof(char));  // was len - a mistake!
	j = 0;
	for(i=0;i<len;i++)
	{
		ch = inString[i];
		if(!(ch=='(' || ch==')' || ch==' '))
			tempStr1[j++] = ch;
	}
	tempStr1[j] = 0;
	len = strlen(tempStr1);
	
	// is there a comma:
	for(i=0;i<len;i++)
	{
		if(tempStr1[i]==',')
		{
			commaIndex = i;
			break;
		}
	}
	
	if(commaIndex==-1)
	{
		// no comma, so real input only
		z.im = 0;
		isGood = fpConvFromString(z.re, tempStr1);
		free(tempStr1);
		return isGood;
	}
	
	// there is a comma
	tempStr = (char*)malloc((len+1)*sizeof(char));
	// get real input
	for(i=0;i<commaIndex;i++)
		tempStr[i] = tempStr1[i];
	tempStr[commaIndex] = 0;
	
	if(!fpConvFromString(z.re, tempStr))
	{
		free(tempStr);
		z.re = z.im = 0;
		return false;
	}
	
	// get imag input
	for(i=commaIndex+1; i<len; i++)
		tempStr[i-commaIndex-1] = tempStr1[i];
	tempStr[len-commaIndex-1] = 0;
	free(tempStr1);
	if(!fpConvFromString(z.im, tempStr))
	{
		free(tempStr);
		z.re = z.im = 0;
		return false;
	}
	
	free(tempStr);
	return true;

}/* fpConvFromString */


char* fpComplexToStr(const fpComplex& x, INT32 decPrec)
{
	
	char	*fpStrRe, *fpStrIm, *outStr;
	INT32	len;
	
	fpStrRe = fpToStr(x.re, decPrec);
	fpStrIm = fpToStr(x.im, decPrec);
	
	len = strlen(fpStrRe) + strlen(fpStrIm) + 10;
	
	outStr = (char*)malloc(len*sizeof(char));
	
	outStr = strcpy(outStr, "(");
	outStr = strcat(outStr, fpStrRe);
	outStr = strcat(outStr, ",");
	outStr = strcat(outStr, fpStrIm);
	outStr = strcat(outStr, ")");
	
	free(fpStrRe);
	free(fpStrIm);
	
	return outStr;

}/* fpComplexToStr */
