#include <stdio.h>

#include <string.h>

#include "cyacas.h"


#include "sysdep.h"

#include "stack.h"

#include "express.h"

#include "output.h"

#include "yacas2e.h"



void do_yacas (void)
{	char s[270];
	scan_space();
	char *p=s;
	strcpy(p,"PrettyForm(");
	p+=strlen(p);
	while (*next!=0 && *next!=1)
	{	*p++=*next++;
		if (p-s>255)
		{	error=1;
			return;
		}
	}
	strcpy(p,")");
	header *hd=new_string(s,strlen(s),"");
	myacas(hd);
}

void * YacasHandle;
int YacasStarted;

typedef void (*VoidFunction) ();
typedef void (*CharFunction) (char *);
typedef char * (*ResFunction) ();

void init_yacas ()
{
	yacas_init();
	YacasStarted=1;
}

void yacas_test ()
{	if (!YacasHandle)
	{	error=1;
		output("Yacas not found!\n");
	}
}

void myacas (header *hd)
{
	header *st=hd,*result;
	char *arg;
	char *res;

	yacas_test();
	if (error) return;
	hd=getvalue(hd); if (error) return;
	if (hd->type!=s_string) wrong_arg_in("dir");
	arg=stringof(hd);
	yacas_eval(arg);
	res=yacas_error();
	if (res)
	{	output("Yacas Error:\n");
		output(res);
		error=1;
		return;
	}

	// Print output:
	res=yacas_output();
	output(res);
	
	res=yacas_result();
	int n=strlen(res);
	if (n>0 && res[n-1]==';') res[n-1]=0;
	result=new_string(res,strlen(res),"");
	if (error) return;
	moveresult(st,result);
}

void myacaseval (header *hd)
{
	header *st=hd,*result;
	char *arg;
	char *res;

	yacas_test();
	if (error) return;
	hd=getvalue(hd); if (error) return;
	if (hd->type!=s_string) wrong_arg_in("dir");
	arg=stringof(hd);
	yacas_eval(arg);
	res=yacas_error();
	if (res)
	{	output("Yacas Error:\n");
		output(res);
		error=1;
		return;
	}
	res=yacas_result();
	int n=strlen(res);
	if (n>0 && res[n-1]==';') res[n-1]=0;
	result=new_string(res,strlen(res),"");
	if (error) return;
	moveresult(st,result);
}

char *call_yacas (char *s)
{
	char *res;

	yacas_eval(s);
	res=yacas_error();
	if (res)
	{	error=1;
		return res;
	}
	res=yacas_result();
	int n=strlen(res);
	if (n>0 && res[n-1]==';') res[n-1]=0;
	return res;
}

void interrupt_yacas ()
{	yacas_test();
	if (error) return;
	yacas_interrupt();
}

void start_yacas ()
{	if (YacasStarted) return;
	yacas_test();
	if (error) return;
	yacas_init();
	YacasStarted=1;
}

void end_yacas ()
{	if (!YacasStarted) return;
	yacas_test();
	if (error) return;
	yacas_exit();
	YacasStarted=0;
}

void exit_yacas ()
{
	end_yacas();
}

void myacasclear (header *hd)
{	yacas_test();
	if (error) return;
	if (YacasStarted) end_yacas();
	if (error) return;
	start_yacas();
	new_real(0,"");
}


syntax highlighted by Code2HTML, v. 0.9.1