aboutsummaryrefslogtreecommitdiffstats
path: root/turtlegr.c
blob: c0245c8b6bec51e87f47c88b496b6723e3f0eceb (plain)
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

/*      file    turtlegr.c                              *
 *      Copyright (C) 1992      sjm@ee.tut.fi           *
 *                              jtl@cc.tut.fi           *
 *                                                      *
 *      Turtlegraphics primitives for the               *
 *      SCM interpreter by Aubrey Jaffer                *
 *                                                      *
 *      Last modification: 13.10.1992                   *
 *                                                      *
 *      Versions:                                       *
 *      12.3.1992       The first version.              *
 *      13.3.1992       Added the possibility to pass   *
 *                      floating point args.            *
 *      15.3.1992       Graphics cards other than EGA   *
 *                      are now supported.              *
 *      9.4.1992        The internal representation     *
 *                      of X & Y is now float.          *
 *      13.10.1992      Added X11 support.              *
 *                      A major rewrite of certain      *
 *                      parts.                          *
 *                      Put -DX11 -DFLOATS to CFLAGS    *
 *                      in Makefile to get it.          *
 *                                                      *
 *      REMEMBER to define INITS=init_turtlegr()        *
 *      in the Makefile.                                *
 *                                                      */

/*                                                                      *
 *       This code tries to compromise between two very different       *
 *      systems: MSDOS and UNIX with the X11 windowing system.          *
 *      The MSDOS version was build first and it really shows.  :)      *
 *      The X port is a partial rewrite of the old MSDOS stuff          *
 *      and plays around with #ifdef's a lot.  The result is,           *
 *      eventually, a C source which is expected to compile             *
 *      under both MSDOS and UNIX (X11).                                *
 *       The X code handles colors emulating CGA palette. It tries      *
 *      to act sensibly even on a monochrome screen and when the        *
 *      color palette is full.                                          *
 *       X event handling is implemented with polling whenever          *
 *      appropriate. This is not The Right Way to do it in X, but       *
 *      it was easiest to adopt in this case.                           *
 *       Another solution would have been to make the X graphics        *
 *      a separate process, but I didn't want to because I wanted       *
 *      to keep it simple. I can't tell how good an example of porting  *
 *      MSDOS software to X this is, but it works.                      *
 *                                                                      *
 *       This has been tested with SunOs 4.1.2 with X11R5, Linux 0.98.1 *
 *      with Xfree86 1.1 (X11R5 port) and in MSDOS with BC 3.1.         *
 *      Because the code uses only the basic Xlib calls, it should      *
 *      compile without problems under _any_ UNIX with X11R4 or newer.  *
 *                                                                      *
 *      Please send bugreports to sjm@ee.tut.fi.                        *
 *      I'm especially interested in hearing about ports to other       *
 *      platforms than those tested by me.                              *
 *                                                                      *
 *      - sjm                                                           *
 *                                                                      */


/****************************************************/
/*****  GENERIC includes & defines              *****/
/****************************************************/
#include        "scm.h"         /* includes scmfig.h as well    */
#include        "patchlvl.h"    /* Guess...                     */
#include        <math.h>        /* sin(), cos(), fmod()         */
#include	<stdlib.h>	/* atexit()			*/

/****************************************************/
/*****  X11 specific includes & defines         *****/
/****************************************************/
#ifdef X11

/* Xlib include files */
# include <X11/Xlib.h>
# include <X11/Xutil.h>
# include <X11/Xatom.h>
# include <stdio.h>

# include "turtle"
# define BITMAPDEPTH 1

# define PROGNAME        "scm"
# define CLASSNAME       "Scm"
# define WINDOWNAME      "TurtleSCM graphics window"
# define ICONNAME        "TurtleSCM"

# define GR_MAX_XSIZE    1024
# define GR_MAX_YSIZE    1024
# define GR_DEF_XSIZE    640
# define GR_DEF_YSIZE    480
# define GR_MIN_XSIZE    64
# define GR_MIN_YSIZE    64

/* Fake CGA colormap with X - yuk!                              */
# define GR_COLORS       16              /* CGA/EGA counterpart  */
# define GR_COLOR00      "black"         /* black                */
# define GR_COLOR01      "blue2"         /* blue                 */
# define GR_COLOR02      "green2"        /* green                */
# define GR_COLOR03      "cyan2"         /* cyan                 */
# define GR_COLOR04      "red3"          /* red                  */
# define GR_COLOR05      "magenta2"      /* magenta              */
# define GR_COLOR06      "yellow2"       /* brown                */
# define GR_COLOR07      "light gray"    /* white                */
# define GR_COLOR08      "gray"          /* gray                 */
# define GR_COLOR09      "blue1"         /* light blue           */
# define GR_COLOR10      "green1"        /* light green          */
# define GR_COLOR11      "cyan1"         /* light cyan           */
# define GR_COLOR12      "red1"          /* light red            */
# define GR_COLOR13      "magenta1"      /* light magenta        */
# define GR_COLOR14      "yellow1"       /* yellow               */
# define GR_COLOR15      "white"         /* bright white         */

# ifdef  __STDC__
static void     gr_events( int );
# else
static void     gr_events();
# endif

#else
/****************************************************/
/*****  PC specific includes & defines          *****/
/****************************************************/
# include        <graphics.h>
# include        <stdlib.h>      /* for getenv()                 */
# include        <stdio.h>       /* for fputs()                  */
# define         BGIDIR_ENVSTRING        "BGIDIR"
#endif

/********************************************/
/***** GENERIC code, declarations       *****/
/********************************************/
#define         SIN( x )                \
                sin( ((x)/180.0) * M_PI )
#define         COS( x )                \
                cos( ((x)/180.0) * M_PI )

static  int             gr_graphicsavail = 0;
static  int             gr_grmode_on = 0;
static  float           gr_dir = 0.0;
static  int             gr_max_x=0, gr_max_y=0, gr_max_color=0;
static  float           gr_x=0.0, gr_y=0.0;
static  int             gr_color = 0;

static  char    s_gr_draw[]             = "draw";
static  char    s_gr_move[]             = "move";
static  char    s_gr_setcolor[]         = "set-color!";
static  char    s_gr_turnright[]        = "turn-right";
static  char    s_gr_turnleft[]         = "turn-left";
static  char    s_gr_turnto[]           = "turn-to!";

static  char    s_gr_getdot[]           = "get-dot";
static  char    s_gr_drawTo[]           = "draw-to!";
static  char    s_gr_drawto[]           = "draw-to";
static  char    s_gr_moveTo[]           = "move-to!";

static  char    s_gr_setdot[]           = "set-dot!";
static  char    s_gr_validXYC[]         = "valid-xyc?";

#ifdef __GNUC__
inline
#else
static
#endif
int      valid_XYC( x, y, color )
int     x, y, color;
{
#ifdef X11
        /* Check for changed window size */
        gr_events(0);
#endif
        if( (x <= gr_max_x) && (y <= gr_max_y) && (color <= gr_max_color)
            && (x >= 0) && (y >= 0) && (color >= 0) )
                return( 1 );
        else
                return( 0 );
} /* valid_XYC() */


/********************************************************************/
/*****  X11 specific variable and function declarations         *****/
/********************************************************************/
#ifdef X11
static Display          *gr_display;            /* The X display        */
static int              gr_screen;              /* The X screen number  */
static Window           gr_win;                 /* The drawable Window  */
static GC               gr_gc;                  /* Graphics Context     */
static unsigned long    gr_colortbl[GR_COLORS]; /* Color table          */
static XEvent           gr_event;               /* Event structure      */

/* These are needed for XSetWMProperties */
static char     *gr_windowname  = WINDOWNAME;
static char     *gr_iconname    = ICONNAME;
static char     gr_progname[]   = PROGNAME;
static char     gr_classname[]  = CLASSNAME;
static int      gr_argc         = 1;
static char     *gr_argv[]      = { gr_progname, NULL };

static void     gr_eventhandler( event )
XEvent          event;
{
          switch( event.type ) {

          case ConfigureNotify:
# ifdef TESTING
            fputs( "Received ConfigureNotify event\n", stderr );
# endif
            gr_max_x = event.xconfigure.width - 1;
            gr_max_y = event.xconfigure.height - 1;
            break;

          case MapNotify:
# ifdef TESTING
            fputs( "Received MapNotify event\n", stderr );
# endif
            break;

          case DestroyNotify:
# ifdef TESTING
            fputs( "Received DestroyNotify event\n", stderr );
# endif
            break;

          case UnmapNotify:
# ifdef TESTING
            fputs( "Received UnmapNotify event\n", stderr );
# endif
            break;

          case Expose:
# ifdef TESTING
            fputs( "Received Expose event\n", stderr );
# endif
            if( event.xexpose.count != 0 )
              break;
            break;

          case ClientMessage:
# ifdef TESTING
            fputs( "Received ClientMessage event\n", stderr );
# endif
            break;

          default:
            /* Throw away any unknown events */
            break;

          } /* switch */
}

static void     gr_events( expected )
int             expected;
{
int             i;

        /* Get at least 'expected' events */
        for( i = 0; i < expected; ++i ) {
          XNextEvent( gr_display, &gr_event );
          gr_eventhandler( gr_event );
        }
        /* Handle all remaining events if there are any */
        /* XPending will call XFlush() if it doesn't find events at once */
        while( XPending(gr_display) ) {
          XNextEvent( gr_display, &gr_event );
          gr_eventhandler( gr_event );
        } /* while */
} /* gr_events() */

static void     gr_typedevent( type )
int             type;
{
        do {
          XNextEvent( gr_display, &gr_event );
          gr_eventhandler( gr_event );
        } while( gr_event.type != type );
        /* Handle all remaining events if there are any */
        /* XPending will call XFlush() if it doesn't find events at once */
        while( XPending(gr_display) ) {
          XNextEvent( gr_display, &gr_event );
          gr_eventhandler( gr_event );
        } /* while */
}


/********************************************************************/
/*****  PC specific variable and function declarations          *****/
/********************************************************************/
#else

static  int             gr_max_display_mode;
static  int             gr_drivernum;

#endif


/********************************************************************/
/********************************************************************/
/***    User callable SCM routines begin here           ***
 ***                                                    ***
 ***                                                    ***/


SCM     gr_helpgr()
{
        fputs( "\
Ret   Name               nargs    args        returns\n\
---------------------------------------------------------\n\
B  graphics-avail?         0       -          #t if graphics available\n\
B  graphics-mode!          0       -          #f if no graphics\n\
B  text-mode!              0       -          #t on success\n\
B  clear-graphics!         0       -          #f if not in graphics mode\n\
i  max-x                   0       -          maximum value of x\n\
i  max-y                   0       -          maximum value of y\n\
i  max-color               0       -          maximum value of color\n\
B  valid-xyc?              3       x y color  #t if valid\n\
B  set-dot!                3       x y color  #t on success\n\
i  get-dot                 2       x y        color of the dot in (x,y)\n\
                                              or #f if (x,y) not legal\n\
\n\
NOTE: Origin (0,0) is in the upper left corner.\n\n\
", stdout );
        return  BOOL_T;
} /* gr_helpgr() */


SCM     gr_helpturtlegr()
{
        fputs( "\
Ret   Name               nargs    args        returns\n\
---------------------------------------------------------\n\
B  goto-home!              0       -          #f if not in graphics mode\n\
B  goto-center!            0       -          #f if not in graphics mode\n\
B  goto-nw!                0       -          #f if not in graphics mode\n\
B  goto-ne!                0       -          #f if not in graphics mode\n\
B  goto-sw!                0       -          #f if not in graphics mode\n\
B  goto-se!                0       -          #f if not in graphics mode\n\
B  draw                    1       length     #t if target within drawing area\n\
B  draw-to                 2       x y        #t if (x,y) within drawing area\n\
B  draw-to!                2       x y        #t if (x,y) within drawing area\n\
B  move                    1       length     #t if target within drawing area\n\
B  move-to!                2       x y        #t if (x,y) within drawing area\n\
i  where-x                 0       -          current x-coordinate\n\
i  where-y                 0       -          current y-coordinate\n\
i  turn-right              1       angle      drawing direction in degrees\n\
i  turn-left               1       angle      drawing direction in degrees\n\
i  turn-to!                1       angle      drawing direction in degrees\n\
i  what-direction          0       -          drawing direction in degrees\n\
B  set-color!              1       color      #t if color valid\n\
i  what-color              0       -          current drawing color\n\n\
", stdout );
        return  BOOL_T;
} /* gr_helpturtlegr() */


SCM     gr_available()
{
        if( gr_graphicsavail )
                return  BOOL_T;
        else
                return  BOOL_F;
} /* gr_available() */


SCM     gr_maxx()
{
        if( !gr_grmode_on )
                return  BOOL_F;
#ifdef X11
        /* Check for changed window size */
        gr_events(0);
#endif
        return  MAKINUM( (long)gr_max_x );
} /* gr_maxx() */


SCM     gr_maxy()
{
        if( !gr_grmode_on )
                return  BOOL_F;
#ifdef X11
        /* Check for changed window size */
        gr_events(0);
#endif
        return  MAKINUM( (long)gr_max_y );
} /* gr_maxy() */

SCM     gr_maxc()
{
        if( !gr_grmode_on )
                return  BOOL_F;
        return  MAKINUM( (long)gr_max_color );
} /* gr_maxc() */


SCM     gr_validXYC( x, y, c )
SCM     x, y, c;
{
int     xi, yi, ci;

        ASRTER( NUMBERP(x), x, ARG1, s_gr_validXYC );
        ASRTER( NUMBERP(y), y, ARG2, s_gr_validXYC );
        ASRTER( NUMBERP(c), c, ARG3, s_gr_validXYC );
        if( !gr_grmode_on )
                return  BOOL_F;

        if( INUMP(x) )
                xi = (int)(INUM(x));
        else
                xi = (int)(REALPART(x));

        if( INUMP(y) )
                yi = (int)(INUM(y));
        else
                yi = (int)(REALPART(y));

        if( INUMP(c) )
                ci = (int)(INUM(c));
        else
                ci = (int)(REALPART(c));

/* valid_XYC() calls gr_events() */

        if( valid_XYC( xi, yi, ci ) )
                return  BOOL_T;
        else
                return  BOOL_F;
} /* gr_validXYC() */


SCM     gr_grmode()
{
        if( !gr_graphicsavail )
                return  BOOL_F;
#ifdef  X11
        /* bwuah... but it works :) */
        if( !gr_grmode_on ) {
            XMapWindow( gr_display, gr_win );
            gr_typedevent( MapNotify );
        }
#else   /* PC version */
        setgraphmode( gr_max_display_mode );
#endif
        gr_grmode_on = 1;
        return  BOOL_T;
} /* gr_grmode() */

SCM     gr_txtmode()
{
        if( !gr_graphicsavail )
                return  BOOL_F;
#ifdef  X11
        /* bwuah... but it works :) */
        if( gr_grmode_on ) {
            XUnmapWindow( gr_display, gr_win );
            gr_typedevent( UnmapNotify );
        }
#else   /* PC version */
        restorecrtmode();
#endif
        gr_grmode_on = 0;
        return  BOOL_T;
} /* gr_txtmode() */


SCM     gr_cleargraph()
{
        if( !gr_grmode_on )
                return  BOOL_F;
#ifdef  X11
        XClearWindow( gr_display, gr_win );
        gr_events(0);
#else   /* PC version */
        cleardevice();
#endif
        return  BOOL_T;
} /* gr_cleargraph() */


SCM     gr_setdot( x, y, c )
SCM     x, y, c;
{
int     xi, yi, ci;

        ASRTER( NUMBERP(x), x, ARG1, s_gr_setdot );
        ASRTER( NUMBERP(y), y, ARG2, s_gr_setdot );
        ASRTER( NUMBERP(c), c, ARG3, s_gr_setdot );
        if( !gr_grmode_on )
                return  BOOL_F;

        if( INUMP(x) )
                xi = (int)(INUM(x));
        else
                xi = (int)(REALPART(x));

        if( INUMP(y) )
                yi = (int)(INUM(y));
        else
                yi = (int)(REALPART(y));

        if( INUMP(c) )
                ci = (int)(INUM(c));
        else
                ci = (int)(REALPART(c));
#ifdef TESTING
        fprintf( stderr, "set-dot! called (%d,%d,%d)\n", xi, yi, ci );
#endif
        if( !valid_XYC( xi, yi, ci ) )
                return  BOOL_F;
#ifdef  X11
        /* Set the drawing color */
        XSetForeground( gr_display, gr_gc, gr_colortbl[ ci ] );
        XDrawPoint( gr_display, gr_win, gr_gc, xi, yi );
        /* Restore the drawing color */
        XSetForeground( gr_display, gr_gc, gr_colortbl[ gr_color ] );
        gr_events(0);
#else   /* PC version */
        putpixel( xi, yi, ci );
#endif
        return  BOOL_T;
} /* gr_setdot() */


SCM     gr_getdot( x, y )
SCM     x, y;
{
int                     xi, yi;
#ifdef  X11
XImage                  *xim;
XWindowAttributes       wattr;
unsigned long           dot;
int                     i;
#endif
        ASRTER( NUMBERP(x), x, ARG1, s_gr_getdot );
        ASRTER( NUMBERP(y), y, ARG2, s_gr_getdot );
        if( !gr_grmode_on )
                return  BOOL_F;
        if( INUMP(x) )
                xi = (int)(INUM(x));
        else
                xi = (int)(REALPART(x));

        if( INUMP(y) )
                yi = (int)(INUM(y));
        else
                yi = (int)(REALPART(y));
#ifdef TESTING
        fprintf( stderr, "get-dot called (%d,%d)\n", xi, yi );
#endif
        if( !valid_XYC( xi, yi, 0 ) )
                return  BOOL_F;
#ifdef  X11
        /* Now, this IS ugly. But it's there if you need it.            */

        /* Have to make sure that the window is mapped.  Tough...       */
        XGetWindowAttributes( gr_display, gr_win, &wattr );
        if( wattr.map_state == IsUnmapped ) {
            XMapWindow( gr_display, gr_win );
            gr_typedevent( MapNotify );
        }
        /* I KNOW this sucks.                                           */
        xim = XGetImage( gr_display, gr_win, xi, yi, 1, 1, AllPlanes, XYPixmap );
        dot = XGetPixel( xim, 0, 0 );
        for( i = 0; i < GR_COLORS; ++i ) {
            if( gr_colortbl[i] == dot )
                return MAKINUM( (long)i );
        }
        /* This should never happen. There's garbage in the window!     */
        fprintf( stderr, "%s: %s: Got an illegal pixel value %lu. \
Is there garbage?\n", gr_progname, s_gr_getdot, dot );
        return BOOL_F;
#else   /* PC version */
        return MAKINUM( (long)getpixel( xi, yi ) );
#endif
} /* gr_getdot() */

SCM     gr_draw( S )
SCM     S;
{
float   xf, yf;
float   sf;
int     ok;

        ASRTER( NUMBERP(S), S, ARG1, s_gr_draw );
        if( !gr_grmode_on )
                return  BOOL_F;
        if( INUMP(S) )
                sf = (float)(INUM(S));
        else
                sf = REALPART(S);
#ifdef TESTING
        fprintf( stderr, "draw called (%f)\n", sf );
#endif
        ok = 1;
        xf = gr_x + ( COS( gr_dir ) * sf );
        yf = gr_y + ( SIN( gr_dir ) * sf );
        if( (int)xf > gr_max_x ) {
                xf = (float)gr_max_x;
                ok = 0;
        }
        else if( xf < 0.0 ) {
                xf = 0.0;
                ok = 0;
        }
        if( (int)yf > gr_max_y ) {
                yf = (float)gr_max_y;
                ok = 0;
        }
        else if( yf < 0.0 ) {
                yf = 0.0;
                ok = 0;
        }
#ifdef  X11
        XDrawLine( gr_display, gr_win, gr_gc,
                   (int)gr_x, (int)gr_y,
                   (int)xf, (int)yf );
        gr_events(0);
#else   /* PC version */
        line( (int)gr_x, (int)gr_y, (int)xf, (int)yf );
#endif
        gr_x = xf;
        gr_y = yf;
        if( ok )
                return  BOOL_T;
        else
                return  BOOL_F;
} /* gr_draw() */


SCM     gr_move( S )
SCM     S;
{
float   xf, yf;
float   sf;
int     ok;

        ASRTER( NUMBERP(S), S, ARG1, s_gr_move );
        if( !gr_grmode_on )
                return  BOOL_F;
        if( INUMP(S) )
                sf = (float)(INUM(S));
        else
                sf = REALPART(S);
#ifdef TESTING
        fprintf( stderr, "move called (%f)\n", sf );
#endif
        ok = 1;
        xf = gr_x + ( COS( gr_dir ) * sf );
        yf = gr_y + ( SIN( gr_dir ) * sf );

        if( (int)xf > gr_max_x ) {
                xf = (float)gr_max_x;
                ok = 0;
        }
        else if( xf < 0.0 ) {
                xf = 0.0;
                ok = 0;
        }
        if( (int)yf > gr_max_y ) {
                yf = (float)gr_max_y;
                ok = 0;
        }
        else if( yf < 0.0 ) {
                yf = 0.0;
                ok = 0;
        }
        gr_x = xf;
        gr_y = yf;
        if( ok )
                return  BOOL_T;
        else
                return  BOOL_F;
} /* gr_move() */


SCM     gr_drawto( x, y )
SCM     x, y;
{
int     xi, yi;

        ASRTER( NUMBERP(x), x, ARG1, s_gr_drawto );
        ASRTER( NUMBERP(y), y, ARG2, s_gr_drawto );
        if( !gr_grmode_on )
                return  BOOL_F;
        if( INUMP(x) )
                xi = (int)(INUM(x));
        else
                xi = (int)(REALPART(x));

        if( INUMP(y) )
                yi = (int)(INUM(y));
        else
                yi = (int)(REALPART(y));
#ifdef TESTING
        fprintf( stderr, "draw-to called (%d,%d)\n", xi, yi );
#endif
        if( !valid_XYC( xi, yi, 0 ) )
                return  BOOL_F;
#ifdef  X11
        XDrawLine( gr_display, gr_win, gr_gc,
                   (int)gr_x, (int)gr_y, xi, yi );
        gr_events(0);
#else   /* PC version */
        line( (int)gr_x, (int)gr_y, xi, yi );
#endif
        return  BOOL_T;
} /* gr_drawto() */


SCM     gr_drawTo( x, y )
SCM     x, y;
{
float   xf, yf;

        ASRTER( NUMBERP(x), x, ARG1, s_gr_drawTo );
        ASRTER( NUMBERP(y), y, ARG2, s_gr_drawTo );
        if( !gr_grmode_on )
                return  BOOL_F;
        if( INUMP(x) )
                xf = (float)(INUM(x));
        else
                xf = (REALPART(x));

        if( INUMP(y) )
                yf = (float)(INUM(y));
        else
                yf = (REALPART(y));
#ifdef TESTING
        fprintf( stderr, "draw-to! called (%d,%d)\n", (int)xf, (int)yf );
#endif
        if( !valid_XYC( (int)xf, (int)yf, 0 ) )
                return  BOOL_F;
#ifdef  X11
        XDrawLine( gr_display, gr_win, gr_gc,
                   (int)gr_x, (int)gr_y,
                   (int)xf, (int)yf );
        gr_events(0);
#else   /* PC version */
        line( (int)gr_x, (int)gr_y, (int)xf, (int)yf );
#endif
        gr_x = xf;
        gr_y = yf;
        return  BOOL_T;
} /* gr_drawTo() */


SCM     gr_moveTo( x, y )
SCM     x, y;
{
float   xf, yf;

        ASRTER( NUMBERP(x), x, ARG1, s_gr_moveTo );
        ASRTER( NUMBERP(y), y, ARG2, s_gr_moveTo );
        if( !gr_grmode_on )
                return  BOOL_F;
        if( INUMP(x) )
                xf = (float)(INUM(x));
        else
                xf = (REALPART(x));

        if( INUMP(y) )
                yf = (float)(INUM(y));
        else
                yf = (REALPART(y));
#ifdef TESTING
        fprintf( stderr, "move-to! called (%d,%d)\n", (int)xf, (int)yf );
#endif
        if( !valid_XYC( (int)xf, (int)yf, 0 ) )
                return  BOOL_F;
        gr_x = xf;
        gr_y = yf;
        return  BOOL_T;
} /* gr_moveTo() */


SCM     gr_setcolor( c )
SCM     c;
{
int     color;

        ASRTER( NUMBERP(c), c, ARG1, s_gr_setcolor );
        if( !gr_grmode_on )
                return  BOOL_F;
        if( INUMP(c) )
                color = (int)(INUM(c));
        else
                color = (int)(REALPART(c));
#ifdef TESTING
        fprintf( stderr, "set-color! called (%d)\n", color );
#endif
        if( !valid_XYC( 0, 0, color ) )
                return  BOOL_F;
        gr_color = color;
#ifdef  X11
        /* Set the drawing color */
        XSetForeground( gr_display, gr_gc, gr_colortbl[ gr_color ] );
        gr_events(0);
#else   /* PC version */
        setcolor( gr_color );
#endif
        return  BOOL_T;
} /* gr_setcolor() */


SCM     gr_turnright( d )
SCM     d;
{
float   df;

        ASRTER( NUMBERP(d), d, ARG1, s_gr_turnright );
        if( !gr_grmode_on )
                return  BOOL_F;
        if( INUMP(d) )
                df = (float)(INUM(d));
        else
                df = REALPART(d);
        df = fmod( df, 360.0 );
        gr_dir -= df;
        gr_dir = fmod( gr_dir, 360.0 );
        return MAKINUM( (long)(gr_dir+.5) );
} /* gr_turnright() */


SCM     gr_turnleft( d )
SCM     d;
{
float   df;

        ASRTER( NUMBERP(d), d, ARG1, s_gr_turnleft );
        if( !gr_grmode_on )
                return  BOOL_F;
        if( INUMP(d) )
                df = (float)(INUM(d));
        else
                df = REALPART(d);
        df = fmod( df, 360.0 );
        gr_dir += df;
        gr_dir = fmod( gr_dir, 360.0 );
        return MAKINUM( (long)(gr_dir+.5) );
} /* gr_turnleft() */


SCM     gr_turnto( d )
SCM     d;
{
float   df;

        ASRTER( NUMBERP(d), d, ARG1, s_gr_turnto );
        if( !gr_grmode_on )
                return  BOOL_F;
        if( INUMP(d) )
                df = (float)(INUM(d));
        else
                df = REALPART(d);
        df = fmod( df, 360.0 );
        gr_dir = df;
        return MAKINUM( (long)(gr_dir+.5) );
} /* gr_turnto() */


SCM     gr_gotohome()
{
        if( !gr_grmode_on )
                return  BOOL_F;
        gr_x = gr_y = 0.0;
        return  BOOL_T;
} /* gr_gotohome() */


SCM     gr_gotocenter()
{
        if( !gr_grmode_on )
                return  BOOL_F;
#ifdef X11
        /* Check for changed window size */
        gr_events(0);
#endif
        gr_x = ((float)gr_max_x+1.0) / 2.0;
        gr_y = ((float)gr_max_y+1.0) / 2.0;
        return  BOOL_T;
} /* gr_gotocenter() */


SCM     gr_gotonw()
{
        if( !gr_grmode_on )
                return  BOOL_F;
#ifdef X11
        /* Check for changed window size */
        gr_events(0);
#endif
        gr_x = 0.0;
        gr_y = 0.0;
        return  BOOL_T;
} /* gr_gotonw() */


SCM     gr_gotosw()
{
        if( !gr_grmode_on )
                return  BOOL_F;
#ifdef X11
        /* Check for changed window size */
        gr_events(0);
#endif
        gr_x = 0.0;
        gr_y = (float)gr_max_y;
        return  BOOL_T;
} /* gr_gotosw() */


SCM     gr_gotone()
{
        if( !gr_grmode_on )
                return  BOOL_F;
#ifdef X11
        /* Check for changed window size */
        gr_events(0);
#endif
        gr_x = (float)gr_max_x;
        gr_y = 0.0;
        return  BOOL_T;
} /* gr_gotone() */


SCM     gr_gotose()
{
        if( !gr_grmode_on )
                return  BOOL_F;
#ifdef X11
        /* Check for changed window size */
        gr_events(0);
#endif
        gr_x = (float)gr_max_x;
        gr_y = (float)gr_max_y;
        return  BOOL_T;
} /* gr_gotose() */


SCM     gr_whatcolor()
{
        if( !gr_grmode_on )
                return  BOOL_F;
        return  MAKINUM( (long)gr_color );
} /* gr_whatcolor() */


SCM     gr_whatdirection()
{
        if( !gr_grmode_on )
                return  BOOL_F;
        return  MAKINUM( (long)(gr_dir+.5) );
} /* gr_whatdirection() */


SCM     gr_wherex()
{
        if( !gr_grmode_on )
                return  BOOL_F;
        return  MAKINUM( (long)gr_x );
} /* gr_wherex() */


SCM     gr_wherey()
{
        if( !gr_grmode_on )
                return  BOOL_F;
        return  MAKINUM( (long)gr_y );
} /* gr_wherey() */


static iproc    graph0[] = {
                { "help-gr", gr_helpgr },
                { "help-turtlegr", gr_helpturtlegr },
                { "graphics-mode!", gr_grmode },
                { "text-mode!", gr_txtmode },
                { "clear-graphics!", gr_cleargraph },
                { "graphics-avail?", gr_available },
                { "max-x", gr_maxx },
                { "max-y", gr_maxy },
                { "max-color", gr_maxc },
                { "what-color", gr_whatcolor },
                { "what-direction", gr_whatdirection },
                { "where-x", gr_wherex },
                { "where-y", gr_wherey },
                { "goto-home!", gr_gotohome },
                { "goto-center!", gr_gotocenter },
                { "goto-nw!", gr_gotonw },
                { "goto-sw!", gr_gotosw },
                { "goto-ne!", gr_gotone },
                { "goto-se!", gr_gotose },
                {0, 0}
        };

static iproc    graph1[] = {
                { s_gr_draw, gr_draw },
                { s_gr_move, gr_move },
                { s_gr_setcolor, gr_setcolor },
                { s_gr_turnright, gr_turnright },
                { s_gr_turnleft, gr_turnleft },
                { s_gr_turnto, gr_turnto },
                {0, 0}
        };

static iproc    graph2[] = {
                { s_gr_getdot, gr_getdot },
                { s_gr_drawTo, gr_drawTo },
                { s_gr_drawto, gr_drawto },
                { s_gr_moveTo, gr_moveTo },
                {0, 0}
        };

static iproc    graph3[] = {
                { s_gr_setdot, gr_setdot },
                { s_gr_validXYC, gr_validXYC },
                {0, 0}
        };

#if defined __STDC__ || defined __TURBOC__
void    close_turtlegr()
{
# ifdef  X11
        gr_events(0);
        XFreeColors( gr_display, DefaultColormap(gr_display, gr_screen),
                     gr_colortbl, GR_COLORS, AllPlanes );
        XFreeGC( gr_display, gr_gc );
        XUnmapWindow( gr_display, gr_win );
        XDestroyWindow( gr_display, gr_win );
# else   /* PC version */
        closegraph();
# endif
} /* close_turtlegr() */
#endif

void init_banner();		/* from scm.c */

void    init_turtlegr() /* detects if graphics is available; must be
                           called among program initializations */
{
#ifdef  X11
  char                  *display_name = NULL;   /* Server to connect to      */
  Pixmap                icon_pixmap;            /* Icon                      */
  XSizeHints            size_hints;             /* Preferred sizes           */
  XSetWindowAttributes  win_attribs;            /* Window attributes         */
  XWMHints              wm_hints;               /* Window manager hints      */
  XClassHint            class_hints;            /* Class hints               */
  XTextProperty         window_name, icon_name; /* Names for Icon & Window   */
  XGCValues             gc_values;              /* Graphics Context values   */
  static char           *colorname[GR_COLORS] = {
                                GR_COLOR00, GR_COLOR01, GR_COLOR02, GR_COLOR03,
                                GR_COLOR04, GR_COLOR05, GR_COLOR06, GR_COLOR07,
                                GR_COLOR08, GR_COLOR09, GR_COLOR10, GR_COLOR11,
                                GR_COLOR12, GR_COLOR13, GR_COLOR14, GR_COLOR15
                        };
  XColor                x_color;                /* X11 Color structure       */
  unsigned long         mask;                   /* Mask for selections       */
  int                   i;                      /* loop counter variable     */

#else   /* PC version */
int     errcode;
#endif

/***************************/
/* generic initializations */
/***************************/
  gr_x = gr_y = gr_dir = 0.0;
  gr_max_x = gr_max_y = gr_max_color = 0;

  gr_graphicsavail = 0; /* DEFAULT is no graphics - you can do without */

/********************************************/
/*****  Initialize X11 turtlegraphics   *****/
/********************************************/
#ifdef X11
        /* connect to X server */
        if( (gr_display = XOpenDisplay(display_name)) != NULL )
        {

          /*****************************/
          /* connection to X server OK */
          /*****************************/

          gr_screen = DefaultScreen( gr_display );      /* X screen number */

          /* Create a window with Black background and border */
          gr_win
            = XCreateSimpleWindow( gr_display,
                                  RootWindow( gr_display, gr_screen),
                                  0, 0, /* initial placement */
                                  GR_DEF_XSIZE, GR_DEF_YSIZE,
                                  3, /* border width */
                                  /* border pixel value */
                                  BlackPixel(gr_display, gr_screen),
                                  /* background pixel value */
                                  BlackPixel(gr_display, gr_screen) );

          /* Select input (events) for the window */
          XSelectInput( gr_display, gr_win,
                        StructureNotifyMask|ExposureMask );

          /* Check for backing store capability */
          if( !DoesBackingStore(DefaultScreenOfDisplay(gr_display)) )
          {
            fprintf( stderr, "%s: Warning: \
X server does not offer backing store capability.\n\
Window cannot be redrawn if obscured. Sorry...\n", gr_progname );
          }
          else
          {
              /* Enable the backing store feature of X server
                 and set bit gravity */
              win_attribs.bit_gravity   = NorthWestGravity;
              win_attribs.backing_store = Always;
              mask                      = CWBitGravity | CWBackingStore;
              XChangeWindowAttributes( gr_display, gr_win, mask, &win_attribs );
          }

          /* Make names of Window and Icon for window manager */
          if( XStringListToTextProperty(&gr_windowname, 1, &window_name) == 0 ) {
            (void)fprintf( stderr, "%s: Structure allocation for windowName\
 failed.\n", gr_progname );
            exit( 42 );
          }
          if( XStringListToTextProperty(&gr_iconname, 1, &icon_name) == 0 ) {
            (void)fprintf( stderr, "%s: Structure allocation for iconName\
 failed.\n", gr_progname );
            exit( 42 );
          }

          /* Create the icon */
          icon_pixmap = XCreateBitmapFromData( gr_display, gr_win, turtle_bits,
                                               turtle_width, turtle_height );

          /* Window size, state, icon etc. hints for the window manager */
          size_hints.flags = PPosition | PMaxSize | PMinSize | USSize;
          /* position and desired size are given to XCreateSimpleWindow call */
          size_hints.min_width          = GR_MIN_XSIZE;
          size_hints.min_height         = GR_MIN_YSIZE;
          size_hints.max_width          = GR_MAX_XSIZE;
          size_hints.max_height         = GR_MAX_YSIZE;
          wm_hints.flags = StateHint | IconPixmapHint | InputHint;
          wm_hints.initial_state        = NormalState;
          wm_hints.input                = False;
          wm_hints.icon_pixmap          = icon_pixmap;
          class_hints.res_name          = gr_progname;
          class_hints.res_class         = gr_classname;
          XSetWMProperties( gr_display, gr_win, &window_name, &icon_name,
                            gr_argv, gr_argc,
                            &size_hints, &wm_hints, &class_hints );


          /* Handle colors; this is quite complicated in X11 */

          if( DefaultDepth( gr_display, gr_screen ) == 1 )
          {
            /* Only 1 bitplane, BW screen */
            /* Emulate colors with 0 as Black and 1-15 White */
            gr_colortbl[0] = BlackPixel( gr_display, gr_screen );
            for( i = 1; i < GR_COLORS; ++i )
              gr_colortbl[i] = WhitePixel( gr_display, gr_screen );
# ifdef TESTING
            fprintf( stderr, "%s: 1-plane system, substituting White for \
colors 1-15.\n", gr_progname );
            fprintf( stderr, "%s: Pixel value is %lu for Black, \
%lu for White\n", gr_progname, gr_colortbl[0], gr_colortbl[1] );
# endif
          }
          else
          {
              /* more than 1 bitplane */
              for( i = 0; i < GR_COLORS; ++i )
              {
                  /* Initialize the colortable using named colors */
                  if( XParseColor( gr_display,
                                   DefaultColormap(gr_display, gr_screen),
                                   colorname[ i ], &x_color ) )
                  {
                      if( !XAllocColor( gr_display,
                                        DefaultColormap(gr_display, gr_screen),
                                        &x_color ) )
                      {
                          fprintf( stderr, "%s: Can't allocate color \
\"%s\" (%d). Substituting White.\n",
                                   gr_progname,
                                   colorname[ i ], i );
                          gr_colortbl[i] = WhitePixel( gr_display, gr_screen );
                      }
                      else
                      {
                          /* succeeded in allocating color */
                          gr_colortbl[ i ] = x_color.pixel;
# ifdef TESTING
                          fprintf( stderr, "%s: Pixel value is %lu for %s.\n",
                                   gr_progname, gr_colortbl[i], colorname[i] );
# endif
                      }
                  }
                  else
                  {
                      /* could not parse color */
                      fprintf( stderr,
                               "%s: Color name \"%s\" (%d) not in database. \
Substituting White.\n",
                               gr_progname, colorname[i], i );
                      gr_colortbl[i] = WhitePixel( gr_display, gr_screen );
                  }
              } /* for */
          } /* else */
          gr_max_color = GR_COLORS - 1;

          /* Create and initialize a default GC */
          gr_gc = XCreateGC( gr_display, gr_win, 0L, &gc_values );

          /* Initialize the drawing color, default's black */
          XSetForeground( gr_display, gr_gc, gr_colortbl[ 0 ] );
          XSetBackground( gr_display, gr_gc, gr_colortbl[ 0 ] );
          gr_color = 0;

          /* OK, we _do_ have graphics available */
          gr_graphicsavail = 1;

# ifdef __STDC__
          /* Let's do the Right Thing if possible :) */
          atexit( close_turtlegr );
# endif
      } /* if */
      else {
          gr_graphicsavail = 0;
      }
/********************************************/
/*****  Initialize PC turtlegraphics    *****/
/********************************************/
#else   /* PC version */
          gr_drivernum = DETECT;

          detectgraph( &gr_drivernum, &gr_max_display_mode );
          if( gr_drivernum != grNotDetected ) {
              if( !getenv( BGIDIR_ENVSTRING ) )
                 fprintf( stderr,
                        "You really should set the %s environment variable.\n",
                        BGIDIR_ENVSTRING );
              initgraph( &gr_drivernum, &gr_max_display_mode,
                         getenv( BGIDIR_ENVSTRING ) );
              errcode = graphresult();
              if( errcode != grOk ) {
                  fputs( "Graphics error: ", stderr );
                  fputs( grapherrormsg( errcode ), stderr );
                  exit( EXIT_FAILURE );
              }
              moveto( 0, 0 );
              gr_x = gr_y = 0.0;
              setcolor( 0 );
              gr_color = 0;
              gr_max_x = getmaxx();
              gr_max_y = getmaxy();
              gr_max_color = getmaxcolor();
              gr_max_display_mode = getmaxmode();
              restorecrtmode();
              gr_graphicsavail = 1;
              atexit( close_turtlegr );
          }
          else {
              gr_graphicsavail = 0;
          }
#endif

/* generic */
        init_iprocs( graph0, tc7_subr_0 );
        init_iprocs( graph1, tc7_subr_1 );
        init_iprocs( graph2, tc7_subr_2 );
        init_iprocs( graph3, tc7_subr_3 );
        gr_grmode_on = 0;

#ifndef X11
  /* PC version clears screen so this must be repeated */
  init_banner();
#endif

  fputs("\nSCM Turtlegraphics Copyright (C) 1992 sjm@cc.tut.fi, jtl@cc.tut.fi\n\
Type `(help-gr)' or `(help-turtlegr)' for a quick reference of\n\
the new primitives.\n", stderr);

  if( !gr_graphicsavail ) {
#ifdef X11
        fprintf( stderr, "%s: No X server found. \
Turtlegraphics not available.\n", gr_progname );
#else
        fputs( "No graphics adapter detected. \
Turtlegraphics not available.\n", stderr );
#endif
  }
  else {
#ifdef X11
        gr_events(0);
#else
        ;
#endif
  }
} /* init_turtlegr() */