
/* Postscript plotting routines */

#include "cx.h"
#include <math.h>
#include <string.h>

#define PAGEX 540       /* Postscript parameters */
#define PAGEY 720
#define CORNX 36
#define CORNY 36
#define LINEWIDTH 0.2
#define BOX 1
#define WIN 0
#define LINE_ACTIVE 0

static double linewidth=LINEWIDTH;
static int box=BOX, win=WIN;
static int line_active=LINE_ACTIVE;
double wxmax, wxmin, wymax, wymin;

set_linewidth(w)
	double w;
{
	linewidth=w;
}

/* Reverse box option */
ps_box()
{	box = (box==0);}

/* Set window */
ps_win(xmin,ymin,xmax,ymax)
	double xmin, ymin, xmax, ymax;
{
	char str[200];

	win=1;
	wxmin=xmin; wxmax=xmax;
	wymin=ymin; wymax=ymax;
	ps_box();
}

/* Scale and box */
ps_window(xmin,ymin,xmax,ymax)
	double xmin, ymin, xmax, ymax;
{
	int marginx, marginy;
	double s, sx, sy, tx, ty;

	sx = PAGEX/(xmax-xmin);
	sy = PAGEY/(ymax-ymin);
	s  = (sx < sy) ? sx : sy;
	marginx = (PAGEX-s*(xmax-xmin))/2;
	marginy = (PAGEY-s*(ymax-ymin))/2;

	printf("%%%%BoundingBox:  %d %d %d %d\n",
		CORNX+marginx,
		CORNY+marginy,
		CORNX+PAGEX-marginx,
		CORNY+PAGEY-marginy);
	printf("%d %d translate\n",
		CORNX+marginx,
		CORNY+marginy);
	printf("%.2lf setlinewidth\n",linewidth);
	printf("%%%%\n");
	printf("%%%% Change to complex coordinates\n");
	printf("%.5lf %.5lf scale\n",s,s);
	printf("currentlinewidth %.5lf div setlinewidth\n",s);
	printf("%.5lf %.5lf translate\n",-xmin,-ymin); 
	if(box)
	printf(
"newpath\n%.5lf %.5lf moveto %.5lf %.5lf lineto\n %.5lf %.5lf lineto %.5lf %.5lf lineto\nclosepath stroke\n",
	xmin,ymin,xmin,ymax,xmax,ymax,xmax,ymin);
	printf(
"newpath\n %.5lf %.5lf moveto %.5lf %.5lf lineto\n %.5lf %.5lf lineto %.5lf %.5lf lineto\nclosepath clip\n",
	xmin,ymin,xmin,ymax,xmax,ymax,xmax,ymin);
	printf("newpath\n");
}

ps_open(argc,argv)
	int argc;
	char *argv[];
{
	int i;

	printf("%%!\n");
	printf("%%%% Lim Version 1.2\n");
	printf("%%%% Command line:\n");
        printf("%%%% ");
        for(i=0; i<argc; i++)
                printf("%s ",argv[i]);
	printf("\n");
}

ps_newline()
{
	if(line_active) printf("stroke\n");
	line_active = 0;
}

ps_move(z)
	complex z;
{
	ps_newline();
	printf("%.3lf %.3lf moveto\n",z.x,z.y);
	line_active=1;
}

ps_draw(z)
	complex z;
{
	if(!line_active) ps_move(z);
	else printf("%.3lf %.3lf lineto\n",z.x,z.y);
}

ps_close()
{
	ps_newline();
	line_active=0;
	printf("showpage\n");
}
