File: gplt_x11.c

package info (click to toggle)
gnuplot 3.5beta6.347-3
  • links: PTS
  • area: main
  • in suites: slink
  • size: 5,032 kB
  • ctags: 4,235
  • sloc: ansic: 42,086; makefile: 561; asm: 539; sh: 386; objc: 379; csh: 297; pascal: 194; perl: 138; lisp: 88
file content (1678 lines) | stat: -rw-r--r-- 50,102 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
#ifndef lint
static char *RCSid = "$Id: gplt_x11.c,v 1.71 1998/04/14 00:15:22 drd Exp $";
#endif

/* GNUPLOT - gplt_x11.c */

/*[
 * Copyright 1986 - 1993, 1998   Thomas Williams, Colin Kelley
 *
 * Permission to use, copy, and distribute this software and its
 * documentation for any purpose with or without fee is hereby granted,
 * provided that the above copyright notice appear in all copies and
 * that both that copyright notice and this permission notice appear
 * in supporting documentation.
 *
 * Permission to modify the software is granted, but not the right to
 * distribute the complete modified source code.  Modifications are to
 * be distributed as patches to the released version.  Permission to
 * distribute binaries produced by compiling modified sources is granted,
 * provided you
 *   1. distribute the corresponding source modifications from the
 *    released version in the form of a patch file along with the binaries,
 *   2. add special version identification to distinguish your version
 *    in addition to the base release version number,
 *   3. provide your name and address as the primary contact for the
 *    support of your modified version, and
 *   4. retain our contact information in regard to use of the base
 *    software.
 * Permission to distribute the released version of the source code along
 * with corresponding source modifications in the form of a patch file is
 * granted with same provisions 2 through 4 for binary distributions.
 *
 * This software is provided "as is" without express or implied warranty
 * to the extent permitted by applicable law.
]*/


/*lph changes:
   (a) make EXPORT_SELECTION the default and specify NOEXPORT to undefine
   (b) append X11 terminal number to resource name
   (c) change cursor for active terminal
 */

/*-----------------------------------------------------------------------------
 *   gnuplot_x11 - X11 outboard terminal driver for gnuplot 3.3
 *
 *   Requires installation of companion inboard x11 driver in gnuplot/term.c
 *
 *   Acknowledgements: 
 *      Chris Peterson (MIT)
 *      Dana Chee (Bellcore) 
 *      Arthur Smith (Cornell)
 *      Hendri Hondorp (University of Twente, The Netherlands)
 *      Bill Kucharski (Solbourne)
 *      Charlie Kline (University of Illinois)
 *      Yehavi Bourvine (Hebrew University of Jerusalem, Israel)
 *      Russell Lang (Monash University, Australia)
 *      O'Reilly & Associates: X Window System - Volumes 1 & 2
 *
 *   This code is provided as is and with no warranties of any kind.
 *
 * drd: change to allow multiple windows to be maintained independently
 *       
 * There is a mailing list for gnuplot users. Note, however, that the
 * newsgroup 
 *	comp.graphics.apps.gnuplot 
 * is identical to the mailing list (they
 * both carry the same set of messages). We prefer that you read the
 * messages through that newsgroup, to subscribing to the mailing list.
 * (If you can read that newsgroup, and are already on the mailing list,
 * please send a message to majordomo@dartmouth.edu, asking to be
 * removed from the mailing list.)
 *
 * The address for mailing to list members is
 *	   info-gnuplot@dartmouth.edu
 * and for mailing administrative requests is 
 *	   majordomo@dartmouth.edu
 * The mailing list for bug reports is 
 *	   bug-gnuplot@dartmouth.edu
 * The list of those interested in beta-test versions is
 *	   info-gnuplot-beta@dartmouth.edu
 *---------------------------------------------------------------------------*/

/* drd : export the graph via ICCCM primary selection. well... not quite
 * ICCCM since we dont support full list of targets, but this
 * is a start.  define EXPORT_SELECTION if you want this feature
 */

/*lph: add a "feature" to undefine EXPORT_SELECTION
      The following makes EXPORT_SELECTION the default and 
      defining NOEXPORT over-rides the default
 */

#ifdef EXPORT_SELECTION
#undef EXPORT_SELECTION
#endif /* EXPORT SELECTION */
#ifndef NOEXPORT
#define EXPORT_SELECTION XA_PRIMARY
#endif  /* NOEXPORT */


#define DEFAULT_X11
#if defined(VMS) || defined(CRIPPLED_SELECT)
#undef DEFAULT_X11
#endif

#if defined(VMS) && defined(CRIPPLED_SELECT)
Error. Incompatible options.
#endif


#include <X11/Xos.h>
#include <X11/Xlib.h>
#include <X11/Xresource.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>
#include <X11/keysym.h>
 
#include <signal.h>

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "ansichek.h"
#include "stdfn.h"

#ifdef HAVE_SYS_BSDTYPES_H
#include <sys/bsdtypes.h>
#endif /* HAVE_SYS_BSDTYPES_H */

#if defined(HAVE_SYS_SELECT_H) && !defined(VMS) && !defined(FD_SET)
#include <sys/select.h>
#endif /* HAVE_SYS_SELECT_H && !VMS && !FD_SET */
 
#ifndef FD_SET

#define FD_SET(n, p)    ((p)->fds_bits[0] |= (1 << ((n) % 32)))
#define FD_CLR(n, p)    ((p)->fds_bits[0] &= ~(1 << ((n) % 32)))
#define FD_ISSET(n, p)  ((p)->fds_bits[0] & (1 << ((n) % 32)))
#define FD_ZERO(p)      memset((char *)(p),'\0',sizeof(*(p))) 

#endif /* !FD_SET */

#if defined(HAVE_SYS_SYSTEMINFO_H) && defined(HAVE_SYSINFO)
#include <sys/systeminfo.h>
#define SYSINFO_METHOD "sysinfo"
#define GP_SYSTEMINFO(host) sysinfo (SI_HOSTNAME, (host), MAXHOSTNAMELEN)
#else
#define SYSINFO_METHOD "gethostname"
#define GP_SYSTEMINFO(host) gethostname ((host), MAXHOSTNAMELEN)
#endif /* HAVE_SYS_SYSTEMINFO_H && HAVE_SYSINFO */

#ifdef VMS
#ifdef __DECC
#include <starlet.h>
#endif /* __DECC */
#define EXIT(status) sys$delprc(0,0)	  /* VMS does not drop itself */
#else
#define EXIT(status) exit(status)
#endif

#ifdef OSK
#define EINTR	E_ILLFNC
#endif

/* information about one window/plot */

typedef struct plot_struct {
	Window window;
	Pixmap pixmap;
	unsigned int posn_flags;
	int x,y;
	unsigned int width, height; /* window size */
	unsigned int px, py; /* pointsize */
	int ncommands, max_commands;
	char **commands;
} plot_struct;

void store_command __PROTO((char *line, plot_struct *plot));
void prepare_plot __PROTO((plot_struct *plot, int term_number));
void delete_plot __PROTO((plot_struct *plot));

int record __PROTO((void));
void process_event __PROTO((XEvent *event)); /* from Xserver */

void mainloop __PROTO((void));

void display __PROTO((plot_struct *plot));

void reset_cursor __PROTO((void));

void preset __PROTO((int argc, char *argv[]));
char *pr_GetR __PROTO((XrmDatabase db, char *resource));
void pr_color __PROTO((void));
void pr_dashes __PROTO((void));
void pr_font __PROTO((void));
void pr_geometry __PROTO((void));
void pr_pointsize __PROTO((void));
void pr_width __PROTO((void));
Window pr_window __PROTO((unsigned int flags, int x, int y, unsigned int width, unsigned height));
void pr_raise __PROTO((void));
void pr_persist __PROTO((void));

#ifdef EXPORT_SELECTION
void export_graph __PROTO((plot_struct *plot));
void handle_selection_event __PROTO((XEvent *event));
#endif

#define FallbackFont "fixed"

#define Ncolors 13
unsigned long colors[Ncolors];

#define Nwidths 10
unsigned int widths[Nwidths] = { 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

#define Ndashes 10
char dashes[Ndashes][5];

#define MAX_WINDOWS 16

#define XC_crosshair 34


struct plot_struct plot_array[MAX_WINDOWS];


Display *dpy;
int scr;
Window root;
Visual *vis;
GC gc = (GC)0;
XFontStruct *font;
int do_raise=1, persist=0;
KeyCode q_keycode;
Cursor cursor;

int windows_open = 0;

int gX = 100, gY = 100;
unsigned int gW = 640, gH = 450;
unsigned int gFlags = PSize;

unsigned int BorderWidth = 2;
unsigned int D; /* depth */

Bool Mono = 0, Gray = 0, Rv = 0, Clear = 0;
char Name[64] = "gnuplot";
char Class[64] = "Gnuplot";

int cx=0, cy=0, vchar;
double xscale, yscale, pointsize;
#define X(x) (int) ((x) * xscale)
#define Y(y) (int) ((4095-(y)) * yscale)
enum JUSTIFY { LEFT, CENTRE, RIGHT } jmode;

#define Nbuf 1024
char buf[Nbuf], **commands = (char **)0;

FILE *X11_ipc;
char X11_ipcpath[32];

/* when using an ICCCM-compliant window manager, we can ask it
 * to send us an event when user chooses 'close window'. We do this
 * by setting WM_DELETE_WINDOW atom in property WM_PROTOCOLS
 */
 
Atom WM_PROTOCOLS, WM_DELETE_WINDOW;

XPoint Diamond[5], Triangle[4];
XSegment Plus[2], Cross[2], Star[4];

/*-----------------------------------------------------------------------------
 *   main program 
 *---------------------------------------------------------------------------*/

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


#ifdef OSK	/* malloc large blocks, otherwise problems with fragmented mem */
   _mallocmin (102400);
#endif

	FPRINTF((stderr,"gnuplot_X11 starting up\n"));

   preset(argc, argv);

/* set up the alternative cursor */
   cursor = XCreateFontCursor(dpy,XC_crosshair);

   mainloop();

	if (persist)
	{
		FPRINTF((stderr,"waiting for %d windows\n, windows_open"));
		/* read x events until all windows have been quit */
		while (windows_open > 0)
		{
			XEvent event;
			XNextEvent(dpy, &event);
			process_event(&event);
		}
	}
		
  	XCloseDisplay(dpy);

	FPRINTF((stderr,"exiting\n"));

	EXIT(0);
}

/*-----------------------------------------------------------------------------
 *   mainloop processing - process X events and input from gnuplot
 *
 *   Three different versions of main loop processing are provided to support
 *   three different platforms.
 * 
 *   DEFAULT_X11:     use select() for both X events and input on stdin 
 *                    from gnuplot inboard driver
 *
 *   CRIPPLED_SELECT: use select() to service X events and check during 
 *                    select timeout for temporary plot file created
 *                    by inboard driver
 *
 *   VMS:             use XNextEvent to service X events and AST to
 *                    service input from gnuplot inboard driver on stdin 
 *---------------------------------------------------------------------------*/


#ifdef DEFAULT_X11
/*-----------------------------------------------------------------------------
 *    DEFAULT_X11 mainloop
 *---------------------------------------------------------------------------*/

void mainloop() {
   int nf, nfds, cn = ConnectionNumber(dpy), in;
   struct timeval timeout, *timer = (struct timeval *)0;
   fd_set rset, tset;
   unsigned long all = 0xffffffff;

   X11_ipc = stdin;
   in = fileno (X11_ipc);

   FD_ZERO(&rset);
   FD_SET(cn, &rset);

   FD_SET(in, &rset);
   nfds = (cn > in) ? cn + 1 : in + 1;

#ifdef ISC22
/* Added by Robert Eckardt, RobertE@beta.TP2.Ruhr-Uni-Bochum.de */
   timeout.tv_sec  = 0;		/* select() in ISC2.2 needs timeout */
   timeout.tv_usec = 300000;	/* otherwise input from gnuplot is */
   timer = &timeout;		/* suspended til next X event. */
#endif /* ISC22 	 (0.3s are short enough not to be noticed */

	while(1) {

		/* XNextEvent does an XFlush() before waiting. But here.
		 * we must ensure that the queue is flushed, since we
		 * dont call XNextEvent until an event arrives. (I have
		 * twice wasted quite some time over this issue, so now
		 * I am making sure of it !
		 */

		XFlush(dpy);
		
		tset = rset;
#if defined(__hpux) && defined(ANSI_C)
		nf = select(nfds, (int *)&tset, (int *)0, (int *)0, timer);
#else
		nf = select(nfds, &tset, (fd_set *)0, (fd_set *)0, timer);
#endif
		if (nf < 0) {
			if (errno == EINTR) continue;
			fprintf(stderr, "gnuplot: select failed. errno:%d\n", errno);
			EXIT(1);
		}
		if (nf > 0) XNoOp(dpy);
		if (FD_ISSET(cn, &tset)) {
			/* used to use CheckMaskEvent() but that cannot receive
			 * maskable events such as ClientMessage. So now we do
			 * one event, then return to the select.
			 * And that almost works, except that under some Xservers
			 * running without a window manager (e.g. Hummingbird Exceed under Win95)
			 * a bogus ConfigureNotify is sent followed by a valid ConfigureNotify
			 * when the window is maximized.  The two events are queued, apparently
			 * in a single I/O because select() above doesn't see the second, valid
			 * event.  This little loop fixes the problem by flushing the
			 * event queue completely.
			 */
			XEvent xe;
			do
			{
			XNextEvent(dpy, &xe);
			process_event(&xe);
			} while(XPending(dpy));
		}
      if (FD_ISSET(in, &tset))
			if (!record())
				/* end of input */
				return;
	}
}

#endif


#ifdef CRIPPLED_SELECT
/*-----------------------------------------------------------------------------
 *    CRIPPLED_SELECT mainloop
 *---------------------------------------------------------------------------*/

void mainloop() {
   int nf, nfds, cn = ConnectionNumber(dpy);
   struct timeval timeout, *timer;
   fd_set rset, tset;
   unsigned long all = 0xffffffff;
   XEvent xe;

   FD_ZERO(&rset);
   FD_SET(cn, &rset);

   timeout.tv_sec = 1;
   timeout.tv_usec = 0;
   timer = &timeout;
   sprintf(X11_ipcpath, "/tmp/Gnuplot_%d", getppid());
   nfds = cn + 1;

   while(1) {
   	XFlush(dpy); /* see above */
      tset = rset;
      nf = select(nfds, &tset, (fd_set *)0, (fd_set *)0, timer);
      if (nf < 0) {
	 if (errno == EINTR) continue;
	 fprintf(stderr, "gnuplot: select failed. errno:%d\n", errno);
	 EXIT(1);
	 }
      nf > 0 && XNoOp(dpy);
      if (FD_ISSET(cn, &tset)) {
	 while (XCheckMaskEvent(dpy, all, &xe)) {
	    process_event(&xe);
	    }
	 }
      if ((X11_ipc = fopen(X11_ipcpath, "r"))) {
	 unlink(X11_ipcpath);
	 record();
	 fclose(X11_ipc);
	 }
      }
   }
#endif /* CRIPPLED_SELECT */


#ifdef VMS
/*-----------------------------------------------------------------------------
 *    VMS mainloop - Yehavi Bourvine - YEHAVI@VMS.HUJI.AC.IL
 *---------------------------------------------------------------------------*/

/*  In VMS there is no decent Select(). hence, we have to loop inside
 *  XGetNextEvent for getting the next X window event. In order to get input
 *  from the master we assign a channel to SYS$INPUT and use AST's in order to
 *  receive data. In order to exit the mainloop, we need to somehow make XNextEvent
 *  return from within the ast. We do this with a XSendEvent() to ourselves !
 *  This needs a window to send the message to, so we create an unmapped window
 *  for this purpose. Event type XClientMessage is perfect for this, but it
 *  appears that such messages come from elsewhere (motif window manager, perhaps ?)
 *  So we need to check fairly carefully that it is the ast event that has been received.
 */

#include <iodef.h>
char    STDIIN[] = "SYS$INPUT:";
short   STDIINchannel, STDIINiosb[4];
struct  { short size, type; char  *address; } STDIINdesc;
char    STDIINbuffer[64];
int     status;

ast()
{
   int status = sys$qio(0, STDIINchannel, IO$_READVBLK, STDIINiosb, record,
		        0, STDIINbuffer, sizeof(STDIINbuffer) -1,0, 0, 0, 0);
   if((status & 0x1) == 0) EXIT(status);
}

Window message_window;

void mainloop()
{
	/* dummy unmapped window for receiving internally-generated terminate
	 * messages
	 */
	message_window = XCreateSimpleWindow(dpy,root, 0,0,1,1, 1,0,0);

	STDIINdesc.size = strlen(STDIIN); 
	STDIINdesc.type = 0;
	STDIINdesc.address = STDIIN;
	status = sys$assign(&STDIINdesc, &STDIINchannel, 0, 0, 0);
	if((status & 0x1) == 0)  EXIT(status); 
	ast();
	
	for (;;)
	{
		XEvent xe;
		XNextEvent(dpy, &xe);
		if (xe.type == ClientMessage && xe.xclient.window == message_window)
		{
			if (xe.xclient.message_type == None &&
			    xe.xclient.format == 8 &&
			    strcmp(xe.xclient.data.b, "die gnuplot die") == 0)
			{
				FPRINTF((stderr,"quit message from ast\n"));
				return;
			}
			else
			{
				FPRINTF((stderr,"Bogus XClientMessage event from window manager ?\n"));
			}
		}
		process_event(&xe);
	}
}

#endif /* VMS */

/* delete a window / plot */

void delete_plot(plot)
plot_struct *plot;
{
	int i;

	FPRINTF((stderr,"Delete plot %d\n", plot - plot_array));
	
	for (i=0; i<plot->ncommands; ++i)
		free(plot->commands[i]);
	plot->ncommands = 0;

	if (plot->window)
	{
		FPRINTF((stderr,"Destroy window 0x%x\n", plot->window));
		XDestroyWindow(dpy,plot->window);
		plot->window = None;
		--windows_open;
	}

	if (plot->pixmap)
	{
		XFreePixmap(dpy, plot->pixmap);
		plot->pixmap = None;
	}

	/* but preserve geometry */
}


/* prepare the plot structure */

void prepare_plot(plot, term_number)
plot_struct *plot;
int term_number;
{
	int i;
        char *term_name, tmp_nam[4];
	for (i=0; i<plot->ncommands; ++i)
		free(plot->commands[i]);
	plot->ncommands = 0;

	if (!plot->posn_flags)
	{
		/* first time this window has been used - use default or -geometry
		 * settings
		 */
		plot->posn_flags = gFlags;
		plot->x = gX;
		plot->y = gY;
		plot->width = gW;
		plot->height = gH;
	}

	if (!plot->window)
	{
		plot->window = pr_window(plot->posn_flags, plot->x, plot->y, plot->width, plot->height);
		++windows_open;

      		/* append the X11 terminal number (if greater than zero) */

      		if (term_number)
      		{
      			char new_name[60];
      			XFetchName(dpy,plot->window,&term_name);
      			FPRINTF((stderr,"Window title is %s\n",term_name));
      			
      			sprintf(new_name,"%.55s%3d",term_name, term_number);
      			FPRINTF((stderr,"term_number  is %d\n",term_number));
      			
      			XStoreName(dpy,plot->window,new_name);

      			sprintf(new_name, "gplt%3d", term_number);
      			XSetIconName(dpy,plot->window,new_name);
      		}
 	}

/* We don't know that it is the same window as before, so we reset the
 * cursors for all windows and then define the cursor for the active
 * window 
 */
      	reset_cursor();
      	XDefineCursor(dpy,plot->window,cursor);

}	

/* store a command in a plot structure */

void store_command(buf, plot)
char *buf;
plot_struct *plot;
{
	char *p;

	FPRINTF((stderr,"Store in %d : %s", plot - plot_array, buf));
	
	if (plot->ncommands >= plot->max_commands)
	{
		plot->max_commands = plot->max_commands*2 + 1;
		plot->commands = (plot->commands)
		    ? (char **)realloc(plot->commands, plot->max_commands * sizeof(char *))
		    : (char **)malloc(sizeof(char *));
	}
	p = (char *)malloc((unsigned)strlen(buf)+1);
	if (!plot->commands || !p) {
		fprintf(stderr, "gnuplot: can't get memory. X11 aborted.\n");
		EXIT(1);
	}
	plot->commands[plot->ncommands++] = strcpy(p, buf);
}

#ifndef VMS
/*-----------------------------------------------------------------------------
 *   record - record new plot from gnuplot inboard X11 driver (Unix)
 *---------------------------------------------------------------------------*/

int record()
{
	static plot_struct *plot = plot_array;
	while (fgets(buf, Nbuf, X11_ipc)) {
		switch (*buf)
		{
			case 'G':                           /* enter graphics mode */
			{
				int plot_number = atoi(buf+1); /* 0 if none specified */
				if (plot_number < 0 || plot_number >= MAX_WINDOWS)
					plot_number = 0;
				FPRINTF((stderr,"plot for window number %d\n", plot_number));
				plot = plot_array + plot_number;
				prepare_plot(plot, plot_number);
				continue;
			}
			case 'E':      /* leave graphics mode / suspend */
				display(plot);
				return 1;
			case 'R':      /* leave x11 mode */
      				reset_cursor();
				return 0;
			default:
				store_command(buf, plot);
				continue;
		}
	}

	/* get here if fgets fails */
	
#ifdef OSK
   if (feof(X11_ipc))      /* On OS-9 sometimes while resizing the window,  */
      _cleareof (X11_ipc); /* and plotting data, the eof or error flag of   */
   if (ferror(X11_ipc))    /* X11_ipc stream gets set, while there is       */
   	  clearerr (X11_ipc);  /* nothing wrong! Probably a bug in my select()? */
#else
   if (feof(X11_ipc) || ferror(X11_ipc)) return 0;
#endif

	return 1;
}

#else    /* VMS */
/*-----------------------------------------------------------------------------
 *   record - record new plot from gnuplot inboard X11 driver (VMS)
 *---------------------------------------------------------------------------*/

record()
{
	static plot_struct *plot = plot_array;

	int	status;
	
	if((STDIINiosb[0] & 0x1) == 0) EXIT(STDIINiosb[0]);
	STDIINbuffer[STDIINiosb[1]] = '\0';
	strcpy(buf, STDIINbuffer);
	
	switch(*buf)
	{
		case 'G':   /* enter graphics mode */
		{
			int plot_number = atoi(buf+1); /* 0 if none specified */
			if (plot_number < 0 || plot_number >= MAX_WINDOWS)
				plot_number = 0;
			FPRINTF((stderr,"plot for window number %d\n", plot_number));
			plot = plot_array + plot_number;
			prepare_plot(plot, plot_number);
			break;
		}
		case 'E':  /* leave graphics mode */
			display(plot);
			break;
		case 'R': /* exit x11 mode */
			FPRINTF((stderr,"received R - sending ClientMessage\n"));
      			reset_cursor();
			sys$cancel(STDIINchannel);
			/* this is ridiculous - cook up an event to ourselves,
			 * in order to get the mainloop() out of the XNextEvent() call
			 * it seems that window manager can also send clientmessages,
			 * so put a checksum into the message
			 */
			{
				XClientMessageEvent event;
				event.type = ClientMessage;
				event.send_event = True;
				event.display = dpy;
				event.window = message_window;
				event.message_type = None;
				event.format = 8;
				strcpy(event.data.b, "die gnuplot die");
				XSendEvent(dpy, message_window, False, 0, (XEvent *)&event);
				XFlush(dpy);
			}
			return; /* no ast */
		default:
			store_command(buf, plot);
			break;
	}
   ast();
}
#endif /* VMS */


/*-----------------------------------------------------------------------------
 *   display - display a stored plot
 *---------------------------------------------------------------------------*/

void display(plot)
plot_struct *plot;
{
   int n, x, y, sw, sl, lt=0, width, type, point, px, py;
   int user_width = 1; /* as specified by plot...linewidth */
   char *buf, *str;

   FPRINTF((stderr,"Display %d ; %d commands\n", plot - plot_array, plot->ncommands));
   
	if (plot->ncommands == 0) return;

   /* set scaling factor between internal driver & window geometry */
   xscale = plot->width / 4096.0;  yscale = plot->height / 4096.0;  

   /* initial point sizes, until overridden with P7xxxxyyyy */
   px = (int) (xscale * pointsize);
   py = (int) (yscale * pointsize);

   /* create new pixmap & GC */
   if (gc)
		XFreeGC(dpy, gc);

	if (!plot->pixmap)
	{
		FPRINTF((stderr,"Create pixmap %d : %dx%dx%d\n", plot - plot_array, plot->width, plot->height, D));
		plot->pixmap = XCreatePixmap(dpy, root, plot->width, plot->height, D);
	}
	
   gc = XCreateGC(dpy, plot->pixmap, 0, (XGCValues *)0);

   XSetFont(dpy, gc, font->fid);

   /* set pixmap background */
   XSetForeground(dpy, gc, colors[0]);
   XFillRectangle(dpy, plot->pixmap, gc, 0, 0, plot->width, plot->height);
   XSetBackground(dpy, gc, colors[0]);

   if (!plot->window)
   {
   	plot->window = pr_window(plot->posn_flags, plot->x, plot->y, plot->width, plot->height);
   	++windows_open;
   }
   	
   /* top the window but don't put keyboard or mouse focus into it. */
   if (do_raise) XMapRaised(dpy, plot->window);

   /* momentarily clear the window first if requested */
   if (Clear) {
      XClearWindow(dpy, plot->window);
      XFlush(dpy);
      }

   /* loop over accumulated commands from inboard driver */
   for (n=0; n<plot->ncommands; n++) {
      buf = plot->commands[n];

      /*   X11_vector(x,y) - draw vector  */
      if (*buf == 'V') { 
	 sscanf(buf, "V%4d%4d", &x, &y);  
	 XDrawLine(dpy, plot->pixmap, gc, X(cx), Y(cy), X(x), Y(y));
	 cx = x; cy = y;
	 }

      /*   X11_move(x,y) - move  */
      else if (*buf == 'M') 
	 sscanf(buf, "M%4d%4d", &cx, &cy);  

      /*   X11_put_text(x,y,str) - draw text   */
      else if (*buf == 'T') { 
	 sscanf(buf, "T%4d%4d", &x, &y);  
	 str = buf + 9; sl = strlen(str) - 1;
	 sw = XTextWidth(font, str, sl);
	 switch(jmode) {
	    case LEFT:   sw = 0;     break;
	    case CENTRE: sw = -sw/2; break;
	    case RIGHT:  sw = -sw;   break;
	    }
	 XSetForeground(dpy, gc, colors[2]);
	 XDrawString(dpy, plot->pixmap, gc, X(x)+sw, Y(y)+vchar/3, str, sl);
	 XSetForeground(dpy, gc, colors[lt+3]);
	 }
	else if (*buf == 'F') { /* fill box */
		int style,x,y,w,h;
		if (sscanf(buf+1, "%4d%4d%4d%4d%4d", &style, &x,&y,&w,&h) == 5) {
			/* gnuplot has origin at bottom left, but X uses top left
			 * There may be an off-by-one (or more) error here.
			 * style ignored here for the moment
			 */
			y += h; /* top left corner of rectangle to be filled */
			w *= xscale;
			h *= yscale;
			XSetForeground(dpy, gc, colors[0]);
			XFillRectangle(dpy,plot->pixmap,gc, X(x), Y(y), w, h);
			XSetForeground(dpy, gc, colors[lt+3]);
		}
	}
      /*   X11_justify_text(mode) - set text justification mode  */
      else if (*buf == 'J') 
	 sscanf(buf, "J%4d", &jmode);

      /*  X11_linewidth(width) - set line width */
      else if (*buf == 'W')
	 sscanf(buf+1, "%4d", &user_width);	

      /*   X11_linetype(type) - set line type  */
      else if (*buf == 'L') { 
	 sscanf(buf, "L%4d", &lt);
	 lt = (lt%8)+2;
     /* default width is 0 {which X treats as 1} */
	 width = widths[lt] ? user_width * widths[lt] : user_width;
	 if (dashes[lt][0]) {
	    type = LineOnOffDash;
	    XSetDashes(dpy, gc, 0, dashes[lt], strlen(dashes[lt]));
	    }
	 else {
	    type = LineSolid;
	    }
	 XSetForeground(dpy, gc, colors[lt+3]);
	 XSetLineAttributes( dpy,gc, width, type, CapButt, JoinBevel);
  	 }

      /*   X11_point(number) - draw a point */
      else if (*buf == 'P') {
      	/* linux sscanf does not like %1d%4d%4d" with Oxxxxyyyy */
 	 /* sscanf(buf, "P%1d%4d%4d", &point, &x, &y); */
	 point = buf[1] - '0';
	 sscanf(buf+2, "%4d%4d", &x, &y);  
 	 if (point==7) {
 	    /* set point size */
 	    px = (int) (x * xscale * pointsize);
 	    py = (int) (y * yscale * pointsize);
 	    }
 	 else {
	    if (type != LineSolid || width != 0) {  /* select solid line */
	       XSetLineAttributes(dpy, gc, 0, LineSolid, CapButt, JoinBevel);
	       }
	    switch(point) {
	       case 0: /* dot */
		   XDrawPoint(dpy,plot->pixmap,gc, X(x), Y(y));
		   break;
	       case 1: /* do diamond */ 
		 Diamond[0].x = (short) X(x) - px;
		 Diamond[0].y = (short) Y(y); 
		 Diamond[1].x = (short) px;
		 Diamond[1].y = (short) -py;
		 Diamond[2].x = (short) px;
		 Diamond[2].y = (short) py;
		 Diamond[3].x = (short) -px;
		 Diamond[3].y = (short) py;
		 Diamond[4].x = (short) -px;
		 Diamond[4].y = (short) -py;
		 
		 /*
		  * Should really do a check with XMaxRequestSize()
		  */
		 XDrawLines(dpy,plot->pixmap,gc, Diamond, 5, CoordModePrevious);
		 XDrawPoint(dpy,plot->pixmap,gc, X(x), Y(y));
		 break;
	       case 2: /* do plus */ 
		 Plus[0].x1 = (short) X(x) - px;
		 Plus[0].y1 = (short) Y(y);
		 Plus[0].x2 = (short) X(x) + px;
		 Plus[0].y2 = (short) Y(y);
		 Plus[1].x1 = (short) X(x);
		 Plus[1].y1 = (short) Y(y) - py;
		 Plus[1].x2 = (short) X(x);
		 Plus[1].y2 = (short) Y(y) + py;

		 XDrawSegments(dpy,plot->pixmap,gc, Plus, 2);
		 break;
	       case 3: /* do box */ 
		 XDrawRectangle(dpy,plot->pixmap,gc, X(x)-px, Y(y)-py, (px+px), (py+py));
		 XDrawPoint(dpy,plot->pixmap,gc, X(x), Y(y));
		 break;
	       case 4: /* do X */ 
		 Cross[0].x1 = (short) X(x) - px;
		 Cross[0].y1 = (short) Y(y) - py;
		 Cross[0].x2 = (short) X(x) + px;
		 Cross[0].y2 = (short) Y(y) + py;
		 Cross[1].x1 = (short) X(x) - px;
		 Cross[1].y1 = (short) Y(y) + py;
		 Cross[1].x2 = (short) X(x) + px;
		 Cross[1].y2 = (short) Y(y) - py;

		 XDrawSegments(dpy,plot->pixmap,gc, Cross, 2);
		 break;
	       case 5: /* do triangle */ 
		 {
		   short temp_x, temp_y;

		   temp_x = (short) (1.33 * (double) px + 0.5);
		   temp_y = (short) (1.33 * (double) py + 0.5);

		   Triangle[0].x = (short) X(x);
		   Triangle[0].y = (short) Y(y) - temp_y;
		   Triangle[1].x = (short) temp_x; 
		   Triangle[1].y = (short) 2 * py;
		   Triangle[2].x = (short) -(2 * temp_x);
		   Triangle[2].y = (short) 0;
		   Triangle[3].x = (short) temp_x;
		   Triangle[3].y = (short) -(2 * py);
		   
		   XDrawLines(dpy,plot->pixmap,gc, Triangle, 4, CoordModePrevious);
		   XDrawPoint(dpy,plot->pixmap,gc, X(x), Y(y));
		 }
		 break;
	       case 6: /* do star */ 
		 Star[0].x1 = (short) X(x) - px;
		 Star[0].y1 = (short) Y(y);
		 Star[0].x2 = (short) X(x) + px;
		 Star[0].y2 = (short) Y(y);
		 Star[1].x1 = (short) X(x);
		 Star[1].y1 = (short) Y(y) - py;
		 Star[1].x2 = (short) X(x);
		 Star[1].y2 = (short) Y(y) + py;
		 Star[2].x1 = (short) X(x) - px;
		 Star[2].y1 = (short) Y(y) - py;
		 Star[2].x2 = (short) X(x) + px;
		 Star[2].y2 = (short) Y(y) + py;
		 Star[3].x1 = (short) X(x) - px;
		 Star[3].y1 = (short) Y(y) + py;
		 Star[3].x2 = (short) X(x) + px;
		 Star[3].y2 = (short) Y(y) - py;

		 XDrawSegments(dpy,plot->pixmap,gc, Star, 4);
		 break;
	       }
	    if (type != LineSolid || width != 0) {  /* select solid line */
	       XSetLineAttributes(dpy, gc, width, type, CapButt, JoinBevel);
	       }
	    }
	 }
      }

   /* set new pixmap as window background */
   XSetWindowBackgroundPixmap(dpy, plot->window, plot->pixmap);

   /* trigger exposure of background pixmap */
   XClearWindow(dpy,plot->window);
   
#ifdef EXPORT_SELECTION
	export_graph(plot);
#endif

   XFlush(dpy);
   }

/*---------------------------------------------------------------------------
 *  reset all cursors (since we dont have a record of the previous terminal #)
 *---------------------------------------------------------------------------*/

void reset_cursor()
{
      	int plot_number;
      	plot_struct *plot = plot_array;

      	for (plot_number=0, plot = plot_array;
      	plot_number < MAX_WINDOWS;
      		++plot_number, ++plot)
      	{
      		if (plot->window)
      		{
      			FPRINTF((stderr,"Window for plot %d exists\n", plot_number));
      			XUndefineCursor(dpy,plot->window);;
      		}
      	}

      	FPRINTF((stderr,"Cursors reset\n"));
      	return;
}

/*-----------------------------------------------------------------------------
 *   resize - rescale last plot if window resized
 *---------------------------------------------------------------------------*/

plot_struct *find_plot(window)
Window window;
{
	int plot_number;
	plot_struct *plot = plot_array;

	for (plot_number=0, plot = plot_array;
	     plot_number < MAX_WINDOWS;
	     ++plot_number, ++plot)
	{
		if (plot->window == window)
		{
			FPRINTF((stderr,"Event for plot %d\n", plot_number));
			return plot;
		}
	}
	
	FPRINTF((stderr,"Bogus window 0x%x in event !\n", window));
	return NULL;
}

void process_event(event)
XEvent *event;
{
	FPRINTF((stderr,"Event 0x%x\n", event->type));

	switch (event->type)
	{
		case ConfigureNotify:
		{
			plot_struct *plot = find_plot(event->xconfigure.window);
			if (plot)
			{
				int w = event->xconfigure.width, h = event->xconfigure.height;

				/* store settings in case window is closed then recreated */
   			plot->x = event->xconfigure.x;
   			plot->y = event->xconfigure.y;
   			plot->posn_flags = (plot->posn_flags & ~PPosition) | USPosition;
   			
				if (w>1 && h>1 && (w != plot->width || h != plot->height)) {
					plot->width = w;
					plot->height = h;
					plot->posn_flags = (plot->posn_flags & ~PSize) | USSize;
					if (plot->pixmap)
					{
						/* it is the wrong size now */
						FPRINTF((stderr,"Free pixmap %d\n", 0));
						XFreePixmap(dpy, plot->pixmap);
						plot->pixmap = None;
					}
					display(plot);
				}
			}
			break;
		}
		case KeyPress:
			if (event->xkey.keycode == q_keycode)
			{
				plot_struct *plot = find_plot(event->xkey.window);
				if (plot) delete_plot(plot);
			}
			break;
		case ClientMessage:
			if (event->xclient.message_type == WM_PROTOCOLS &&
			    event->xclient.format == 32 &&
			    event->xclient.data.l[0] == WM_DELETE_WINDOW)
			{
				plot_struct *plot = find_plot(event->xclient.window);
				if (plot) delete_plot(plot);
			}
			break;
#ifdef EXPORT_SELECTION
		case SelectionNotify:
		case SelectionRequest:
			handle_selection_event(event);
			break;
#endif
	}
}

/*-----------------------------------------------------------------------------
 *   preset - determine options, open display, create window
 *---------------------------------------------------------------------------*/

#define On(v) ( !strcmp(v,"on") || !strcmp(v,"true") || \
                !strcmp(v,"On") || !strcmp(v,"True") || \
                !strcmp(v,"ON") || !strcmp(v,"TRUE") )

#define AppDefDir "/usr/lib/X11/app-defaults"
#ifndef MAXHOSTNAMELEN
#define MAXHOSTNAMELEN 64
#endif

static XrmDatabase dbCmd, dbApp, dbDef, dbEnv, db = (XrmDatabase)0;

char *pr_GetR(), *getenv(), *type[20];
XrmValue value;

static XrmOptionDescRec options[] = {
   {"-mono",             ".mono",             XrmoptionNoArg,   (caddr_t) "on" },
   {"-gray",             ".gray",             XrmoptionNoArg,   (caddr_t) "on" },
   {"-clear",            ".clear",            XrmoptionNoArg,   (caddr_t) "on" },
   {"-tvtwm",            ".tvtwm",            XrmoptionNoArg,   (caddr_t) "on" },
   {"-pointsize",        ".pointsize",        XrmoptionSepArg,  (caddr_t) NULL },
   {"-display",          ".display",          XrmoptionSepArg,  (caddr_t) NULL },
   {"-name",             ".name",             XrmoptionSepArg,  (caddr_t) NULL },
   {"-geometry",         "*geometry",         XrmoptionSepArg,  (caddr_t) NULL },
   {"-background",       "*background",       XrmoptionSepArg,  (caddr_t) NULL },
   {"-bg",               "*background",       XrmoptionSepArg,  (caddr_t) NULL },
   {"-foreground",       "*foreground",       XrmoptionSepArg,  (caddr_t) NULL },
   {"-fg",               "*foreground",       XrmoptionSepArg,  (caddr_t) NULL },
   {"-bordercolor",      "*bordercolor",      XrmoptionSepArg,  (caddr_t) NULL },
   {"-bd",               "*bordercolor",      XrmoptionSepArg,  (caddr_t) NULL },
   {"-borderwidth",      ".borderwidth",      XrmoptionSepArg,  (caddr_t) NULL },
   {"-bw",               ".borderwidth",      XrmoptionSepArg,  (caddr_t) NULL },
   {"-font",             "*font",             XrmoptionSepArg,  (caddr_t) NULL },
   {"-fn",               "*font",             XrmoptionSepArg,  (caddr_t) NULL },
   {"-reverse",          "*reverseVideo",     XrmoptionNoArg,   (caddr_t) "on" },
   {"-rv",               "*reverseVideo",     XrmoptionNoArg,   (caddr_t) "on" },
   {"+rv",               "*reverseVideo",     XrmoptionNoArg,   (caddr_t) "off"},
   {"-iconic",           "*iconic",           XrmoptionNoArg,   (caddr_t) "on" },
   {"-synchronous",      "*synchronous",      XrmoptionNoArg,   (caddr_t) "on" },
   {"-xnllanguage",      "*xnllanguage",      XrmoptionSepArg,  (caddr_t) NULL },
   {"-selectionTimeout", "*selectionTimeout", XrmoptionSepArg,  (caddr_t) NULL },
   {"-title",            ".title",            XrmoptionSepArg,  (caddr_t) NULL },
   {"-xrm",              NULL,                XrmoptionResArg,  (caddr_t) NULL },
   {"-raise",            "*raise",            XrmoptionNoArg,   (caddr_t) "on" },
   {"-noraise",          "*raise",            XrmoptionNoArg,   (caddr_t) "off" },
   {"-persist",          "*persist",          XrmoptionNoArg,   (caddr_t) "on" }
};

#define Nopt (sizeof(options) / sizeof(options[0]))

void preset(argc, argv) int argc; char *argv[]; {
   int Argc = argc; char **Argv = argv;

#ifdef VMS
   char *display = (char *) 0;
#else
   char *display = getenv("DISPLAY");
#endif
   char *home = getenv("HOME");
   char *server_defaults, *env, buf[256];

   /* avoid bus error when env vars are not set */
   if(display==NULL) display="";
   if(home==NULL) home="";

   /*---set to ignore ^C and ^Z----------------------------------------------*/

   signal(SIGINT, SIG_IGN);
#ifdef SIGTSTP
   signal(SIGTSTP, SIG_IGN);
#endif

   /*---prescan arguments for "-name"----------------------------------------*/

   while(++Argv, --Argc > 0) {
      if (!strcmp(*Argv, "-name") && Argc > 1) {
	 strncpy(Name, Argv[1], 64);
	 strncpy(Class, Argv[1], 64);
	 if (Class[0] >= 'a' && Class[0] <= 'z') Class[0] -= 0x20;
	 }
      }
   Argc = argc; Argv = argv;

   /*---parse command line---------------------------------------------------*/

   XrmInitialize();
   XrmParseCommand(&dbCmd, options, Nopt, Name, &Argc, Argv);
   if (Argc > 1) {
      fprintf(stderr, "\ngnuplot: bad option: %s\n", Argv[1]);
      fprintf(stderr, "gnuplot: X11 aborted.\n");
      EXIT(1);
      }
   if (pr_GetR(dbCmd, ".display")) display = (char *) value.addr;

   /*---open display---------------------------------------------------------*/

   dpy = XOpenDisplay(display); 
   if (!dpy) {
      fprintf(stderr, "\ngnuplot: unable to open display '%s'\n", display);
      fprintf(stderr, "gnuplot: X11 aborted.\n");
      EXIT(1);
      }
   scr = DefaultScreen(dpy);
   vis = DefaultVisual(dpy,scr);
   D = DefaultDepth(dpy,scr);
   root = DefaultRootWindow(dpy);
   server_defaults = XResourceManagerString(dpy);

   /*---get symcode for key q ---*/

   q_keycode = XKeysymToKeycode(dpy, XK_q);

   /**** atoms we will need later ****/
   
	WM_PROTOCOLS = XInternAtom(dpy,"WM_PROTOCOLS", False);
	WM_DELETE_WINDOW = XInternAtom(dpy,"WM_DELETE_WINDOW", False);


   /*---get application defaults--(subset of Xt processing)------------------*/

#ifdef VMS
   strcpy (buf, "DECW$USER_DEFAULTS:GNUPLOT_X11.INI");
#else
#ifdef OS2
/* for Xfree86 ... */
   {
   char *appdefdir = "XFree86/lib/X11/app-defaults" ;
   char *xroot = getenv( "X11ROOT" ) ; 
   sprintf(buf, "%s/%s/%s", xroot, appdefdir, "Gnuplot");
   }
#else
   sprintf(buf, "%s/%s", AppDefDir, "Gnuplot");
#endif
#endif
   dbApp = XrmGetFileDatabase(buf);
   XrmMergeDatabases(dbApp, &db);

   /*---get server or ~/.Xdefaults-------------------------------------------*/

   if (server_defaults)
      dbDef = XrmGetStringDatabase(server_defaults);
   else {
#ifdef VMS
      strcpy(buf,"DECW$USER_DEFAULTS:DECW$XDEFAULTS.DAT");
#else
      sprintf(buf, "%s/.Xdefaults", home);
#endif
      dbDef = XrmGetFileDatabase(buf);
      }
   XrmMergeDatabases(dbDef, &db);

   /*---get XENVIRONMENT or  ~/.Xdefaults-hostname---------------------------*/

#ifndef VMS
   if (env = getenv("XENVIRONMENT")) 
      dbEnv = XrmGetFileDatabase(env);
   else {
      char *p, host[MAXHOSTNAMELEN];

      if (GP_SYSTEMINFO(host) < 0) {
         fprintf(stderr, "gnuplot: %s failed. X11 aborted.\n", SYSINFO_METHOD);
	 EXIT(1);
	 }
      if (p = index(host, '.')) *p = '\0';
      sprintf(buf, "%s/.Xdefaults-%s", home, host);
      dbEnv = XrmGetFileDatabase(buf);
      }
   XrmMergeDatabases(dbEnv, &db);
#endif   /* not VMS */

   /*---merge command line options-------------------------------------------*/

   XrmMergeDatabases(dbCmd, &db);

   /*---set geometry, font, colors, line widths, dash styles, point size-----*/

   pr_geometry();
   pr_font();
   pr_color();
   pr_width();
   pr_dashes();
   pr_pointsize();
	pr_raise();
	pr_persist();
   } 

/*-----------------------------------------------------------------------------
 *   pr_GetR - get resource from database using "-name" option (if any)
 *---------------------------------------------------------------------------*/

char *
pr_GetR(db, resource) XrmDatabase db; char *resource; {
   char name[128], class[128], *rc;

   strcpy(name, Name); strcat(name, resource);
   strcpy(class, Class); strcat(class, resource);
   rc = XrmGetResource(db, name, class, type, &value)
      ? (char *)value.addr 
      : (char *)0;
   return(rc);
   }

/*-----------------------------------------------------------------------------
 *   pr_color - determine color values
 *---------------------------------------------------------------------------*/

char color_keys[Ncolors][30] =   { 
   "background", "bordercolor", "text", "border", "axis", 
   "line1", "line2", "line3",  "line4", 
   "line5", "line6", "line7",  "line8" 
   };
char color_values[Ncolors][30] = { 
   "white", "black",  "black",  "black",  "black", 
   "red",   "green",  "blue",   "magenta", 
   "cyan",  "sienna", "orange", "coral" 
   };
char gray_values[Ncolors][30] = { 
   "black",   "white",  "white",  "gray50", "gray50",
   "gray100", "gray60", "gray80", "gray40", 
   "gray90",  "gray50", "gray70", "gray30" 
   };

void pr_color() {
   unsigned long black = BlackPixel(dpy, scr), white = WhitePixel(dpy,scr);
   char option[20], color[30], *v, *type; 
   XColor xcolor;
   Colormap cmap;
   double intensity = -1;
   int n;

   pr_GetR(db, ".mono")         && On(value.addr) && Mono++;
   pr_GetR(db, ".gray")         && On(value.addr) && Gray++;
   pr_GetR(db, ".reverseVideo") && On(value.addr) && Rv++;

   if (!Gray && (vis->class == GrayScale || vis->class == StaticGray)) Mono++;

   if (!Mono) {
      cmap = DefaultColormap(dpy, scr);
      type = (Gray) ? "Gray" : "Color";

      for (n=0; n<Ncolors; n++) {
	 strcpy(option, ".");
	 strcat(option, color_keys[n]);
	 (n > 1) && strcat(option, type);
	 v = pr_GetR(db, option) 
	     ? (char *) value.addr
	     : ((Gray) ? gray_values[n] : color_values[n]);

	 if (sscanf(v,"%30[^,],%lf", color, &intensity) == 2) {
	    if (intensity < 0 || intensity > 1) {
	       fprintf(stderr, "\ngnuplot: invalid color intensity in '%s'\n",
                       color);
	       intensity = 1;
	       }
	    }
	 else { 
	    strcpy(color, v);
	    intensity = 1;
	    }

	 if (!XParseColor(dpy, cmap, color, &xcolor)) {
	    fprintf(stderr, "\ngnuplot: unable to parse '%s'. Using black.\n",
                    color);
	    colors[n] = black;
	    }
	 else {
	    xcolor.red *= intensity;
	    xcolor.green *= intensity;
	    xcolor.blue *= intensity;
	    if (XAllocColor(dpy, cmap, &xcolor)) {
	       colors[n] = xcolor.pixel;
	       }
	    else {
	       fprintf(stderr, "\ngnuplot: can't allocate '%s'. Using black.\n",
                        v);
	       colors[n] = black;
	       }
	    }
	 }
      }
   else {
      colors[0] = (Rv) ? black : white ;
      for (n=1; n<Ncolors; n++)  colors[n] = (Rv) ? white : black;
      }
   }

/*-----------------------------------------------------------------------------
 *   pr_dashes - determine line dash styles 
 *---------------------------------------------------------------------------*/

char dash_keys[Ndashes][10] =   { 
   "border", "axis",
   "line1", "line2", "line3",  "line4", "line5", "line6", "line7",  "line8" 
   };

char dash_mono[Ndashes][10] =   { 
   "0", "16",
   "0", "42", "13",  "44", "15", "4441", "42",  "13" 
   };

char dash_color[Ndashes][10] =   { 
   "0", "16",
   "0", "0", "0", "0", "0", "0", "0", "0" 
   };

void pr_dashes() {
   int n, j, l, ok;
   char option[20], *v; 
   for (n=0; n<Ndashes; n++) {
      strcpy(option, ".");
      strcat(option, dash_keys[n]);
      strcat(option, "Dashes");
      v = pr_GetR(db, option) 
	  ? (char *) value.addr
	  : ((Mono) ? dash_mono[n] : dash_color[n]);
      l = strlen(v);
      if (l == 1 && *v == '0') {
	 dashes[n][0] = (unsigned char)0;
	 continue;
	 }
      for (ok=0, j=0; j<l; j++) { v[j] >= '1' && v[j] <= '9' && ok++; }
      if (ok != l || (ok != 2 && ok != 4)) {
	 fprintf(stderr, "gnuplot: illegal dashes value %s:%s\n", option, v);
	 dashes[n][0] = (unsigned char)0;
	 continue;
	 }
      for(j=0; j<l; j++) {
	 dashes[n][j] = (unsigned char) (v[j] - '0');
	 }
      dashes[n][l] = (unsigned char)0;
      }
   }

/*-----------------------------------------------------------------------------
 *   pr_font - determine font          
 *---------------------------------------------------------------------------*/

void pr_font() {
   char *fontname = pr_GetR(db, ".font");

   if (!fontname) fontname = FallbackFont;
   font = XLoadQueryFont(dpy, fontname);
   if (!font) {
      fprintf(stderr, "\ngnuplot: can't load font '%s'\n", fontname);
      fprintf(stderr, "gnuplot: using font '%s' instead.\n", FallbackFont);
      font = XLoadQueryFont(dpy, FallbackFont);
      if (!font) {
	 fprintf(stderr, "gnuplot: can't load font '%s'\n", FallbackFont);
	 fprintf(stderr, "gnuplot: no useable font - X11 aborted.\n");
         EXIT(1);
	 }
      }
   vchar = font->ascent + font->descent;
   }

/*-----------------------------------------------------------------------------
 *   pr_geometry - determine window geometry      
 *---------------------------------------------------------------------------*/

void pr_geometry() {
   char *geometry = pr_GetR(db, ".geometry");
   int x, y, flags;
   unsigned int w, h; 

   if (geometry) {
      flags = XParseGeometry(geometry, &x, &y, &w, &h);
      if (flags & WidthValue)  gW = w;
      if (flags & HeightValue) gH = h;
		if (flags & (WidthValue | HeightValue))
			gFlags = (gFlags & ~PSize) | USSize;

      if (flags & XValue)
         gX = (flags & XNegative) ? x + DisplayWidth(dpy,scr) - gW - BorderWidth*2 : x;

      if (flags & YValue)
         gY = (flags & YNegative) ? y + DisplayHeight(dpy,scr) - gH - BorderWidth*2 : y;

		if (flags & (XValue | YValue))
         gFlags = (gFlags & ~PPosition) | USPosition;
	}
}

/*-----------------------------------------------------------------------------
 *   pr_pointsize - determine size of points for 'points' plotting style
 *---------------------------------------------------------------------------*/

void pr_pointsize() {
    if (pr_GetR(db, ".pointsize")) {
	if (sscanf( (char *) value.addr,"%lf", &pointsize) == 1) {
	    if (pointsize <= 0 || pointsize > 10) {
		fprintf(stderr, "\ngnuplot: invalid pointsize '%s'\n", value.addr);
		pointsize = 1;
	    }
	} else { 
	    fprintf(stderr, "\ngnuplot: invalid pointsize '%s'\n", value.addr);
	    pointsize = 1;
	}
    } else {
    	pointsize=1;
    }
}

/*-----------------------------------------------------------------------------
 *   pr_width - determine line width values
 *---------------------------------------------------------------------------*/

char width_keys[Nwidths][30] =   { 
   "border", "axis",
   "line1", "line2", "line3",  "line4", "line5", "line6", "line7",  "line8" 
   };

void pr_width() {
   int n;
   char option[20], *v; 
   for (n=0; n<Nwidths; n++) {
      strcpy(option, ".");
      strcat(option, width_keys[n]);
      strcat(option, "Width");
      if (v = pr_GetR(db, option)) {
	 if ( *v < '0' || *v > '4' || strlen(v) > 1)
	    fprintf(stderr, "gnuplot: illegal width value %s:%s\n", option, v);
	 else 
	    widths[n] = (unsigned int)atoi(v);
	 }
      }
   }

/*-----------------------------------------------------------------------------
 *   pr_window - create window 
 *---------------------------------------------------------------------------*/

Window pr_window(flags, x, y, width, height)
unsigned int flags;
int x,y;
unsigned int width, height;
{
   char *title =  pr_GetR(db, ".title");
   static XSizeHints hints;
   int Tvtwm = 0;

   Window win = XCreateSimpleWindow(dpy, root, x, y, width, height, BorderWidth,
                             colors[1], colors[0]);

   /* ask ICCCM-compliant window manager to tell us when close window
    * has been chosen, rather than just killing us
    */

   XChangeProperty(dpy, win, WM_PROTOCOLS, XA_ATOM, 32, PropModeReplace,
	  (unsigned char *)&WM_DELETE_WINDOW, 1);

   pr_GetR(db, ".clear") && On(value.addr) && Clear++;
   pr_GetR(db, ".tvtwm") && On(value.addr) && Tvtwm++;

   if (!Tvtwm) {
      hints.flags = flags;
      }
   else {
      hints.flags = flags & ~USPosition | PPosition; /* ? */
      }
   hints.x = gX; hints.y = gY;        
   hints.width = width; hints.height = height;

   XSetNormalHints(dpy, win, &hints);

   if (pr_GetR(db, ".iconic") && On(value.addr)) {
      XWMHints wmh;

      wmh.flags = StateHint ;
      wmh.initial_state = IconicState;
      XSetWMHints(dpy, win, &wmh);
      } 

   XStoreName(dpy, win, ((title) ? title : Class));

   XSelectInput(dpy, win, KeyPressMask | StructureNotifyMask);
   XMapWindow(dpy, win);

	return win;   
}


/***** pr_raise ***/
void pr_raise()
{
	if ( pr_GetR(db, ".raise")) do_raise=(On(value.addr));
}


void pr_persist()
{
	if (pr_GetR(db, ".persist")) persist = (On(value.addr));
}

/************ code to handle selection export *********************/

#ifdef EXPORT_SELECTION

/* bit of a bodge, but ... */
static struct plot_struct *exported_plot;

void export_graph(plot)
struct plot_struct *plot;
{
	FPRINTF((stderr,"export_graph(0x%x)\n", plot));
	
	XSetSelectionOwner(dpy, EXPORT_SELECTION, plot->window, CurrentTime);
	/* to check we have selection, we would have to do a
	 * GetSelectionOwner(), but if it failed, it failed - no big deal
	 */
	exported_plot = plot;
}

void handle_selection_event(event)
XEvent *event;
{
	switch (event->type)
	{
		case SelectionRequest:
		{
			XEvent reply;
			
			static Atom XA_TARGETS = (Atom) 0;
			if (XA_TARGETS==0)
				XA_TARGETS = XInternAtom(dpy, "TARGETS", False);
			
			reply.type = SelectionNotify;
			reply.xselection.send_event = True;
			reply.xselection.display = event->xselectionrequest.display;
			reply.xselection.requestor = event->xselectionrequest.requestor;
			reply.xselection.selection = event->xselectionrequest.selection;
			reply.xselection.target = event->xselectionrequest.target;
			reply.xselection.property = event->xselectionrequest.property;
			reply.xselection.time = event->xselectionrequest.time;
			
			FPRINTF((stderr,"selection request\n"));

			if (reply.xselection.target == XA_TARGETS) {
				static Atom targets[] = { XA_PIXMAP, XA_COLORMAP };
				FPRINTF((stderr,"Targets request from %d\n", reply.xselection.requestor));
				XChangeProperty(dpy, reply.xselection.requestor,
				  reply.xselection.property, reply.xselection.target, 32, PropModeReplace,
				  (unsigned char *)targets, 2);
			} else if (reply.xselection.target == XA_COLORMAP) {
				Colormap cmap = DefaultColormap(dpy,0);
				FPRINTF((stderr,"colormap request from %d\n", reply.xselection.requestor));
				XChangeProperty(dpy, reply.xselection.requestor,
				  reply.xselection.property, reply.xselection.target, 32, PropModeReplace,
				  (unsigned char *)&cmap, 1);
			} else if (reply.xselection.target == XA_PIXMAP) {
				FPRINTF((stderr,"pixmap request from %d\n", reply.xselection.requestor));
				XChangeProperty(dpy, reply.xselection.requestor,
				  reply.xselection.property, reply.xselection.target, 32, PropModeReplace,
				  (unsigned char *)&(exported_plot->pixmap), 1);
			} else {
				reply.xselection.property = None;
			}
			
			XSendEvent(dpy, reply.xselection.requestor, False, 0L, &reply);
			/* we never block on XNextEvent(), so must flush manually
			 * (took me *ages* to find this out !)
			 */
			 
			XFlush(dpy);
		}
		break;
	}
}
			
#endif /* EXPORT_SELECTION */