/*--------------------------------------------------------------------
 *	$Id: pslegend.c,v 1.46 2004/09/29 06:58:08 pwessel Exp $
 *
 *	Copyright (c) 1991-2004 by P. Wessel and W. H. F. Smith
 *	See COPYING file for copying and redistribution conditions.
 *
 *	This program is free software; you can redistribute it and/or modify
 *	it under the terms of the GNU General Public License as published by
 *	the Free Software Foundation; version 2 of the License.
 *
 *	This program is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *	GNU General Public License for more details.
 *
 *	Contact info: gmt.soest.hawaii.edu
 *--------------------------------------------------------------------*/
/*
 * pslegend will make map legends from input that specifies what will go
 * into the legend, such as headers, symbols with explanatory text,
 * paragraph text, and empty space and horizontal/vertical lines.
 *
 * Author:	Paul Wessel
 * Date:	18-SEP-2001
 * Version:	4
 *
 */

#include "gmt.h"

#ifdef WIN32
#include <process.h>
char *del = "del";
char *null = "NUL";
char *escape = "^";
char quote = ' ';
#else
char *del = "rm -f";
char *null = "/dev/null";
char *escape = "\\";
char quote = '\'';
#endif

void GMT_replace_symbol (char *symbol);

main(int argc, char **argv)
{
	int i, k, n, justify, n_columns = 1, error = 0, symbol_number = 0, n_files = 0, colon, n_scan;
	BOOLEAN gave_xy = FALSE, do_fill = FALSE, flush_paragraph = FALSE, save_script = FALSE, draw_vertical_line = FALSE, draw_box = FALSE;
	double x_legend_pos, y_legend_pos, x_off, width, height, west, east, south, north, x, y, x_gap = 0.05, y_gap = 0.05, line_spacing_factor = 1.1;
	double half_line_spacing, quarter_line_spacing, one_line_spacing, x0, y0, L, off_s, off_t, V, y_start, d_off, y_use;
	char txt_a[32], txt_b[32], txt_c[32], txt_d[32], txt_e[128], txt_f[128], key[32], *f = CNULL, sub[64], cmd[BUFSIZ];
	char symbol[256], text[BUFSIZ], *u = CNULL, image[BUFSIZ], xx[32], yy[32], size[32], angle[32], mapscale[128];
	char font[32], lspace[32], tw[32], jj[32], line[BUFSIZ], vpen[32], script[256], sarg[256], *jarg = CNULL;
	char txtcolor[32], psxy[32], pstext[128], *script_name = CNULL;
	struct GMT_FILL fill;
	struct rasterfile header;
	FILE *fp = NULL, *fpo;
	
	argc = GMT_begin (argc, argv);

	/* Check and interpret the command line arguments */
	
	for (i = 1; i < argc; i++) {
		if (argv[i][0] == '-') {
			switch(argv[i][1]) {
		
				/* Common parameters */
			
				case 'J':
					jarg = argv[i];	/* Keep this for later */
				case 'K':
				case 'O':
				case 'P':
				case 'R':
				case 'V':
				case 'X':
				case 'x':
				case 'Y':
				case 'y':
				case '\0':
					error += GMT_get_common_args (argv[i], &west, &east, &south, &north);
					break;
				
				case 'U':	/* Just need a pointer to pass along */
					u = &argv[i][2];
					break;
					
				/* Supplemental parameters */
			
				case 'C':	/* Sets the clearance between frame and internal items */
					sscanf (&argv[i][2], "%[^/]/%s", txt_a, txt_b);
					x_gap = GMT_convert_units (txt_a, GMT_INCH);
					y_gap = GMT_convert_units (txt_b, GMT_INCH);
					break;
				case 'D':	/* Sets position and size of legend */
					if (argv[i][2] == 'x') {	/* Gave location directly in projected units (inches, cm, etc) */
						gave_xy = TRUE;
						k = 3;
					}
					else				/* Gave lon, lat */
						k = 2;
					n = sscanf (&argv[i][k], "%[^/]/%[^/]/%[^/]/%[^/]/%s", txt_a, txt_b, txt_c, txt_d, key);
					if (n != 5) {
						fprintf (stderr, "%s ERROR: Syntax is -D[x]<xpos>/<ypos>/<width>/<height>/<justify>\n", GMT_program);
						error++;
					}
					if (argv[i][2] == 'x') {
						x_legend_pos = GMT_convert_units (txt_a, GMT_INCH);
						y_legend_pos = GMT_convert_units (txt_b, GMT_INCH);
					}
					else {	/* Given in user units, likely degrees */
						error += GMT_verify_expectations (GMT_io.in_col_type[0], GMT_scanf (txt_a, GMT_io.in_col_type[0], &x_legend_pos), txt_a);
						error += GMT_verify_expectations (GMT_io.in_col_type[1], GMT_scanf (txt_b, GMT_io.in_col_type[1], &y_legend_pos), txt_b);
					}
					width   = GMT_convert_units (txt_c, GMT_INCH);
					height  = GMT_convert_units (txt_d, GMT_INCH);
					justify = GMT_just_decode (key, -1, -1);
					break;
				case 'F':
					draw_box = TRUE;
					break;
				case 'G':	/* Inside legend fill? */
					if (GMT_getfill (&argv[i][2], &fill)) {	/* We check syntax here */
						GMT_fill_syntax ('G');
						error++;
					}
					do_fill = TRUE;
					f = argv[i];		/* Pointer to fill argument */
					break;
				case 'L':			/* Sets linespacing in units of fontsize [1.1] */
					line_spacing_factor = atof (&argv[i][2]);
					break;
				case 'S':
					save_script = TRUE;
					if (argv[i][2]) {	/* Specified script filename */
						script_name = &argv[i][2];
					}
					break;
					
				/* Options not recognized */
						
				default:
					error = TRUE;
					GMT_default_error (argv[i][1]);
					break;
			}
		}
		else if (n_files == 0) {
			if ((fp = fopen (argv[i], "r")) == NULL) {
				fprintf (stderr, "%s ERROR: Cannot open file %s\n", GMT_program, argv[i]);
				exit (EXIT_FAILURE);
			}
			n_files++;
		}
		else {
			fprintf (stderr, "%s ERROR: Only one file argument allowed\n", GMT_program);
			exit (EXIT_FAILURE);
		}
	}
	
	if (argc == 1 || GMT_quick) {
		fprintf (stderr, "pslegend %s - To plot legends on maps\n\n", GMT_VERSION);
		fprintf (stderr, "usage: pslegend [<infofile>] -D[x]<x0>/<y0>/w/h/just -J<params> -R<w>/<e>/<s>/<n>\n");
		fprintf (stderr, "\t[-C<dx>/<dy>] [-F] [-G<fill>] [-K] [-L<spacing>] [-O] [-P] [-S[<script>]] [-U[<label>]] [-V]\n\n");
		fprintf (stderr, "\tReads legend layout information from <infofile> [or stdin]\n");
		fprintf (stderr, "\t(See manual page for more information)\n");
		if (GMT_quick) exit (EXIT_FAILURE);
		
		fprintf (stderr, "\t-D sets position and size of legend box.  Prepend x if coordinates are projected.\n");
		fprintf (stderr, "\t   Append the justification of the whole legend box using pstext justification codes.\n");
		GMT_explain_option ('j');
		GMT_explain_option ('R');
		fprintf (stderr, "\n\tOPTIONS:\n");
		GMT_explain_option ('b');
		fprintf (stderr, "\t-C sets the clearance between legend frame and internal items [0.05i/0.05i]\n");
		fprintf (stderr, "\t-F Draw border around the legend (using FRAME_PEN) [Default is no border]\n");
		fprintf (stderr, "\t-G set the fill for the legend box [no fill]\n");
		GMT_explain_option ('K');
		GMT_explain_option ('O');
		GMT_explain_option ('P');
		fprintf (stderr, "\t-S Dump legend script to stdout, or optionally to file <script>.\n");
		fprintf (stderr, "\t   [Default is to write PostScript output]\n");
		GMT_explain_option ('U');
		GMT_explain_option ('V');
		GMT_explain_option ('X');
		GMT_explain_option ('.');
		exit (EXIT_FAILURE);
	}

	/* Check that the options selected are mutually consistent */
	
	if (x_gap < 0.0 || y_gap < 0.0) {
		fprintf (stderr, "%s: GMT SYNTAX ERROR -C option:  clearances cannot be negative!\n", GMT_program);
		error++;
	}
	if (width < 0.0 || height < 0.0) {
		fprintf (stderr, "%s: GMT SYNTAX ERROR -D option:  legend box sizes cannot be negative!\n", GMT_program);
		error++;
	}
	if (!project_info.region_supplied) {
		fprintf (stderr, "%s: GMT SYNTAX ERROR:  Must specify -R option\n", GMT_program);
		error++;
	}

	if (error) exit (EXIT_FAILURE);

	GMT_put_history (argc, argv);	/* Update .gmtcommands4 */

	if (save_script) {
		if (script_name) {
			if ((fpo = GMT_fopen (script_name, "w")) == NULL) {
				fprintf (stderr, "%s: GMT SYNTAX ERROR -S option:  Cannot create file %s\n", GMT_program, script_name);
				exit (EXIT_FAILURE);
			}
			if (gmtdefs.verbose) fprintf (stderr, "%s: Generate legend script %s\n", GMT_program, script_name);
		}
		else {
			fpo = GMT_stdout;
			if (gmtdefs.verbose) fprintf (stderr, "%s: Generate legend script [stdout]\n", GMT_program);
		}
	}
	else {
		if (gmtdefs.verbose) fprintf (stderr, "%s: Generate legend plot\n", GMT_program);
		sprintf (script, "GMT%d.bat", getpid ());
		fpo = fopen (script, "w");
	}
	if (!fp) fp = stdin;
	
	GMT_map_setup (west, east, south, north);
	
	if (!gave_xy) {
		GMT_geo_to_xy (x_legend_pos, y_legend_pos, &x, &y);
		x_legend_pos = x;	y_legend_pos = y;
	}
	
	/* Adjust for -X -Y shifts */
	
	x_legend_pos += gmtdefs.x_origin;
	y_legend_pos += gmtdefs.y_origin;
	
	/* Allow for justification */
	
	x_legend_pos -= 0.5 * ((justify-1)%4) * width;
	y_legend_pos -= 0.5 * (justify/4) * height;
		
	/* First draw legend frame box.  Note -JX%gi/-%gi which means y is positive down from the top of the box */
	
	if (draw_box || do_fill)
		sprintf (cmd, "psbasemap -R0/%g/0/%g -JX%gi/-%gi -X%gi -Y%gi -K", width, height, width, height, x_legend_pos, y_legend_pos);
	else
		sprintf (cmd, "psxy -R0/%g/0/%g -JX%gi/-%gi %s -X%gi -Y%gi -K", width, height, width, height, null, x_legend_pos, y_legend_pos);
	sprintf (pstext, "pstext -R -JX -O -K");
	sprintf (psxy, "psxy -R -JX -O -K");
	if (gmtdefs.page_orientation & 1) strcat (cmd, " -P");
	if (draw_box) strcat (cmd, " -B0");
	if (gmtdefs.overlay) strcat (cmd, " -O");
	if (do_fill) {
		sprintf (sub, " %s", f);
		strcat (cmd, sub);
	}
	if (u) {
		sprintf (sub, " -U\"%s\"", u);
		strcat (cmd, sub);
	}
	fprintf (fpo, "%s\n", cmd);
	
	x0 = x_gap;
	y0 = y_gap;
	one_line_spacing = line_spacing_factor * gmtdefs.annot_font_size[0] / 72.0;
	half_line_spacing = 0.5 * one_line_spacing;
	quarter_line_spacing = 0.25 * one_line_spacing;
	symbol_number = 0;
	
	while (fgets (line, BUFSIZ, fp)) {

		if (line[0] == '\0' || line[0] == '#') continue;	/* Skip blank lines or # comments */
		
		switch (line[0]) {
			case 'C':	/* Color change */
				if (flush_paragraph) fprintf (fpo, "%s -M pslegend_tmp.txt\n%s pslegend_tmp.txt\n", pstext, del);
				sscanf (&line[2], "%[^\n]", txtcolor);
				if (txtcolor[0] == '-') sprintf (pstext, "pstext -R -JX -O -K");
				else sprintf (pstext, "pstext -R -JX -O -K -G%s", txtcolor);
				break;
			case 'H':	/* Header record */
				if (flush_paragraph) fprintf (fpo, "%s -M pslegend_tmp.txt\n%s pslegend_tmp.txt\n", pstext, del);
				flush_paragraph = FALSE;
				if (n_columns > 1 && symbol_number > 0 && symbol_number%n_columns != 0) y0 += half_line_spacing, symbol_number = 0;	/* Did not end with full column */
				sscanf (&line[2], "%s %s %[^\n]", size, font, text);
				if (size[0] == '-') sprintf (size, "%g", gmtdefs.header_font_size);
				if (font[0] == '-') sprintf (font, "%d", gmtdefs.header_font);
				y0 += line_spacing_factor * atoi (size) / 72.0;
				fprintf (fpo, "echo %c%g %g %s 0 %s CB %s%c | %s\n", quote, 0.5 * width, y0, size, font, text, quote, pstext);
				break;
				
			case 'I':	/* Image record */
				if (flush_paragraph) fprintf (fpo, "%s -M pslegend_tmp.txt\n%s pslegend_tmp.txt\n", pstext, del);
				flush_paragraph = FALSE;
				if (n_columns > 1 && symbol_number > 0 && symbol_number%n_columns != 0) y0 += half_line_spacing, symbol_number = 0;	/* Did not end with full column */
				sscanf (&line[2], "%s %s %s", image, size, key);
				(void) ps_loadraster (image, &header, FALSE, FALSE, FALSE, NULL, NULL);
				justify = GMT_just_decode (key, -1, -1);
				x_off = (justify%4 == 1) ? x0 : ((justify%4 == 3) ? width - x_gap : 0.5 * width);
				L = GMT_convert_units (size, GMT_INCH) * ((double)header.ras_height / (double)header.ras_width);
				fprintf (fpo, "psimage -O -K %s -W%s -C%gi/%gi/%s\n", image, size, x_off, height-y0, key);
				y0 += L + half_line_spacing;
				break;
				
			case 'L':	/* Label record */
				if (flush_paragraph) fprintf (fpo, "%s -M pslegend_tmp.txt\n%s pslegend_tmp.txt\n", pstext, del);
				flush_paragraph = FALSE;
				if (n_columns > 1 && symbol_number > 0 && symbol_number%n_columns != 0) y0 += half_line_spacing, symbol_number = 0;	/* Did not end with full column */
				sscanf (&line[2], "%s %s %s %[^\n]", size, font, key, text);
				if (size[0] == '-') sprintf (size, "%g", gmtdefs.label_font_size);
				if (font[0] == '-') sprintf (font, "%d", gmtdefs.label_font);
				y0 += line_spacing_factor * atoi (size) / 72.0;
				justify = GMT_just_decode (key, -1, 0);
				x_off = (justify%4 == 1) ? x0 : ((justify%4 == 3) ? width - x_gap : 0.5 * width);
				fprintf (fpo, "echo %c%g %g %s 0 %s B%s %s%c | %s\n", quote, x_off, y0, size, font, key, text, quote, pstext);
				break;
				
			case 'M':	/* Map scale record M lon0|- lat0 length[:label:just] f|p [-R -J] */
				if (flush_paragraph) fprintf (fpo, "%s -M pslegend_tmp.txt\n%s pslegend_tmp.txt\n", pstext, del);
				flush_paragraph = FALSE;
				if (n_columns > 1 && symbol_number > 0 && symbol_number%n_columns != 0) y0 += half_line_spacing, symbol_number = 0;	/* Did not end with full column */
				n_scan = sscanf (&line[2], "%s %s %s %s %s %s", txt_a, txt_b, txt_c, txt_d, txt_e, txt_f);
				if (txt_d[0] != 'f') txt_d[0] = 'p';	/* Default is plain unless f is given */
				for (i = colon = 0; txt_c[i] && colon != 2; i++) if (txt_c[i] == ':') colon++;
				if (colon) {	/* Specified alternate label (could be upper case, hence 0.85) and justification */
					d_off = 0.0;
					/* if (txt_c[i] == 't') d_off = 0.75 * (gmtdefs.map_scale_height + gmtdefs.label_font_size / 72.0); */
					if (txt_c[i] == 't') d_off = gmtdefs.label_offset + 0.85 * fabs (gmtdefs.label_font_size / 72.0);
				}
				else {	/* Default places a lower case title on top, hence only 0.75 size */
					/* d_off = 0.75 * (gmtdefs.map_scale_height + gmtdefs.label_font_size / 72.0); */
					d_off = gmtdefs.label_offset + 0.75 * fabs (gmtdefs.label_font_size / 72.0);
				}
				y0 += d_off - quarter_line_spacing;
				x_off = 0.5 * width;
				y_use = height - y0;
				if (!strcmp (txt_a, "-"))	/* No longitude needed */
					sprintf (mapscale, "%cx%gi/%gi/%s/%s", txt_d[0], 0.5 * width, y_use, txt_b, txt_c);
				else				/* Gave both lon and lat for scale */
					sprintf (mapscale, "%cx%gi/%gi/%s/%s/%s", txt_d[0], 0.5 * width, y_use, txt_a, txt_b, txt_c);
				
				if (n_scan == 6)	/* Gave specific -R -J on M line */
					fprintf (fpo, "psbasemap %s %s -O -K -L%s\n", txt_e, txt_f, mapscale);
				else	/* Use -R -J supplied to pslegend */
					fprintf (fpo, "psbasemap -R%lg/%lg/%lg/%lg %s -O -K -L%s\n", west, east, south, north, jarg, mapscale);
				d_off = 0.0;
				if (colon && txt_c[i] == 'b') {	/* Specified bottom justification */
					d_off = 0.75 * gmtdefs.label_font_size / 72.0 + fabs(gmtdefs.label_offset);
				}
				else	/* Default */
					d_off = 0.0;
				/* y0 += half_line_spacing + gmtdefs.map_scale_height + d_off; */
				y0 += gmtdefs.map_scale_height + d_off + 0.75 * gmtdefs.annot_font_size[0] / 72.0 + quarter_line_spacing;
				break;
				
			case 'S':	/* Symbol record */
				if (flush_paragraph) fprintf (fpo, "%s -M pslegend_tmp.txt\n%s pslegend_tmp.txt\n", pstext, del);
				flush_paragraph = FALSE;
				symbol_number++;
				sscanf (&line[2], "%s %s %s %s %s %s %[^\n]", txt_a, symbol, size, txt_c, txt_d, txt_b, text);
				off_s = GMT_convert_units (txt_a, GMT_INCH);
				off_t = GMT_convert_units (txt_b, GMT_INCH);
				if (n_columns == 1 || symbol_number%n_columns == 1) y0 += half_line_spacing;
				if ((txt_c[0] == 'P' || txt_c[0] == 'p') && symbol[0] != 'k') {	/* Must use kustom equivalent symbol */
					GMT_replace_symbol (symbol);	/* E.g., convert c0.5i to kcircle/0.5i */
				}
				x_off = x0 + (width / n_columns) * ((symbol_number - 1) % n_columns);
				if (symbol[0] == 'f') {	/* Front is different, must plot as a line segment */
					i = 0;
					while (size[i] != '/' && size[i]) i++;
					if (size[i] != '/') {
						fprintf (stderr, "%s: ERROR: -Sf option must have a tick length\n", GMT_program);
						exit (EXIT_FAILURE);
					}
					i++;
					x = 0.5*GMT_convert_units (size, gmtdefs.measure_unit);
					fprintf (fpo, "echo %g %g > pslegend_tmp.txt\necho %g %g >> pslegend_tmp.txt\n", x_off + off_s-x, y0, x_off + off_s+x, y0);
					sprintf (cmd, "%s -S%s%s pslegend_tmp.txt", psxy, symbol, &size[i]);
					if (txt_c[0] != '-') {
						sprintf (sub, " -G%s", txt_c);
						strcat (cmd, sub);
					}
					if (txt_d[0] != '-') {
						sprintf (sub, " -W%s", txt_d);
						strcat (cmd, sub);
					}
					fprintf (fpo, "%s\n", cmd);
					fprintf (fpo, "%s pslegend_tmp.txt\n", del);
				}
				else {	/* Regular symbols */
					if (symbol[0] == 'k')
						sprintf (sub, "%s/%s", symbol, size);
				/*	else if (symbol[0] == 'l')
						sprintf (sub, "%s", symbol); */
					else
						sprintf (sub, "%s%s", symbol, size);
					if (symbol[0] == 'E' || symbol[0] == 'e') {	/* Ellipse needs more arguments */
						x = 0.5*GMT_convert_units (size, gmtdefs.measure_unit);
						sprintf (sarg, "%g %g 0 %g %g", x_off + off_s, y0, x, 0.65*x);
					}
					else if (symbol[0] == 'V' || symbol[0] == 'v') {	/* Vector also need more args */
						i = 0;
						while (size[i] != '/' && size[i]) i++;
						if (size[i] != '/') {
							sprintf (sub, "vb");
							exit (EXIT_FAILURE);
						}
						else
							sprintf (sub, "%sb%s", symbol, &size[++i]);
						x = GMT_convert_units (size, gmtdefs.measure_unit);
						sprintf (sarg, "%g %g 0 %g", x_off + off_s, y0, x);
					}
					else if (symbol[0] == 'w') {	/* Wedge also need more args */
						x = GMT_convert_units (size, GMT_INCH);
						sprintf (sarg, "%g %g 20 60", x_off + off_s -0.5*x, y0+0.25*x);
					}
					else
						sprintf (sarg, "%g %g", x_off + off_s, y0);
					sprintf (cmd, "echo %s | %s -S%s", sarg, psxy, sub);
					if (txt_c[0] != '-') {
						sprintf (sub, " -G%s", txt_c);
						strcat (cmd, sub);
					}
					if (txt_d[0] != '-') {
						sprintf (sub, " -W%s", txt_d);
						strcat (cmd, sub);
					}
					fprintf (fpo, "%s\n", cmd);
				}
				fprintf (fpo, "echo %c%g %g %g 0 %d LM %s%c | %s\n", quote, x_off + off_t, y0, gmtdefs.annot_font_size[0], gmtdefs.annot_font[0], text, quote, pstext);
				if (n_columns == 1 || symbol_number%n_columns == 0) y0 += half_line_spacing;
				break;
				
			case 'D':	/* Delimiter record */
				if (flush_paragraph) fprintf (fpo, "%s -M pslegend_tmp.txt\n%s pslegend_tmp.txt\n", pstext, del);
				flush_paragraph = FALSE;
				if (n_columns > 1 && symbol_number > 0 && symbol_number%n_columns != 0) y0 += half_line_spacing, symbol_number = 0;	/* Did not end with full column */
				sscanf (&line[2], "%s %s", txt_a, txt_b);
				L = GMT_convert_units (txt_a, GMT_INCH);
				y0 += quarter_line_spacing;
				fprintf (fpo, "echo %g %g > pslegend_tmp.txt\necho %g %g >> pslegend_tmp.txt\n", L, y0, width - L, y0);
				fprintf (fpo, "%s -W%s pslegend_tmp.txt\n%s pslegend_tmp.txt\n", psxy, txt_b, del);
				y0 += quarter_line_spacing;
				break;
				
			case 'G':	/* Gap record */
				if (flush_paragraph) fprintf (fpo, "%s -M pslegend_tmp.txt\n%s pslegend_tmp.txt\n", pstext, del);
				flush_paragraph = FALSE;
				if (n_columns > 1 && symbol_number > 0 && symbol_number%n_columns != 0) y0 += half_line_spacing, symbol_number = 0;	/* Did not end with full column */
				sscanf (&line[2], "%s", txt_a);
				L = (txt_a[strlen(txt_a)-1] == 'l') ? atoi (txt_a) * one_line_spacing : GMT_convert_units (txt_a, GMT_INCH);
				y0 += L;
				break;
			case 'N':	/* n_columns record */
				if (flush_paragraph) fprintf (fpo, "%s -M pslegend_tmp.txt\n%s pslegend_tmp.txt\n", pstext, del);
				flush_paragraph = FALSE;
				if (n_columns > 1 && symbol_number > 0 && symbol_number%n_columns != 0) y0 += half_line_spacing, symbol_number = 0;	/* Did not end with full column */
				sscanf (&line[2], "%s", txt_a);
				n_columns = atoi (txt_a);
				symbol_number = 0;
				break;
				
			case 'V':	/* Vertical line from here to next V */
				if (flush_paragraph) fprintf (fpo, "%s -M pslegend_tmp.txt\n%s pslegend_tmp.txt\n", pstext, del);
				flush_paragraph = FALSE;
				if (n_columns > 1 && symbol_number > 0 && symbol_number%n_columns != 0) y0 += half_line_spacing, symbol_number = 0;	/* Did not end with full column */
				if (draw_vertical_line) {	/* Second time, now draw line */
					fprintf (fpo, "echo # vertical lines > pslegend_tmp.txt\n");
					for (i = 1; i < n_columns; i++) {
						x_off = i * width / n_columns;
						fprintf (fpo, "echo %s> bar %d >> pslegend_tmp.txt\n", escape, i);
						fprintf (fpo, "echo %g %g >> pslegend_tmp.txt\necho %g %g >> pslegend_tmp.txt\n", x_off, y_start+V-quarter_line_spacing, x_off, y0-V+quarter_line_spacing);
					}
					fprintf (fpo, "%s -W%s -H -M pslegend_tmp.txt\n%s pslegend_tmp.txt\n", psxy, vpen, del);
					draw_vertical_line = FALSE;
				}
				else {
					draw_vertical_line = TRUE;
					y_start = y0;
					sscanf (&line[2], "%s %s", txt_a, vpen);
					V = GMT_convert_units (txt_a, GMT_INCH);
				}
				break;
				
			case '>':	/* Paragraph text header */
				n = sscanf (&line[1], "%s %s %s %s %s %s %s %s %s", xx, yy, size, angle, font, key, lspace, tw, jj);
				if (!(n <= 0 || n == 9)) {
					fprintf (stderr, "%s: ERROR: The > record must have 0 or 9 arguments (only %d found)\n", GMT_program, n);
					exit (EXIT_FAILURE);
				}
				if (n < 0) n = 0;	/* Since -1 is returned if no arguments */
				if (n == 0 || xx[0] == '-') sprintf (xx, "%g", x0);
				if (n == 0 || yy[0] == '-') sprintf (yy, "%g", y0);
				if (n == 0 || size[0] == '-') sprintf (size, "%g", gmtdefs.annot_font_size[0]);
				if (n == 0 || angle[0] == '-') sprintf (angle, "0");
				if (n == 0 || font[0] == '-') sprintf (font, "%d", gmtdefs.annot_font[0]);
				if (n == 0 || key[0] == '-') sprintf (key, "TL");
				if (n == 0 || lspace[0] == '-') sprintf (lspace, "%gi", one_line_spacing);
				if (n == 0 || tw[0] == '-') sprintf (tw, "%gi", width - 2.0 * x_gap);
				if (n == 0 || jj[0] == '-') sprintf (jj, "j");
				fprintf (fpo, "echo %s> %s %s %s %s %s %s %s %s %s > pslegend_tmp.txt\n", escape, xx, yy, size, angle, font, key, lspace, tw, jj);
				flush_paragraph = TRUE;
				break;
				
			case 'T':	/* paragraph text record */
				sscanf (&line[2], "%[^\n]", text);
				fprintf (fpo, "echo %c%s%c >> pslegend_tmp.txt\n", quote, text, quote);
				break;
				
			default:
				fprintf (stderr, "%s: ERROR: Unrecognized record (%s)\n", GMT_program, line);
				exit (EXIT_FAILURE);
			break;
		}	
	}
	if (fp != stdin) fclose (fp);
	
	if (flush_paragraph) fprintf (fpo, "%s -M pslegend_tmp.txt\n%s pslegend_tmp.txt\n", pstext, del);
	/* Revert to original region (-R), projection and size (-J) and position (-X, -Y) */
	sprintf (cmd, "psxy %s -R%g/%g/%g/%g %s -X%gi -Y%gi -O", null, west, east, south, north, jarg, -x_legend_pos, -y_legend_pos);
	if (!gmtdefs.last_page) strcat (cmd, " -K");
	fprintf (fpo, "%s\n", cmd);
	
	if (!save_script) {	/* Add auto-delete command at the end of the script and then execute it */
		fprintf (fpo, "%s %s\n", del, script);
		if (fpo != GMT_stdout) GMT_fclose (fpo);
		if (gmtdefs.verbose) fprintf (stderr, "%s: Executing legend script\n", GMT_program);
#ifdef WIN32
		system (script);
#else
		sprintf (cmd, "sh %s", script);
		system (cmd);
#endif
	}	

	if (gmtdefs.verbose) fprintf (stderr, "%s: Done\n", GMT_program);

 	GMT_end (argc, argv);
}

void GMT_replace_symbol (char *symbol)
{
	char new[BUFSIZ];
	
	switch (symbol[0]) {
		case 'a':	/* Star */
			sprintf (new, "kstar");
			break;
		case 'c':	/* Circle */
			sprintf (new, "kcircle");
			break;
		case 'd':	/* Diamond */
			sprintf (new, "kdiamond");
			break;
		case 'h':	/* Hexagon */
			sprintf (new, "khexagon");
			break;
		case 'i':	/* Inverted triangle */
			sprintf (new, "kinvtriangle");
			break;
		case 'n':	/* Pentagon */
			sprintf (new, "kpentagon");
			break;
		case 's':	/* Square */
			sprintf (new, "ksquare");
			break;
		case 't':	/* Triangle */
			sprintf (new, "ktriangle");
			break;
		default:	/* None of the above */
			strcpy (new, symbol);
			break;
	}
	strcpy (symbol, new);
}

