#include "all.h"
#include "mygraph.h"

typedef struct {double x1,y1,x2,y2; char *name; } Aname;

static Aname *names;
static int nnam=0,maxnam;

int name_add(void);
int name_add(void)
{
	Aname *new;
	if (nnam>=maxnam) {
		maxnam+=20;
		new = myallocz(sizeof(Aname)*maxnam);
		if (names!=NULL) {
			memcpy(new,names,sizeof(Aname)*nnam);
			myfree(names);
		}
		names = new;
	}
	return nnam++;
}

int swap_minmax(double *x1, double *y1, double *x2, double *y2);
name_set(char *n,double x1,double y1,double x2,double y2)
{
	double xx1,yy1,xx2,yy2;
	int i;

	strupr(n);
	for (i=0;i<nnam;i++) if (strcmp(n,names[i].name)==0) break;
	if (i>=nnam) {
		i = name_add();
		names[i].name = sdup(n);
	}
	g_dev(x1,y1,&xx1,&yy1);
	g_dev(x2,y2,&xx2,&yy2);
	swap_minmax(&xx1, &yy1, &xx2, &yy2);
	names[i].x1= xx1;
	names[i].y1 = yy1;
	names[i].x2= xx2;
	names[i].y2= yy2;
}
swap_minmax(double *x1, double *y1, double *x2, double *y2)
{
	double a;
	if (*x1 > *x2) { a = *x1; *x1 = *x2; *x2 = a;}
	if (*y1 > *y2) { a = *y1; *y1 = *y2; *y2 = a;}
}
name_show()
{
	int i;
	for (i=0;i<nnam;i++) {
		gprint("Name %d {%s} \n",i,names[i].name);
	}
}
name_get(char *n,double *x1,double *y1,double *x2,double *y2)
{
	int i;
	double xx1,yy1,xx2,yy2;
	for (i=0;i<nnam;i++) {
		if (strcmp(n,names[i].name)==0) break;
	}
	if (i>=nnam) {
		gprint("Name not defined {%s} \n",n);
		i=0;
		return;
	}
	g_undev(names[i].x1,names[i].y1,&xx1,&yy1);
	g_undev(names[i].x2,names[i].y2,&xx2,&yy2);
	swap_minmax(&xx1, &yy1, &xx2, &yy2);
	*x1 = xx1;
	*y1 = yy1;
	*x2 = xx2;
	*y2 = yy2;
}


