#include "arbfunc.h"
#include <math.h>
#include <assert.h>
#include <string.h>
#include <String.h>

arbfunc::~arbfunc() {}

C char *C arbfunc::Enotmine = "Line given to parse() isn't id() or idtmp()";

char * arbfunc::read(FILE *fp)
{
 char line[600];
 char *err;
 while(fgets(line, sizeof(line), fp))
	if((err=parse(line))!=0 && strcmp(err, Enotmine)!=0)
		return err;
 if(! all_set())	{
	char buf[200];
	sprintf(buf, "File does not contain %s %s setup info",
					partial_set() ? "complete" : "any",
					id());
	return strdup(buf);
	}
 return 0;
}

char * arbfunc::read(C char *fn)
{
 FILE *fp = fopen(fn, "r");
 if(!fp)
	return (String("arbfunc::read: Can't open file: ")+String(fn)).array();
 char *tmp = read(fp);
 fclose(fp);
 return tmp;
}

BOOL arbfunc::write_check(FILE *fp, double x) C
{
 char xstr[200];
 sprintf(xstr, "%g", x);
 double x_as_written;
 sscanf(xstr, "%lf", &x_as_written);

 char ystr[200];
 C static char *fmtlist[] = {"%g", "%e", "%f", "%12g", "%12e", "%12f",
							"%18g", "%18e", "%18f", 0};
 C double y = (*this)(x_as_written);
 double y_as_written;
 C char **fmt = fmtlist;
 do	{
 	sprintf(ystr, *fmt, y);
	sscanf(ystr, "%lf", &y_as_written);
	} while(!check_is_ok(y, y_as_written) && *++fmt);
 if(*fmt)
 	fprintf(fp, "%s %s %s\n", id_check(), xstr, ystr);
 else fprintf(fp, "ERR: %s.write_check(%g) -- can't find format\n",
						id_check(), x);
 return fmt && !ferror(fp);
}
