summaryrefslogtreecommitdiff
path: root/libraries.c
blob: 7962d7b7ba726c5cdb295b4213908207dfe6beee (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
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
/*-------------------------------------------------------------------------*/
/* libraries.c --- xcircuit routines for the builtin and user libraries    */
/* Copyright (c) 2002  Tim Edwards, Johns Hopkins University        	   */
/*-------------------------------------------------------------------------*/

/*-------------------------------------------------------------------------*/
/*      written by Tim Edwards, 8/13/93    				   */
/*-------------------------------------------------------------------------*/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#ifndef XC_WIN32
#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>
#endif
#ifdef TCL_WRAPPER 
#include <tk.h>
#else
#ifndef XC_WIN32
#include "Xw/Xw.h"
#endif
#endif

#include <math.h>

/*-------------------------------------------------------------------------*/
/* Local includes							   */
/*-------------------------------------------------------------------------*/

#include "colordefs.h"
#include "xcircuit.h"

/*----------------------------------------------------------------------*/
/* Function prototype declarations                                      */
/*----------------------------------------------------------------------*/
#include "prototypes.h"

/*-------------------------------------------------------------------------*/
/* Global Variable definitions						   */
/*-------------------------------------------------------------------------*/

extern Display	*dpy;   /* Works well to make this globally accessible */
extern Cursor	appcursors[NUM_CURSORS];
extern Globaldata xobjs;
extern XCWindowData *areawin;
extern char _STR[150];
extern short fontcount;
extern fontinfo *fonts;
extern Boolean was_preselected;
extern int number_colors;
extern colorindex *colorlist;

/*---------------------------------------------------------*/
/* Find the Helvetica font for use in labeling the objects */
/*---------------------------------------------------------*/

short findhelvetica()
{
   short fval;

   if (fontcount == 0) loadfontfile("Helvetica");

   for (fval = 0; fval < fontcount; fval++)
      if (!strcmp(fonts[fval].psname, "Helvetica"))
	 break; 

   /* If not there, use the first Helvetica font */

   if (fval == fontcount) {
      for (fval = 0; fval < fontcount; fval++)
         if (!strcmp(fonts[fval].family, "Helvetica"))
	    break; 
   }

   /* If still not there, use the first non-Symbol font */
   /* If this doesn't work, then the libraries are probably misplaced. . .*/

   if (fval == fontcount) {
      for (fval = 0; fval < fontcount; fval++)
         if (strcmp(fonts[fval].family, "Symbol"))
	    break; 
   }

   return fval;
}

/*-------------------------------------------*/
/* Return to drawing window from the library */
/*-------------------------------------------*/

void catreturn()
{
   /* Pop the object being edited from the push stack. */

   popobject(NULL, (pointertype)1, NULL);
}

/*------------------------------------------------------*/
/* Find page number from cursor position		*/
/* Mode = 0:  Look for exact corresponding page number  */
/*   and return -1 if out-of-bounds			*/
/* Mode = 1:  Look for position between pages, return	*/
/*   page number of page to the right.  		*/
/*------------------------------------------------------*/

int pageposition(short libmode, int x, int y, int mode)
{
   int xin, yin, bpage, pages;
   int gxsize, gysize, xdel, ydel;

   pages = (libmode == PAGELIB) ? xobjs.pages : xobjs.numlibs;
   computespacing(libmode, &gxsize, &gysize, &xdel, &ydel);
   window_to_user(x, y, &areawin->save);

   if (mode == 0) {	/* On-page */
      if (areawin->save.x >= 0 && areawin->save.y <= 0) {
         xin = areawin->save.x / xdel;
         yin = areawin->save.y / ydel; 
         if (xin < gxsize && yin > -gysize) {
            bpage = (xin % gxsize) - (yin * gxsize);
            if (bpage < pages)
	       return bpage;
         }
      }
      return -1;
   }
   else {		/* Between-pages */
      xin = (areawin->save.x + (xdel >> 1)) / xdel;
      if (xin > gxsize) xin = gxsize;
      if (xin < 0) xin = 0;
      yin = areawin->save.y  / ydel; 
      if (yin > 0) yin = 0;
      if (yin < -gysize) yin = -gysize;
      bpage = (xin % (gxsize + 1)) + 1 - (yin * gxsize);
      if (bpage > pages + 1) bpage = pages + 1;
      return bpage;
   }
}

/*------------------------------------------------------*/
/* Find the number of other pages linked to the		*/
/* indicated page (having the same filename, and	*/
/* ignoring empty pages).  result is the total number	*/
/* of pages in the output file.				*/
/*------------------------------------------------------*/

short pagelinks(int page)
{
   int i;
   short count = 0;

   for (i = 0; i < xobjs.pages; i++)
      if (xobjs.pagelist[i]->pageinst != NULL)
	 if (xobjs.pagelist[i]->pageinst->thisobject->parts > 0)
	    if ((i == page) || (xobjs.pagelist[i]->filename &&
			xobjs.pagelist[page]->filename &&
			(!filecmp(xobjs.pagelist[i]->filename,
			xobjs.pagelist[page]->filename))))
	       count++;

   return count;
}

/*------------------------------------------------------*/
/* This is an expanded version of pagelinks() (above),	*/
/* to deal with the separate issues of independent top-	*/
/* level schematics and subcircuits.  For the indicated	*/
/* page, return a list of pages depending on the mode:	*/
/*							*/
/* mode = INDEPENDENT: independent top-level pages	*/
/* mode = DEPENDENT: dependent pages (subcircuits)	*/
/* mode = PAGE_DEPEND: subcircuits of the current page,	*/
/* mode = LINKED_PAGES: subcircuits of the current	*/
/*	page, including parameter links			*/
/* mode = TOTAL_PAGES: independent pages + subcircuits  */
/* mode = ALL_PAGES: all pages in xcircuit		*/
/*							*/
/* The list is the size of the number of pages, and	*/
/* entries corresponding to the requested mode are set	*/
/* nonzero (the actual number indicates the number of	*/
/* references to the page, which may or may not be	*/
/* useful to know).					*/
/*							*/
/* It is the responsibility of the calling routine to	*/
/* free the memory allocated for the returned list.	*/
/*------------------------------------------------------*/

short *pagetotals(int page, short mode)
{
   int i;
   short *counts, *icount;

   if (xobjs.pagelist[page]->pageinst == NULL) return NULL;

   counts = (short *)malloc(xobjs.pages * sizeof(short));
   icount = (short *)malloc(xobjs.pages * sizeof(short));
   for (i = 0; i < xobjs.pages; i++) {
      *(counts + i) = 0;
      *(icount + i) = 0;
   }

   /* Find all the subcircuits of this page */

   if (mode != ALL_PAGES)
      findsubschems(page, xobjs.pagelist[page]->pageinst->thisobject,
		0, counts, (mode == LINKED_PAGES) ? TRUE : FALSE);

   /* Check independent entries (top-level pages which are not	*/
   /* subcircuits of another page, but have the same filename	*/
   /* as the page we started from).  Set the counts entry to -1	*/
   /* to mark each independent page.				*/

   if (mode != PAGE_DEPEND)
      for (i = 0; i < xobjs.pages; i++)
         if (xobjs.pagelist[i]->pageinst != NULL)
	    if (xobjs.pagelist[i]->pageinst->thisobject->parts > 0)
	    {
	       if (mode == ALL_PAGES)
		  (*(counts + i)) = 1;
	       else
	       {
	          if ((i == page) || (xobjs.pagelist[i]->filename
			&& xobjs.pagelist[page]->filename
			&& (!filecmp(xobjs.pagelist[i]->filename,
			xobjs.pagelist[page]->filename))))
		     if ((mode == INDEPENDENT) || (*(counts + i) == 0))
		        (*(icount + i))++;
	       }
	    }

   /* Check other dependent entries (top-level pages which are 	*/
   /* subcircuits of any independent page).			*/

   if ((mode == DEPENDENT) || (mode == TOTAL_PAGES) || (mode == LINKED_PAGES))
   {
      for (i = 0; i < xobjs.pages; i++)
	 if ((i != page) && (*(icount + i) > 0))
	    findsubschems(i, xobjs.pagelist[i]->pageinst->thisobject,
		0, counts, (mode == LINKED_PAGES) ? TRUE : FALSE);
   }

   if (mode == INDEPENDENT)
   {
      free((char *)counts);
      return icount;
   }
   else
   {
      if ((mode == TOTAL_PAGES) || (mode == LINKED_PAGES)) {
	 /* merge dependent and independent */
	 for (i = 0; i < xobjs.pages; i++)
	    if (*(icount + i) > 0)
	       (*(counts + i))++;
      }
      free((char *)icount);
      return counts;
   }
}

/*---------------------------------------------------------*/
/* Test whether a library instance is a "virtual" instance */
/*---------------------------------------------------------*/

Boolean is_virtual(objinstptr thisinst) {
   int libno;
   liblistptr ilist;

   libno = libfindobject(thisinst->thisobject, NULL);

   for (ilist = xobjs.userlibs[libno].instlist; ilist != NULL; ilist = ilist->next)
      if ((ilist->thisinst == thisinst) && (ilist->virtual == TRUE))
	 return TRUE;

   return FALSE;
}

/*------------------------------------------------------*/
/* Test whether an object is a page, and return the	*/
/* page number if it is.  Otherwise, return -1.		*/
/*------------------------------------------------------*/

int is_page(objectptr thisobj)
{
   int i;
   
   for (i = 0; i < xobjs.pages; i++)
      if (xobjs.pagelist[i]->pageinst != NULL)
         if (xobjs.pagelist[i]->pageinst->thisobject == thisobj) return i;

   return -1;
}

/*------------------------------------------------------*/
/* Test whether an object is a library, and return the	*/
/* library number if it is.  Otherwise, return -1.	*/
/*------------------------------------------------------*/

int is_library(objectptr thisobj)
{
   int i;
   
   for (i = 0; i < xobjs.numlibs; i++)
      if (xobjs.libtop[i + LIBRARY]->thisobject == thisobj) return i;

   return -1;
}

/*------------------------------------------------------*/
/* Check for library name (string).  Because XCircuit   */
/* generates the text "Library: <filename>" for		*/
/* library names, we also check against <filename>	*/
/* only in these names (this library name syntax is	*/
/* deprecated, but the check is retained for backwards	*/
/* compatibility).					*/
/*							*/
/* If no library matches the given name, return -1.	*/
/*------------------------------------------------------*/

int NameToLibrary(char *libname)
{
   char *slib;
   int i;

   for (i = 0; i < xobjs.numlibs; i++) {
      slib = xobjs.libtop[i + LIBRARY]->thisobject->name;
      if (!strcmp(libname, slib)) {
	 return i;
      }
      else if (!strncmp(slib, "Library: ", 9)) {
	 if (!strcmp(libname, slib + 9)) {
	    return i;
         }
      }
   }
   return -1;
}

/*------------------------------------------------------*/
/* Move an object and all of its virtual instances from	*/
/* one library to another.				*/
/*------------------------------------------------------*/

int libmoveobject(objectptr thisobject, int libtarget)
{
   int j, libsource;
   liblistptr spec, slast, srch;

   libsource = libfindobject(thisobject, &j);

   if (libsource == libtarget) return libsource; /* nothing to do */
   if (libsource < 0) return libsource;		 /* object not in the library */

   /* Move the object from library "libsource" to library "libtarget" */

   xobjs.userlibs[libtarget].library = (objectptr *)
		realloc(xobjs.userlibs[libtarget].library,
		(xobjs.userlibs[libtarget].number + 1) * sizeof(objectptr));

   *(xobjs.userlibs[libtarget].library + xobjs.userlibs[libtarget].number) = thisobject;
   xobjs.userlibs[libtarget].number++;

   for (; j < xobjs.userlibs[libsource].number; j++)
      *(xobjs.userlibs[libsource].library + j) =
		*(xobjs.userlibs[libsource].library + j + 1);
      xobjs.userlibs[libsource].number--;

   /* Move all instances from library "libsource" to library "libtarget" */

   slast = NULL;
   for (spec = xobjs.userlibs[libsource].instlist; spec != NULL;) {
      if (spec->thisinst->thisobject == thisobject) {

	 /* Add to end of spec list in target */
	 srch = xobjs.userlibs[libtarget].instlist;
	 if (srch == NULL)
	    xobjs.userlibs[libtarget].instlist = spec;
	 else {
	    for (; srch->next != NULL; srch = srch->next);
	    spec->next = srch->next;
	    srch->next = spec;
	 }
	 
	 if (slast != NULL) {
	    slast->next = spec->next;
	    spec = slast->next;
	 }
	 else {
	    xobjs.userlibs[libsource].instlist = spec->next;
	    spec = xobjs.userlibs[libsource].instlist;
	 }
      }
      else {
	 slast = spec;
	 spec = spec->next;
      }
   }

   return libsource;
}

/*------------------------------------------------------*/
/* Determine which library contains the specified	*/
/* object.  If found, return the library number, or	*/
/* else return -1 if the object was not found in any	*/
/* library.  If "partidx" is non-null, fill with the	*/
/* integer offset of the object from the beginning of	*/
/* the library.						*/
/*------------------------------------------------------*/

int libfindobject(objectptr thisobject, int *partidx)
{
   int i, j;
   objectptr libobj;

   for (i = 0; i < xobjs.numlibs; i++) {
      for (j = 0; j < xobjs.userlibs[i].number; j++) {
         libobj = *(xobjs.userlibs[i].library + j);
	 if (libobj == thisobject) {
	    if (partidx != NULL) *partidx = j;
	    return i;
	 }
      }
   }
   return -1;
}

/*------------------------------------------------------*/
/* ButtonPress handler during page catalog viewing mode */
/*------------------------------------------------------*/

void pagecat_op(int op, int x, int y)
{
   int bpage;
   short mode;

   for (mode = 0; mode < LIBRARY; mode++) {
      if (areawin->topinstance == xobjs.libtop[mode]) break;
   }
   if (mode == LIBRARY) return;  /* Something went wrong if this happens */

   if (op != XCF_Cancel) {
      if ((bpage = pageposition(mode, x, y, 0)) >= 0) {
		  
	 if (eventmode == ASSOC_MODE) {
	    if (mode == PAGELIB) {
	       /* using changepage() allows use of new page for schematic */
	       changepage(bpage);
	       /* associate the new schematic */
	       schemassoc(topobject, areawin->stack->thisinst->thisobject);
	       /* pop back to calling (symbol) page */
	       catreturn();
	       eventmode = NORMAL_MODE;
	    }
	    else {
	       areawin->lastlibrary = bpage;
	       startcatalog(NULL, (pointertype)(LIBRARY + bpage), NULL);
	    }
	    return;
         }
	 else if (op == XCF_Select) {
	    if (mode == PAGELIB)    /* No such method for LIBLIB is defined. */
	       select_add_element(OBJINST);
	 }
	 else if ((op == XCF_Library_Pop) || (op == XCF_Finish)) {

	    /* like catreturn(), but don't actually go to the popped page */
	    unselect_all();
	    eventmode = NORMAL_MODE;
	    if (mode == PAGELIB) {
	       newpage(bpage);
	    }
	    else {
	       startcatalog(NULL, (pointertype)(LIBRARY + bpage), NULL);
	    }
	    return;
	 }
      }
   }
   else {
      eventmode = NORMAL_MODE;
      catreturn();
   }
}

/*------------------------------------------------------------------------------*/
/* Subroutine to find the correct scale and position of the object instance	*/
/* representing an entire page in the page directory.				*/
/*------------------------------------------------------------------------------*/

void pageinstpos(short mode, short tpage, objinstptr drawinst, int gxsize,
	int gysize, int xdel, int ydel)
{
   objectptr libobj = drawinst->thisobject;
   float scalex, scaley;

   drawinst->position.x = (tpage % gxsize) * xdel;
   drawinst->position.y = -(tpage / gxsize + 1) * ydel;

   /* center the object on its page bounding box */

   if (drawinst->bbox.width == 0 || drawinst->bbox.height == 0) {
      drawinst->scale = 0.45 * libobj->viewscale;
      drawinst->position.x += 0.05 * xdel - libobj->pcorner.x * drawinst->scale;
      drawinst->position.y += 0.05 * ydel - libobj->pcorner.y * drawinst->scale;
   }
   else {
      scalex = (0.9 * xdel) / drawinst->bbox.width;
      scaley = (0.9 * ydel) / drawinst->bbox.height;
      if (scalex > scaley) {
         drawinst->scale = scaley;
	 drawinst->position.x -= (drawinst->bbox.lowerleft.x * scaley);
         drawinst->position.x += (xdel - (drawinst->bbox.width * scaley)) / 2;
         drawinst->position.y += 0.05 * ydel - drawinst->bbox.lowerleft.y
			* drawinst->scale;
      }
      else {
         drawinst->scale = scalex;
	 drawinst->position.y -= (drawinst->bbox.lowerleft.y * scalex);
         drawinst->position.y += (ydel - (drawinst->bbox.height * scalex)) / 2;
         drawinst->position.x += 0.05 * xdel - drawinst->bbox.lowerleft.x
			* drawinst->scale;
      }
   }
}

/*--------------------------------------------------------------*/
/* Make a new instance for inserting into the page directory	*/
/*--------------------------------------------------------------*/

objinstptr newpageinst(objectptr pageobj)
{
   objinstptr newinst = (objinstptr) malloc(sizeof(objinst));
   instancedefaults(newinst, pageobj, 0, 0);
   newinst->type = OBJINST;
   newinst->color = DEFAULTCOLOR;
   newinst->style = NORMAL;	/* Do not scale linewidth with page scale */
   return newinst;
}

/*-----------------------------------------------------------*/
/* Find spacing of objects for pages in the page directories */
/*-----------------------------------------------------------*/

void computespacing(short mode, int *gxsize, int *gysize, int *xdel, int *ydel)
{
   int pages = (mode == PAGELIB) ? xobjs.pages : xobjs.numlibs;

   *gxsize = (int)sqrt((double)pages) + 1;
   *gysize = 1 + pages / (*gxsize);

   /* 0.5 is the default vscale;  g#size is the number of pages per line */

   *xdel = areawin->width / (0.5 * (*gxsize));
   *ydel = areawin->height / (0.5 * (*gysize));
}

/*-------------------------------------------------------------------*/
/* Draw the catalog of page ordering or the library master directory */
/*-------------------------------------------------------------------*/

void composepagelib(short mode)
{
   genericptr *pgen;
   objinstptr drawinst;
   objectptr libobj, directory = xobjs.libtop[mode]->thisobject;
   short i;
   polyptr *drawbox;
   labelptr *pagelabel;
   stringpart *strptr;
   pointlist pointptr;
   int margin, xdel, ydel, gxsize, gysize;
   int pages = (mode == PAGELIB) ? xobjs.pages : xobjs.numlibs;
   short fval = findhelvetica();

   /* Like the normal libraries, instances come from a special list, so	 */
   /* they should not be destroyed, but will be null'd out and retrieved */
   /* from the list.							 */

   for (pgen = directory->plist; pgen < directory->plist + directory->parts; pgen++)
      if (IS_OBJINST(*pgen)) *pgen = NULL;

   reset(directory, NORMAL);

   /* generate the list of object instances */

   directory->plist = (genericptr *)malloc(sizeof(genericptr));
   directory->parts = 0;

   computespacing(mode, &gxsize, &gysize, &xdel, &ydel);
   margin = xdel / 40;	/* margin between pages */

   for (i = 0; i < pages; i++) {
      drawinst = (mode == PAGELIB) ? xobjs.pagelist[i]->pageinst :
		xobjs.libtop[i + LIBRARY];
      if (drawinst != NULL) {
	 libobj = drawinst->thisobject;

	 /* This is a stop-gap measure. . . should be recalculating the bounds of */
	 /* the instance on every action, not just before arranging the library.  */
	 drawinst->bbox.lowerleft.x = libobj->bbox.lowerleft.x;
	 drawinst->bbox.lowerleft.y = libobj->bbox.lowerleft.y;
	 drawinst->bbox.width = libobj->bbox.width;
	 drawinst->bbox.height = libobj->bbox.height;
	 /* End stop-gap measure */

	 PLIST_INCR(directory);
	 *(directory->plist + directory->parts) = (genericptr)drawinst;
	 directory->parts++;
         pageinstpos(mode, i, drawinst, gxsize, gysize, xdel, ydel);
      }

      /* separate pages (including empty ones) with bounding boxes */

      NEW_POLY(drawbox, directory);
      (*drawbox)->color = LOCALPINCOLOR;   /* default red */
      (*drawbox)->style = NORMAL;      	   /* CLOSED */
      (*drawbox)->width = 1.0;
      (*drawbox)->number = 4;
      (*drawbox)->points = (pointlist) malloc(4 * sizeof(XPoint));
      (*drawbox)->passed = NULL;
      (*drawbox)->cycle = NULL;
      pointptr = (*drawbox)->points;
      pointptr->x = (i % gxsize) * xdel + margin;
      pointptr->y = -(i / gxsize) * ydel - margin;
      pointptr = (*drawbox)->points + 1;
      pointptr->x = ((i % gxsize) + 1) * xdel - margin;
      pointptr->y = -(i / gxsize) * ydel - margin;
      pointptr = (*drawbox)->points + 2;
      pointptr->x = ((i % gxsize) + 1) * xdel - margin;
      pointptr->y = -((i / gxsize) + 1) * ydel + margin;
      pointptr = (*drawbox)->points + 3;
      pointptr->x = (i % gxsize) * xdel + margin;
      pointptr->y = -((i / gxsize) + 1) * ydel + margin;

      /* each page gets its name printed at the bottom */

      if (drawinst != NULL) {
	 NEW_LABEL(pagelabel, directory);
	 labeldefaults(*pagelabel, False, (pointptr->x + (pointptr-1)->x) / 2,
			pointptr->y - 5);
	 (*pagelabel)->color = DEFAULTCOLOR;
	 (*pagelabel)->scale = 0.75;
	 (*pagelabel)->string->data.font = fval;
         (*pagelabel)->passed = NULL;
	 strptr = makesegment(&((*pagelabel)->string), NULL);
	 strptr->type = TEXT_STRING;
	 strptr->data.string = (char *) malloc(1 + strlen(libobj->name));
	 strcpy(strptr->data.string, libobj->name);
	 (*pagelabel)->anchor = TOP | NOTBOTTOM | NOTLEFT;
      }
   }

   /* calculate a bounding box for this display */
   /* and center it in its window */

   calcbbox(xobjs.libtop[mode]);
   centerview(xobjs.libtop[mode]);
}

/*------------------------------------------------------------*/
/* Update the page or library directory based on new bounding */
/* box information for the page or library passed in "tpage". */
/*------------------------------------------------------------*/

void updatepagelib(short mode, short tpage)
{
   objectptr compobj, libinst = xobjs.libtop[mode]->thisobject;
   objinstptr pinst;
   genericptr *gelem;
   int i, xdel, ydel, gxsize, gysize, lpage;

   /* lpage is the number of the page as found on the directory page */
   lpage = (mode == PAGELIB) ? tpage : tpage - LIBRARY;
   compobj = (mode == PAGELIB) ? xobjs.pagelist[tpage]->pageinst->thisobject
		: xobjs.libtop[tpage]->thisobject;

   computespacing(mode, &gxsize, &gysize, &xdel, &ydel);

   for (i = 0; i < libinst->parts; i++) {
      gelem = libinst->plist + i;
      if (IS_OBJINST(*gelem)) {
	 pinst = TOOBJINST(gelem);
         if (pinst->thisobject == compobj) {
	    /* recalculate scale and position of the object instance */
            pageinstpos(mode, lpage, pinst, gxsize, gysize, xdel, ydel);
	    break;
	 }
      }
   }

   /* if there is no instance for this page, then recompose the whole library */

   if (i == libinst->parts) composelib(mode);
}

/*----------------------*/
/* Rearrange pages	*/
/*----------------------*/

void pagecatmove(int x, int y)
{
   int bpage;
   objinstptr exchobj;
   Pagedata *ipage, **testpage, **tpage2;

   if (areawin->selects == 0) return;
   else if (areawin->selects > 2) {
      Wprintf("Select maximum of two objects.");
      return;
   }

   /* Get the page corresponding to the first selected object */

   exchobj = SELTOOBJINST(areawin->selectlist);
   for (testpage = xobjs.pagelist; testpage < xobjs.pagelist + xobjs.pages; testpage++)
      if (*testpage != NULL && (*testpage)->pageinst == exchobj)
	 break;

   /* If two objects are selected, then exchange their order */

   if (areawin->selects == 2) {
      exchobj = SELTOOBJINST(areawin->selectlist + 1);
      for (tpage2 = xobjs.pagelist; tpage2 < xobjs.pagelist + xobjs.pages; tpage2++)
	 if (*tpage2 != NULL && (*tpage2)->pageinst == exchobj)
	    break;

      ipage = *testpage;
      *testpage = *tpage2;
      *tpage2 = ipage;
   }

   /* If one object selected; find place to put from cursor position */

   else if ((bpage = pageposition(PAGELIB, x, y, 1)) >= 0) {
      int k, epage;
      Pagedata *eptr;

      /* Find page number of the original page */

      epage = (int)(testpage - xobjs.pagelist);
      eptr = *(xobjs.pagelist + epage);

      /* move page (epage) to position between current pages */
      /* (bpage - 2) and (bpage - 1) by shifting pointers.   */

      if ((bpage - 1) < epage) {
	 for (k = epage - 1; k >= bpage - 1; k--) {
	    *(xobjs.pagelist + k + 1) = *(xobjs.pagelist + k);
	    renamepage(k + 1);
	 }
	 *(xobjs.pagelist + bpage - 1) = eptr;
	 renamepage(bpage - 1);
      }
      else if ((bpage - 2) > epage) {
	 for (k = epage + 1; k <= bpage - 2; k++) {
	    *(xobjs.pagelist + k - 1) = *(xobjs.pagelist + k);
	    renamepage(k - 1);
	 }
	 *(xobjs.pagelist + bpage - 2) = eptr;
	 renamepage(bpage - 2);
      }
   }

   unselect_all();
   composelib(PAGELIB);
   drawarea(NULL, NULL, NULL);
}

/*-----------------------------------------*/
/* Draw the catalog of predefined elements */
/*-----------------------------------------*/

void composelib(short mode)
{
   genericptr *pgen;
   objinstptr drawinst;
   labelptr *drawname;
   objectptr libobj, libpage = xobjs.libtop[mode]->thisobject;
   liblistptr spec;
   int xpos = 0, ypos = areawin->height << 1;
   int nypos = 220, nxpos;
   short fval;
   short llx, lly, urx, ury, width, height, xcenter;

   int totalarea, targetwidth;
   double scale, savescale;
   short savemode;
   XPoint savepos;

   /* Also make composelib() a wrapper for composepagelib() */
   if ((mode > FONTLIB) && (mode < LIBRARY)) {
      composepagelib(mode);
      return;
   }

   /* The instances on the library page come from the library's		*/
   /* "instlist".  So that we don't destroy the actual instance when we	*/
   /* call reset(), we find the pointer to the instance and NULL it.	*/
   
   for (pgen = libpage->plist; pgen < libpage->plist + libpage->parts; pgen++)
      if (IS_OBJINST(*pgen)) *pgen = NULL;

   /* Before resetting, save the position and scale.  We will restore	*/
   /* them at the end.							*/

   savepos = libpage->pcorner;
   savescale = libpage->viewscale;
   reset(libpage, NORMAL);

   /* Return if library defines no objects or virtual instances */

   if (xobjs.userlibs[mode - LIBRARY].instlist == NULL) return;

   /* Find the Helvetica font for use in labeling the objects */

   fval = findhelvetica();

   /* Attempt to produce a library with the same aspect ratio as the	*/
   /* drawing window.  This is only approximate, and does not take	*/
   /* into account factors such as the length of the name string.	*/

   totalarea = 0;
   for (spec = xobjs.userlibs[mode - LIBRARY].instlist; spec != NULL;
                spec = spec->next) {
      libobj = spec->thisinst->thisobject;

      /* "Hidden" objects are not drawn */
      if (libobj->hidden == True) continue;

      drawinst = spec->thisinst;
      drawinst->position.x = 0;
      drawinst->position.y = 0;

      /* Get the bounding box of the instance in the page's coordinate system */
      calcinstbbox((genericptr *)(&drawinst), &llx, &lly, &urx, &ury);
      width = urx - llx;
      height = ury - lly;
      width += 30;	/* space padding */
      height += 30;	/* height padding */
      if (width < 200) width = 200;	/* minimum box width */
      if (height < 220) height = 220;	/* minimum box height */
      totalarea += (width * height);
   }

   scale = (double)totalarea / (double)(areawin->width * areawin->height);
   targetwidth = (int)(sqrt(scale) * (double)areawin->width);

   /* generate the list of object instances and their labels */

   savemode = eventmode;
   eventmode = CATALOG_MODE;
   for (spec = xobjs.userlibs[mode - LIBRARY].instlist; spec != NULL;
		spec = spec->next) {
      libobj = spec->thisinst->thisobject;

      /* "Hidden" objects are not drawn */
      if (libobj->hidden == True) continue;

      drawinst = spec->thisinst;
      drawinst->position.x = 0;
      drawinst->position.y = 0;

      /* Generate the part;  unlike the usual NEW_OBJINST, the	*/
      /* instance record isn't allocated.			*/

      PLIST_INCR(libpage); 
      *(libpage->plist + libpage->parts) = (genericptr)drawinst;
      libpage->parts++;

      /* Get the bounding box of the instance in the page's coordinate system */
      calcinstbbox((genericptr *)(&drawinst), &llx, &lly, &urx, &ury);
      xcenter = (llx + urx) >> 1;
      width = urx - llx;
      height = ury - lly;

      /* Add an ad-hoc spacing rule of 30 for padding space between objects */
      width += 30;

      /* Prepare the object name and determine its width.  Adjust width	*/
      /* needed for object on the library page if necessary.		*/

      if (fval < fontcount) {
	 stringpart *strptr;
	 TextExtents tmpext;

	 NEW_LABEL(drawname, libpage);
	 labeldefaults(*drawname, False, 0, 0);
	 (*drawname)->color = (spec->virtual) ?
			OFFBUTTONCOLOR : DEFAULTCOLOR;
         (*drawname)->scale = 0.75;
	 (*drawname)->string->data.font = fval;
	 strptr = makesegment(&((*drawname)->string), NULL);
	 strptr->type = TEXT_STRING;

         strptr->data.string = strdup(libobj->name);
         (*drawname)->anchor = TOP | NOTBOTTOM | NOTLEFT;

	 /* If the label is longer than the object width, then	*/
	 /* adjust positions accordingly.  Note that as an ad-	*/
	 /* hoc spacing rule, a padding of 30 is put between	*/
	 /* objects; this padding is reduced to 5 		*/

	 tmpext = ULength(*drawname, drawinst, NULL);

	 /* Ad-hoc spacing rule is 5 for labels */
	 tmpext.width += 5;

	 if (tmpext.width > width)
	    width = tmpext.width;
      }

      /* Minimum allowed width is 200 */
      if (width < 200) width = 200;

      /* Determine the area needed on the page to draw the object */

      nxpos = xpos + width;
      if ((nxpos > targetwidth) && (xpos > 0)) {
	 nxpos -= xpos; 
	 xpos = 0;
	 ypos -= nypos;
	 nypos = 200;
      }

      if (height > (nypos - 50)) nypos = height + 50;

      drawinst->position.x = xpos + (width >> 1) - xcenter;
      drawinst->position.y = ypos - (height + lly);
      if (height <= 170) drawinst->position.y -= ((170 - height) >> 1);
      drawinst->color = DEFAULTCOLOR;

      if (fval < fontcount) {
         (*drawname)->position.x = xpos + (width >> 1);

         if (height > 170)
            (*drawname)->position.y = drawinst->position.y + lly - 10;
         else
            (*drawname)->position.y = ypos - 180;

      }
      xpos = nxpos;
   }
   eventmode = savemode;

   /* Compute the bounding box of the library page */
   calcbbox(xobjs.libtop[mode]);

   /* Update the library directory */
   updatepagelib(LIBLIB, mode);

   /* Restore original view position */
   libpage->pcorner = savepos;
   libpage->viewscale = savescale;
}

/*----------------------------------------------------------------*/
/* Find any dependencies on an object.				  */
/*   Return values:  0 = no dependency, 1 = dependency on page,	  */
/*	2 = dependency in another library object.		  */
/*   Object/Page with dependency (if any) returned in "compobjp". */
/*----------------------------------------------------------------*/

short finddepend(objinstptr libobj, objectptr **compobjp)
{
   genericptr *testobj;
   short page, i, j;
   objectptr *compobj;
  
   for (i = 0; i < xobjs.numlibs; i++) {
      for (j = 0; j < xobjs.userlibs[i].number; j++) {
	 compobj = xobjs.userlibs[i].library + j;
         *compobjp = compobj;
		     
         for (testobj = (*compobj)->plist; testobj < (*compobj)->plist
	          + (*compobj)->parts; testobj++) {
	    if (IS_OBJINST(*testobj)) {
	       if (TOOBJINST(testobj)->thisobject == libobj->thisobject) return 2;
	    }
	 }
      }
   }

   /* also look in the xobjs.pagelist */

   for (page = 0; page < xobjs.pages; page++) {
      if (xobjs.pagelist[page]->pageinst == NULL) continue;
      compobj = &(xobjs.pagelist[page]->pageinst->thisobject);
      *compobjp = compobj;
      for (testobj = (*compobj)->plist; testobj < (*compobj)->plist
	       + (*compobj)->parts; testobj++) {
	 if (IS_OBJINST(*testobj)) {
	    if (TOOBJINST(testobj)->thisobject == libobj->thisobject) return 1;
	 }
      }
   }
   return 0;
}

/*--------------------------------------------------------------*/
/* Virtual copy:  Make a separate copy of an object on the same	*/
/* library page as the original, representing an instance of	*/
/* the object with different parameters.  The object must have	*/
/* parameters for this to make sense, so check for parameters	*/
/* before allowing the virtual copy.				*/
/*--------------------------------------------------------------*/

void catvirtualcopy()
{
   short i, *newselect;
   objinstptr libobj, libinst;

   if (areawin->selects == 0) return;
   else if ((i = is_library(topobject)) < 0) return;

   /* Check for existance of parameters in the object for each */
   /* selected instance */

   for (newselect = areawin->selectlist; newselect < areawin->selectlist
	  + areawin->selects; newselect++) {
      libobj = SELTOOBJINST(newselect);
      libinst = addtoinstlist(i, libobj->thisobject, TRUE);
      instcopy(libinst, libobj);
      tech_mark_changed(GetObjectTechnology(libobj->thisobject));
   }

   clearselects();
   composelib(LIBRARY + i);
   drawarea(NULL, NULL, NULL);
}

/*----------------------------------------------------------------*/
/* "Hide" an object (must have a dependency or else it disappears)*/
/*----------------------------------------------------------------*/

void cathide()
{
   int i;
   short *newselect;
   objectptr *compobj;
   objinstptr libobj;

   if (areawin->selects == 0) return;

   /* Can only hide objects which are instances in other objects; */
   /* Otherwise, object would be "lost".			  */

   for (newselect = areawin->selectlist; newselect < areawin->selectlist
	  + areawin->selects; newselect++) {
      libobj = SELTOOBJINST(newselect);

      if (finddepend(libobj, &compobj) == 0) {
	 Wprintf("Cannot hide: no dependencies");
      }
      else { 		/* All's clear to hide. */
	 libobj->thisobject->hidden = True;
      }
   }

   clearselects();

   if ((i = is_library(topobject)) >= 0) composelib(LIBRARY + i);

   drawarea(NULL, NULL, NULL);
}

/*----------------------------------------------------------------*/
/* Delete an object from the library if there are no dependencies */
/*----------------------------------------------------------------*/

void catdelete()
{
   short *newselect, *libpobjs;
   int i;
   /* genericptr *testobj, *tobj; (jdk) */
   objinstptr libobj;
   liblistptr ilist, llist;
   objectptr *libpage, *compobj, *tlib, *slib;

   if (areawin->selects == 0) return;

   if ((i = is_library(topobject)) >= 0) {
      libpage = xobjs.userlibs[i].library;
      libpobjs = &xobjs.userlibs[i].number;
   }
   else
      return;  /* To-do: Should have a mechanism here for deleting pages! */

   for (newselect = areawin->selectlist; newselect < areawin->selectlist
	  + areawin->selects; newselect++) {
      libobj = SELTOOBJINST(newselect);

      /* If this is just a "virtual copy", simply remove it from the list */

      llist = NULL;
      for (ilist = xobjs.userlibs[i].instlist; ilist != NULL;
		llist = ilist, ilist = ilist->next) {
	 if ((ilist->thisinst == libobj) && (ilist->virtual == TRUE)) {
	    if (llist == NULL)
	       xobjs.userlibs[i].instlist = ilist->next;
	    else
	       llist->next = ilist->next;
	    break;
	 }
      }
      if (ilist != NULL) {
         free(ilist);
	 continue;
      }

      /* Cannot delete an object if another object uses an instance of it, */
      /* or if the object is used on a page.				   */

      if (finddepend(libobj, &compobj)) {
	 Wprintf("Cannot delete: dependency in \"%s\"", (*compobj)->name);
      }
      else { 		/* All's clear to delete.		     	   */

         /* Clear the undo stack so that any references to this object	*/
	 /* won't screw up the database (this could be kinder & gentler	*/
	 /* by first checking if there are any references to the object	*/
	 /* in the undo stack. . .					*/

	 flush_undo_stack();

	 /* Next, remove the object from the library page. */

	 for (tlib = libpage; tlib < libpage + *libpobjs; tlib++)
	    if ((*tlib) == libobj->thisobject) {
	       for (slib = tlib; slib < libpage + *libpobjs - 1; slib++)
		  (*slib) = (*(slib + 1));
	       (*libpobjs)--;
	       break;
	    }
	 
	 /* Next, remove all instances of the object on	the library page. */
	  
         llist = NULL;
         for (ilist = xobjs.userlibs[i].instlist; ilist != NULL;
		llist = ilist, ilist = ilist->next) {
	    if (ilist->thisinst->thisobject == libobj->thisobject) {
	       if (llist == NULL) {
	          xobjs.userlibs[i].instlist = ilist->next;
	          free(ilist);
	          if (!(ilist = xobjs.userlibs[i].instlist)) break;
	       }
	       else {
	          llist->next = ilist->next;
	          free(ilist);
	          if (!(ilist = llist)) break;
	       }
	    }
	 }

	 /* Finally, delete the object (permanent---no undoing this!) */
         tech_mark_changed(GetObjectTechnology(libobj->thisobject));
	 reset(libobj->thisobject, DESTROY);
      }
   }

   clearselects();

   if ((i = is_library(topobject)) >= 0) {
      composelib(LIBRARY + i);
   }

   drawarea(NULL, NULL, NULL);
}

/*------------------------------------------------------*/
/* Linked list rearrangement routines			*/
/*------------------------------------------------------*/

void linkedlistswap(liblistptr *spec, int o1, int o2)
{
   liblistptr s1, s1m, s2, s2m, stmp;
   int j;

   if (o1 == o2) return;

   s1m = NULL;
   s1 = *spec;
   for (j = 0; j < o1; j++) {
      s1m = s1;
      s1 = s1->next;
   }

   s2m = NULL;
   s2 = *spec;
   for (j = 0; j < o2; j++) {
      s2m = s2;
      s2 = s2->next;
   }

   if (s2m)
      s2m->next = s1;
   else
      *spec = s1;

   if (s1m)
      s1m->next = s2;
   else
      *spec = s2;

   stmp = s1->next;
   s1->next = s2->next;
   s2->next = stmp;
}

/*------------------------------------------------------*/

void linkedlistinsertafter(liblistptr *spec, int o1, int o2)
{
  liblistptr s1, s1m, s2; /* , s2m, stmp; (jdk) */
   int j;

   if ((o1 == o2) || (o1 == (o2 + 1))) return;

   s1m = NULL;
   s1 = *spec;
   for (j = 0; j < o1; j++) {
      s1m = s1;
      s1 = s1->next;
   }

   s2 = *spec;
   for (j = 0; j < o2; j++)
      s2 = s2->next;

   if (s1m)
      s1m->next = s1->next;
   else
      *spec = s1->next;

   if (o2 == -1) {   /* move s1 to front */
      s1->next = *spec;
      *spec = s1;
   }
   else {
      s1->next = s2->next;
      s2->next = s1;
   }
}

/*------------------------------------------------------*/
/* Set the "changed" flag in a library if any object	*/
/* in that library has changed.				*/
/*							*/
/* If "technology" is NULL, check all objects,		*/
/* otherwise only check objects with a matching		*/
/* technology.						*/
/*------------------------------------------------------*/

void tech_set_changes(TechPtr refns)
{
   TechPtr ns;
   int i, j;
   objectptr thisobj;

   for (i = 0; i < xobjs.numlibs; i++) {
      for (j = 0; j < xobjs.userlibs[i].number; j++) {
         thisobj = *(xobjs.userlibs[i].library + j);
         if (getchanges(thisobj) > 0) {
            ns = GetObjectTechnology(thisobj);
	    if ((refns == NULL) || (refns == ns)) 
	       ns->flags |= TECH_CHANGED;
	 }
      }
   }
}

/*------------------------------------------------------*/
/* Mark a technology as having been modified.		*/
/*------------------------------------------------------*/

void tech_mark_changed(TechPtr ns)
{
   if (ns != NULL) ns->flags |= TECH_CHANGED;
}

/*------------------------------------------------------*/
/* Rearrange objects in the library			*/
/*------------------------------------------------------*/

void catmove(int x, int y)
{
  int i, j, k, s1, s2, ocentx, ocenty, rangey, l; /* rangex, (jdk) */
   liblistptr spec;
   objinstptr exchobj, lobj;

   /* make catmove() a wrapper for pagecatmove() */

   if ((i = is_library(topobject)) < 0) {
      pagecatmove(x, y);
      return;
   }

   if (areawin->selects == 0) return;

   /* Add selected object or objects at the cursor position */

   window_to_user(x, y, &areawin->save);

   s2 = -1;
   for (j = 0, spec = xobjs.userlibs[i].instlist; spec != NULL;
		spec = spec->next, j++) {
      lobj = spec->thisinst;
      for (k = 0; k < areawin->selects; k++) {
	 exchobj = SELTOOBJINST(areawin->selectlist + k);
	 if (lobj == exchobj) break;
      }
      if (k < areawin->selects) continue;	/* ignore items being moved */

      ocentx = lobj->position.x + lobj->bbox.lowerleft.x
	        + (lobj->bbox.width >> 1);
      ocenty = lobj->position.y + lobj->bbox.lowerleft.y
	        + (lobj->bbox.height >> 1);
      rangey = (lobj->bbox.height > 200) ? 
	        (lobj->bbox.height >> 1) : 100;

      if ((areawin->save.y < ocenty + rangey) && (areawin->save.y 
	         > ocenty - rangey)) {
	 s2 = j - 1;
	 if (areawin->save.x < ocentx) break;
	 else s2 = j;
      }
   }
   if ((s2 == -1) && (spec == NULL)) {
      if (areawin->save.y <
		xobjs.libtop[i + LIBRARY]->thisobject->bbox.lowerleft.y)
	 s2 = j - 1;
      else if (areawin->save.y <=
		xobjs.libtop[i + LIBRARY]->thisobject->bbox.lowerleft.y +
		xobjs.libtop[i + LIBRARY]->thisobject->bbox.height) {
	 unselect_all();	
	 Wprintf("Could not find appropriate place to insert object");
	 return;
      }
   }

   /* Find object number s2 (because s2 value may change during insertion) */
   if (s2 > -1) {
      for (k = 0, spec = xobjs.userlibs[i].instlist; k < s2; spec = spec->next, k++);
      lobj = spec->thisinst;
   }
   else lobj = NULL;

   /* Move items; insert them after item s2 in order selected */

   j = i;
   for (k = 0; k < areawin->selects; k++) {

      /* Find number of lobj (may have changed) */

      if (lobj == NULL)
	 s2 = -1;
      else {
         for (s2 = 0, spec = xobjs.userlibs[i].instlist; spec != NULL;
		spec = spec->next, s2++)
	    if (spec->thisinst == lobj)
	       break;
      }

      exchobj = SELTOOBJINST(areawin->selectlist + k);
      for (s1 = 0, spec = xobjs.userlibs[i].instlist; spec != NULL;
		spec = spec->next, s1++)
         if (spec->thisinst == exchobj)
	    break;

      if (spec == NULL) {
	 /* Object came from another library */
         if ((l = libmoveobject(exchobj->thisobject, i)) >= 0) j = l;
      }
      else {
         linkedlistinsertafter(&(xobjs.userlibs[i].instlist), s1, s2);
      }
   }

   unselect_all();
   composelib(LIBRARY + i);
   if (j != i) {
      composelib(LIBRARY + j);
      centerview(xobjs.libtop[LIBRARY + j]);
   }

   drawarea(NULL, NULL, NULL);
}

/*------------------------------------------------------*/
/* Make a duplicate of an object, put in the User	*/
/* Library or the current library (if we're in one).	*/
/*							*/
/* Updated 2/8/2014 for use with technology namespaces:	*/
/* it is most likely that the copied object is to be	*/
/* modified but kept in the same namespace.  So, when	*/
/* renaming the object, prepend "_" to the object name	*/
/* instead of the namespace prefix.			*/
/*------------------------------------------------------*/

void copycat()
{
   short *newselect;
   objectptr *newobj, *curlib, oldobj;
   objinstptr libobj;
   oparamptr ops, newops;
   int i, libnum;
   char *cptr;

   libnum = is_library(topobject);
   if (libnum < 0) libnum = USERLIB - LIBRARY;  /* default */

   for (newselect = areawin->selectlist; newselect < areawin->selectlist
	  + areawin->selects; newselect++) {

      libobj = SELTOOBJINST(newselect);
      oldobj = libobj->thisobject;

      /* generate new entry in user library */

      curlib = (objectptr *) realloc(xobjs.userlibs[libnum].library,
	 (xobjs.userlibs[libnum].number + 1) * sizeof(objectptr));
      xobjs.userlibs[libnum].library = curlib;
      newobj = xobjs.userlibs[libnum].library + xobjs.userlibs[libnum].number;
      *newobj = (objectptr) malloc(sizeof(object));
      xobjs.userlibs[libnum].number++;

      /* give the new object a unique name */

      cptr = strstr(oldobj->name, "::");
      if (cptr == NULL)
	 sprintf((*newobj)->name, "_%s", oldobj->name);
      else {
	 strcpy((*newobj)->name, oldobj->name);
	 sprintf((*newobj)->name + (cptr - oldobj->name) + 2, "_%s", cptr + 2);
      }
      checkname(*newobj);

      /* copy other object properties */

      (*newobj)->bbox.width = oldobj->bbox.width;
      (*newobj)->bbox.height = oldobj->bbox.height;
      (*newobj)->bbox.lowerleft.x = oldobj->bbox.lowerleft.x;
      (*newobj)->bbox.lowerleft.y = oldobj->bbox.lowerleft.y;
      (*newobj)->pcorner.x = oldobj->pcorner.x;
      (*newobj)->pcorner.y = oldobj->pcorner.y;
      (*newobj)->viewscale = oldobj->viewscale;
      /* don't attach the same schematic. . . */
      (*newobj)->symschem = NULL;
      /* don't copy highlights */
      (*newobj)->highlight.netlist = NULL;
      (*newobj)->highlight.thisinst = NULL;

      /* Copy the parameter structure */
      (*newobj)->params = NULL;
      for (ops = oldobj->params; ops != NULL; ops = ops->next) {
	 newops = (oparamptr)malloc(sizeof(oparam));
	 newops->next = (*newobj)->params;
	 newops->key = strdup(ops->key);
	 (*newobj)->params = newops;
	 newops->type = ops->type;
	 newops->which = ops->which;
	 switch (ops->type) {
	    case XC_INT:
	       newops->parameter.ivalue = ops->parameter.ivalue;
	       break;
	    case XC_FLOAT:
	       newops->parameter.fvalue = ops->parameter.fvalue;
	       break;
	    case XC_STRING:
	       newops->parameter.string = stringcopy(ops->parameter.string);
	       break;
	    case XC_EXPR:
	       newops->parameter.expr = strdup(ops->parameter.expr);
	       break;
	 }
      }

      (*newobj)->schemtype = oldobj->schemtype;
      (*newobj)->netnames = NULL;
      (*newobj)->ports = NULL;
      (*newobj)->calls = NULL;
      (*newobj)->polygons = NULL;
      (*newobj)->labels = NULL;
      (*newobj)->valid = False;
      (*newobj)->traversed = False;
      (*newobj)->hidden = False;

      /* copy over all the elements of the original object */

      (*newobj)->parts = 0;
      (*newobj)->plist = (genericptr *)malloc(sizeof(genericptr));

      for (i = 0; i < oldobj->parts; i++) {
	 switch(ELEMENTTYPE(*(oldobj->plist + i))) {
	    case(PATH): {
	       register pathptr *npath, cpath = TOPATH(oldobj->plist + i);

	       NEW_PATH(npath, (*newobj));
	       pathcopy(*npath, cpath);
	       } break;

	    case(ARC): {
	       register arcptr *narc, carc = TOARC(oldobj->plist + i);

	       NEW_ARC(narc, (*newobj));
	       arccopy(*narc, carc);
               } break;
      
	    case(POLYGON): {
	       register polyptr *npoly, cpoly = TOPOLY(oldobj->plist + i);

	       NEW_POLY(npoly, (*newobj));
	       polycopy(*npoly, cpoly);
               } break;

	    case(SPLINE): {
	       register splineptr *nspl, cspl = TOSPLINE(oldobj->plist + i);

	       NEW_SPLINE(nspl, (*newobj));
	       splinecopy(*nspl, cspl);
      	       } break;

	    case(LABEL): {
	       register labelptr *nlabel, clabel = TOLABEL(oldobj->plist + i);

	       NEW_LABEL(nlabel, (*newobj));
	       labelcopy(*nlabel, clabel);
               } break;
      
	    case(OBJINST): {
	       register objinstptr *ninst, cinst = TOOBJINST(oldobj->plist + i);

	       NEW_OBJINST(ninst, (*newobj));
	       instcopy(*ninst, cinst);
               } break;
         }
      }
   }

   /* make instance for library and measure its bounding box */
   addtoinstlist(USERLIB - LIBRARY, *newobj, FALSE);

   composelib(USERLIB);
   unselect_all();

   if (areawin->topinstance == xobjs.libtop[USERLIB])
      drawarea(NULL, NULL, NULL);
   else startcatalog(NULL, (pointertype)USERLIB, NULL);
   zoomview(NULL, NULL, NULL);
}

/*--------------------------------------------------------*/
/* ButtonPress handler during normal catalog viewing mode */
/*--------------------------------------------------------*/

void catalog_op(int op, int x, int y)
{
   short *newselect;
   objinstptr *newobject, *libobj;
   objectptr libpage = topobject;
   short ocentx, ocenty, rangex, rangey, xdiff, ydiff, flag = 0;
   XPoint oldpos;

   /* Make catalog_op() a wrapper for pagecat_op() */

   if (is_library(topobject) < 0) {
      pagecat_op(op, x, y);
      return;
   }

   /* If XCF_Cancel was invoked, return without a selection. */

   if (op == XCF_Cancel) {
      eventmode = NORMAL_MODE;
      catreturn();
   }
   else {

      window_to_user(x, y, &areawin->save);
	
      for (libobj = (objinstptr *)topobject->plist; libobj <
		(objinstptr *)topobject->plist + topobject->parts; libobj++) {
	 if (IS_OBJINST(*libobj)) {

 	    ocentx = (*libobj)->position.x + (*libobj)->bbox.lowerleft.x
	        + ((*libobj)->bbox.width >> 1);
 	    ocenty = (*libobj)->position.y + (*libobj)->bbox.lowerleft.y
	        + ((*libobj)->bbox.height >> 1);

	    rangex = ((*libobj)->bbox.width > 200) ? 
	        ((*libobj)->bbox.width >> 1) : 100;
	    rangey = ((*libobj)->bbox.height > 200) ? 
	        ((*libobj)->bbox.height >> 1) : 100;

	    if (areawin->save.x > ocentx - rangex && areawin->save.x <
		   ocentx + rangex && areawin->save.y < ocenty + rangey
		   && areawin->save.y > ocenty - rangey) {

	       /* setup to move object around and draw the selected object */

	       if (eventmode == ASSOC_MODE) {

	          /* revert to old page */
		  topobject->viewscale = areawin->vscale;
		  topobject->pcorner = areawin->pcorner;
	          areawin->topinstance = (areawin->stack == NULL) ?
			   xobjs.pagelist[areawin->page]->pageinst
			   : areawin->stack->thisinst;
		  /* associate the new object */
		  schemassoc(topobject, (*libobj)->thisobject); 
   	          setpage(TRUE);
		  catreturn();
		  eventmode = NORMAL_MODE;
	       }
	       else if ((op == XCF_Library_Pop) || (op == XCF_Library_Copy)) {
		  int saveselects;

	          /* revert to old page */

		  topobject->viewscale = areawin->vscale;
		  topobject->pcorner = areawin->pcorner;
	          areawin->topinstance = (areawin->stack == NULL) ?
			   xobjs.pagelist[areawin->page]->pageinst
			   : areawin->stack->thisinst;

	          /* retrieve drawing window state and set position of object to
	             be correct in reference to that window */

	          snap(x, y, &oldpos);

		  saveselects = areawin->selects;
		  areawin->selects = 0;
   	          setpage(FALSE);
		  areawin->selects = saveselects;
	    
	          snap(x, y, &areawin->save);
	          xdiff = areawin->save.x - oldpos.x;
	          ydiff = areawin->save.y - oldpos.y;

                  /* collect all of the selected items */

	          for (newselect = areawin->selectlist; newselect <
		     areawin->selectlist + areawin->selects; newselect++) {
		     NEW_OBJINST(newobject, topobject);
		     instcopy(*newobject, TOOBJINST(libpage->plist + *newselect));
		     /* color should be recast as current color */
		     (*newobject)->color = areawin->color;
		     /* position modified by (xdiff, ydiff) */
		     (*newobject)->position.x += xdiff;
		     (*newobject)->position.y += ydiff;

	             u2u_snap(&((*newobject)->position));
		     *newselect = (short)(newobject - (objinstptr *)topobject->plist);
		     if ((*newobject)->thisobject == (*libobj)->thisobject)
		        flag = 1;
	          }

                  /* add final object to the list of object instances */

	          if (!flag) {
		     NEW_OBJINST(newobject, topobject);
		     instcopy(*newobject, *libobj);
		     (*newobject)->color = areawin->color;
                     (*newobject)->position.x = areawin->save.x;
	             (*newobject)->position.y = areawin->save.y; 

	             /* add this object to the list of selected items */

	             newselect = allocselect();
                     *newselect = (short)(newobject - (objinstptr *)topobject->plist);

	          }
	          if (op == XCF_Library_Copy) {

		     /* Key "c" pressed for "copy" (default binding) */

                     XDefineCursor(dpy, areawin->window, COPYCURSOR);
                     eventmode = COPY_MODE;
#ifndef TCL_WRAPPER
                     xcAddEventHandler(areawin->area, PointerMotionMask |
				ButtonMotionMask, False,
				(xcEventHandler)xlib_drag, NULL);
#endif
	          }
	          else {
                     eventmode = MOVE_MODE;
		     was_preselected = FALSE;
	 	     register_for_undo(XCF_Library_Pop, UNDO_MORE, areawin->topinstance,
		  		areawin->selectlist, areawin->selects);
	          }
#ifdef TCL_WRAPPER
		  /* fprintf(stderr, "Creating event handler for xctk_drag: "); */
		  /* printeventmode();		*/
                  Tk_CreateEventHandler(areawin->area, PointerMotionMask |
			ButtonMotionMask, (Tk_EventProc *)xctk_drag, NULL);
#endif
                  catreturn();
               }

               /* Select the closest element and stay in the catalog.	   */
	       /* Could just do "select_element" here, but would not cover */
	       /* the entire area in the directory surrounding the object. */

	       else if (op == XCF_Select) {
		  short newinst = (short)(libobj - (objinstptr *)topobject->plist);
		  /* (ignore this object if it is already in the list of selects) */
		  for (newselect = areawin->selectlist; newselect <
			areawin->selectlist + areawin->selects; newselect++)
		     if (*newselect == newinst) break;
		  if (newselect == areawin->selectlist + areawin->selects) {
		     newselect = allocselect();
		     *newselect = newinst;
		     XcTopSetForeground(SELECTCOLOR);
		     UDrawObject(*libobj, SINGLE, SELECTCOLOR,
				xobjs.pagelist[areawin->page]->wirewidth, NULL);
		  }
	       }
	       break;
	    }
	 }
      }
   }
}

/*------------------------------*/
/* Switch to the next catalog	*/
/*------------------------------*/

void changecat()
{
   int i, j;

   if ((i = is_library(topobject)) < 0) {
      if (areawin->lastlibrary >= xobjs.numlibs) areawin->lastlibrary = 0;
      j = areawin->lastlibrary;
      eventmode = CATALOG_MODE;
   }
   else {
      j = (i + 1) % xobjs.numlibs;
      if (j == i) {
	 Wprintf("This is the only library.");
	 return;
      }
      areawin->lastlibrary = j;
   }

   if (eventmode == CATMOVE_MODE)
      delete_for_xfer(NORMAL, areawin->selectlist, areawin->selects);

   startcatalog(NULL, (pointertype)(j + LIBRARY), NULL);
}

/*--------------------------------------*/
/* Begin catalog viewing mode		*/
/*--------------------------------------*/

void startcatalog(xcWidget w, pointertype libmod, caddr_t nulldata)
{
   if (xobjs.libtop == NULL) return;	/* No libraries defined */

   if ((xobjs.libtop[libmod]->thisobject == NULL) ||
		(areawin->topinstance == xobjs.libtop[libmod])) return;

   if (libmod == FONTLIB) {
      XDefineCursor (dpy, areawin->window, DEFAULTCURSOR);
      if (eventmode == TEXT_MODE)
         eventmode = FONTCAT_MODE;
      else
         eventmode = EFONTCAT_MODE;
   }
   else if (eventmode == ASSOC_MODE) {
      XDefineCursor (dpy, areawin->window, DEFAULTCURSOR);
   }
   else if (libmod == PAGELIB || libmod == LIBLIB) {
      XDefineCursor (dpy, areawin->window, DEFAULTCURSOR);
      eventmode = CATALOG_MODE;
   }
   else if (eventmode != CATMOVE_MODE) {
      /* Don't know why I put this here---causes xcircuit to redraw	*/
      /* the schematic view when switching between library pages.	*/
      // finish_op(XCF_Cancel, 0, 0);
      eventmode = CATALOG_MODE;
   }

   /* Push the current page onto the push stack, unless	we're going */
   /* to a library from the library directory or vice versa, or	    */
   /* library to library.					    */

   if (!(((is_library(topobject) >= 0)
		|| (areawin->topinstance == xobjs.libtop[LIBLIB])
		|| (areawin->topinstance == xobjs.libtop[PAGELIB]))
		&& libmod >= PAGELIB)) {
      push_stack(&areawin->stack, areawin->topinstance, NULL);
   }

   /* set library as new object */

   topobject->viewscale = areawin->vscale;
   topobject->pcorner = areawin->pcorner;
   areawin->topinstance = xobjs.libtop[libmod];

   if (libmod == FONTLIB)
      setpage(FALSE);
   else {
      setpage(TRUE);
      transferselects();
   }

   /* draw the new screen */

   refresh(NULL, NULL, NULL);
}

/*-------------------------------------------------------------------------*/