File: utility.cc

package info (click to toggle)
gri 2.4.2-1
  • links: PTS
  • area: main
  • in suites: potato
  • size: 4,540 kB
  • ctags: 1,966
  • sloc: cpp: 32,542; lisp: 3,243; perl: 806; makefile: 548; sh: 253
file content (1709 lines) | stat: -rw-r--r-- 41,007 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
//#define DEBUG_RE

#include	<string>
#include	<ctype.h>
#include	<math.h>
#include	<stdio.h>
#include        <stdarg.h>

#if defined(MSDOS)		// need all these?
#include <stdlib.h>
#include <conio.h>
#include <dir.h>
#include <io.h>
#include <process.h>
#include <signal.h>
#endif

#include "extern.hh"
#include "debug.hh"
#include "defaults.hh"
#include "gr.hh"
#include "superus.hh"
#include "GriTimer.hh"

#ifdef DEBUG_RE
static void     show_pattern(char *target, int tlen, int star, int plus);
#endif
extern double   strtod(const char *, char **);

// Keep this in static area, so as not to waste time with
// multiple allocation/deallocation for scratch strings
static string tmp_string;

// Return true if string is all space/tab chars
bool
string_is_blank(const char *s)
{
	int len = strlen(s);
	for (int i = 0; i < len; i++)
		if (!isspace(s[i]))
			return false;
	return true;
}

// Returns number column data that are missing in *any* variable
unsigned int
number_missing_cols()
{
	// Only examine other columns if they have same length
	unsigned int length = _colX.size();
	bool do_y     = _colY.size()     == length;
	bool do_z     = _colZ.size()     == length;
	bool do_U     = _colU.size()     == length;
	bool do_V     = _colV.size()     == length;
	bool do_R     = _colR.size()     == length;
	bool do_THETA = _colTHETA.size() == length;
	unsigned int missing = 0;
	for (unsigned int i = 0; i < length; i++) {
		if (            gr_missing(_colX[i]))     { missing++; continue; }
		if (do_y     && gr_missing(_colY[i]))	  { missing++; continue; }
		if (do_z     && gr_missing(_colZ[i]))	  { missing++; continue; }
		if (do_U     && gr_missing(_colU[i]))	  { missing++; continue; }
		if (do_V     && gr_missing(_colV[i]))	  { missing++; continue; }
		if (do_R     && gr_missing(_colR[i]))	  { missing++; continue; }
		if (do_THETA && gr_missing(_colTHETA[i])) { missing++; continue; }
	}
	return missing;
}

/* Return true if string starts and ends with character `"' */
bool
quoted(const char *s)
{
	int len = strlen(s);
	if (len < 2)
		return false;
	return (*s == '"' && *(s + len - 1) == '"') ? true : false;
}

/* Return transformed -- see code that calls it. */
double
quantize(double x, int levels, double dx)
{
	if (dx < 0.0)
		dx = -dx;
	if (dx)
		return (dx * levels / (1.0 + levels) * (floor(1.0 + x / dx)));
	else
		return x;
}

/* Change escaped quotes in word to quotes.  Strlen changed! */
void
remove_esc_quotes(char *w)
{
	int             i, max = strlen(w);
	char            last;
	last = ' ';
	for (i = 0; i < max; i++) {
		if (w[i] == '\\' && w[i + 1] == '"' && last != '\\') {
			/* gobble rest up */
			int             j;
			for (j = i; j < max; j++) {
				w[j] = w[j + 1];
			}
		} else {
			last = w[i];
		}
	}
}

// Is the i-th word of _word[] equal to given word? (return 0 if too few
// words)
bool
word_is(int i, const char *word)
{
	return ((-1 < i && i < _nword && !strcmp(word, _word[i])) ? true : false);
}

void
check_psfile()
{
	extern FILE    *_grPS;
	if (ferror(_grPS)) {
		/* never returns */
		fatal_err(" IO error on PostScript output file\n");
	}
}

bool
delete_file(const char *filename)
{
	char            sys_cmd[200];
#if defined(VMS)
	sprintf(sys_cmd, "DEL %s;*", filename);
	system(sys_cmd);
	return true;
#elif defined(MSDOS)
	sprintf(sys_cmd, "DEL %s", filename);
	system(sys_cmd);
	return true;
#else
	sprintf(sys_cmd, "rm %s", filename);
	system(sys_cmd);
	return true;
#endif
}

// Convert full filename to tilde name
char *
cshell_name(char *s)
{
	char *            new_name;
#if defined(HAVE_GETENV)
#if defined(MSDOS)		// for MSDOS, return input
	new_name = new char [1 + strlen(s)];
	if (!new_name) OUT_OF_MEMORY;
	strcpy(new_name, s);
	return new_name;
#else				// not MSDOS
	char *            user = (char *) getenv("USER");
	char *            home = (char *) getenv("HOME");
	if (user && home) {
		// The environment variables were recovered ok.
		if (!strncmp(s, home, strlen(home))) {
			// Below asks for 1 extra space; what the heck.
			new_name = new char [3 + strlen(user) + strlen(s) - strlen(home)];
			if (!new_name) OUT_OF_MEMORY;
			strcpy(new_name, "~");
			strcat(new_name, user);
			strcat(new_name, s + strlen(home));
		} else {
			new_name = new char[1 + strlen(s)];
			if (!new_name) OUT_OF_MEMORY;
			strcpy(new_name, s);
		}
	} else {
		// Could not recover environment variables
		new_name = new char[1 + strlen(s)];
		if (!new_name) OUT_OF_MEMORY;
		strcpy(new_name, s);
	}
	return new_name;
#endif				// not MSDOS
#else				// No environment variables
	new_name = new char[1 + strlen(s)];
	if (!new_name) OUT_OF_MEMORY;
	strcpy(new_name, s);
	return new_name;
#endif
}

/*
 * skip_space () -- return number of spaces at start of string. (A space may
 * be SPC, TAB, etc.)
 */
int
skip_space(const char *s)
{
	int             i = 0;
	while (isspace(*(s + i)) && *(s + i) != '\0')
		i++;
	return i;
}

// skip_nonspace () -- return number of non-spaces at start of string. (A
// space may be SPC, TAB, etc.)
int
skip_nonspace(const char *s)
{
	int             i = 0;
	while (!isspace(*(s + i)) && *(s + i) != '\0')
		i++;
	return i;
}

// Store result of 'printenv _word[3]' into _word[2] (If no such environment
// variable, store "" into _word[2].)
bool
get_envCmd()
{
	if (_nword == 4) {
		char *            result;
		if (!is_syn(_word[2])) {
			err("No synonym name given");
			demonstrate_command_usage();
			return false;
		}
		result = egetenv((const char*)_word[3]);
		if (result == NULL) {
			if (!put_syn(_word[2], "", true)) {
				gr_Error("Ran out of storage");
				return false;
			}
			warning("No environment variable called `\\", _word[3], "' exits.", "\\");
		} else {
			if (!put_syn(_word[2], result, true)) {
				gr_Error("Ran out of storage");
				return false;
			}
		}
	} else {
		NUMBER_WORDS_ERROR;
		demonstrate_command_usage();
		return false;
	}
	return true;			/* never reached */
}

/* Paste a single character onto the end of a string. */
void
strcat_c(char *s, int c)
{
	int             slen = strlen(s);
	s[slen] = c;
	s[++slen] = '\0';
}

bool
is_punctuation(int c)
{
	return ((c == ' ' || c == '\t' ||
		 c == '!' ||
		 c == '@' ||
		 c == '#' ||
		 c == '$' ||
		 c == '%' ||
		 c == '^' ||
		 c == '&' ||
		 c == '*' ||
		 c == '(' || c == ')' ||
		 c == '-' ||
		 c == '+' || c == '=' ||
		 c == '~' || c == '`' ||
		 c == '{' || c == '[' ||
		 c == '}' || c == ']' ||
		 c == '\\' ||
		 c == ':' || c == ';' ||
		 c == ',' || c == '<' ||
		 c == '"' || c == '<' ||
		 c == '.' || c == '>' ||
		 c == '/' || c == '?'
		) ? true : false);
}

char *
complete_filename(const char *filename)
{
	char *            return_value;
#if defined(VMS)
	return_value = strdup(filename);
	return return_value;
#elif defined(MSDOS)
	return_value = strdup(filename);
	return return_value;
#else
	string rval;
	if (filename[0] == '~') {
		if (strlen(filename) < 2)
			return NULL; // broken filename
		rval.append(egetenv("HOME"));
		rval.append(filename + 1);
		return_value = new char[1 + rval.size()];
		if (!return_value) OUT_OF_MEMORY;
		strcpy(return_value, rval.c_str());
	} else if (filename[0] == '/' || filename[0] == '\\') {
		return_value = new char[1 + strlen(filename)];
		if (!return_value) OUT_OF_MEMORY;
		strcpy(return_value, filename);
	} else {
		// Normal file.  Prepend current working directory
		return_value = new char[2
				       + strlen(_current_directory.c_str())
				       + strlen(filename)];
		if (!return_value) OUT_OF_MEMORY;
		strcpy(return_value, _current_directory.c_str());
#if defined(MSDOS)
		strcat(return_value, "\\");
#else
		strcat(return_value, "/");
#endif
		strcat(return_value, filename);
	}
	remove_trailing_blanks(return_value);
	return return_value;
#endif
}

char *
tilde_expand(const char *filename)
{
	char *return_value;
	if (filename[0] != '~') {
		return_value = new char[1 + strlen(filename)];
		if (!return_value) OUT_OF_MEMORY;
		strcpy(return_value, filename);
	} else {
		char *home = egetenv("HOME");
		return_value = new char[1 + strlen(filename) - 2 + strlen(home)];
		if (!return_value) OUT_OF_MEMORY;
		strcpy(return_value, home);
		strcat(return_value, "/");
		strcat(return_value, filename + 2); // skip the ~/ chars
	}
	return return_value;
}

char *
pwd()
{
#if defined(VMS)		/* vms version braindead */
	return "";
#elif defined(MSDOS)		/* msdos version braindead */
	return "";
#else
#if !defined(HAVE_POPEN)
	err("Cannot do `pwd' because computer lacks popen() subroutine");
	return "";
#else
	char            msg[1024];
	FILE           *pipefile = (FILE *) popen("pwd", "r");
	if (pipefile) {
		char *            result;
		if (1 == fscanf(pipefile, "%s", msg)) {
			pclose(pipefile);
			result = new char[1 + strlen(msg)];
			if (!result) OUT_OF_MEMORY;
			strcpy(result, msg);
			return result;
		} else {
			pclose(pipefile);
			warning("Can't determine name of working directory; using `.' instead.");
			result = new char[2];
			if (!result) OUT_OF_MEMORY;
			strcpy(result, ".");
			return result;
		}
	} else {
		return ".";
	}
#endif
#endif
}

char *
egetenv(const char *s)
{
	if (!strcmp(s, "PWD")) {
		return (char *) pwd();
	} else if (!strcmp(s, "USER")) {
#if defined(HAVE_GETENV)
		return (char *) getenv(s);
#else
		return "unknown";
#endif
	} else if (!strcmp(s, "SYSTEM")) {
#if defined(VMS)
		return "vax";
#elif defined(MSDOS)
		return "msdos";
#else
		return "unix";
#endif
	} else if (!strcmp(s, "HOST")) {
#if defined(HAVE_GETENV)
		return (char *) getenv(s);
#else
		return "unknown";
#endif
	} else if (!strcmp(s, "HOME")) {
#if defined(HAVE_GETENV)
		return (char *) getenv(s);
#else
		return "unknown";
#endif
	} else if (!strcmp(s, "PAGER")) {
#if defined(HAVE_GETENV)
		return (char *) getenv(s);
#else
		return "unknown";
#endif
	} else if (!strcmp(s, "GRIINPUTS")) {
		/*
		 * Of form ".:/usr/local/lib/gri"
		 */
#if defined(HAVE_GETENV)
		return (char *) getenv(s);
#else
		return NULL;		/* will use default */
#endif
	} else {
#if defined(HAVE_GETENV)
		return (char *) getenv(s);
#else
		return "unknown";
#endif
	}
}

/* sprintfCmd() -- print things into a string */
#define N 20
bool
sprintfCmd()
{
	int             i;
	char *            fmt;
	char            msg[1024];
	double          x[N];
	if (_nword < 4) {
		err("`sprintf \\synonym \"format\"' requires variable list to process");
		return false;
	}
	*(_word[2] + strlen(_word[2]) - 1) = '\0';
	fmt = _word[2] + 1;
	for (i = 3; i < _nword; i++) {
		getdnum(_word[i], &x[i - 3]);
	}
	switch (_nword) {
	case 4:
		sprintf(msg, fmt,
			x[0]);
		break;
	case 5:
		sprintf(msg, fmt,
			x[0], x[1]);
		break;
	case 6:
		sprintf(msg, fmt,
			x[0], x[1], x[2]);
		break;
	case 7:
		sprintf(msg, fmt,
			x[0], x[1], x[2], x[3]);
		break;
	case 8:
		sprintf(msg, fmt,
			x[0], x[1], x[2], x[3], x[4]);
		break;
	case 9:
		sprintf(msg, fmt,
			x[0], x[1], x[2], x[3], x[4],
			x[5]);
		break;
	case 10:
		sprintf(msg, fmt,
			x[0], x[1], x[2], x[3], x[4],
			x[5], x[6]);
		break;
	case 11:
		sprintf(msg, fmt,
			x[0], x[1], x[2], x[3], x[4],
			x[5], x[6], x[7]);
		break;
	case 12:
		sprintf(msg, fmt,
			x[0], x[1], x[2], x[3], x[4],
			x[5], x[6], x[7], x[8]);
		break;
	case 13:
		sprintf(msg, fmt,
			x[0], x[1], x[2], x[3], x[4],
			x[5], x[6], x[7], x[8], x[9]);
		break;
	case 14:
		sprintf(msg, fmt,
			x[0], x[1], x[2], x[3], x[4],
			x[5], x[6], x[7], x[8], x[9],
			x[10]);
		break;
	case 15:
		sprintf(msg, fmt,
			x[0], x[1], x[2], x[3], x[4],
			x[5], x[6], x[7], x[8], x[9],
			x[10], x[11]);
		break;
	case 16:
		sprintf(msg, fmt,
			x[0], x[1], x[2], x[3], x[4],
			x[5], x[6], x[7], x[8], x[9],
			x[10], x[11], x[12]);
		break;
	case 17:
		sprintf(msg, fmt,
			x[0], x[1], x[2], x[3], x[4],
			x[5], x[6], x[7], x[8], x[9],
			x[10], x[11], x[12], x[13]);
		break;
	case 18:
		sprintf(msg, fmt,
			x[0], x[1], x[2], x[3], x[4],
			x[5], x[6], x[7], x[8], x[9],
			x[10], x[11], x[12], x[13], x[14]);
		break;
	case 19:
		sprintf(msg, fmt,
			x[0], x[1], x[2], x[3], x[4],
			x[5], x[6], x[7], x[8], x[9],
			x[10], x[11], x[12], x[13], x[14],
			x[15]);
		break;
	case 20:
		sprintf(msg, fmt,
			x[0], x[1], x[2], x[3], x[4],
			x[5], x[6], x[7], x[8], x[9],
			x[10], x[11], x[12], x[13], x[14],
			x[15], x[16]);
		break;
	case 21:
		sprintf(msg, fmt,
			x[0], x[1], x[2], x[3], x[4],
			x[5], x[6], x[7], x[8], x[9],
			x[10], x[11], x[12], x[13], x[14],
			x[15], x[16], x[17]);
		break;
	case 22:
		sprintf(msg, fmt,
			x[0], x[1], x[2], x[3], x[4],
			x[5], x[6], x[7], x[8], x[9],
			x[10], x[11], x[12], x[13], x[14],
			x[15], x[16], x[17], x[18]);
		break;
	case 23:
		sprintf(msg, fmt,
			x[0], x[1], x[2], x[3], x[4],
			x[5], x[6], x[7], x[8], x[9],
			x[10], x[11], x[12], x[13], x[14],
			x[15], x[16], x[17], x[18], x[19]);
		break;
	default:
		err("Can only do `sprintf' for 1-20 variables");
		return false;
	}
	if (!is_syn(_word[1])) {
		demonstrate_command_usage();
		err("Second word of command must begin with `\\'");
		return false;
	}
	if (!put_syn(_word[1], msg, true)) {
		gr_Error("Ran out of storage");
		return false;
	}
	return true;
}

#undef N

/*
 * get (double) values from a list of words (typically the words in the cmd
 * line).  Typically this is used in getting optional parameters from
 * commands, and _dstack[] is used for objects. RETURN number of objects
 * actually found
 */
int
get_cmd_values(char ** w, int nw, const char *key, int nobjects, double *objects)
{
	int             istart = -1, i, found = 0, iobject;
	if (nobjects > _num_dstackMAX)
		return 0;
	for (i = 0; i < nw; i++)
		if (!strcmp(w[i], key)) {
			istart = i + 1;
			break;
		}
	if (istart == -1)
		return 0;		/* 'key' not present */
	if (istart + nobjects > nw)
		return -1;		/* too few */
	for (i = istart, iobject = 0; iobject < nobjects; i++, iobject++) {
		if (true != getdnum(w[i], &objects[iobject]))
			return found;
		found++;
	}
	return found;
}

char
last_character(const char *s)
{
	return s[strlen(s) - 1];
}

// getinum -- return 0 if can't get number
bool
getinum(const char *s, int *i)
{
	if (*s == '\0')
		return 0;
	extern double   _grMissingValue;
	double          d;
	char *            ptr = NULL;
	d = _grMissingValue;
	*i = (int) strtod(s, &ptr);
	if (*ptr == '\0') {
		// It was a normal number with no problems in reading.
		return true;
	}
	// Cannot read as a normal number.  Check to see if it's a variable or
	// NaN/Inf.
	if (is_var(s)) {
		if (get_var(s, &d)) {
			*i = (int) d;
			return true;
		} else {
			if (!skipping_through_if()) {
				err("variable `\\", s, "' is not defined yet", "\\");
				return false;
			} else {
				*i = (int) _grMissingValue;
				return true;
			}
		}
	} else if (!strcmp(s, "-NaN") 
		   || !strcmp(s, "NaN") 
		   || !strcmp(s, "Inf")
		   || !strcmp(s, "Infinity")
		   || !strcmp(s, "-Inf") 
		   || !strcmp(s, "-Infinity") 
		) {
		*i = (int) (_grMissingValue);
		return true;
	} else {
		// Maybe it's a fortran 'D' exponential
		tmp_string.assign(s);
		int loc;
		loc=tmp_string.find('d'); if (-1!=loc) tmp_string.replace(loc,1,"e");
		loc=tmp_string.find('D'); if (-1!=loc) tmp_string.replace(loc,1,"e");
		*i = (int)strtod(tmp_string.c_str(), &ptr);
		if (*ptr == '\0')
			return true;
	}
	// It's a mystery.  report error, fatal or nonfatal depending on
	// whether the user is interested in errors.
	*i = (int) _grMissingValue;
	if (!_ignore_error) {
		err("Cannot interpret `\\",
		    s,
		    "' as a number.",
		    "\\");
	}
	return false;
}

// getdnum -- return 0 if can't get number
bool
getdnum(const char *s, double *d)
{
	if (*s == '\0')
		return 0;
	extern double   _grMissingValue;
	char *            ptr = NULL;
	*d = strtod(s, &ptr);
	if (*ptr == '\0') {
		// Normal number; check for infinity/not-a-number
#if defined(HAVE_ISNAN) && defined(HAVE_ISINF)
#if !defined(__MACHTEN__)
		if (isinf(*d) || isnan(*d))
			*d = (double) _grMissingValue;
#endif
#endif
		return true;
	}
	// Cannot read as a normal number.  Check to see if it's a variable or
	// NaN/Inf.
	if (is_var(s)) {
		if (get_var(s, d)) {
			return true;
		} else {
			if (!skipping_through_if()) {
				err("variable `\\", s, "' is not defined yet", "\\");
				return false;
			} else {
				*d = _grMissingValue;
				return true;
			}
		}
	} else if (!strcmp(s, "-NaN") || !strcmp(s, "NaN") || !strcmp(s, "-Inf") || !strcmp(s, "Inf")) {
		*d = _grMissingValue;
		return true;
	} else {
		// Maybe it's a fortran 'D' exponential
		tmp_string.assign(s);
		int loc;
		loc=tmp_string.find('d'); if (-1!=loc) tmp_string.replace(loc,1,"e");
		loc=tmp_string.find('D'); if (-1!=loc) tmp_string.replace(loc,1,"e");
		*d = (double)strtod(tmp_string.c_str(), &ptr);
		if (*ptr == '\0')
			return true;
	}
	// It's a mystery.  report error, fatal or nonfatal depending on
	// whether the user is interested in errors.
	if (!_ignore_error) {
		err("Cannot interpret `\\",
		    s,
		    "' as a number.",
		    "\\");
	}
	return false;
}

/*
 * fatal_err () -- print error message.  If the first (string) argument ends
 * in '\\', then several strings follow, ended by a string consisting only of
 * "\\".
 */
void
fatal_err(const char *string,...)
{
	char            msg[1024];
	bool            several = false;
	int             len;
	char *            p;
	va_list         ap;
	if (!_error_in_cmd && _beep)
		gr_textput("\007");
	/* Have standard args */
	if (string != NULL) {
		va_start(ap, string);
		strcpy(msg, string);
		len = strlen(msg);
		if (msg[len - 1] == '\\') {
			msg[len - 1] = '\0';
			several = true;
		}
		gr_textput("FATAL ERROR: ");
		do {
			gr_textput(msg);
			if (several) {
				p = va_arg(ap, char *);
				strcpy(msg, p);
			}
		}
		while (several && strcmp(msg, "\\"));
		gr_textput("\n");
		_error_in_cmd = true;
		va_end(ap);
	}
	//
	// Print file:line so emacs mode can locate error
	//
	if (((unsigned) superuser()) & FLAG_AUT1) {
		// Remove quotes around source indicator
		extern char source_indicator[];
		sprintf(msg, " Error detected at %s\n", source_indicator);
	} else {
		if (block_level() > 0) {
			if (block_source_file() != NULL) {
				printf("DEBUG utility.cc:fatal_err(): block_source_line()=%d\n",block_source_line());
				sprintf(msg,
					" Error detected at %s:%d\n",
					block_source_file(),
					block_source_line() + block_offset_line() - 1);
			} else {
				strcat(msg, "");
			}
		} else {
			if (what_file() != NULL)
				sprintf(msg,
					" Error detected at %s:%d\n",
					what_file(),
					what_line());
			else
				strcat(msg, "");
		}
	}
	gr_textput(msg);
	if (_error_action == 1) {
		gri_abort();
	} else {
		gri_exit(1);
	}
}

char           *
what_file()
{
	if (block_level() > 0) {
		if (_cmd_being_done < 1) {
			return NULL;
		} else {
			return _command[_cmd_being_done_code[_cmd_being_done - 1]].filename;
		}
	} else {
		return _cmdFILE.back().get_name();
	}
}

int
what_line()
{
	if (block_level() > 0) {
		if (_cmd_being_done < 1) {
			return -1;		/* note: what_file() will give NULL */
		} else {
			return
				_command[_cmd_being_done_code[_cmd_being_done - 1]].fileline
				+ block_offset_line() - 1;
		}
	} else {
		return _cmdFILE.back().get_line();
	}
}

/*
 * err () -- print error message.  If the first (string) argument ends in
 * '\\', then several strings follow, ended by a string consisting only of
 * "\\".
 */
void
err(const char *string,...)
{
	char            msg[1024];
	bool            several = false;
	int             len;
	char *            p;
	va_list         ap;
	if (!_error_in_cmd && _beep)
		gr_textput("\007");
	if (string != NULL) {
		va_start(ap, string);
		strcpy(msg, string);
		len = strlen(msg);
		if (msg[len - 1] == '\\') {
			msg[len - 1] = '\0';
			several = true;
		}
		gr_textput("ERROR: ");
		do {
			gr_textput(msg);
			if (several) {
				p = va_arg(ap, char *);
				strcpy(msg, p);
			}
		}
		while (several && strcmp(msg, "\\"));
		gr_textput("\n");
	}
	_error_in_cmd = true;
	va_end(ap);
}

// warning () -- print warning message.  All arguments must be char*.
// If the first argument ends in '\\', then several strings follow,
// ended by a string consisting only of "\\".  If only string is '\\',
// then this is a request to notify of number of repeats of last msg.
void
warning(const char *s,...)
{
	static          unsigned int msg_last_copies = 0;
	static string   msg_last;	// must be static
	static string msg;		// static only for efficiency if called a lot
	bool            several = false;
	int             len;
	char           *p = NULL;
	va_list         ap;
	if (!_error_in_cmd && _beep)
		gr_textput("\007");
	// Check for final wrap-up command
	if (!strcmp(s, "\\\\")) {
		if (msg_last_copies > 0) {
			char buffer[100];
			sprintf(buffer,
				"         ... this warning was repeated %d times.\n",
				++msg_last_copies);
			gr_textput(buffer);
		}
		return;
	}
	if (s != NULL) {
		va_start(ap, s);
		len = strlen(s);
		msg = s;
		if (msg[len - 1] == '\\') {
			msg.STRINGERASE(len - 1, 1);
			several = true;
		}
		do {
			if (several) {
				p = va_arg(ap, char *);
				if (strcmp(p, "\\"))
					msg += p;
			}
		} while (several && strcmp(p, "\\"));
		if (msg == msg_last) {
			// Same as last msg.  Collect till a new one.
			msg_last_copies++;
		} else {
			// Not same as last msg.
			if (msg_last_copies > 0) {
				// This msg repeated
				char buffer[100];
				sprintf(buffer,
					"Warning: (The last warning was repeated %d times.)\n",
					msg_last_copies + 1);
				gr_textput(buffer);
				// Now show current msg
				gr_textput("Warning: ");
				gr_textput(msg.c_str());
				gr_textput("\n");
			} else {
				// First time for this msg
				gr_textput("Warning: ");
				gr_textput(msg.c_str());
				gr_textput("\n");
			}
			msg_last_copies = 0;
		}
		msg_last = msg;
	} va_end(ap);
}

/*
 * ExtractQuote() -- extract quote `sout' from string `s'. NOTE: You must
 * ensure sout is as long as s. RETURN VALUE: character position at end of
 * extracted quote, if all was OK.  Otherwise 0.
 */
int
ExtractQuote(char *sout, const char *s)
{
	int             i = 0, last_char = 0;
	while (*(s + i) != '"') {
		if (*(s + i) == '\0') {
			*sout = '\0';
			return 0;
		}
		i++;
	}
	strcpy(sout, s + i + 1);
	last_char = i;
	i = 0;
	while (*(sout + i) != '\0') {
		if (*(sout + i) == '"' && *(sout + i - 1) != '\\') {
			*(sout + i) = '\0';
			return (2 + last_char + i);
		}
		i++;
	}
	return (2 + last_char + i);
}

// Make all trailing blanks, tabs, etc, into null chars
void
remove_trailing_blanks(char *s)
{
	int             i = strlen(s);
	while (--i > -1)
		if (isspace(s[i]))
			s[i] = '\0';
		else
			break;
}

void
beep_terminal()
{
	if (_beep)
		fprintf(stderr, "\007");
}

#define BETWEEN(l,r,m)  ( (l)<(r) ? (m)<=(r)&&(l)<=(m) : (r)<=(m)&&(m)<=(l) )
/* matrix_limits() - find min/max of matrix */
void
matrix_limits(double *min, double *max)
{
	bool            first = true;
	double          f;
	*min = *max = 0.0;
	for (unsigned int c = 0; c < _num_xmatrix_data; c++) {
		for (unsigned int r = 0; r < _num_ymatrix_data; r++) {
			if (_legit_xy(c, r) == true) {
				f = _f_xy(c, r);
				if (first == true) {
					*min = *max = f;
					first = false;
				}
				if (f < *min)
					*min = f;
				if (*max < f)
					*max = f;
			}
		}
	}
	if (first == true) {
		*min = gr_currentmissingvalue();
		*max = gr_currentmissingvalue();
	}
}

/*
 * inside_box - see if data point inside clip box DESCRIPTION Returns 1 if
 * either: (1) clipping turned off or	(2) clipping on and inside axes or
 * (3) clipping on and inside (xl,xr)(yb,yt) box
 */
bool
inside_box(double x, double y)
{
	extern char     _grTempString[];
	extern gr_axis_properties _grTransform_x, _grTransform_y;
	/* If logarithmic, ensure that positive value */
	if (_grTransform_x == gr_axis_LOG && x <= 0.0)
		return false;
	if (_grTransform_y == gr_axis_LOG && y <= 0.0)
		return false;
	if (_clipData == 0) {	/* user did `set clip off' */
		return true;
	} else if (_clipData == 1) {/* user did `set clip on xl xr yb yt' */
		if (!BETWEEN(_clipxleft, _clipxright, x)) {
			if (_debugFlag & DEBUG_CLIPPED) {
				sprintf(_grTempString, "Clipping (%g, %g)\n", x, y);
				gr_textput(_grTempString);
			}
			return false;
		}
		if (!BETWEEN(_clipybottom, _clipytop, y)) {
			if (_debugFlag & 0x01) {
				sprintf(_grTempString, "Clipping (%g, %g)\n", x, y);
				gr_textput(_grTempString);
			}
			return false;
		}
		return true;
	} else {			/* user did `set clip on' */
		if (!BETWEEN(_xleft, _xright, x)) {
			if (_debugFlag & 0x01) {
				sprintf(_grTempString, "Clipping (%g, %g)\n", x, y);
				gr_textput(_grTempString);
			}
			return false;
		}
		if (!BETWEEN(_ybottom, _ytop, y)) {
			if (_debugFlag & 0x01) {
				sprintf(_grTempString, "Clipping (%g, %g)\n", x, y);
				gr_textput(_grTempString);
			}
			return false;
		}
		return true;
	}
}

bool
grid_exists()
{
	Require(_xgrid_exists,
		err("First `set x grid' or `read grid x'"));
	Require(_ygrid_exists,
		err("First `set y grid' or `read grid y'"));
	Require(_grid_exists,
		err("First `read grid data' or `convert columns to grid'"));
	return true;
}

bool
scales_defined()
{
	return ((_xscale_exists && _yscale_exists) ? true : false);
}

// Set environment for line drawing.
bool
set_environment()
{
	// Update some things possibly ruined by other routines. BUG: I don't
	// think most of this is required; Macintosh remants
	gr_fontID       old_font = gr_currentfont();
	double          fontsize = FONTSIZE_PT_DEFAULT;
	double          linewidth = LINEWIDTH_DEFAULT;
	double          symbolsize = SYMBOLSIZE_DEFAULT;
	double          tic_direction = 0.0; // out
	double          tic_size = 0.2;
	double          xmargin = XMARGIN_DEFAULT;
	double          ymargin = YMARGIN_DEFAULT;
	double          xsize = XSIZE_DEFAULT;
	double          ysize = YSIZE_DEFAULT;
	if (!get_var("..fontsize..", &fontsize))
		warning("(set_environment), ..fontsize.. undefined so using 12");
	gr_setfontsize_pt(fontsize);
	gr_setfont(old_font);	// weird, since already set
	if (!get_var("..linewidth..", &linewidth))
		warning("(set_environment), ..linewidth.. undefined so using default");
	_griState.set_linewidth_line(linewidth);

	if (!get_var("..linewidthsymbol..", &linewidth))
		warning("(set_environment), ..linewidthsymbol.. undefined so using default");
	_griState.set_linewidth_symbol(linewidth);

	if (!get_var("..symbolsize..", &symbolsize))
		warning("(set_environment) ..symbolsize.. undefined so using 5.0");
	gr_setsymbolsize_cm(symbolsize);
	if (!get_var("..tic_direction..", &tic_direction))
		warning("(set_environment) ..tic_direction.. undefined so using OUT");
	gr_setticdirection(int(floor(0.5 + tic_direction)) ? true : false);
	if (!get_var("..tic_size..", &tic_size)) {
		warning("(set_environment) ..tic_size.. undefined so using default (0.2cm)");
		gr_setticsize_cm((double) TICSIZE_DEFAULT);
	} else
		gr_setticsize_cm(tic_size);
	if (!get_var("..xmargin..", &xmargin))
		warning("(set_environment) ..xmargin.. undefined so using default");
	if (!get_var("..ymargin..", &ymargin))
		warning("(set_environment) ..ymargin.. undefined so using default");
	if (!get_var("..xsize..", &xsize))
		warning("(set_environment) ..xsize.. undefined so using default");
	if (!get_var("..ysize..", &ysize))
		warning("(set_environment) ..ysize.. undefined so using default");
	gr_setxtransform(_xtype);
	gr_setxscale(xmargin, xmargin + xsize, _xleft, _xright);
	gr_setytransform(_ytype);
	gr_setyscale(ymargin, ymargin + ysize, _ybottom, _ytop);
	gr_record_scale();
	return true;
}

bool
draw_axes_if_needed()
{
	if (_need_x_axis && _need_y_axis)
		draw_axes(_axesStyle, 0.0, (gr_axis_properties) gr_axis_LEFT, true);
	return true;
}

bool
batch()
{
	double          batch;
	get_var("..batch..", &batch);
	if (batch)
		return true;
	else
		return false;
}

int
superuser()
{
	return _griState.superuser();
}

// display file on terminal
void
more_file_to_terminal(const char *filename)
{
	char            sys_cmd[100];
#if defined(VMS)		// vax-vms machine
	sprintf(sys_cmd, "TYPE %s/PAGE", filename);
	system(sys_cmd);
#elif defined(MSDOS)		// ibm-style msdos machine
	GriString fn(filename);
	fn.convert_slash_to_MSDOS();
	sprintf(sys_cmd, "COMMAND.COM MORE < %s", fn.getValue());
	system(sys_cmd);
#else				// a neutral machine
	char *            egetenv(const char *);
	char *            pager = egetenv("PAGER");
	if (pager) {
		sprintf(sys_cmd, "%s %s", pager, filename);
		system(sys_cmd);
	} else {
		sprintf(sys_cmd, "more %s", filename);
		system(sys_cmd);
	}
#endif
}

bool
demonstrate_command_usage()
{
	ShowStr("PROPER USAGE: `");
	if (cmd_being_done() > -1) {
		ShowStr(_command[cmd_being_done()].syntax);
		ShowStr("'\n");
	} else {
		ShowStr(" unknown.\n");
	}
	return true;
}

bool            find_target(const char *pattern, int *pindex, int plen, char *target, int *tlen, int *star, int *plus);

// Regular expression search. This is limited; presently can match:

// (1) characters; (2) alternative characters given in square brackets; (3)
// multiple characters followed by '*' or by '+'; (4) the '\s' metacharacter
// (for whitespace, either SPACE, TAB or NEWLINE).

// Notes: (1) notation is standard for regular expressions, in the 'perl' style;
// (2) '^' is not supported (implied anyway); (3) '+' not supported, but easy
// if I ever need it; (4) () not supported.
bool
re_compare(const char *s, const char *pattern)
{
	int             slen = strlen(s);
	int             plen = strlen(pattern); 
	int             tlen;	// for target
	int             sindex = 0;
	int             pindex = 0;
	int             tindex = 0;
	int             star;	// is subpattern followed by '*'?
	int             plus;	// is subpattern followed by '+'?
	bool            need_new_target = true;
	int             matches = 0;
	// Search through pattern
	GriString target(strlen(pattern));
	while (sindex < slen) {
		bool            this_matches = false;
		if (need_new_target) {
			if (!find_target(pattern, &pindex, plen, target.getValue(), &tlen, &star, &plus)) {
#ifdef DEBUG_RE
				printf("ran out of pattern\n");
#endif
				return false;
			}
			matches = 0;
		}
		// Now see if source string matches
#ifdef DEBUG_RE
		printf("source[%d] = `%c'  ", sindex, s[sindex]);
		show_pattern(target.getValue(), tlen, star, plus);
#endif
		for (tindex = 0; tindex < tlen; tindex++) {
			if (s[sindex] == target[tindex] || target[tindex] == '.') {
				this_matches = true;
				matches++;
				break;
			}
		}
		// See if match
		if (this_matches) {
			if (star || plus) {
				need_new_target = false;
			}
		} else {
			// Not match.  See if it was a repeat pattern ('*' or '+')
			if (star) {
				need_new_target = true;
				sindex--;	// try again on this one
			} else if (plus) {
				if (matches < 1) {
					return false;
				}
				need_new_target = true;
				sindex--;	// try again on this one
			} else {
				return false;	// Failed match
			}
		}
		sindex++;
	}				// while (sindex < slen)
	// Have matched all the way through the source string.  So we have a
	// complete match if and only if the pattern string is now exhausted.
	if (pindex == plen) {
		return true;
	}
	// Some pattern left.  See if all remaining targets are '*' types; then
	// have a match.
	while (find_target(pattern, &pindex, plen, target.getValue(), &tlen, &star, &plus)) {
		if (!star) {
#ifdef DEBUG_RE
			printf(" ... still some non-* target left: `%s'\n", target.getValue());
#endif
			return false;
		}
	}
	// All remaining patterns (if any) were * type, so don't need to match
	return true;
}

bool
find_target(const char *pattern, int *pindex, int plen, char *target, int *tlen, int *star, int *plus)
{
	/*
	 * Determine present target, leaving *pindex pointing at next part of
	 * pattern.
     */
	*star = *plus = 0;
	if (*pindex >= plen)
		return false;
	switch (pattern[*pindex]) {
	case '\\':
		/*
		 * Check against list of known escapes
		 */
		switch (pattern[*pindex + 1]) {
		case '\\':
			target[0] = '\\';
			target[1] = '\0';
			*tlen = 1;
			(*pindex)++;	/* the backslash */
			(*pindex)++;	/* the '\\' */
			break;
		case 's':		/* whitespace as in perl */
			target[0] = ' ';	// blank
			target[1] = '\t';	// tab
			target[2] = '\n';	// newline
			target[3] = '\0';
			*tlen = 3;
			(*pindex)++;	/* the backslash */
			(*pindex)++;	/* the 's' */
			break;
		default:
			printf("unknown escape pattern in search string");
			return false;
		}
		break;
	case '[':
		/*
		 * List of alternatives.
		 */
		(*pindex)++;		/* skip the '[' */
		*tlen = 0;
		while (pattern[*pindex] != ']' && pattern[*pindex] != '\0') {
			target[(*tlen)++] = pattern[(*pindex)++];
		}
		(*pindex)++;		/* skip the ']' */
		target[*tlen] = '\0';
		break;
	default:
		/*
		 * Single character.
		 */
		target[0] = pattern[(*pindex)++];
		target[1] = '\0';
		*tlen = 1;
	}
	if (pattern[*pindex] == '*') {
		*star = 1;
		(*pindex)++;		/* skip the '*' */
	} else if (pattern[*pindex] == '+') {
		*plus = 1;
		(*pindex)++;		/* skip the '+' */
	}
	return true;
}

#ifdef DEBUG_RE
static void
show_pattern(char *target, int tlen, int star, int plus)
{
	int             i;
	printf("target: ");
	for (i = 0; i < tlen; i++) {
		printf(" `%c'", target[i]);
	}
	if (star)
		printf("*");
	else if (plus)
		printf("+");
	printf("\n");
}
#endif

void
swap(double& a, double& b)
{
	double tmp = a;
	a = b;
	b = tmp;
}

// Indicate if this command will take a long time. Usage example:
// GriTimer t;
// for (i = 0; i < n; i++) {
//     if (!warned)
//         double frac = double(i) / double(n - 1);
//         warned = warn_if_slow(&t, frac, "draw something");
//     ... possibly slow code
// }
bool
warn_if_slow(GriTimer *t, double fraction_done, const char *cmd)
{
	const double calibrate = 10.0; // wait this long to calibrate speed
	double dt = t->elapsed_time();
	extern char _grTempString[];
	if (_chatty < 1)
		return true;		// user does not want this
	if (fraction_done == 0.0)
		return false;
	if (dt > calibrate) {
		dt = dt / fraction_done;
		if (dt > 3600.0) {
			sprintf(_grTempString, "\n`%s':\n  This operation will take %.1g h; it is now %s",
				cmd,
				dt / 3600.0, 
				t->now_ascii());
			ShowStr(_grTempString);
		} else if (dt > 60.0) {
			sprintf(_grTempString, "\n`%s':\n  This operation will take %.1g min; it is now %s",
				cmd,
				dt / 60.0,
				t->now_ascii());
			ShowStr(_grTempString);
		} else if (dt > 15.0) {
			sprintf(_grTempString, "\n`%s':\n  This operation will take %.0g sec; it is now %s",
				cmd,
				dt,
				t->now_ascii());
			ShowStr(_grTempString);
		}
		return true;
	}
	return false;
}

// Returns portion of filename after last '/' character, if 
// there is one, otherwise returns full filename.
const char 
*filename_sans_dir(const char *fullfilename)
{
	int i, len = strlen(fullfilename);
	for (i = len - 1; i > -1; i--) {
		if (fullfilename[i] == '/') {
			return fullfilename + i + 1;
		}
	}
	return fullfilename;
}

void
bounding_box_display(const char *msg)
{
	printf("%s\n", msg);
	printf("bbox: (%f %f) (%f %f) cm\n",
	       _bounding_box.llx(),_bounding_box.lly(),
	       _bounding_box.urx(),_bounding_box.ury());
}

// Update bounding box (stored in cm on page)
void
bounding_box_update(const rectangle& box)
{
	// Only process if supplied bbox is nonzero in size
	if (box.llx()    != box.urx()
	    || box.lly() != box.ury()) {
		// If have existing bbox, see if this lies outside ...
		if (_bounding_box.llx()    != _bounding_box.urx()
		    || _bounding_box.lly() != _bounding_box.ury()) {
			if (box.llx() < _bounding_box.llx())
				_bounding_box.set_llx(box.llx());
			if (box.lly() < _bounding_box.lly()) 
				_bounding_box.set_lly(box.lly());
			if (_bounding_box.urx() < box.urx())
				_bounding_box.set_urx(box.urx());
			if (_bounding_box.ury() < box.ury()) 
				_bounding_box.set_ury(box.ury());
		} else {		// ... else just copy it
			_bounding_box.set_llx(box.llx());
			_bounding_box.set_lly(box.lly());
			_bounding_box.set_urx(box.urx());
			_bounding_box.set_ury(box.ury());
		}
	}
}

double
vector_min(double *v, unsigned n)
{
	double return_value = v[0];
	for (unsigned i = 1; i < n; i++)
		if (v[i] < return_value)
			return_value = v[i];
	return return_value;
}

double
vector_max(double *v, unsigned n)
{
	double return_value = v[0];
	for (unsigned i = 1; i < n; i++)
		if (return_value < v[i])
			return_value = v[i];
	return return_value;
}

void
set_ps_color(char what)		// what='p' for path or 't' for text
{
	extern FILE *_grPS;
	extern bool _grWritePS;
	if (!_grWritePS)
		return;
	double r, g, b;
	if (what == 'p')
		_griState.color_line().getRGB(&r, &g, &b);
	else
		_griState.color_text().getRGB(&r, &g, &b);
	if (r == g && g == b) {
		fprintf(_grPS, "%.3g g\n", r);
		fprintf(_grPS, "%.3g G\n", r);
	} else {
		fprintf(_grPS, "%.3g %.3g %.3g rg\n", r, g, b);
		fprintf(_grPS, "%.3g %.3g %.3g RG\n", r, g, b);
	}
}

void
gri_abort()
{
	close_data_files();
	abort();
}

void
gri_exit(int code)
{
	close_data_files();
	exit(code);
}

// Determine a 1-2-5 scaling for interval xl<x<xr, trying
// to get n increments each of which is a multiple of 1, 2, or 5.
// The results are xlr, ylr = the new range, which includes 
// the old range as a subset, and nr = the number of increments.
void
gr_scale125(double xl, double xr, int n, double *xlr, double *xrr, int *nr)
{
	const int max_tries = 5;
	int n_orig = n;
	int tries = 0;
	do {
		double delta = fabs((xr - xl) / n);
		if (delta == 0.0) {
			*xlr = xl - 1.0;
			*xrr = xr + 1.0;
			*nr = 1;
			return;
		}
		double order_of_magnitude = pow(10.0, floor(log10(delta)));
		double delta125 = delta / order_of_magnitude;
		if (delta125 < 2.0)
			delta125 = 1.0;
		else if (delta125 < 5.0)
			delta125 = 2.0;
		else
			delta125 = 5.0;
		delta125 *= order_of_magnitude;
		if (xr > xl) {
			*xlr = delta125 * (floor(xl / delta125));
			*xrr = delta125 * (ceil(xr / delta125));
			*nr = (int) floor(0.5 + (*xrr - *xlr) / delta125);
		} else {
			*xlr = delta125 * (ceil(xl / delta125));
			*xrr = delta125 * (floor(xr / delta125));
			*nr = (int) floor(0.5 - (*xrr - *xlr) / delta125);
		}
		n = int(0.8 * n);
		if (n < 1) 
			n = 1;		// need at least 1 segment
	} while ((*nr > int(1.75 * n_orig)) && ++tries < max_tries);
}

double
rho(double S /* PSU */, double T /* in-situ degC */, double p /* dbar */)
{
	double          rho_w, Kw, Aw, Bw, p1, S12, ro, xkst;
	rho_w = 999.842594 +
		T * (6.793952e-2 +
		     T * (-9.095290e-3 +
			  T * (1.001685e-4 +
			       T * (-1.120083e-6 + T * 6.536332e-9))));
	Kw = 19652.21
		+ T * (148.4206 +
		       T * (-2.327105 +
			    T * (1.360477e-2 - T * 5.155288e-5)));
	Aw = 3.239908 +
		T * (1.43713e-3 +
		     T * (1.16092e-4 -
			  T * 5.77905e-7));
	Bw = 8.50935e-5 +
		T * (-6.12293e-6 +
		     T * 5.2787e-8);
	p1 = 0.1 * p;
	S12 = sqrt(S);
	ro = rho_w +
		S * (8.24493e-1 +
		     T * (-4.0899e-3 +
			  T * (7.6438e-5 +
			       T * (-8.2467e-7 + T * 5.3875e-9))) +
		     S12 * (-5.72466e-3 +
			    T * (1.0227e-4 -
				 T * 1.6546e-6) +
			    S12 * 4.8314e-4));
	xkst = Kw +
		S * (54.6746 +
		     T * (-0.603459 +
			  T * (1.09987e-2 -
			       T * 6.1670e-5)) +
		     S12 * (7.944e-2 +
			    T * (1.6483e-2 +
				 T * (-5.3009e-4)))) +
		p1 * (Aw +
		      S * (2.2838e-3 +
			   T * (-1.0981e-5 +
				T * (-1.6078e-6)) +
			   S12 * (1.91075e-4)) +
		      p1 * (Bw +
			    S * (-9.9348e-7 +
				 T * (2.0816e-8 +
				      T * (9.1697e-10)))));
	return (ro / (1.0 - p1 / xkst));
}

double
pot_temp(double S, double t, double p, double pref)
{
	double dp, sq2;
	double dt1, t1, q1;
	double dt2, t2, q2;
	double dt3, t3, q3;
	double dt4, t4;

	dp = pref - p;
	sq2 = sqrt(2.);
    
	dt1 = dp * lapse_rate(S, t, p);
	q1 = dt1;
	t1 = t + 0.5 * dt1;

	dt2 = dp * lapse_rate(S, t1, p + 0.5 * dp);
	q2 = (2. - sq2) * dt2 + (-2. + 3. / sq2) * q1;
	t2 = t1 + (1. - 1. / sq2) * (dt2 - q1);

	dt3 = dp * lapse_rate(S, t2, p + 0.5*dp);
	q3 = (2 + sq2) * dt3 + (-2. - 3. / sq2) * q2;
	t3 = t2 + (1. + 1. / sq2) * (dt3 - q2);

	dt4 = dp * lapse_rate(S, t3, p + dp);
	t4 = t3 + 1. / 6. * (dt4 - 2. * q3);

	return t4;
}

/* From Unesco technical papers in marine science, number 44 (1983).
 * 
 * SYNTAX        double lapse_rate(double S, double t, double p)
 * 
 * UNITS         S in psu; t in degC; p in dbar;
 * 
 * RETURN VALUE  adiabatic lapse rate in degC/dbar
 *
 * Note: used to compute potential temperature.
 */
double
lapse_rate(double S, double t, double p)
{
	const double a0 = 3.5803e-5;
	const double a1 = 8.5258e-6;
	const double a2 = -6.8360e-8;
	const double a3 = 6.6228e-10;
	const double b0 = 1.8932e-6;
	const double b1 = -4.2393e-8;
	const double c0 = 1.8741e-8;
	const double c1 = -6.7795e-10;
	const double c2 = 8.7330e-12;
	const double c3 = -5.4481e-14;
	const double d0 = -1.1351e-10;
	const double d1 = 2.7759e-12;
	const double e0 = -4.6206e-13;
	const double e1 = 1.8676e-14;
	const double e2 = -2.1687e-16;
    
	double Gamma;

	Gamma = a0 + t * (a1 + t * (a2 + t * a3))
		+ (S - 35.) * (b0 + t * b1)
		+ p * (c0 + t * (c1 + t * (c2 + t * c3))
		       + (S - 35.) * (d0 + t * d1)
		       + p * (e0 + t * (e1 + t * e2)));
    
	return Gamma;
}