File: imd.c

package info (click to toggle)
x11iraf 1.2-4
  • links: PTS
  • area: contrib
  • in suites: woody
  • size: 13,168 kB
  • ctags: 14,531
  • sloc: ansic: 143,143; makefile: 964; perl: 549; csh: 249; yacc: 247; fortran: 238; tcl: 199; lex: 125; lisp: 88; sh: 23; sed: 6
file content (1600 lines) | stat: -rw-r--r-- 45,794 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
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <netdb.h>
#include <fcntl.h>
#include <stdio.h>
#define  CDL_LIBRARY_SOURCE
#include "cdl.h"


/*
 *  IMAGE DISPLAY -- The image display interface is responsible for actually
 *  displaying an image to the server, for reading back a raster from the
 *  server, and cursor positioning.  This is a mid-level interface for 
 *  handling the steps necessary for image display operations without dealing
 *  directly with the details of communicating with the server.
 *
 *           imd = imd_open  (imtdev)
 *         imd_displayImage  (imd, pix, nx, ny, frame, fbconfig, comp_wcs)
 *           imd_readCursor  (imd, sample, &x, &y, &wcs, &key)
 *         imd_[set|get]WCS  (imd, name, title, a, b, c, d, tx, ty, z1, z2, zt)
 *                imd_close  (imd)
 *
 *     Low Level Procedures
 *     --------------------
 *           imd_writeImage  (imd, pix, nx, ny, lx, ly)
 *            imd_readImage  (imd, &pix, &nx, &ny)
 *      imd_readFrameBuffer  (imd, &pix, &nx, &ny)
 *             imd_setFrame  (imd, frame)
 *          imd_setFBConfig  (imd, configno)
 *          imd_getFBConfig  (imd, &configno, &width, &height, &nframes))
 *              imd_setName  (imd, name)
 *             imd_setTitle  (imd, title)
 *            imd_setCursor  (imd, x, y, wcs)
 *           imd_clearFrame  (imd)
 *       imd_writeSubRaster  (imd, lx, ly, nx, ny, pix)
 *        imd_readSubRaster  (imd, lx, ly, nx, ny, &pix)
 *
 *      We leave it to the higher level procedures to handle Z-scale trans-
 *  formations, spatial scaling, and high level image I/O.  All display pixels
 *  are assumed to be scaled to 8-bits already.
 */

/* Function prototypes */
#ifdef __STDC__
#include <stddef.h>
#include <stdlib.h>
#endif

#define	SZ_BLOCK	16384

/* Types of coordinate and greyscale transformations. */
#define W_UNITARY       0               /* values map without change	*/
#define W_LINEAR        1               /* linear mapping		*/
#define W_LOG           2               /* logarithmic mapping		*/
#define W_USER          3               /* user transformation 		*/

/* Connection types. */
#define	UNIX		10
#define	INET		11
#define	FIFO		12

/* Default Values. */
#define	DEF_FBCONFIG	1		/* default frame buffer config 	*/
#define DEF_OSDEV_1     "unix:/tmp/.IMT%d"
#define DEF_OSDEV_2     "fifo:/dev/imt1i:/dev/imt1o"

/* Frame buffer configuration file definitions. */
#define FBCONFIG_1      ".imtoolrc"
#define FBCONFIG_2      "/usr/local/lib/imtoolrc"
#define FBCONFIG_ENV1   "imtoolrc"
#define FBCONFIG_ENV2   "IMTOOLRC"      
#define DEF_FRAME_WIDTH  512
#define DEF_FRAME_HEIGHT 512


int	imd_debug = 0;		/* deug flag	*/
char	buf[SZ_LINE];		/* temp buffer	*/


#ifdef ANSI_FUNC

static int imd_writeLine(IMDPtr imd, uchar *pix, int nbytes, int x, int y);
static int imd_readLine(IMDPtr imd, uchar *pix, int nbytes, int x, int y);
static IMDPtr imd_initialize(int fdin, int fdout, int domain);
static int imd_parseImtdev(char *imtdev, char *unixaddr, unsigned short *host_port, unsigned long *host_addr, char *ififo, char *ofifo);
static int imd_loadImtoolrc(IMDPtr imd);
static int imd_getstr(char **ipp, char *obuf, int maxch);
static void imd_minmax(uchar *pix, int nbytes, int *pmin, int *pmax);

#else

static  IMDPtr  imd_initialize();
static  int     imd_parseImtdev(), imd_loadImtoolrc(), imd_getstr();
static  int     imd_writeLine(), imd_readLine();
static  void    imd_minmax();

#endif


/*  IMD_OPEN -- Open a connection to the display server.  The caller may 
 *  either specify a connection at device open time, or the procedure will
 *  attempt to first connect on a unix socket or fifo pipe if that fails.
 *  The syntax for the imtdev argument is as follows:
 *
 *      	<domain> : <address>
 *
 *  where <domain> is one of "inet" (internet tcp/ip socket), "unix" (unix
 *  domain socket) or "fifo" (named pipe).  The form of the address depends
 *  upon the domain, as illustrated in the examples below.
 *
 *  inet:5137                   Server connection to port 5137 on the local
 *                              host.  For a client, a connection to the
 *                              given port on the local host.
 *
 *  inet:5137:foo.bar.edu       Client connection to port 5137 on internet
 *                              host foo.bar.edu.  The dotted form of address
 *                              may also be used.
 *
 *  unix:/tmp/.IMT212           Unix domain socket with the given pathname
 *                              IPC method, local host only.
 *
 *  fifo:/dev/imt1i:/dev/imt1o  FIFO or named pipe with the given pathname.
 *                              IPC method, local host only.  Two pathnames
 *                              are required, one for input and one for
 *                              output, since FIFOs are not bidirectional.
 *                              For a client the first fifo listed will be
 *                              the client's input fifo; for a server the
 *                              first fifo will be the server's output fifo.
 *                              This allows the same address to be used for
 *                              both the client and the server, as for the
 *                              other domains.
 *
 *  The address field may contain up to two "%d" fields.  If present, the
 *  user's UID will be substituted (e.g. "unix:/tmp/.IMT%d"). The default
 *  connection if no imtdev is specified is "unix:/tmp/.IMT%d", failing that,
 *  a connection is attempted on the /dev/imt1[io] named fifo pipes.
 */

#ifdef ANSI_FUNC

IMDPtr 
imd_open (
    char *imtdev		/* connection type 	*/
)
#else

IMDPtr
imd_open (imtdev)
char 	*imtdev;		/* connection type 	*/
#endif
{
	IMDPtr	imd;
	int	domain, fd, fdin, fdout, free_imtdev=0;
	unsigned short host_port;
	unsigned long  host_addr;
	char 	unixaddr[SZ_NAME];
	char 	input_fifo[SZ_NAME], output_fifo[SZ_NAME];

	if (imtdev == NULL) {
	    struct  sockaddr_un sockaddr;

	    /* Try first to connect on a unix socket. */
	    if ((fd = socket (AF_UNIX, SOCK_STREAM, 0)) < 0) {
		imtdev = DEF_OSDEV_2;
		if (imd_debug)
		    printf ("Can't get unix socket...\n");
		goto retry;
	    }

	    /* Compose network address. */
            bzero ((char *)&sockaddr, sizeof(sockaddr));
            sockaddr.sun_family = AF_UNIX;
            sprintf (sockaddr.sun_path, "/tmp/.IMT%d", (int)getuid());

	    if (connect(fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr))<0){
                close (fd);
		imtdev = DEF_OSDEV_2;
		if (imd_debug)
		    printf ("Can't connect to socket '%s'\n",sockaddr.sun_path);
	        goto retry;		/* no connection */
            } else {
		imtdev = (char *) malloc (SZ_IMTDEV);
		free_imtdev++;
		strcpy (imtdev, sockaddr.sun_path);
                fdin = fdout = fd;
	    }

	} else {
retry: 	    domain =  imd_parseImtdev (imtdev, unixaddr, &host_port, &host_addr,
		input_fifo, output_fifo);
	    switch (domain) {
	    case FIFO:
               /* Open the fifos. */
                if ((fdin = open (input_fifo, O_RDONLY|O_NDELAY)) != ERR)
                    fcntl (fdin, F_SETFL, O_RDONLY);
                if ((fdout = open (output_fifo, O_WRONLY|O_NDELAY)) != ERR)
                    fcntl (fdout, F_SETFL, O_WRONLY);

                /* Clean up if there is an error. */
                if (fdin < 0 || fdout < 0) {
		    (void) close (fdin);
		    (void) close (fdout);
		    if (imd_debug)
		        printf ("Can't connect to fifo '%s'\n",input_fifo);
                    goto err;
		}
                break;     

	    case UNIX:
		{   struct  sockaddr_un sockaddr;

	            /* Try first to connect on a unix socket. */
	            if ((fd = socket (AF_UNIX, SOCK_STREAM, 0)) < 0) {
			if (imd_debug)
		    	    printf ("Can't get unix socket...\n");
		        goto err;
		    }

	            /* Compose network address. */
                    bzero ((char *)&sockaddr, sizeof(sockaddr));
                    sockaddr.sun_family = AF_UNIX;
                    strcpy (sockaddr.sun_path, unixaddr);

	            if (connect(fd, (struct sockaddr *)&sockaddr, 
		        sizeof(sockaddr))<0){
                            close (fd);
			    if (imd_debug)
		    	        printf ("Can't connect to socket '%s'\n",
				    sockaddr.sun_path);
	                    goto err;		/* no connection */
                    } else
                        fdin = fdout = fd;
		}
		break;

	    case INET:
		{   struct  sockaddr_in sockaddr;

                    /* Get socket. */
                    if ((fd = socket (AF_INET, SOCK_STREAM, 0)) < 0) {
			if (imd_debug)
		    	    printf ("Can't get inet socket...\n");
                        goto err;
		    }

                    /* Compose network address. */
                    bzero ((char *)&sockaddr, sizeof(sockaddr));
                    sockaddr.sin_family = AF_INET;
                    sockaddr.sin_port = host_port;
                    bcopy ((char *)&host_addr, (char *)&sockaddr.sin_addr,
                        sizeof(host_addr));

                    /* Connect to server. */
                    if (connect (fd, (struct sockaddr *)&sockaddr, 
		        sizeof(sockaddr)) < 0) {
                            close (fd);
			    if (imd_debug)
		    	        printf ("Can't connect to socket '%s'\n",
				    (char *)sockaddr.sin_addr.s_addr);
                            goto err;
                    } else
                        fdin = fdout = fd;
		}
		break;

	    default:
		goto err;
	    } 
	}

	/* Allocate and initialize imd structure.  */
	imd = imd_initialize (fdin, fdout, domain);

	if (imd_debug)
	    fprintf (stderr, "Connection established on '%s'\n", imtdev);
	if (free_imtdev)
	    free ((char *)imtdev);
	return (imd);

err:
	fprintf (stderr, "Cannot open server connection on '%s'.\n", imtdev);
	if (free_imtdev)
	    free ((char *)imtdev);
	return NULL;
}


/* IMD_DISPLAYIMAGE --  Display an image to the server, setting the WCS and
 * frame as needed.  This is a high-level procedure used to make image
 * display easy.  It is assumed that the pixel array has already been scaled
 * to 8-bits.
 */

int
imd_displayImage (imd, pix, nx, ny, frame, fbconfig, comp_wcs)
IMDPtr	imd;			/* package pointer	  */
uchar 	*pix;			/* pixels to display	  */
int	nx, ny;			/* dimensions		  */
int	frame;			/* frame to display	  */
int	fbconfig;		/* fb config number	  */
int	comp_wcs;		/* compute a WCS	  */
{
	register uchar	*ip = pix;
	register uchar	*bp, *pp;
	register int i, nnx = nx, nny = ny;
	int	status, use_subras = 0;
	int	pmin, pmax, x_off = 0, y_off = 0, lx, ly;
	int	fbwidth  = imd->fbtab[fbconfig-1]->width;
	int	fbheight = imd->fbtab[fbconfig-1]->height;
	int	imd_writeImage();

	if (imd_debug)
	    printf ("[imd_displayImage] frame=%d fb=%d->[%d,%d] %dx%d bytes\n",
		frame, fbconfig, fbwidth, fbheight, nx, ny);

	imd_setFrame (imd, frame);			/* select frame	*/
	imd_clearFrame (imd);				/* erase frame	*/
	imd_setFBConfig (imd, fbconfig);		/* set fbconfig	*/

	/* Check to see if the image to be displayed is larger than the
	 * current frame buffer.  If so we'll need to pull out a subraster
	 * the size of the FB for display.
	 */
	if (nx > fbwidth || ny > fbheight) {
	    nnx = min(nx, fbwidth);		/* get new dimensions */
	    nny = min(ny, fbheight);
	    bp = ip = (uchar *) calloc (nnx * nny, sizeof (uchar));
	    use_subras++;

	    /* Pull out the subraster for display */
	    x_off =  (nx>fbwidth ? ((nx - fbwidth) / 2 - 1) : 0);
	    y_off =  (ny>fbheight ? ((ny - fbheight) / 2 - 1) : 0);
	    pp = pix + (y_off * nx) + x_off;
	    for (i=0; i < nny; i++) {
		bcopy (pp, bp, nnx);
		pp += nx;
		bp += nnx;
	    }
	}

	if (imd_debug)
	    printf("[imd_displayImage] nnx=%d nny=%d xo=%d yo=%d\n",
		nnx, nny, x_off, y_off);

	/* Compute a WCS for this image if it's not already defined. */
	if (comp_wcs) {
	    imd->a  =  1.0;
	    imd->b  =  0.0;
	    imd->c  =  0.0;
	    imd->d  = -1.0;
	    imd->tx = (float) (nnx / 2) - (fbwidth / 2) + 1;
	    imd->ty = (float) (fbheight / 2) + (nny / 2);
	    if (x_off)
	        imd->tx += (float) x_off;
	    if (y_off)
	        imd->ty += (float) y_off;
	    if (imd->name == (char *)NULL)
                imd->name  = (char *) calloc (SZ_NAME, sizeof(char));
	    if (imd->title == (char *)NULL)
                imd->title = (char *) calloc (SZ_NAME, sizeof(char));
	    if (imd->z1 == INDEF || imd->z2 == INDEF)
	        imd_minmax (pix, nnx*nny, &pmin, &pmax);
	    if (imd->z1 == INDEF)
	        imd->z1 = (float) pmin;
	    if (imd->z2 == INDEF)
	        imd->z2 = (float) pmax;
	    imd->ztrans = W_LINEAR;
	    if (imd_setWCS (imd, imd->name, imd->title, imd->a, imd->b, imd->c,
		imd->d, imd->tx, imd->ty, imd->z1, imd->z2, imd->ztrans))
	            return (ERR);
	}

	/* Finally, display the image. Compute the placement is user coords.
	 */
	lx = (fbwidth / 2) - (nnx / 2);
	ly = fbheight - ((fbheight / 2) + (nny / 2));
	status = imd_writeImage (imd, ip, nnx, nny, lx, ly);

	if (use_subras)
	    free ((char *)ip);
	return (status);
}


/* IMD_READCURSOR -- Read the current cursor position.  If sample is defined
 * logical cursor position will be sampled and returned immediately, otherwise
 * the server will block until a key is hit and we return that value as well.
 */

#ifdef ANSI_FUNC

int 
imd_readCursor (
    IMDPtr imd,			/* package pointer	*/
    int sample,			/* wait for keystroke?	*/
    float *x,
    float *y,			/* position		*/
    int *wcs,			/* WCS			*/
    char *key			/* keystroke		*/
)
#else

int
imd_readCursor (imd, sample, x, y, wcs, key)
IMDPtr	imd;			/* package pointer	*/
int	sample;			/* wait for keystroke?	*/
float	*x, *y;			/* position		*/
int 	*wcs;			/* WCS			*/
char	*key;			/* keystroke		*/
#endif
{
	if (imd_debug)
	    printf ("[imd_readCursor]\n");

	return (com_readCursor(imd->datain, imd->dataout, 
	    sample, x, y, wcs, key));
}


/* IMD_SETWCS -- Set the WCS of the screen.  The WCS is passed in a string
 * defined as:
 *      	Image_Name_String\n a b c d tx ty z1 z2 zt
 * where:
 *              X' = a*X + c*Y + tx
 *              Y' = b*X + d*Y + ty
 *
 * z1 is the minimum pixel value, z2 is the maximum pixel value,  zt
 * defines the type of transformation to use.
 */

#ifdef ANSI_FUNC

int 
imd_setWCS (
    IMDPtr imd,			/* package pointer	*/
    char *name,			/* name string		*/
    char *title,			/* title string		*/
    float a,
    float b,
    float c,
    float d,		/* WCS values		*/
    float tx,
    float ty,			/* translation		*/
    float z1,
    float z2,			/* zscale values	*/
    int zt			/* transformation type	*/
)
#else

int
imd_setWCS (imd, name, title, a, b, c, d, tx, ty, z1, z2, zt)
IMDPtr	imd;			/* package pointer	*/
char	*name;			/* name string		*/
char	*title;			/* title string		*/
float	a, b, c, d;		/* WCS values		*/
float	tx, ty;			/* translation		*/
float	z1, z2;			/* zscale values	*/
int	zt;			/* transformation type	*/
#endif
{
	if (imd_debug) {
	    printf ("[imd_setWCS] name='%s' title='%s'\n", name, title);
	    printf ("\ta=%g b=%g c=%g d=%g tx=%g ty=%g z1=%g z2=%g zt=%d\n", 
		a, b, c, d, tx, ty, z1, z2, zt);
	}

	sprintf (buf, "%s%s%s", (name ? name : " "), (title ? " - " : " "),
	    (title ? title : " "));
	return(com_writeWCS(imd->dataout, buf, a, b, c, d, tx, ty, z1, z2, zt));
}


/* IMD_GETWCS -- Get the current display frame WCS information.
 */

#ifdef ANSI_FUNC

int 
imd_getWCS (
    IMDPtr imd,			/* package pointer	*/
    char *name,			/* name string		*/
    char *title,			/* title string		*/
    float *a,
    float *b,
    float *c,
    float *d,		/* WCS values		*/
    float *tx,
    float *ty,		/* translation		*/
    float *z1,
    float *z2,		/* zscale values	*/
    int *zt			/* transformation type	*/
)
#else

int
imd_getWCS (imd, name, title, a, b, c, d, tx, ty, z1, z2, zt)
IMDPtr	imd;			/* package pointer	*/
char	*name;			/* name string		*/
char	*title;			/* title string		*/
float	*a, *b, *c, *d;		/* WCS values		*/
float	*tx, *ty;		/* translation		*/
float	*z1, *z2;		/* zscale values	*/
int	*zt;			/* transformation type	*/
#endif
{
	if (com_readWCS(imd->datain, imd->dataout, buf, a, b, c, d, tx, ty,
	    z1, z2, zt))
	        return (ERR);

	name[0] = title[0] = '\0';
	sscanf (buf, "%s - %s", name, title);

	if (imd_debug) {
	    printf ("[imd_getWCS] name='%s' title='%s'\n", name, title);
	    printf ("\ta=%g b=%g c=%g d=%g tx=%g ty=%g z1=%g z2=%g zt=%d\n", 
		*a, *b, *c, *d, *tx, *ty, *z1, *z2, *zt);
	}
 
	return (OK);
}


/* IMD_CLOSE -- Close the connection to the display server.
 */

#ifdef ANSI_FUNC

int 
imd_close (
    IMDPtr imd			/* package pointer	*/
)
#else

int
imd_close (imd)
IMDPtr	imd;			/* package pointer	*/
#endif
{
	if (imd_debug)
	    printf ("[imd_close]\n");

	if (imd) {
	    register int i;

	    /* Close the connection. */
	    if (imd->datain)
		close (imd->datain);
	    if (imd->dataout)
		close (imd->dataout);

	    /* Free the frame buffer configuration table. */
            for (i=0;  i < MAX_FBCONFIG;  i++)
	        free ((char *)imd->fbtab[i]);

	    /* Free the pointers in the imd structure. */
	    free (imd->title);
	    free (imd->name);
	    free (imd);
	}

	return (OK);
}


/* --------------------
 * Low-Level Procedures
 * --------------------*/

/* IMD_WRITEIMAGE -- Display a raw pixel array to the server given the array
 * dimensions, and a location.  We use this instead of imd_writeSubRaster()
 * since we can assume the frame is blank and we wish to avoid the overhead
 * having to read back the frame buffer.  The image corner position is given
 * in user coords where the [0,0] origin is in the LL of the display window,
 * we convert this to frame buffer coords where the origin is in the UL.
 */

int
imd_writeImage (imd, pix, nx, ny, llx, lly)
IMDPtr	imd;			/* package pointer	 */
uchar 	*pix;			/* pixels to display	 */
int	nx, ny;			/* dimensions		 */
int	llx, lly;		/* LL corner of image    */
{
	register int i, j, k, y, nbytes, nl = ny, imline;
	register int nnx = nx, nny = ny, block_has_data = 0;
	register uchar *ip = pix;
	register uchar *bp, *block, *ep;
	register int lx, ly, nblocks, lines_per_block, fbline;
	int	 x_off = 0, y_off = 0;
	int	 fbwidth  = imd->fbtab[imd->fbconfig-1]->width;
	int	 fbheight = imd->fbtab[imd->fbconfig-1]->height;


        /* Check to see if the image to be displayed is larger than the
         * current frame buffer.
         */
        if (nx > fbwidth || ny > fbheight) {
            nnx = min(nx, fbwidth);             /* get new dimensions */
            nny = min(ny, fbheight);
            x_off =  (nx>fbwidth ? ((nx - fbwidth) / 2 - 1) : 0);
            y_off =  (ny>fbheight ? ((ny - fbheight) / 2 - 1) : 0);
        }

	/* Now see whether the image extends over the boundaries of the
  	 * frame buffer in any direction.  If so we'll set up to write 
	 * only those pixels on the frame buffer.
	 */
	if (llx < 0) {			/* image is left of frame 	  */
            x_off = -llx;
	    nnx = nx + llx;
	}
	if (lly < 0) {			/* image is below frame 	  */
            y_off = -lly;
	    nny = ny + lly;
	}
	if ((llx + nx) > fbwidth) 	/* image overflows frame to right */
	    nnx = fbwidth - llx;
	if ((lly + ny) > fbheight) 	/* image overflows frame at top   */
	    nny = fbheight - lly;
	ip = pix + (y_off * nx) + x_off;

	/* Convert corner position to frame buffer coords. */
	lx = max (0, llx);
	ly = min (fbheight - 1, fbheight - lly - 1);

	/* Compute the corner points in user units. */
	imd->xs = llx;
	imd->xe = llx + nnx - 1;
	imd->ys = lly;
	imd->ye = lly + nny - 1;

	if (imd_debug) {
	    printf("[imd_writeImage] %dx%d bytes at [%d,%d] of [%d,%d]\n", 
		nx, ny, lx, ly, fbwidth, fbheight);
	    printf("[imd_writeImage] Xends = [%d,%d]  Yends = [%d,%d]\n",
		imd->xs, imd->xe, imd->ys, imd->ye);
	    printf("[imd_writeImage] nnx=%d nny=%d llx=%d lly=%d xo=%d yo=%d\n",
                nnx, nny, llx, lly, x_off, y_off);
	    imd_debug = 1;
	}

	/* Display image. */
	lines_per_block = (int) (SZ_BLOCK / fbwidth);
	nblocks = (int) (fbheight / lines_per_block);
	nbytes = fbwidth * lines_per_block;
	block = (uchar *) calloc (nbytes, sizeof (uchar));

	if (imd_debug) {
	    printf ("height=%d nblocks=%d lines/block=%d\n", 
	        fbheight, nblocks, lines_per_block);
	}

	/* For each of the blocks we're sending.... */
	fbline = fbheight - 1;
	imline = ly;
	ep = ip + nx * ny;
	for (i=0, y = fbheight - lines_per_block; i < nblocks; i++) {
	    bp = block + (lines_per_block - 1) * fbwidth;
	    block_has_data = 0;

	    if (nnx != fbwidth || nny != fbheight)
	        /* Clear the block array */
		for (k=0; k < nbytes; k++)
		    block[k] = 0;

	    /* Map image pixels to the data block. */
	    for (j=0; j < lines_per_block && nl >= 0; j++) {
	        if (fbline == imline && ip < ep) {
		    block_has_data = 1;
		    bcopy (ip, bp+lx, nnx);
		    ip += nx;
		    imline--;
		    nl--;
		} 
		bp -= fbwidth;
	        fbline--;
	    }

	    if (block_has_data)
	        if (imd_writeLine(imd, block, nbytes, 0, y))
	            return (ERR);
	    y -= lines_per_block;
	}

	/* Now take care of any remaining pixels in the frame buffer. */
	nbytes = (fbwidth * fbheight) - (nblocks * nbytes);
        if (nbytes && nl >= 0) {
	    lines_per_block = nbytes / fbwidth;
            bp = block + (lines_per_block - 1) * fbwidth;

            if (nnx != fbwidth || nny != fbheight) {
                /* Clear the block array */
                for (k=0; k < nbytes; k++)
                    block[k] = 0;
            }

            /* Map image pixels to the data block. */
	    if (nl >= 0) {
                for (j=0; j < lines_per_block && nl >= 0; j++) {
                    if (fbline == imline) {
                        bcopy (ip, bp+lx, nnx);
                        ip += nx;
                        imline--;
                        nl--;
                    }
                    bp -= fbwidth;
                    fbline--;
                }
                if (imd_writeLine(imd, block, nbytes, 0, 0))
                    return (ERR);  
            }
        }

	free ((char *)block);
	return (OK);
}


/* IMD_READIMAGE -- Read the currently displayed image and return a pointer to
 * the array and it's dimensions.  Since we know where the image was written
 * in the frame buffer this is really just a large subregion read.
 */

int
imd_readImage (imd, pix, nx, ny)
IMDPtr	imd;			/* package pointer	*/
uchar	*pix;			/* image pixels (output)*/
int	*nx, *ny;		/* dimensions (output) 	*/
{
	*nx = (imd->xe - imd->xs + 1);
	*ny = (imd->ye - imd->ys + 1);

	if (imd_debug)
	    printf ("[imd_readImage]  nx=%d ny=%d at [%d,%d]\n",
		*nx, *ny, imd->xs, imd->ys);

        /* Read the image region buffer. */
	if (!pix)
	    pix = (uchar *) malloc ((*nx) * (*ny));
	return (imd_readSubRaster(imd, imd->xs, imd->ys, *nx, *ny, pix));
}


/* IMD_READFRAMEBUFFER -- Read the contents of the entire frame buffer and
 * return a pointer to the array and it's dimensions. 
 */

int
imd_readFrameBuffer (imd, pix, nx, ny)
IMDPtr	imd;			/* package pointer	*/
uchar	*pix;			/* image pixels (output)*/
int	*nx, *ny;		/* dimensions (output) 	*/
{
	if (imd_debug)
	    printf ("[imd_readFrameBuffer]\n");

	*nx = imd->fbtab[imd->fbconfig-1]->width;
	*ny = imd->fbtab[imd->fbconfig-1]->height;

	if (imd_debug)
	    printf ("[imd_readFrameBuffer]  nx=%d ny=%d at [%d,%d]\n",
		*nx, *ny, 0, 0);

        /* Read the frame buffer. */
	if (!pix)
	    pix = (uchar *) malloc ((*nx) * (*ny));
	return (imd_readSubRaster(imd, 0, 0, *nx, *ny, pix));
}


/* IMD_SETFRAME -- Set the current display frame.
 */

#ifdef ANSI_FUNC

int 
imd_setFrame (
    IMDPtr imd,			/* package pointer	*/
    int frame			/* frame number		*/
)
#else

int
imd_setFrame (imd, frame)
IMDPtr	imd;			/* package pointer	*/
int	frame;			/* frame number		*/
#endif
{
	if (imd_debug)
	    printf ("[imd_setFrame] frame = %d\n", frame);

	imd->frame = frame;
	return (com_setFrame (imd->dataout, imd->frame));
}


/* IMD_SETFBCONFIG -- Select the frame buffer configuration.
 */

#ifdef ANSI_FUNC

int 
imd_setFBConfig (
    IMDPtr imd,			/* package pointer	*/
    int configno		/* frame config number	*/
)
#else

int
imd_setFBConfig (imd, configno)
IMDPtr	imd;			/* package pointer	*/
int	configno;		/* frame config number	*/
#endif
{
	if (imd_debug)
	    printf ("[imd_setFBConfig] config = %d\n", configno);

	imd->fbconfig  = configno;
	return (com_setFBConfig (imd->dataout, imd->fbconfig));
}


/* IMD_GETFBCONFIG -- Get the current frame buffer config info used by the
 * the interface.
 */

#ifdef ANSI_FUNC

int 
imd_getFBConfig (
    IMDPtr imd,			/* package pointer	*/
    int *configno,		/* frame config number	*/
    int *width,
    int *height,	/* frame buffer size	*/
    int *nframes		/* number of frames	*/
)
#else

int
imd_getFBConfig (imd, configno, width, height, nframes)
IMDPtr	imd;			/* package pointer	*/
int	*configno;		/* frame config number	*/
int	*width, *height;	/* frame buffer size	*/
int	*nframes;		/* number of frames	*/
#endif
{
	*configno = imd->fbconfig;
	*width    = imd->fbtab[imd->fbconfig-1]->width;
	*height   = imd->fbtab[imd->fbconfig-1]->height;
	*nframes  = imd->fbtab[imd->fbconfig-1]->nframes;
	if (imd_debug)
	    printf ("[imd_getFBConfig] config=%d w=%d h=%d nf=%d\n",
		*configno, *width, *height, *nframes);

	return (com_setFBConfig (imd->dataout, imd->fbconfig));
}


/* IMD_SETNAME -- Set the current image name (for the WCS string);
 */

#ifdef ANSI_FUNC

int 
imd_setName (
    IMDPtr imd,			/* package pointer	*/
    char *name			/* image name		*/
)
#else

int
imd_setName (imd, name)
IMDPtr	imd;			/* package pointer	*/
char	*name;			/* image name		*/
#endif
{
	if (imd_debug)
	    printf ("[imd_setName] Name = %s\n", name);

	strcpy (imd->name, name);
	return (OK); 
}


/* IMD_SETTITLE -- Set the current image title (for the WCS string)
 */

#ifdef ANSI_FUNC

int 
imd_setTitle (
    IMDPtr imd,			/* package pointer	*/
    char *title			/* image title		*/
)
#else

int
imd_setTitle (imd, title)
IMDPtr	imd;			/* package pointer	*/
char	*title;			/* image title		*/
#endif
{
	if (imd_debug)
	    printf ("[imd_setTitle] title = %s\n", title);

	strcpy (imd->title, title);
	return (OK); 
}


/* IMD_SETCURSOR -- Set the image cursor position.
 */

#ifdef ANSI_FUNC

int 
imd_setCursor (
    IMDPtr imd,			/* package pointer	*/
    int x,
    int y,			/* position		*/
    int wcs			/* cursor wcs		*/
)
#else

int
imd_setCursor (imd, x, y, wcs)
IMDPtr	imd;			/* package pointer	*/
int	x, y;			/* position		*/
int	wcs;			/* cursor wcs		*/
#endif
{
	if (imd_debug)
	    printf ("[imd_setCursor] position = [%d,%d]\n", x, y);

	/* need to convert to frame coords? */

	return (com_setCursor(imd->dataout, x, y, wcs));
}


/* IMD_CLEARFRAME -- Clear the current display frame.
 */

#ifdef ANSI_FUNC

int 
imd_clearFrame (
    IMDPtr imd			/* package pointer	*/
)
#else

int
imd_clearFrame (imd)
IMDPtr	imd;			/* package pointer	*/
#endif
{
	if (imd_debug)
	    printf ("[imd_eraseFrame]\n");

	return (com_eraseFrame(imd->dataout));
}


/* IMD_READSUBRASTER -- Read a rectangular region of the frame buffer.
 */

int
imd_readSubRaster (imd, llx, lly, nx, ny, pix)
IMDPtr	imd;			/* package pointer	*/
int	llx, lly;		/* region corner  	*/
int	nx, ny;			/* dimensions  		*/
uchar	*pix;			/* image pixels (output)*/
{
	register int i, j, nl, y, nbytes, lx, ly;
	register uchar *ip = NULL, *bp = NULL, *block = NULL;
	register int nblocks, lines_per_block;
	register int nnx = nx, nny = ny, x_off = 0, y_off = 0;
	int	fbwidth  = imd->fbtab[imd->fbconfig-1]->width;
	int	fbheight = imd->fbtab[imd->fbconfig-1]->height;


	/* Make sure we've got a reasonable request. */
	if (nx > fbwidth || ny > fbheight) {
	    fprintf (stderr,
		"Error: attempt to read raster larger than display.\n");
	    return (ERR);
	}

        /* Now see whether the raster extends over the boundaries of the
         * frame buffer in any direction.  If so we'll clip the raster to
         * write only those pixels on the frame buffer.
         */

        if (-llx > imd->xs) {		/* raster overflows bottom */
            x_off = -llx + imd->xs;
            nnx = nx - x_off;
        }
        if (-lly > imd->ys) {		/* raster overflows left   */
            y_off = -lly + imd->ys;
            nny = ny - y_off;
        }
        if ((llx + nx) > fbwidth) {      /* raster overflows right */
            nnx = fbwidth - llx;
	}
        if ((lly + ny) > fbheight) {     /* raster overflows top   */
            nny = fbheight - lly;
	    /*y_off = ny - nny;*/
	}

	/* Allocate the pointer if needed.  Clear the output array if we're
	 * clipping to guarantee zero values.
	 */
	if (!pix)
	    pix = (uchar *) calloc (nx * ny, sizeof (uchar));

        /* Convert corner position to frame buffer coords. */
	lx = max (0, llx + imd->xs);
	ly = min (fbheight - 1, fbheight - (lly + imd->ys) - 0);

	if (imd_debug) {
	    printf ("[imd_readSubRas] %d bytes at [%d,%d] orig [%d,%d]\n", 
		nx*ny, lx, ly, llx, lly);
	    printf ("[imd_readSubRas] img corner at [%d,%d] -> [%d,%d]\n",
		imd->xs, imd->ys, imd->xe, imd->ye);
	}

	/* Figure out how many reads we'll need. */
	lines_per_block = min (nny, (int)(SZ_BLOCK / fbwidth));
	nbytes = fbwidth * lines_per_block;
	nblocks = (int) (nny / lines_per_block);
	block = (uchar *) calloc (nbytes, sizeof (uchar));

	if (imd_debug) {
	    printf("[imd_readSubRas] ny=%d nblks=%d lin/bl=%d nbytes=%d\n", 
	        ny, nblocks, lines_per_block, nbytes);
            printf("[imd_readSubRas] nnx=%d nny=%d llx=%d lly=%d xo=%d yo=%d\n",
                nnx, nny, llx, lly, x_off, y_off);
	}


	/* Loop over each of the blocks needed to get the region.  */
	nl = nny;
	ip = pix + (y_off * nx) + x_off;
	y = ly - lines_per_block + 1;
	for (i=0; i < nblocks; i++, y -= lines_per_block) {
	    if (imd_readLine(imd, block, nbytes, 0, y))
		return (ERR);

	    /* Pull the requested pixels from the block.  */
	    bp = block + (lines_per_block - 1) * fbwidth;
	    for (j=0; j < lines_per_block && nl; j++) {
		/*bcopy (bp+lx+x_off-1, ip, nnx);*/
		bcopy (bp+lx, ip, nnx);
		bp -= fbwidth;
		ip += nx;
		nl--;
	    }
	}

	/* Take care of the remaining pixels. */
	if (nl) {
	    nbytes = nl * fbwidth;
	    y += lines_per_block - nl + 1;

	    /* Read the last block. */
	    if (imd_readLine(imd, block, nbytes, 0, y))
	        return (ERR);

	    /* Pull the requested pixels from the block.  */
	    bp = block + (nl - 1) * fbwidth;
	    for (j=0; j < nl; j++) {
		/*bcopy (bp+lx+x_off-1, ip, nx);*/
		bcopy (bp+lx, ip, nnx);
		bp -= fbwidth;
		ip += nx;
	    }
	}

	free ((char *)block);
	return (OK);
}


/* IMD_WRITESUBRASTER -- Write a rectangular region of the frame buffer.
 */

int
imd_writeSubRaster (imd, llx, lly, nx, ny, pix)
IMDPtr	imd;			/* package pointer	*/
int	llx, lly;		/* region corner  	*/
int	nx, ny;			/* dimensions  		*/
uchar	*pix;			/* subraster pixels 	*/
{
        register int i, j, nl, y, nbytes, lx, ly;
        register uchar *ip = NULL, *bp = NULL, *block = NULL;
        register int nblocks, lines_per_block;
	register int nnx = nx, nny = ny, x_off = 0, y_off = 0;
        int     fbwidth  = imd->fbtab[imd->fbconfig-1]->width;
        int     fbheight = imd->fbtab[imd->fbconfig-1]->height;


	/* Make sure at least part of the raster is on the frame buffer,
	 * otherwise it's an error.
	 */
	if (llx > fbwidth || lly > fbheight || (llx+nx) < 0 || (lly+ny) < 0) {
	    fprintf (stderr, "Error: attempt to write raster out of bounds.\n");
	    return (ERR);
	}

        /* Now see whether the raster extends over the boundaries of the
         * frame buffer in any direction.  If so we'll clip the raster to
	 * write only those pixels on the frame buffer.
         */
        if (-llx > imd->xs) {		/* raster overflows bottom */
            x_off = -llx + imd->xs;
            nnx = nx - x_off;
        }
        if (-lly > imd->ys) {		/* raster overflows left   */
            y_off = -lly + imd->ys;
            nny = ny - y_off;
        }
        if ((llx + nx) > fbwidth)       /* raster overflows right  */
            nnx = fbwidth - llx;
        if ((lly + ny) > fbheight)      /* raster overflows top    */
            nny = fbheight - lly;

        /* Check to see if the image to be displayed is larger than the
         * current frame buffer.
         */
        if (nx > fbwidth || ny > fbheight) {
            nnx = min(nx, fbwidth);             /* get new dimensions */
            nny = min(ny, fbheight);
            x_off =  (nx>fbwidth ? ((nx - fbwidth) / 2 - 1) : 0);
            y_off =  (ny>fbheight ? ((ny - fbheight) / 2 - 1) : 0);
        }

        ip = pix + (y_off * nx) + x_off;

        /* Convert corner position to frame buffer coords. */
        lx = max (0, llx + imd->xs);
        ly = min (fbheight - 1, fbheight - (lly + imd->ys) - 0);

        if (imd_debug)
            printf ("[imd_writeSubRaster] %d bytes at [%d,%d] of [%d,%d]\n",
                nx*ny, lx, ly, fbwidth, fbheight);

        /* Figure out how many reads we'll need. */
        lines_per_block = min (nny, (int)(SZ_BLOCK / fbwidth));
        nbytes = fbwidth * lines_per_block;
        nblocks = (int) (nny / lines_per_block);
        block = (uchar *) calloc (nbytes, sizeof (uchar));

        if (imd_debug) {
	    printf ("\tnnx=%d nny=%d llx=%d lly=%d xo=%d yo=%d xs=%d ys=%d\n",
		nnx, nny, llx, lly, x_off, y_off, imd->xs, imd->ys);
            printf ("\tny=%d nblocks=%d lines/block=%d nbytes=%d\n",
                ny, nblocks, lines_per_block, nbytes);
        }

        /* Loop over each of the blocks needed to get the region. */
        nl = nny;
        y = ly - lines_per_block + 1;
        for (i=0; i < nblocks; i++, y -= lines_per_block) {
            /* Read a block of data containing the subraster but only if 
	     * we need to.
	     */
	    if (nnx != fbwidth)
                if (imd_readLine(imd, block, nbytes, 0, y))
                    return (ERR);

            /* Copy the subraster pixels to the block just read. */
            bp = block + (lines_per_block - 1) * fbwidth;
            for (j=0; j < lines_per_block && nl; j++) {
                bcopy (ip, bp+lx, nnx);
                bp -= fbwidth;
                ip += nx;
                nl--;
            }

            /* Write the edited block back to the server. */
            if (imd_writeLine(imd, block, nbytes, 0, y))
                return (ERR);
        }

        /* Take care of the remaining pixels. */
        if (nl) {
            nbytes = nl * fbwidth;

            /* Read the last block. */
	    y += lines_per_block - nl + 1;
	    if (nnx != fbwidth)
                if (imd_readLine(imd, block, nbytes, 0, y))
                    return (ERR);

            /* Copy the subraster pixels to the block just read. */
            bp = block + (nl - 1) * fbwidth;
            for (j=0; j < nl; j++) {
                bcopy (ip, bp+lx, nnx);
                bp -= fbwidth;
                ip += nx;
            }

            /* Write the edited block back to the server. */
            if (imd_writeLine(imd, block, nbytes, 0, y))
                return (ERR);
        }

        free ((char *)block);
	return (OK);
}


/* IMD_SETDEBUG -- Set the state of the debug flag.
 */

#ifdef ANSI_FUNC

int 
imd_setDebug (int state)
#else

int
imd_setDebug (state)
int	state;
#endif
{
	imd_debug = state;
	return (OK);
}



/* ------------------
 * PRIVATE PROCEDURES
 * ------------------*/

/* IMD_WRITELINE --  Send the command to write a block of pixels to the
 * server.  This is a low-level routine called to either write a single
 * line of data, or when the number of bytes exceeds the frame buffer width
 * it can be used to send a complete "block" in the image display.
 */

static int
imd_writeLine (imd, pix, nbytes, x, y)
IMDPtr	imd;				/* package pointer	*/
uchar	*pix;				/* pixel array		*/
int	nbytes;				/* npix to write	*/
int	x, y;				/* coords for start	*/
{
	register short sx=x, sy=y;

	if (imd_debug > 1)
	    printf ("[imd_writeLine] %d bytes at [%d,%d]\n", nbytes, x, y);

	return (com_writeData(imd->dataout, sx, sy, pix, nbytes));
}


/* IMD_READLINE --  Send the command to read a sequential block of pixels
 * from the server. 
 */

static int
imd_readLine (imd, pix, nbytes, x, y)
IMDPtr	imd;				/* package pointer	*/
uchar	*pix;				/* pixel array		*/
int	nbytes;				/* npix to write	*/
int	x, y;				/* coords for start	*/
{
	register short sx=x, sy=y;

	if (imd_debug)
	    printf ("[imd_readLine] %d bytes at [%d,%d]\n", nbytes, x, y);

	return (com_readData(imd->datain, imd->dataout, sx, sy, pix, &nbytes));
}


/* IMD_INITIALIZE -- Allocate and initialize the imd package structure.
 */

#ifdef ANSI_FUNC

static IMDPtr 
imd_initialize (
    int fdin,
    int fdout,			/* device descriptors  	*/
    int domain				/* connection type	*/
)
#else

static IMDPtr
imd_initialize (fdin, fdout, domain)
int	fdin, fdout;			/* device descriptors  	*/
int	domain;				/* connection type	*/
#endif
{
	IMDPtr	imd;

        /* Allocate and initialize imd structure. */
        imd = (struct IMD *) calloc (1, sizeof (struct IMD));
        imd->datain   = fdin;
        imd->dataout  = fdout;
        imd->domain   = domain;
        imd->ztrans   = W_LINEAR;
        imd->frame    = 1;
        imd->fbconfig = 1;

        /* Initialize a WCS. */
        imd->a  = 1.0;                  
        imd->b  = 0.0;
        imd->c  = 0.0;
        imd->d  = -1.0;
        imd->tx = 1.0;                  /* default for 512x512 fb */
        imd->ty = 512.0;                /* default for 512x512 fb */
        imd->z1 = 0.0;
        imd->z2 = 255.0;

        imd->name  = (char *) calloc (SZ_NAME, sizeof(char));
        imd->title = (char *) calloc (SZ_NAME, sizeof(char));

        /* Load the frame buffer configuration file. */
        imd_loadImtoolrc (imd);

	return (imd);
}


/* IMD_PARSEIMTDEV -- Parse an IMTDEV device string, returning the domain
 * type as the function value and loading the path/host information as
 * needed.
 */

#ifdef ANSI_FUNC

static int 
imd_parseImtdev (
    char *imtdev,		/* device string     */
    char *unixaddr,		/* unix socket path  */
    unsigned short *host_port,		/* inet port number  */
    unsigned long *host_addr,		/* inet host address */
    char *ififo,
    char *ofifo		/* fifo paths	     */
)
#else

static int
imd_parseImtdev (imtdev, unixaddr, host_port, host_addr, ififo, ofifo)
char		*imtdev;		/* device string     */
char		*unixaddr;		/* unix socket path  */
unsigned short	*host_port;		/* inet port number  */
unsigned long	*host_addr;		/* inet host address */
char		*ififo, *ofifo;		/* fifo paths	     */
#endif
{
	char	*ip;
	char	osfn[SZ_LINE*2];

	if (imtdev == NULL)
	    return ERR;
	else {
            /* Expand any %d fields in the network address to the UID. */
            sprintf (osfn, (char *)imtdev, getuid(), getuid());
 
	    if (strncmp (osfn, "fifo:", 5) == 0) {
                /* FIFO (named pipe) connection.  */
                ip = osfn + 5;
                if (!imd_getstr (&ip, ififo, SZ_NAME))
                    return ERR;
                if (!imd_getstr (&ip, ofifo, SZ_NAME))
                    return ERR;

		return FIFO;

	    } else if (strncmp (osfn, "inet:", 5) == 0) {

                /* Internet connection.  */
                char port_str[SZ_NAME], host_str[SZ_NAME];
                unsigned short port;
                struct servent *sv;
                struct hostent *hp;

                /* Get port number.  This may be specified either as a service
                 * name or as a decimal port number.
                 */
                ip = osfn + 5;
                if (imd_getstr (&ip, port_str, SZ_NAME) <= 0)
                    return ERR;
                if (isdigit (port_str[0])) {
                    port = atoi (port_str);
                    *host_port = htons (port);
                } else if ((sv = getservbyname(port_str,"tcp"))) {
                    *host_port = sv->s_port;
                } else
                    return ERR;

                /* Get host address.  This may be specified either has a host
                 * name or as an Internet address in dot notation.  If no host
                 * name is specified default to the local host.
                 */
                if (imd_getstr (&ip, host_str, SZ_NAME) <= 0)
                    strcpy (host_str, "localhost");
                if (isdigit (host_str[0])) {
                    *host_addr = inet_addr (host_str);
                    if ((int)*host_addr == -1)
                        return ERR;
                } else if ((hp = gethostbyname(host_str))) {
                    bcopy (hp->h_addr, (char *)host_addr, sizeof(*host_addr));
                } else
                    return ERR;

		return INET;

	    } else if (strncmp (osfn, "unix:", 5) == 0) {
                /* Unix domain socket connection.  */
                ip = osfn + 5;
                if (!imd_getstr (&ip, unixaddr, SZ_NAME))
                    return ERR;

		return UNIX;
	    }
	}
	return (ERR);
}


/* IMD_LOADIMTOOLRC -- Load the frame buffer configuration table into a
 * runtime table.  An error is returned if the table cannot be found and
 * a default frame buffer size of 512x512 with 2 frames is available (this
 * is all the server will have abvailable anyway).
 */

#ifdef ANSI_FUNC

static int 
imd_loadImtoolrc (
    IMDPtr imd			/* package pointer	*/
)
#else

static int
imd_loadImtoolrc (imd)
IMDPtr	imd;			/* package pointer	*/
#endif
{
        register char   *ip;
        register FILE   *fp = NULL;
        int     config, nframes, width, height, i;
        char    *fname;
#ifndef __STDC__
	char	*getenv();
#endif

        /* Initialize the config table. */
        for (i=0;  i < MAX_FBCONFIG;  i++) {
	    imd->fbtab[i] = (FBTab *) malloc (sizeof (FBTab));
            imd->fbtab[i]->config  = i;
            imd->fbtab[i]->nframes = 2;
            imd->fbtab[i]->width   = DEF_FRAME_WIDTH;
            imd->fbtab[i]->height  = DEF_FRAME_HEIGHT;
        }

        /* Attempt to open the config file. */
        if ((fname=getenv(FBCONFIG_ENV1)) || (fname=getenv(FBCONFIG_ENV2))) {
            fp = fopen (fname, "r");
	    if (imd_debug)
	        printf ("Using IMTOOLRC='%s'...\n", fname);
	}
        if (!fp && (fname = getenv ("HOME"))) {
	    if (imd_debug)
	        printf ("$IMTOOLRC not found...\n");
            sprintf (buf, "%s/%s", fname, FBCONFIG_1);
            fp = fopen (fname = buf, "r");
	    if (fp && imd_debug)
	        printf ("Using $HOME/.imtoolrc...\n");
	}
        if (!fp) {
	    if (imd_debug)
	        printf ("$HOME/.imtoolrc not found...\n");
            fp = fopen ((fname = FBCONFIG_2), "r");
	    if (fp && imd_debug)
	        printf ("Using /usr/local/lib/imtoolrc...\n");
	}
        if (!fp) {
            fprintf (stderr, 
		"Warning: cannot find frame buffer configuration table.\n");
            return (ERR);
	}
   
        /* Scan the frame buffer configuration file.
         */
        while (fgets (buf, SZ_LINE, fp) != NULL) {
            /* Skip comment lines and blank lines. */
            for (ip=buf;  *ip == ' ' || *ip == '\t';  ip++)
                ;
            if (*ip == '\n' || *ip == '#')
                continue;
            if (!isdigit (*ip))
                continue;
            switch (sscanf (ip, "%d%d%d%d",&config,&nframes,&width,&height)) {
            case 4:
                break;                  /* normal case */
            case 3:
                height = width;         /* default to square format */
                break;
            default:
                fprintf (stderr, "Warning: bad config `%s'\n", ip);
                continue;
            }

            nframes = max (1, nframes);
            width   = max (1, width);
            height  = max (1, height);

            /* Since the frame buffer is stored in a memory pixrect
             * (effectively), the line length should be an integral number
             * of 16 bit words.
             */
            if (width & 1) {
                fprintf (stderr, "Warning: fb config %d [%d-%dx%d] - ",
                    config, nframes, width, height);
                fprintf (stderr, "frame width should be even, reset to %d\n",
                    --width);
            }

            imd->fbtab[config-1]->config  = max(1,min(MAX_FBCONFIG, config));
            imd->fbtab[config-1]->nframes = nframes;
            imd->fbtab[config-1]->width   = width;
            imd->fbtab[config-1]->height  = height;

	    if (imd_debug > 1)
		printf ("%3d %2d %6d %6d\n", config, nframes, width, height);
        }

        fclose (fp); 
	return (OK);
}


/* IMD_GETSTR -- Internal routine to extract a colon delimited string from a
 * network filename.
 */
#ifdef ANSI_FUNC

static int 
imd_getstr (char **ipp, char *obuf, int maxch)
#else

static int
imd_getstr (ipp, obuf, maxch)
char **ipp;
char *obuf;
int maxch;
#endif
{
        register char *ip = *ipp, *op = obuf;
        register char *otop = obuf + maxch;
        char *start;

        while (isspace(*ip))
            ip++;
        for (start=ip;  *ip;  ip++) {
            if (*ip == ':') {
                ip++;
                break;
            } else if (op && op < otop)
                *op++ = *ip;
        }

        if (op)
            *op = '\0';
        *ipp = ip;

        return (ip - start);
}


/* IMD_MINMAX -- Compute the min/max values of an array.
 */

static void
imd_minmax (pix, nbytes, pmin, pmax)
uchar 	*pix;
int	nbytes;
int	*pmin, *pmax;
{
	register int i;

	*pmin = *pmax = pix[0];
	for (i=1; i<nbytes; i++) {
	    *pmin = min (*pmin, pix[i]);
	    *pmax = max (*pmax, pix[i]);
	}
}