summaryrefslogtreecommitdiff
path: root/xc/programs/Xserver/PEX5/ddpex/mi/level4/miStruct.c
blob: 7bf23045be8ec17bf31128844480c106e350e2f5 (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
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
/* $XConsortium: miStruct.c,v 5.12 94/04/17 20:37:33 hersh Exp $ */
/*

Copyright (c) 1989, 1990, 1991  X Consortium

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of the X Consortium shall
not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization
from the X Consortium.


Copyright (c) 1989, 1990, 1991 by Sun Microsystems, Inc. 
All Rights Reserved

Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of Sun Microsystems
not be used in advertising or publicity pertaining to distribution
of the software without specific, written prior permission.

SUN MICROSYSTEMS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT
SHALL SUN MICROSYSTEMS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.

*/

#include "mipex.h"
#include "ddpex4.h"
#include "miStruct.h"
#include "PEXErr.h"
#include "PEXproto.h"
#include "pexError.h"
#include "pexUtils.h"
#include "miStrMacro.h"

/*  Level 4 Workstation Support */
/*  Structure Procedures  */

extern cssTableType CreateCSSElementTable[];
extern cssTableType DestroyCSSElementTable[];
extern cssTableType CopyCSSElementTable[];
extern cssTableType ReplaceCSSElementTable[];
extern cssTableType InquireCSSElementTable[];

extern ddBOOL   miGetStructurePriority();

extern ddpex4rtn miDealWithStructDynamics();
extern ddpex4rtn miDealWithDynamics();

void            miPrintPath();

#define SET_STR_HEADER(pStruct, pheader)				\
    register miStructPtr pheader = (miStructPtr) pStruct->deviceData

#define DESTROY_STR_HEADER(pheader)					\
	if (pheader->parents)	puDeleteList(pheader->parents);		\
	if (pheader->children)	puDeleteList(pheader->children);	\
	if (pheader->wksPostedTo)  puDeleteList(pheader->wksPostedTo);	\
	if (pheader->wksAppearOn)  puDeleteList(pheader->wksAppearOn);	\
	if (MISTR_ZERO_EL(pheader))  xfree(MISTR_ZERO_EL(pheader));	\
	if (MISTR_LAST_EL(pheader))  xfree(MISTR_LAST_EL(pheader));	\
	xfree(pheader)

#define	CHECK_DELETE(pHandle, pheader)					\
	if ((pheader)->freeFlag && !(pheader)->refCount) {		\
		DESTROY_STR_HEADER(pheader);				\
		xfree(pHandle);						\
	}

/*++
 |
 |  Function Name:	pos2offset
 |
 |  Function Description:
 |	  a utility function for converting whence, offset values to a valid
 |	  structure offset
 |
 |  Note(s):
 |
 --*/

static          ddpex4rtn
pos2offset(pstruct, ppos, poffset)
/* in */
	miStructStr    *pstruct;/* pointer to the structure involved */
	ddElementPos   *ppos;	/* the position information */
/* out */
	ddULONG        *poffset;/* the valid offset calculated from the
				 * postition */
{
	ddUSHORT        whence = ppos->whence;
	ddLONG          offset = ppos->offset, temp;

#ifdef DDTEST
	ErrorF("    POSITION : ");
#endif

	switch (whence) {
	case PEXBeginning:

#ifdef DDTEST
		ErrorF("PEXBeginning, ");
#endif

		temp = offset;
		break;

	case PEXCurrent:

#ifdef DDTEST
		ErrorF("PEXCurrent, ");
#endif

		temp = MISTR_CURR_EL_OFFSET(pstruct) + offset;
		break;

	case PEXEnd:

#ifdef DDTEST
		ErrorF("End, ");
#endif

		/* numElements is the same as the last elements offset */
		temp = MISTR_NUM_EL(pstruct) + offset;
		break;

	default:

#ifdef DDTEST
		ErrorF("Bad Value\n ");
#endif

		/* value error */
		return (BadValue);
		break;
	}

#ifdef DDTEST
	ErrorF("%d", offset);
#endif

	/* now check that the new offset is in range of the structure */
	if (temp < 0)
		*poffset = 0;
	else if (temp > MISTR_NUM_EL(pstruct))
		*poffset = MISTR_NUM_EL(pstruct);
	else
		*poffset = temp;

#ifdef DDTEST
	ErrorF(" = %d\n", *poffset);
#endif

	return (0);
}

/*++
 |
 |  Function Name:	CreateStructure
 |
 |  Function Description:
 |	 Handles the PEXCreateStructure request.
 |
 |  Note(s):
 |
 --*/

ddpex4rtn
CreateStructure(pStruct)
/* in */
	diStructHandle  pStruct;/* structure handle */
/* out */
{
    register miStructStr *pheader;
    register miGenericElementPtr pelement;

#ifdef DDTEST
    ErrorF("\nCreateStructure %d\n", pStruct->id);
#endif

    pStruct->deviceData = NULL;

    if ((pheader = (miStructStr *) xalloc(sizeof(miStructStr))) == NULL)
	return (BadAlloc);

    MISTR_EDIT_MODE(pheader) = PEXStructureInsert;
    MISTR_NUM_EL(pheader) = 0;
    MISTR_LENGTH(pheader) = 0;

    pheader->refCount = 0;
    pheader->freeFlag = MI_FALSE;

    pheader->parents = pheader->children = pheader->wksPostedTo = pheader->wksAppearOn = NULL;

    pheader->parents = puCreateList(DD_STRUCT);
    pheader->children = puCreateList(DD_STRUCT);
    pheader->wksPostedTo = puCreateList(DD_WKS);
    pheader->wksAppearOn = puCreateList(DD_WKS);
    if (    !pheader->parents	    || !pheader->children
	 || !pheader->wksPostedTo   || !pheader->wksAppearOn) {
	DESTROY_STR_HEADER(pheader);
	return (BadAlloc);
    }
    /* create dummy first and last elements */
    if ((pelement = (miGenericElementPtr)xalloc(sizeof(miGenericElementStr)))
	    == NULL) {
	DESTROY_STR_HEADER(pheader);
	return (BadAlloc);
    }
    MISTR_PREV_EL(pelement) = NULL;
    MISTR_EL_TYPE(pelement) = PEXOCNil;
    MISTR_EL_LENGTH(pelement) = 1;
    MISTR_ZERO_EL(pheader) = MISTR_CURR_EL_PTR(pheader) = pelement;
    MISTR_CURR_EL_OFFSET(pheader) = 0;

    if ((pelement = (miGenericElementPtr) xalloc(sizeof(miGenericElementStr)))
	    == NULL) {
	DESTROY_STR_HEADER(pheader);
	return (BadAlloc);
    }
    MISTR_EL_TYPE(pelement) = PEXOCNil;
    MISTR_EL_LENGTH(pelement) = 1;
    MISTR_PREV_EL(pelement) = MISTR_ZERO_EL(pheader);
    MISTR_NEXT_EL(pelement) = NULL;
    MISTR_NEXT_EL(MISTR_ZERO_EL(pheader)) = pelement;
    MISTR_LAST_EL(pheader) = pelement;

    pStruct->deviceData = (ddPointer) pheader;
    return (Success);
}				/* CreateStructure */

/*++
 |
 |  Function Name:	CopyStructure
 |
 |  Function Description:
 |	 Handles the PEXCopyStructure request.
 |
 |  Note(s):
 |
 --*/

ddpex4rtn
CopyStructure(pSrcStruct, pDestStruct)
/* in */
    diStructHandle  pSrcStruct;	/* source structure */
    diStructHandle  pDestStruct;	/* destination structure */
{
    SET_STR_HEADER(pSrcStruct, psource);
    SET_STR_HEADER(pDestStruct, pdest);
    ddpex4rtn       err = Success;
    ddElementRange  sourceRange;
    ddElementPos    destPos;
    miGenericElementPtr pel;
    register ddULONG i;

#ifdef DDTEST
    ErrorF("\nCopyStructure\n");
#endif

    /* to do: make this smarter so it can use Replace if possible */

    i = MISTR_NUM_EL(pdest);
    MISTR_DEL_ELS(pDestStruct, pdest, 1, i);	/* can't use NUM_EL macro here 
						 * because the num of els
						 * changes as they are deleted */

    MISTR_CURR_EL_OFFSET(pdest) = 0;
    MISTR_CURR_EL_PTR(pdest) = MISTR_ZERO_EL(pdest);

    sourceRange.position1.whence = PEXBeginning;
    sourceRange.position1.offset = 0;
    sourceRange.position2.whence = PEXEnd;
    sourceRange.position2.offset = 0;
    destPos.whence = PEXBeginning;
    destPos.offset = 0;

    /* Copy Elements will redraw picture if nec */
    if (err = CopyElements(pSrcStruct, &sourceRange, pDestStruct, &destPos)
	    != Success)
	return (err);

    MISTR_EDIT_MODE(pdest) = MISTR_EDIT_MODE(psource);
    MISTR_CURR_EL_OFFSET(pdest) = MISTR_CURR_EL_OFFSET(psource);

    MISTR_FIND_EL(pdest, MISTR_CURR_EL_OFFSET(pdest), pel);
    MISTR_CURR_EL_PTR(pdest) = pel;

    return (Success);
}				/* CopyStructure */

/* find_execute_structure looks for the specified execute structure element
 * If the specified structure is NULL, then it finds the next one.
 * If the element is found, its offset from the start is returned in poffset
 * When calling this repeatedly to look for all occurrences of the element,
 * be sure to check that you've reached the end of the structure. Otherwise
 * you would infinitely loop on finding the last element if it is a match.
 */
static          ddpex4rtn
find_execute_structure(pStruct, pStartPos, structHandle, poffset)
diStructHandle  pStruct;/* search this structure */
ddElementPos   *pStartPos;
diStructHandle  structHandle;	/* for this exec structure element */
ddULONG        *poffset;
{
    SET_STR_HEADER(pStruct, pstruct);
    ddUSHORT        foundExecuteElement;
    ddUSHORT        executeStructureElement = PEXOCExecuteStructure;
    miGenericElementPtr pel;
    ddpex4rtn	    err = Success;

    while (err == Success) {
	/** Get the position of the next execute structure element **/
	err = ElementSearch(	pStruct, pStartPos, (ddULONG) PEXForward, 
				(ddULONG) 1, (ddULONG) 0,
				&executeStructureElement, (ddUSHORT *) NULL,
				&foundExecuteElement, poffset);

	if (foundExecuteElement == PEXFound) {
	    MISTR_FIND_EL(pstruct, *poffset, pel);

	    if (    (structHandle == (diStructHandle) MISTR_GET_EXSTR_STR(pel))
		 || (structHandle == (diStructHandle) NULL))
			return (PEXFound);

	    /*
	     * continue searching at the next element unless this one 
	     * was the last
	     */
	    if (*poffset == MISTR_NUM_EL(pstruct)) return (PEXNotFound);

	    pStartPos->whence = PEXBeginning;
	    pStartPos->offset = *poffset + 1;
	} else
	    return (PEXNotFound);

    }
    if (err != Success) return (PEXNotFound);
    return (PEXFound);
}

/*++
 |
 |  Function Name:	DeleteStructureRefs
 |
 |  Function Description:
 |	 Handles the PEXDeleteStructures request.
 |
 |          This routine deletes all structure elements in all of the
 |       structures which reference the specified structure. It is called
 |       by DeleteStructure.
 |
 |  Note(s):
 |	This does not correct the picture because it is called by
 |	DeleteStructure, which does correct it
 |
 --*/

ddpex4rtn
DeleteStructureRefs(pStruct)
/* in */
    diStructHandle  pStruct;/* structure handle */
/* out */
{

    SET_STR_HEADER(pStruct, pstruct);
    diStructHandle  parentHandle;
    miStructPtr     pparentStruct;
    ddElementPos    position;
    miGenericElementPtr newPointer;
    miGenericElementPtr pel, pprevel;
    ddLONG          newOffset;
    ddULONG         offsetFromStart, numParents;

#ifdef DDTEST
    ErrorF("\nDeleteStructureRefs of structure %d\n", pStruct->id);
#endif				/* DDTEST */

    /** Search through each of the structure's parents **/

    /*
     * The tricky part here is that each time the execute structure
     * element is deleted from the parent, the structure's parent list
     * changes (in DeleteElements) so, remember how many parents there
     * originally are and look at that many.  Each time a parent is
     * deleted from the list, it's always deleted from the front of the
     * list, so the next parent will be at the front of the list the next
     * time through
     */
    for (numParents = pstruct->parents->numObj; numParents > 0;) {
	parentHandle = *(diStructHandle *) pstruct->parents->pList;

	/*
	 * look through all of this structure's elements to delete
	 * all references to the structure being deleted
	 */
	pparentStruct = (miStructPtr) (parentHandle)->deviceData;

	newOffset = 0;
	newPointer = NULL;

	/*
	 * look for all execute structure (child) elements in the
	 * parent structure and delete them this could do only one
	 * element at a time. any other elements would be gotten
	 * later because the parent is duplicated in the childs list
	 * for each occurrence and the outer loop would find the
	 * parent again.
	 */
	/* start looking at the beginning of the parent structure */
	position.whence = PEXBeginning;
	position.offset = 0;

	/*
	 * dont' forget we're really comparing the structure handles
	 * because the id was replaced with the handle in the exec
	 * str elements
	 */
	while (find_execute_structure(	parentHandle, &position, pStruct,
					&offsetFromStart)
		== PEXFound) {
	    if (offsetFromStart == MISTR_CURR_EL_OFFSET(pparentStruct)) {
		newOffset = MISTR_CURR_EL_OFFSET(pparentStruct) - 1;
		newPointer = MISTR_PREV_EL(MISTR_CURR_EL_PTR(pparentStruct));
	    } else if (offsetFromStart < MISTR_CURR_EL_OFFSET(pparentStruct)) {
		newOffset = MISTR_CURR_EL_OFFSET(pparentStruct) - 1;
		newPointer = MISTR_CURR_EL_PTR(pparentStruct);
	    } else {
		newOffset = MISTR_CURR_EL_OFFSET(pparentStruct);
		newPointer = MISTR_CURR_EL_PTR(pparentStruct);
	    }

	    MISTR_FIND_EL(pparentStruct, offsetFromStart, pel);
	    pprevel = MISTR_PREV_EL(pel);

	    MISTR_DEL_ONE_EL(parentHandle, pprevel, pel);

	    MISTR_CURR_EL_PTR(pparentStruct) = newPointer;
	    MISTR_CURR_EL_OFFSET(pparentStruct) = newOffset;

	    numParents--;

	    /*
	     * continue looking for other execute structures
	     * after the one found but it just got deleted, so
	     * the next one is now the same offset as the old one
	     */
	    position.whence = PEXBeginning;
	    position.offset = offsetFromStart;
	}

    }

    return (Success);
}				/* DeleteStructureRefs */

/*++
 |
 |  Function Name: DeleteStructure
 |
 |  Function Description:
 |	Deletes all storage associated with the structure
 |
 |  Note(s):
 |
 --*/

ddpex4rtn
DeleteStructure(pStruct, Sid)
/* in */
    diStructHandle  pStruct;/* structure handle */
    ddResourceId    Sid;	/* structure resource id */
/* out */
{
    SET_STR_HEADER(pStruct, pheader);
    register ddULONG i, imax;
    diWKSHandle     pwks;
    ddpex4rtn       err = Success, next_err = Success;
    listofObj      *pwksToLookAt;

#ifdef DDTEST
    ErrorF("\nDeleteStructure %d\n", pStruct->id);
#endif

    /*
     * Errors are ignored to try to delete and update as much info as possible;
     * however, if an error is found, the last error detected is returned.
     */

    /*
     * Save the posted to list before unposting this structure so wks
     * pictures can be updated if necessary.
     */
    /* Do this here before the parent and children lists are changed. */

    /** Build up a list of workstations from the PostedTo and AppearOn
     ** lists in the structure structure.  They are inserted in such a
     ** manner so that duplicates between the lists are eliminated.
     **/

    pwksToLookAt = (listofObj *) NULL;

    if (pheader->wksPostedTo->numObj || pheader->wksAppearOn->numObj) {
	pwksToLookAt = puCreateList(DD_WKS);
	if (!pwksToLookAt) err = BadAlloc;
	else
	    err = puMergeLists(	pheader->wksPostedTo, pheader->wksAppearOn, 
				pwksToLookAt);
    }

    /*
     * This changes the structures posted to list (because unpost removes
     * the wks from this list) so always get the first wks from the list.
     */
    imax = pheader->wksPostedTo->numObj;
    for (i = 0; i < imax; i++) {
	pwks = ((diWKSHandle *) pheader->wksPostedTo->pList)[0];
	next_err = UnpostStructure(pwks, pStruct);
    }

    /*
     * Now, delete all of the references to this struct (i.e. remove this
     * structure from its parents).
     */
    next_err = DeleteStructureRefs(pStruct);
    if (next_err != Success) err = next_err;

    /* loop through to delete all of the elements */
    i = MISTR_NUM_EL(pheader);
    MISTR_DEL_ELS(pStruct, pheader, 1, i);

    /* now redraw picture for all workstations (determined above) */
    if (pwksToLookAt) {
	next_err = miDealWithDynamics(DELETE_STR_DYNAMIC, pwksToLookAt);
	if (next_err != Success) err = next_err;
	puDeleteList(pwksToLookAt);
    }

    /*
     * Don't delete the structure until sc and pick resources aren't using it.
     */
    pStruct->id = PEXAlreadyFreed;
    pheader->freeFlag = MI_TRUE;
    CHECK_DELETE(pStruct, pheader);

    return (err);
}				/* DeleteStructure */

/*++
 |
 |  Function Name:	InquireStructureInfo
 |
 |  Function Description:
 |	 Handles the PEXGetStructureInfo request.
 |
 |  Note(s):
 |
 --*/

ddpex4rtn
InquireStructureInfo(fpFormat, pStruct, itemMask, pEditMode, pElOffset, pNumElements, pLength, pHasRefs)
/* in */
	ddEnumTypeIndex fpFormat;
	diStructHandle  pStruct;	/* structure handle */
	ddBitmask       itemMask;
/* out */
	ddUSHORT       *pEditMode;	/* edit mode */
	ddULONG        *pElOffset;	/* current element pointer */
	ddULONG        *pNumElements;	/* number of elements in structure */
	ddULONG        *pLength;	/* total size of structure */
	ddUSHORT       *pHasRefs;	/* is structure referenced by others */
{
	SET_STR_HEADER(pStruct, pheader);

#ifdef DDTEST
	ErrorF("\nInquireStructureInfo of %d\n", pStruct->id);
#endif

	/* Since all info is easily available and this is a fixed-length
	 * request, ignore itemMask (to the dismay of lint).
	 */
	*pEditMode = MISTR_EDIT_MODE(pheader);
	*pElOffset = MISTR_CURR_EL_OFFSET(pheader);
	*pNumElements = MISTR_NUM_EL(pheader);

	/*
	 * test here: if fpFormat is double precision, then recalculate
	 * length
	 */
	*pLength = MISTR_LENGTH(pheader);
	*pHasRefs = MISTR_NUM_PARENTS(pheader) != 0;
	return (Success);
}				/* InquireStructureInfo */

/*++
 |
 |  Function Name:	InquireElementInfo
 |
 |  Function Description:
 |	 Handles the PEXGetElementInfo request.
 |
 |  Note(s):
 |
 --*/

ddpex4rtn
InquireElementInfo(pStruct, pRange, pNumElements, pBuffer)
/* in */
	diStructHandle  pStruct;/* structure handle */
	ddElementRange *pRange;	/* element range */
/* out */
	ddULONG        *pNumElements;	/* number of items in list */
	ddBufferPtr     pBuffer;/* list of element information */
{
	SET_STR_HEADER(pStruct, pheader);
	ddULONG         offset1, offset2, needbytes, i;
	int             peisize;
	ddPointer       pbuf;
	miGenericElementPtr pel;

#ifdef DDTEST
	ErrorF("\nInquireElementInfo %d\n", pStruct->id);
#endif

	peisize = sizeof(pexElementInfo);

	if (pos2offset(pheader, &(pRange->position1), &offset1))
		return (BadValue);	/* bad whence value */

	if (pos2offset(pheader, &(pRange->position2), &offset2))
		return (BadValue);	/* bad whence value */

	if (offset1 > offset2) {
		i = offset1;
		offset1 = offset2;
		offset2 = i;
	}

	if (offset1 == 0)
		if (offset2 == 0)
			return(Success);
		else
			offset1 = 1;


	/* make sure buffer is large enough */
	needbytes = (offset2 - offset1 + 1) * peisize;
	PU_CHECK_BUFFER_SIZE(pBuffer, needbytes);

	pbuf = pBuffer->pBuf;

	MISTR_FIND_EL(pheader, offset1, pel);

	/*
	 * remember that element data is required to have the type & length
	 * first so this is portable
	 */
	for (i = offset1; i <= offset2; i++, pbuf += peisize) {
		mibcopy(&MISTR_EL_DATA(pel), pbuf, peisize);
		pel = MISTR_NEXT_EL(pel);
	}

	*pNumElements = offset2 - offset1 + 1;
	pBuffer->dataSize = *pNumElements * peisize;

	return (Success);
}				/* InquireElementInfo */

static          ddpex4rtn
get_structure_net(pStruct, plist)
	diStructHandle  pStruct;
	listofObj      *plist;
{
	SET_STR_HEADER(pStruct, pheader);
	register int    i;
	register diStructHandle *pchild;

	/* put this structure on the list  */
	if (puAddToList((ddPointer) & pStruct, (ddULONG) 1, plist) ==
	    MI_ALLOCERR)
		return (BadAlloc);

	/* loop through all of the children of this structure */
	pchild = (diStructHandle *) pheader->children->pList;
	for (i = 0; i < pheader->children->numObj; i++, pchild++)
		if (get_structure_net(*pchild, plist) == BadAlloc)
			return (BadAlloc);

	return (Success);
}

/*++
 |
 |  Function Name:	InquireStructureNetwork
 |
 |  Function Description:
 |	 Handles the PEXGetStructuresInNetwork request.
 |
 |  Note(s):
 |
 --*/

ddpex4rtn
InquireStructureNetwork(pStruct, which, pNumSids, pBuffer)
/* in */
    diStructHandle  pStruct;	/* structure handle */
    ddUSHORT        which;	/* which structures to inquire */
/* out */
    ddULONG        *pNumSids;	/* number of ids in list */
    ddBufferPtr     pBuffer;	/* list of structure ids */
{
    register int	i, j, num;
    ddResourceId	*pbuf;
    ddStructResource	**pstruct, **pparent;
    listofObj		*plist1, *plist2;
    ddBOOL		removing;

#ifdef DDTEST
    ErrorF("\nInquireStructureNetwork\n");
#endif

    pBuffer->dataSize = 0;
    *pNumSids = 0;

    plist1 = puCreateList(DD_STRUCT);
    if (!plist1) return (BadAlloc);

    plist2 = puCreateList(DD_STRUCT);
    if (!plist2) {
	puDeleteList(plist1);
	return (BadAlloc);
    }

    if (get_structure_net(pStruct, plist1) != Success) {
	puDeleteList(plist1);
	puDeleteList(plist2);
	return (BadAlloc);
    }
    /* now, make the list unique */
    puMergeLists(plist1, plist2, plist2);

    /* adjust for orphans if requested */
    if (which == PEXOrphans) {

	/*
	 * Look at the parents of each structure in list 3 if any parent is 
	 * not in the list, then that structure is not an orphan (i.e., it 
	 * is referenced by a structure not in this net), so remove it from 
	 * the list.
	 * 
	 * This is a pain though, because we aren't guaranteed that all
	 * parents of a structure precede it in the list; e.g., if plist2 
	 * for the network below starting at A is A, B, C, D, then when C
	 * is reached, both of its parents (B & D) are in the list, so it
	 * won't be deleted.  But when D is reached, (after C) it will have 
	 * parent E not in the list, so D will be deleted. Now C should be 
	 * deleted also.
	 *
	 * A   E / \ / B   D \ / C
	 * 
	 * My solution to this is to loop through plist2 multiple times until 
	 * it is gone through once without any structs being deleted from it. 
	 * If you have a better algorithm for this, then tell me about it.
	 * One solution is to guarantee the list has all parents in it before 
	 * their children.  I can't think of a way to do this, however.
	 */
	removing = MI_TRUE;
	while (removing) {
	    removing = MI_FALSE;
	    pstruct = (ddStructResource **) plist2->pList;

	    /*
	     * Note, while going through the list, it may be changed, so be
	     * careful of when pstruct gets incremented and be sure num
	     * reflects the original size of the list, not any changes made 
	     * to it.
	     */
	    num = plist2->numObj;
	    for (i = 0; i < num; i++, pstruct++) {
		pparent = (ddStructResource **)((miStructPtr)(*pstruct)->deviceData)->parents->pList;
		for ( j = 0;
		      j < ((miStructPtr)(*pstruct)->deviceData)->parents->numObj;
		      j++, pparent++) {
		    if (!puInList((ddPointer) pparent, plist2)) {

			/*
			 * This struct is not an orphan.
			 */
			puRemoveFromList((ddPointer) pstruct, plist2);
			removing = MI_TRUE;

			/*
			 * Decrement the pointer so when it gets incremented
			 * in the for loop, it points to where the deleted
			 * struct was,
			 */
			pstruct--;
			break;
		    }
		}
	    }
	}
    }
    /* now, return the structure ids */
    if (PU_BUF_TOO_SMALL(pBuffer, plist2->numObj * sizeof(ddResourceId))) {
	if (puBuffRealloc(pBuffer, (ddULONG) plist2->numObj) != Success) {
	    pBuffer->dataSize = 0;
	    puDeleteList(plist1);
	    puDeleteList(plist2);
	    return (BadAlloc);
	}
    }
    *pNumSids = plist2->numObj;
    pbuf = (ddResourceId *) pBuffer->pBuf;
    pstruct = (ddStructResource **) plist2->pList;
    for (i = 0; i < plist2->numObj; i++, pbuf++, pstruct++)
	*pbuf = (*pstruct)->id;

    pBuffer->dataSize = plist2->numObj * sizeof(ddResourceId);

    puDeleteList(plist1);
    puDeleteList(plist2);
    return (Success);
}				/* InquireStructureNetwork */


/* bufSave is the size of the buffer header when the buffer is
 * passed into inq ancestors/descendants.  the pBuf pointer
 * is changed as paths are added to the buffers and bufSave
 * is used to find where pBuf originally started
 */
static int      bufSave;

#define MI_ANCESTORS 0
#define MI_DESCENDANTS 1

/* given a path, which is a list of descendants (in top-down order)
 * or ancestors (in bottom-down order), see if the depth-length
 * pathPart part of the list matches any of the lists already
 * put in the buffer.  If it doesn't, then it's unique and this
 * proc returns MI_TRUE, else it returns MI_FALSE
 */
static          ddBYTE
path_unique(pathPart, depth, pNumLists, pBuffer, pPath, which)
    ddUSHORT        pathPart;
    ddULONG         depth;
    ddULONG        *pNumLists;
    ddBufferPtr     pBuffer;
    listofObj      *pPath;	/* current path */
    ddSHORT         which;
{
    register int    i, j;
    ddPointer       pb;
    ddULONG        *ll;
    ddElementRef   *pref, *ppath, *pathstart;
    ddBYTE          match;

    if (!depth || pPath->numObj < depth) depth = pPath->numObj;

    pb = pBuffer->pHead + bufSave;
    pathstart = (ddElementRef *) pPath->pList;
    if (which == MI_DESCENDANTS)
	pathstart += (pathPart == PEXTopPart) ? 0 : pPath->numObj - depth;
    else
	pathstart += ((pathPart == PEXTopPart) ? pPath->numObj - 1 : depth - 1);

    for (i = 0; i < *pNumLists; i++) {
	ll = (ddULONG *) pb;
	pb += 4;
	pref = (ddElementRef *) pb;
	ppath = pathstart;
	match = MI_TRUE;
	if (*ll == depth) {
	    if (which==MI_DESCENDANTS) {/* descendants: increment through path */
		for (j = 0; (j < *ll && match); j++, pref++, ppath++) {
		    if (    (ppath->structure != pref->structure)
			 || (ppath->offset != pref->offset))
			match = MI_FALSE;
		}
	    } else {/* ancestors: decrement through path */
		for (j = 0; (j < *ll && match); j++, pref++, ppath--) {
		    if (    (ppath->structure != pref->structure)
			 || (ppath->offset != pref->offset))
			match = MI_FALSE;
		}
	    }
	}
	pb += *ll * sizeof(ddElementRef);
	if (match) return (MI_FALSE);
    }

    return (MI_TRUE);
}

static          ddpex4rtn
copy_list_to_buf(pathPart, depth, pNumLists, pBuffer, pPath, which)
	ddUSHORT        pathPart;
	ddULONG         depth;
	ddULONG        *pNumLists;
	ddBufferPtr     pBuffer;
	listofObj      *pPath;
	ddSHORT         which;
{
	ddUSHORT        listsize;
	ddULONG        *pb;
	ddElementRef   *pref, *pbref;

	if (!depth || (pPath->numObj < depth))
		depth = pPath->numObj;
	listsize = depth * sizeof(ddElementRef);
	PU_CHECK_BUFFER_SIZE(pBuffer, listsize + 4);

	pb = (ddULONG *) pBuffer->pBuf;
	*pb++ = depth;
	pref = (ddElementRef *) pPath->pList;
	if (which == MI_DESCENDANTS) {
		if (pathPart == PEXTopPart)
			mibcopy(pref, pb, listsize);
		else {
			pbref = (ddElementRef *) pb;
			pref += pPath->numObj - 1;
			while (depth--)
				*pbref++ = *pref--;
		}
	} else {
		if (pathPart == PEXBottomPart)
			mibcopy(pref, pb, listsize);
		else {
			pbref = (ddElementRef *) pb;
			pref += pPath->numObj - 1;
			while (depth--)
				*pbref++ = *pref--;
		}
	}
	(*pNumLists)++;
	pBuffer->pBuf += listsize + 4;
	pBuffer->dataSize += listsize + 4;

	return (Success);
}

static          ddpex4rtn
get_ancestors(pStruct, pathPart, depth, pNumLists, pBuffer, pPath)
    diStructHandle  pStruct;
    ddUSHORT        pathPart;
    ddULONG         depth;
    ddULONG        *pNumLists;
    ddBufferPtr     pBuffer;
    listofObj      *pPath;	/* current path */
{
    SET_STR_HEADER(pStruct, pheader);
    diStructHandle  pParent;
    miStructPtr     pparent;
    register int    num;
    ddElementRef    newref;
    ddULONG         offset;
    ddElementPos    position;
    ddpex4rtn       err;
    listofObj      *singleparents;

    /* start out with the current struct */
    if (!pPath->numObj) {
	newref.structure = (diStructHandle) pStruct->id;
	newref.offset = 0;
	if (puAddToList((ddPointer) & newref, (ddULONG) 1, pPath) != Success)
	    return (BadAlloc);
    }
    /* we're at the root or have gone far enough */
    num = pheader->parents->numObj;
    if (!num || ((pathPart==PEXBottomPart) && depth && (pPath->numObj==depth))) {
	if (	(pathPart == PEXTopPart) && depth && (pPath->numObj > depth)
	     && !path_unique(	pathPart, depth, pNumLists, pBuffer, pPath, 
				MI_ANCESTORS))

	    /*
	     * if path is top first and has to be truncated to depth, don't 
	     * add it to the buffer unless it's unique
	     */
	    err = Success;
	else
	    err = copy_list_to_buf( pathPart, depth, pNumLists, pBuffer, pPath,
				    MI_ANCESTORS);

/*>>>	pPath->numObj--; */
	return (err);
    }

    /* take duplicates out of the list of parents */
    singleparents = puCreateList(DD_STRUCT);
    if (!singleparents) return (BadAlloc);

    if (puMergeLists(pheader->parents, singleparents, singleparents) != Success)
	return (BadAlloc);

    num = singleparents->numObj;
    while (num--) {
	pParent = ((diStructHandle *) singleparents->pList)[num];
	pparent = (miStructPtr) pParent->deviceData;

	/*
	 * now, look for each execute structure of this structure in the parent
	 */
	position.whence = PEXBeginning;
	position.offset = 0;

	while (find_execute_structure(pParent, &position, pStruct, &offset)
		       == PEXFound) {

	    newref.structure = (diStructHandle) pParent->id;
	    newref.offset = offset;
	    if (puAddToList((ddPointer) & newref, (ddULONG) 1, pPath) != Success)
		return (BadAlloc);

	    /*
	     * get the ancestors of this parent struct
	     */
	    if (err = get_ancestors(	pParent, pathPart, depth, pNumLists,
					pBuffer, pPath) != Success)
		return (err);

	    /*
	     * go on to get the next exec struct element in the parent
	     */
	    position.whence = PEXBeginning;
	    position.offset = offset + 1;

	    /*
	     * Remove previous parent/ofset from the pathlist so the same 
	     * pathlist can be used for the next path.
	     */
	    pPath->numObj--;

	    /*
	     * if the last one found was the last element in the
	     * struct, don't continue
	     */
	    if (offset == MISTR_NUM_EL(pparent)) break;

	}	/* end while finding execute structure elements in the parent */
    }		/* end while (num--): while this child has parents to look at */

    puDeleteList(singleparents);

    return (Success);
}

static          ddpex4rtn
get_descendants(pStruct, pathPart, depth, pNumLists, pBuffer, pPath)
    diStructHandle  pStruct;
    ddUSHORT        pathPart;
    ddULONG         depth;
    ddULONG        *pNumLists;
    ddBufferPtr     pBuffer;
    listofObj      *pPath;	/* current path */
{
    SET_STR_HEADER(pStruct, pheader);
    register int    num;
    ddElementRef    newref;
    diStructHandle  newstruct;
    ddULONG         offset;
    ddElementPos    position;
    ddpex4rtn       err;
    miGenericElementPtr pel;

    /* if we're at the end of the path put the path in the buffer  */
    num = pheader->children->numObj;
    if (!num || ((pathPart == PEXTopPart) && depth && (pPath->numObj == depth))){
	/* add this structure  to the path */

	/*
	 * don't need to do this if (pathPart == PEXTopPart) && depth
	 *  && (pPath->numObj == depth), but it's ok to do it because
	 * it won't get put into the buffer
	 */
	newref.structure = (diStructHandle) pStruct->id;
	newref.offset = 0;
	if (puAddToList((ddPointer) & newref, (ddULONG) 1, pPath) != Success)
	    return (BadAlloc);

	if (	(pathPart == PEXBottomPart) && depth && (pPath->numObj > depth)
	     && !path_unique(	pathPart, depth, pNumLists, pBuffer, pPath,
				MI_DESCENDANTS))

	    /*
	     * If path is bottom first and has to be truncated to depth, 
	     * don't add it to the buffer unless it's unique.
	     */
	    err = Success;
	else
	    err = copy_list_to_buf( pathPart, depth, pNumLists, pBuffer, pPath,
				    MI_DESCENDANTS);

	pPath->numObj--;
	return (err);
    }

    /* now, look for each execute structure element in the structure  */
    position.whence = PEXBeginning;
    position.offset = 0;
    while (find_execute_structure(  pStruct, &position, (diStructHandle) NULL,
				    &offset)
	       == PEXFound) {
	newref.structure = (diStructHandle) pStruct->id;
	newref.offset = offset;
	if (puAddToList((ddPointer) & newref, (ddULONG) 1, pPath) != Success)
	    return (BadAlloc);

	/*
	 * get the descendants of this child struct remember,
	 */
	MISTR_FIND_EL(pheader, offset, pel);

	newstruct = (diStructHandle) MISTR_GET_EXSTR_STR(pel);
	if (err = get_descendants(  newstruct, pathPart, depth, pNumLists,
				    pBuffer, pPath) != Success)
	    return (err);

	/* go on to get the next child */
	position.whence = PEXBeginning;
	position.offset = offset + 1;

	/*
	 * remove previous child from the pathlist so the same
	 * pathlist can be used for the next path
	 */
	pPath->numObj--;

	/*
	 * if the last one found was the last element in the struct,
	 * don't continue
	 */
	if (offset == MISTR_NUM_EL(pheader)) break;
    }

    return (Success);
}

/*++
 |
 |  Function Name:	InquireAncestors
 |
 |  Function Description:
 |	 Handles the PEXGetAncestors request.
 |
 |  Note(s):
 |
 --*/

ddpex4rtn
InquireAncestors(pStruct, pathPart, depth, pNumLists, pBuffer)
/* in */
    diStructHandle  pStruct;/* structure handle */
    ddUSHORT        pathPart;	/* which paths to return */
    ddULONG         depth;	/* how deep to search */
/* out */
    ddULONG        *pNumLists;	/* number of lists returned */
    ddBufferPtr     pBuffer;/* list of lists of element refs */
{
    listofObj      *pathlist;
    ddpex4rtn       err;

#ifdef DDTEST
    ErrorF("\nInquireAncestors\n");
#endif

    bufSave = PU_BUF_HDR_SIZE(pBuffer);
    pBuffer->dataSize = 0;
    *pNumLists = 0;

    pathlist = puCreateList(DD_ELEMENT_REF);
    if (!pathlist) return (BadAlloc);

    err = get_ancestors(pStruct, pathPart, depth, pNumLists, pBuffer, pathlist);

    pBuffer->pBuf = pBuffer->pHead + bufSave;
    puDeleteList(pathlist);
    return (err);
}				/* InquireAncestors */

/*++
 |
 |  Function Name:	InquireDescendants
 |
 |  Function Description:
 |	 Handles the PEXGetDescendants request.
 |
 |  Note(s):
 |
 --*/

ddpex4rtn
InquireDescendants(pStruct, pathPart, depth, pNumLists, pBuffer)
/* in */
    diStructHandle  pStruct;	/* structure handle */
    ddUSHORT        pathPart;	/* which paths to return */
    ddULONG         depth;	/* how deep to search */
/* out */
    ddULONG        *pNumLists;	/* number of lists returned */
    ddBufferPtr     pBuffer;	/* list of lists of element refs */
{
    listofObj      *pathlist;
    ddpex4rtn       err;

#ifdef DDTEST
    ErrorF("\nInquireDescendants\n");
#endif

    bufSave = PU_BUF_HDR_SIZE(pBuffer);
    pBuffer->dataSize = 0;
    *pNumLists = 0;

    pathlist = puCreateList(DD_ELEMENT_REF);
    if (!pathlist) return (BadAlloc);

    err = get_descendants(pStruct, pathPart, depth, pNumLists, pBuffer,pathlist);

    pBuffer->pBuf = pBuffer->pHead + bufSave;
    puDeleteList(pathlist);
    return (err);
}				/* InquireDescendants */


/*++
 |
 |  Function Name:	InquireElements
 |
 |  Function Description:
 |	 Handles the PEXFetchElements request.
 |
 |  Note(s):
 |
 --*/

ddpex4rtn
InquireElements(pStruct, pRange, pNumOCs, pBuffer)
/* in */
	diStructHandle  pStruct;/* structure handle */
	ddElementRange *pRange;	/* range of elements */
/* out */
	ddULONG        *pNumOCs;/* number of items in list */
	ddBufferPtr     pBuffer;/* list of element OCs */
{
	SET_STR_HEADER(pStruct, pheader);
	ddULONG         offset1, offset2, i;
	miGenericElementPtr pel;
	ddpex4rtn       err;

#ifdef DDTEST
	ErrorF("\nInquireElements of %d\n", pStruct->id);
#endif

	*pNumOCs = 0;

	if (pheader->numElements == 0) return(Success);

	if (pos2offset(pheader, &(pRange->position1), &offset1))
		return (BadValue);	/* bad whence value */

	if (pos2offset(pheader, &(pRange->position2), &offset2))
		return (BadValue);	/* bad whence value */

	if (offset1 > offset2) {
		i = offset1;
		offset1 = offset2;
		offset2 = i;
	}

	if (offset1 == 0)
		if (offset2 == 0)
			return(Success);
		else
			offset1 = 1;

	MISTR_FIND_EL(pheader, offset1, pel);

	for (i = offset1; i <= offset2; i++) {
	    /* Propreitary calls (and OCNil) through 0th Table Entry */
	    if (MI_HIGHBIT_ON(MISTR_EL_TYPE(pel)))
		err = (*InquireCSSElementTable[MI_OC_PROP])
				      (pel, pBuffer, &(pBuffer->pBuf));
	    else {
		/* not Proprietary see if valid PEX OC */
		if (MI_IS_PEX_OC(MISTR_EL_TYPE(pel)))
		    err = (*InquireCSSElementTable[MISTR_EL_TYPE(pel)])
				      (pel, pBuffer, &(pBuffer->pBuf));
		else
		    err = !Success;
	    }

	    if (err != Success) {
		*pNumOCs = i - offset1;
		return (err);
	    }
	    pBuffer->dataSize += sizeof(CARD32)
				*(((ddElementInfo *)(pBuffer->pBuf))->length);
	    pBuffer->pBuf += sizeof(CARD32)
				* (((ddElementInfo *)(pBuffer->pBuf))->length);

	    pel = MISTR_NEXT_EL(pel);
	}

	*pNumOCs = offset2 - offset1 + 1;
	return (Success);

}				/* InquireElements */

/*++
 |
 |  Function Name:	SetEditMode
 |
 |  Function Description:
 |	 Handles the PEXSetEditingMode request.
 |
 |  Note(s):
 |
 --*/

ddpex4rtn
SetEditMode(pStruct, editMode)
/* in */
	diStructHandle  pStruct;/* structure handle */
	ddUSHORT        editMode;	/* edit mode */
/* out */
{
	SET_STR_HEADER(pStruct, pheader);

#ifdef DDTEST
	ErrorF("\nSetEditMode of %d\n", pStruct->id);
#endif

	switch (editMode) {
	case PEXStructureInsert:
	case PEXStructureReplace:
		MISTR_EDIT_MODE(pheader) = editMode;
		return (Success);

	default:
		return (BadValue);
	}
}				/* SetEditMode */

/*++
 |
 |  Function Name:	SetElementPointer
 |
 |  Function Description:
 |	 Handles the PEXSetElementPointer request.
 |
 |  Note(s):
 |
 --*/

ddpex4rtn
SetElementPointer(pStruct, pPosition)
/* in */
	diStructHandle  pStruct;/* structure handle */
	ddElementPos   *pPosition;	/* position to set pointer at */
/* out */
{
	SET_STR_HEADER(pStruct, pstruct);
	register miGenericElementPtr pel;
	ddULONG         newoffset;


#ifdef DDTEST
	ErrorF("\nSetElementPointer of %d\n", pStruct->id);
#endif

	if (pos2offset(pstruct, pPosition, &newoffset)) {
		/* bad whence value */
		return (BadValue);
	}
	if (newoffset == MISTR_CURR_EL_OFFSET(pstruct))
		return (Success);

	/* special case */
	if (newoffset == 0) {
		MISTR_CURR_EL_OFFSET(pstruct) = 0;
		MISTR_CURR_EL_PTR(pstruct) = MISTR_ZERO_EL(pstruct);
		return (Success);
	}
	MISTR_FIND_EL(pstruct, newoffset, pel);

	MISTR_CURR_EL_OFFSET(pstruct) = newoffset;
	MISTR_CURR_EL_PTR(pstruct) = pel;
	return (Success);
}				/* SetElementPointer */

/* look for the next label */
static          ddpex4rtn
find_label(pStruct, label, startPos, poffset)
diStructHandle  pStruct;
ddLONG          label;
ddElementPos    startPos;
ddULONG        *poffset;
{
    ddUSHORT        foundLabelElement;
    SET_STR_HEADER(pStruct, pstruct);
    ddUSHORT        labelElement = PEXOCLabel;
    miGenericElementPtr pel;
    ddpex4rtn	    err = Success;

    do {
	err = ElementSearch(	pStruct, &startPos, (ddULONG) PEXForward,
				(ddULONG) 1, (ddULONG) 0, &labelElement,
				(ddUSHORT *) NULL, &foundLabelElement, poffset);

	if (foundLabelElement == PEXFound) {
	    MISTR_FIND_EL(pstruct, *poffset, pel);

	    if (label == MISTR_GET_LABEL(pel)) return (PEXFound);

	    if (*poffset == MISTR_NUM_EL(pstruct)) return (PEXNotFound);

	    /* continue searching after the new current element */
	    startPos.whence = PEXBeginning;
	    startPos.offset = *poffset + 1;

	} else return (PEXNotFound);

    } while (err == Success);

    if (err != Success) return (PEXNotFound);
    return (PEXFound);
}

/*++
 |
 |  Function Name:	SetElementPointerAtLabel
 |
 |  Function Description:
 |	 Handles the PEXSetElementPointerAtLabel request.
 |
 |  Note(s):
 |
 --*/

ddpex4rtn
SetElementPointerAtLabel(pStruct, label, offset)
/* in */
    diStructHandle  pStruct;/* structure handle */
    ddLONG          label;	/* label id */
    ddLONG          offset;	/* offset from label */
/* out */
{
    SET_STR_HEADER(pStruct, pstruct);
    ddElementPos    position;
    ddULONG         offsetFromStart;
    miGenericElementPtr pel;

#ifdef DDTEST
    ErrorF("\nSetElementPointerAtLabel\n");
#endif

    position.whence = PEXCurrent;
    position.offset = 1;

    if (find_label(pStruct, label, position, &offsetFromStart) == PEXNotFound)
	return (PEXERR(PEXLabelError));

    offsetFromStart += offset;

    if (offsetFromStart > MISTR_NUM_EL(pstruct))
	offsetFromStart = MISTR_NUM_EL(pstruct);

    MISTR_FIND_EL(pstruct, offsetFromStart, pel);

    MISTR_CURR_EL_PTR(pstruct) = pel;
    MISTR_CURR_EL_OFFSET(pstruct) = offsetFromStart;

    return (Success);
}				/* SetElementPointerAtLabel */

static          ddBOOL
InList(val, numInList, list)
	register ddUSHORT val;
	ddULONG         numInList;
	register ddUSHORT list[];
{
	/** Just do a linear search **/
	register int    i;
	for (i = 0; i < numInList; i++) {
		if ((val == list[i]) || PEXOCAll == list[i])
			return (MI_TRUE);
	}
	return (MI_FALSE);
}


/*++
 |
 |  Function Name:	ElementSearch
 |
 |  Function Description:
 |	 Handles the PEXElementSearch request.
 |
 |  Note(s):
 |
 --*/

ddpex4rtn
ElementSearch(pStruct, pPosition, direction, numIncl, numExcl,
	      pIncls, pExcls, pStatus, pOffset)
/* in */
    diStructHandle  pStruct;/* structure handle */
    ddElementPos   *pPosition;	/* search start position */
    ddULONG         direction;	/* search direction (forward/backward) */
    ddULONG         numIncl;/* number of types in incl list */
    ddULONG         numExcl;/* number of types in excl list */
    ddUSHORT       *pIncls;	/* list of included element types */
    ddUSHORT       *pExcls;	/* list of excluded element types */
/* out */
    ddUSHORT       *pStatus;/* (found/notfound) */
    ddULONG        *pOffset;/* offset from the start position */
{

    SET_STR_HEADER(pStruct, str);
    ddULONG         positionOffset;
    miGenericElementPtr pel;

#ifdef DDTEST
    ErrorF("\nElementSearch of %d\n", pStruct->id);
#endif

    /** An element is considered "being searched for" if it is in the
     ** include list and not in the exclude list.  Elements in both
     ** are excluded.  An OCAll element specifies that all elements
     ** match
     **/

    if (pos2offset(str, pPosition, &positionOffset)) return (BadValue);

    *pStatus = PEXNotFound;
    *pOffset = 0;

    MISTR_FIND_EL(str, positionOffset, pel);

    /*
     * search is either forwards or backwards, check for end of search
     * for both
     */
    while ((positionOffset >= 0) && (positionOffset <= MISTR_NUM_EL(str))) {
	ddUSHORT        elType;

	elType = MISTR_EL_TYPE(pel);

	/** If current element is in include list and not in exclude
	 ** list, then succeed PEXOCAll matches all elements, even PEXOCNil */
	if (	InList(elType, numIncl, pIncls) 
	    && !InList(elType, numExcl, pExcls)) {
		*pStatus = PEXFound;
		*pOffset = positionOffset;
		return (Success);
	} else {
	    if (direction == PEXForward) {
		positionOffset++;
		pel = MISTR_NEXT_EL(pel);
	    } else {
		positionOffset--;
		pel = MISTR_PREV_EL(pel);
	    }
	}
    }

    return (Success);
}				/* ElementSearch */

/*++
 |
 |  Function Name:	StoreElements
 |
 |  Function Description:
 |	 Handles the PEXStoreElements request.
 |
 |  Note(s):
 |
 --*/

ddpex4rtn
StoreElements(pStruct, numOCs, pOCs, ppErr)
/* in */
    diStructHandle  pStruct;	/* structure handle */
    register ddULONG numOCs;	/* number of output commands */
    ddElementInfo  *pOCs;	/* list of output commands */
/* out */
    pexOutputCommandError   **ppErr;
{
    SET_STR_HEADER(pStruct, pstruct);
    register ddElementInfo	*poc;
    register miGenericElementPtr    pprevel,	/* insert new one after this */
				    preplel;	/* or replace this one: preplel =
						 * pprevel->next */
    miGenericElementPtr pnewel;	/* new el to insert */
    int			count;
    ddpex4rtn		err = Success;

#ifdef DDTEST
    ErrorF("\nStoreElements in %d\n", pStruct->id);
#endif

    switch (MISTR_EDIT_MODE(pstruct)) {
	case PEXStructureReplace:
	    for (   poc = pOCs, count = 0,
		    preplel = MISTR_CURR_EL_PTR(pstruct),
		    pprevel = MISTR_PREV_EL(preplel);
		    numOCs > 0;
		    numOCs--,
		    pprevel = MISTR_NEXT_EL(pprevel),
		    preplel = MISTR_NEXT_EL(pprevel), poc += poc->length) {

		/*
		 * replace iff
		 * we're not at the end
		 * * and the types match
		 * * and we're not at the beginning
		 * * * and elements are the same size 
		 */

		if ((preplel != MISTR_LAST_EL(pstruct))
		    && (poc->elementType == MISTR_EL_TYPE(preplel))
		    && (preplel != MISTR_ZERO_EL(pstruct)) 
		    && (MISTR_EL_LENGTH(preplel) == poc->length)) {

		      /*
		       * *  Replace calls Parse functions 
		       */

			/* Propreitary OC (and OCNil) through 0th Table Entry */
			if (MI_HIGHBIT_ON(poc->elementType))
			    err = (*ReplaceCSSElementTable[MI_OC_PROP])
						(pStruct, preplel, poc );
                        else {
			    /* not Proprietary see if valid PEX OC */
			    if (MI_IS_PEX_OC(poc->elementType))
			      err = (*ReplaceCSSElementTable[poc->elementType])
						    (pStruct, preplel, poc);
			    else {
			      /* Bad Element Type Exit Now */
			      err = !Success;
			      break;
			    }
			}
		} else
		    /* Bad Replace */
		    err = !Success;

		if (err != Success) {	/* create new el */
		    /* Propreitary OC (and OCNil) through 0th Table Entry */
		    if (MI_HIGHBIT_ON(poc->elementType))
			err = (*CreateCSSElementTable[MI_OC_PROP])
						(pStruct, poc, &pnewel);
		    else {
			/* not Proprietary see if valid PEX OC */
			if (MI_IS_PEX_OC(poc->elementType))
			    err = (*CreateCSSElementTable[poc->elementType])
						    (pStruct, poc, &pnewel);
			else
			    /* Bad Element Type */
			    err = !Success;
		    }

		if (err != Success) break;

		count++;
		if (	(preplel != MISTR_LAST_EL(pstruct))
		     && (preplel != MISTR_ZERO_EL(pstruct))) {
		    /* get rid of old el */
		    MISTR_DEL_ONE_EL(pStruct, pprevel, preplel);
		}
		if (preplel == MISTR_ZERO_EL(pstruct))
		    pprevel = preplel;

		MISTR_INSERT_ONE_EL(pprevel, pnewel);
		}
	    }

	    if (err != Success) break;
	    MISTR_CURR_EL_PTR(pstruct) = pprevel;
	    MISTR_FIND_OFFSET(pstruct, pprevel, MISTR_CURR_EL_OFFSET(pstruct));

	    break;


	case PEXStructureInsert:
	    for (   count = 0, poc = pOCs, pprevel = MISTR_CURR_EL_PTR(pstruct);
		    numOCs > 0;
		    numOCs--, pprevel = pnewel, poc += poc->length) {

		/* Propreitary OC (and OCNil) through 0th Table Entry */
		if (MI_HIGHBIT_ON(poc->elementType))
		    err = (*CreateCSSElementTable[MI_OC_PROP]) 
						 (pStruct, poc, &pnewel);
		else {
		    /* not Proprietary see if valid PEX OC */
		    if (MI_IS_PEX_OC(poc->elementType))
			err = (*CreateCSSElementTable[poc->elementType])
					    (pStruct, poc, &pnewel);
		    else
			/* Bad Element Type */
			err = !Success;
		}

		if (err != Success) break;

		count++;
		MISTR_INSERT_ONE_EL(pprevel, pnewel);
		}

	    if (err != Success) break;
	    if (count) {
		MISTR_CURR_EL_PTR(pstruct) = pprevel;
		MISTR_FIND_OFFSET(  pstruct, pprevel,
				    MISTR_CURR_EL_OFFSET(pstruct));
		}
	    break;

	default:
	    /* better not get here */
	    ErrorF("tsk, tsk, the edit mode was set wrong\n");
	    return (BadImplementation);
	    break;
	}

    if (err != Success) {
	*ppErr = (pexOutputCommandError *)Xalloc(sizeof(pexOutputCommandError));
	(*ppErr)->type = 0;
	(*ppErr)->errorCode = PEX_ERROR_CODE(PEXOutputCommandError);
	(*ppErr)->resourceId = pStruct->id;
	(*ppErr)->opcode = poc->elementType;
	(*ppErr)->numCommands = count;
	return (err);
    }


    miDealWithStructDynamics(STR_MODIFY_DYNAMIC, pStruct);

    return (Success);
}				/* StoreElements */

/*++
 |
 |  Function Name:	DeleteElements
 |
 |  Function Description:
 |	 Handles the PEXDeleteElements request.
 |
 |  Note(s):
 |
 --*/

ddpex4rtn
DeleteElements(pStruct, pRange)
/* in */
	diStructHandle  pStruct;/* structure handle */
	ddElementRange *pRange;	/* range of elements to delete */
/* out */
{
	ddULONG         low, high, temp;
	SET_STR_HEADER(pStruct, pstruct);
	ddElementPos    newElementPointer;
	ddpex4rtn       err;

#ifdef DDTEST
	ErrorF("\nDeleteElements in %d\n", pStruct->id);
#endif

	if (pos2offset(pstruct, &(pRange->position1), &low))
		return (BadValue);	/* bad whence value */
	if (pos2offset(pstruct, &(pRange->position2), &high))
		return (BadValue);	/* bad whence value */

	/**  first pos needn't be lower then second pos, so order them now **/
	if (low > high) {
		temp = low;
		low = high;
		high = temp;
	}
	/** deleting element 0 equivalent to a NO-OP **/
	if (low == 0) {
		if (high == 0)
			return (Success);
		else
			low = 1;
	}
	MISTR_DEL_ELS(pStruct, pstruct, low, high);

	/*
	 * the current element pointer may now be invalid, so set it back to
	 * the beginning so it can be set correctly
	 */
	MISTR_CURR_EL_PTR(pstruct) = MISTR_ZERO_EL(pstruct);
	MISTR_CURR_EL_OFFSET(pstruct) = 0;

	/** Now, according to PEX spec, set element pointer to element
         ** preceding the range of deletion **/
	newElementPointer.whence = PEXBeginning;
	newElementPointer.offset = low - 1;
	err = SetElementPointer(pStruct, &newElementPointer);

	err = miDealWithStructDynamics(STR_MODIFY_DYNAMIC, pStruct);

	return (err);
}				/* DeleteElements */

/*++
 |
 |  Function Name:	DeleteToLabel
 |
 |  Function Description:
 |	 Handles the PEXDeleteElementsToLabel request.
 |
 |  Note(s):
 |
 --*/

ddpex4rtn
DeleteToLabel(pStruct, pPosition, label)
/* in */
    diStructHandle  pStruct;/* structure handle */
    ddElementPos   *pPosition;	/* starting position */
    ddLONG          label;	/* label id to delete to */
/* out */
{
    SET_STR_HEADER(pStruct, pstruct);
    ddElementPos    position;
    ddElementRange  range;
    ddULONG         labelOffset;
    ddULONG         start;

#ifdef DDTEST
    ErrorF("\nDeleteToLabel\n");
#endif

    if (pos2offset(pstruct, pPosition, &start))
	return (BadValue);	/* bad whence value */

    position.whence = PEXBeginning;
    position.offset = start + 1;

    if (find_label(pStruct, label, position, &labelOffset) == PEXNotFound)
	return (PEXERR(PEXLabelError));

    /*
     * Now call DeleteElements to delete the elements, but first adjust
     * the range since DeleteElements does an inclusive delete and
     * DeleteToLabel doesn't.
     */
    if ((start == labelOffset) || ((start + 1) == labelOffset)) {
	/* there are no elements between them */
	/* set the element pointer to point to the offset */
	return(SetElementPointer(pStruct, pPosition));
    }

    range.position1.whence = PEXBeginning;
    range.position1.offset = start + 1;
    range.position2.whence = PEXBeginning;
    range.position2.offset = labelOffset - 1;

    /* DeleteElements also updates picture if nec. */
    return (DeleteElements(pStruct, &range));

}				/* DeleteToLabel */

/*++
 |
 |  Function Name:	DeleteBetweenLabels
 |
 |  Function Description:
 |	 Handles the PEXDeleteElementsBetweenLabels request.
 |
 |  Note(s):
 |
 --*/

ddpex4rtn
DeleteBetweenLabels(pStruct, label1, label2)
/* in */
	diStructHandle  pStruct;/* structure handle */
	ddLONG          label1;	/* first label id */
	ddLONG          label2;	/* second label id */
/* out */
{
	ddElementPos    position;
	ddULONG         labelOffset;

#ifdef DDTEST
	ErrorF("\nDeleteBetweenLabels\n");
#endif

	position.whence = PEXCurrent;
	position.offset = 1;

	if (find_label(pStruct, label1, position, &labelOffset) == PEXNotFound)
		return (PEXERR(PEXLabelError));

	position.whence = PEXBeginning;
	position.offset = labelOffset;

	/* DeleteToLabel also updates picture if nec. */
	return (DeleteToLabel(pStruct, &position, label2));

}				/* DeleteBetweenLabels */

/*++
 |
 |  Function Name:	CopyElements
 |
 |  Function Description:
 |	 Handles the PEXCopyElements request.
 |
 |  Note(s):
 |
 --*/

ddpex4rtn
CopyElements(pSrcStruct, pSrcRange, pDestStruct, pDestPosition)
/* in */
	diStructHandle  pSrcStruct;	/* source structure handle */
	ddElementRange *pSrcRange;	/* element range to copy */
	diStructHandle  pDestStruct;	/* destination structure handle */
	ddElementPos   *pDestPosition;	/* destination position to put stuff */
/* out */
{
	SET_STR_HEADER(pSrcStruct, psource);
	SET_STR_HEADER(pDestStruct, pdest);
	ddULONG         src_low, src_high, dest_offset, i, count;
	miGenericElementPtr psrcel, pdestel, pdestprev;
	miGenericElementStr pfirst, plast;	/* dummies */
	ddpex4rtn       err4 = Success;


#ifdef DDTEST
	ErrorF("\nCopyElements\n");
#endif
	if (pos2offset(psource, &(pSrcRange->position1), &src_low))
		return (BadValue);	/* bad whence value */

	if (pos2offset(psource, &(pSrcRange->position2), &src_high))
		return (BadValue);	/* bad whence value */

	if (pos2offset(pdest, pDestPosition, &dest_offset))
		return (BadValue);	/* bad whence value */

	if (src_low > src_high) {
		i = src_low;
		src_low = src_high;
		src_high = i;
	}
	if (src_low == 0) {
		if (src_high == 0)
			return (Success);
		else
			src_low = 1;
	}
	MISTR_FIND_EL(psource, src_low, psrcel);

	/*
	 * copy els to dummy list, then add dummy list to dest NOTE:
	 * CopyCSSElement procedure is passed pDestStruct for the copy even
	 * though the element is not really being inserted into the structure
	 * yet. This should be OK, but beware!!
	 */
	MISTR_NEXT_EL(&pfirst) = &plast;
	MISTR_PREV_EL(&plast) = &pfirst;
	MISTR_PREV_EL(&pfirst) = MISTR_NEXT_EL(&plast) = NULL;
	pdestprev = &pfirst;

	for (i = src_low, count = 0; i <= src_high; i++) {

		/* Propreitary OC (and OCNil) through 0th Table Entry */
		if (MI_HIGHBIT_ON(MISTR_EL_TYPE(psrcel)))
			err4 = (*CopyCSSElementTable[MI_OC_PROP])
				(psrcel, pDestStruct, &pdestel);
		else {
		    /* not Proprietary see if valid PEX OC */
		    if (MI_IS_PEX_OC(MISTR_EL_TYPE(psrcel)))
			err4 = (*CopyCSSElementTable[MISTR_EL_TYPE(psrcel)])
				(psrcel, pDestStruct, &pdestel);
		    else
			/* Bad Element Type - Problem if you get here */
			err4 = !Success;
		}

		if (err4 != Success)
			break;

		count++;
		MISTR_INSERT_ONE_EL(pdestprev, pdestel);
		pdestprev = pdestel;
		psrcel = MISTR_NEXT_EL(psrcel);
	}

	if (count) {
		MISTR_FIND_EL(pdest, dest_offset, pdestprev);

		MISTR_NEXT_EL(MISTR_PREV_EL(&plast)) = MISTR_NEXT_EL(pdestprev);
		MISTR_PREV_EL(MISTR_NEXT_EL(pdestprev)) = MISTR_PREV_EL(&plast);

		MISTR_NEXT_EL(pdestprev) = MISTR_NEXT_EL(&pfirst);
		MISTR_PREV_EL(MISTR_NEXT_EL(&pfirst)) = pdestprev;

		MISTR_CURR_EL_PTR(pdest) = MISTR_PREV_EL(&plast);
		MISTR_FIND_OFFSET(pdest, MISTR_CURR_EL_PTR(pdest), MISTR_CURR_EL_OFFSET(pdest));
	}
	err4 = miDealWithStructDynamics(STR_MODIFY_DYNAMIC, pDestStruct);

	return (err4);
}				/* CopyElements */

/*++
 |
 |  Function Name:	ChangeStructureReferences
 |
 |  Function Description:
 |	 Handles the PEXChangeStructureReferences request.
 |
 |  Note(s):
 |
 --*/

ddpex4rtn
ChangeStructureReferences(pStruct, pNewStruct)
/* in */
    diStructHandle  pStruct;/* structure handle */
    diStructHandle  pNewStruct;	/* new structure resource */
/* out */
{

    SET_STR_HEADER(pStruct, pstruct);
    SET_STR_HEADER(pNewStruct, pnewstruct);
    diStructHandle  parentHandle;
    miStructPtr     pparentStruct;
    int             loopcount;
    ddElementPos    position;
    ddpex4rtn       foundExecuteElement, err;
    ddULONG         offsetFromStart;
    diWKSHandle     pWks;
    miGenericElementPtr pel;
    pexExecuteStructure execStrOC;
    ddFLOAT         prity;

#ifdef DDTEST
    ErrorF("\nChangeStructureReferences\n");
#endif				/* DDTEST */

    /* set up OC with new structure that will replace old  */
    execStrOC.head.elementType = PEXOCExecuteStructure;
    execStrOC.head.length = 2;
    execStrOC.id = (pexStructure) pNewStruct;

    /*
     * Update all references to this structure by walking through the
     * structure's parent list.  Note that if the structure is referenced
     * more than once by a parent structure, there will be more than one
     * occurence of the parent in the parent list.
     */
    
    for (loopcount = pstruct->parents->numObj; loopcount > 0; loopcount--) {

	/* The parent list changes in loop, so always get first parent */
	parentHandle = *(diStructHandle *) pstruct->parents->pList;
	pparentStruct = (miStructPtr) (parentHandle)->deviceData;

	/* start looking at the beginning of the parent structure */
        position.whence = PEXBeginning;
        position.offset = 0;
        offsetFromStart = 0;

    	foundExecuteElement = find_execute_structure (parentHandle, &position,
		pStruct, &offsetFromStart);

    	if (foundExecuteElement == PEXFound) {
		MISTR_FIND_EL(pparentStruct, offsetFromStart, pel);
		err = (*ReplaceCSSElementTable[PEXOCExecuteStructure])
					(parentHandle, pel, &execStrOC);
		if (err != Success) return (err);
	} else
		return (!Success);
    }

    /*
     * this changes the old structures posted to list (because unpost removes 
     * the wks from this list) so always get the first wks from the list and 
     * be sure to check the original number of posted wks
     */
    for (loopcount = pstruct->wksPostedTo->numObj; loopcount > 0; loopcount--) {
	pWks = ((diWKSHandle *) pstruct->wksPostedTo->pList)[0];
	if (puInList((ddPointer) pWks, pnewstruct->wksPostedTo))
	    err = UnpostStructure(pWks, pStruct);
	else {
	    miGetStructurePriority(pWks, pStruct, &prity);
	    err = PostStructure(pWks, pNewStruct, prity);
	}
	if (err) return (err);
    }

    err = miDealWithStructDynamics(REF_MODIFY_DYNAMIC, pNewStruct);

    return (Success);
}				/* ChangeStructureReferences */

int
miAddWksToAppearLists(pStruct, pWKS)
    diStructHandle  pStruct;
    diWKSHandle     pWKS;
{
    SET_STR_HEADER(pStruct, pheader);
    register ddULONG i, num;
    diStructHandle *ps;

    /* loop through the structures list of children */
    num = pheader->children->numObj;
    ps = (diStructHandle *) pheader->children->pList;
    for (i = 0; i < num; i++, ps++) {
	if (puAddToList(    (ddPointer) & pWKS, (ddULONG) 1,
			    ((miStructPtr) (*ps)->deviceData)->wksAppearOn)
	    == MI_ALLOCERR)
	    return (MI_ALLOCERR);

	    /* recur to do the children of this child */
	    if (miAddWksToAppearLists(*ps, pWKS) != MI_SUCCESS)
		return (MI_ALLOCERR);
    }
    return (MI_SUCCESS);
}

void
miRemoveWksFromAppearLists(pStruct, pWKS)
    diStructHandle  pStruct;
    diWKSHandle     pWKS;
{
    SET_STR_HEADER(pStruct, pheader);
    register ddULONG i, num;
    diStructHandle *ps;

#ifdef DDTEST
    ErrorF("\tmiRemoveWksFromAppearLists (of structure %d)\n", pStruct->id);
#endif

    num = pheader->children->numObj;
    ps = (diStructHandle *) pheader->children->pList;

    /* look at all children of this structure */
    for (i = 0; i < num; i++, ps++) {
	/* remove the wks from the child's list */
	puRemoveFromList(   (ddPointer) & pWKS,
			    ((miStructPtr) (*ps)->deviceData)->wksAppearOn);

	/* recur to do the children of this child */
	miRemoveWksFromAppearLists(*ps, pWKS);
    }
    return;
}

/*++
 |
 |  Function Name:	UpdateStructRefs
 |
 |  Function Description:
 |	A utility function to change the cross-reference lists in the structure.
 |	Each structure has a list of every workstation and structure which uses
 |	it.
 |
 |  Note(s):
 |
 --*/

ddpex4rtn
UpdateStructRefs(pStruct, pResource, which, action)
/* in */
    diStructHandle  pStruct;/* structure handle */
    diResourceHandle pResource;	/* wks, struct, sc handle */
    ddResourceType  which;	/* wks, struct, pick, sc */
    ddAction        action;	/* add or remove */
/* out */
{
    SET_STR_HEADER(pStruct, pheader);

#ifdef DDTEST
    ErrorF("\nUpdateStructRefs\n");
#endif

    switch (which) {
	case WORKSTATION_RESOURCE:

	    /*
	     * for each workstation, do it to the specified structures
	     * wksPostedTo list and do it to the wksAppearOn list of all
	     * of the structures children
	     */
	    if (action == ADD) {
		if (puAddToList(    (ddPointer) & pResource, (ddULONG) 1,
				    pheader->wksPostedTo) == MI_ALLOCERR)
		    return (BadAlloc);	/* couldn't add to list */
		if (miAddWksToAppearLists(pStruct, (diWKSHandle) pResource))
		    return (BadAlloc);	/* couldn't add to list */
	    } else {
		puRemoveFromList((ddPointer) & pResource, pheader->wksPostedTo);
		miRemoveWksFromAppearLists(pStruct, (diWKSHandle) pResource);
	    }

	    break;

	case PARENT_STRUCTURE_RESOURCE:
	    if (action == ADD) {
		if (puAddToList(    (ddPointer) & pResource, (ddULONG) 1,
				    pheader->parents) == MI_ALLOCERR)
		    return (BadAlloc);	/* couldn't add to list */
	    } else
		puRemoveFromList((ddPointer) & pResource, pheader->parents);

	    break;

	case CHILD_STRUCTURE_RESOURCE:
	    if (action == ADD) {
		if (puAddToList(    (ddPointer) & pResource, (ddULONG) 1,
				    pheader->children) == MI_ALLOCERR)
		    return (BadAlloc);	/* couldn't add to list */
	    } else
		puRemoveFromList((ddPointer) & pResource, pheader->children);

	    break;

	case SEARCH_CONTEXT_RESOURCE:
	case PICK_RESOURCE:	/* for both pick device & pick measure */
	    if (action == ADD)
		pheader->refCount++;
	    else {
		pheader->refCount--;
		CHECK_DELETE(pStruct, pheader);
	    }
	    break;

	default:		/* better not get here */
	    break;
    }
    return (Success);
}

/* get_wks_postings for InquireWksPostings
 * implement it here since it uses structure stuff
 */
ddpex4rtn
get_wks_postings(pStruct, pBuffer)
    diStructHandle  pStruct;
    ddBufferPtr     pBuffer;
{
    SET_STR_HEADER(pStruct, pheader);
    listofObj      *wkslist;
    diWKSHandle    *pwks;
    ddResourceId   *pbuf;
    register int    i;

    pBuffer->dataSize = 0;

    wkslist = pheader->wksPostedTo;

    if (PU_BUF_TOO_SMALL(pBuffer,(ddULONG)wkslist->numObj *sizeof(ddResourceId)))
	if (puBuffRealloc(  pBuffer,
			    (ddULONG)(wkslist->numObj * sizeof(ddResourceId)))
		!= Success) {
	    puDeleteList(wkslist);
	    return (BadAlloc);
	}
    pwks = (diWKSHandle *) wkslist->pList;
    pbuf = (ddResourceId *) pBuffer->pBuf;
    for (i = 0; i < wkslist->numObj; i++, pwks++, pbuf++) *pbuf = (*pwks)->id;
    pBuffer->dataSize = wkslist->numObj * sizeof(ddResourceId);

    return (Success);
}

/* make a generic puPrintList and put it in dipex/util/pexUtils.c sometime */
void
miPrintPath(pPath)
	listofObj      *pPath;
{
	register int    i;
	register ddElementRef *pref;

	ErrorF("\nELEMENT REF PATH\n");
	pref = (ddElementRef *) pPath->pList;
	for (i = 0; i < pPath->numObj; i++, pref++)
		ErrorF("\tstructure id: %d\toffset: %d\n",
		       pref->structure, pref->offset);
	ErrorF("\nEND PATH\n");
}

/*++
 |
 |  Function Name:	miPrintStructure
 |
 |  Function Description:
 |     Prints out the contents of a structure for debugging
 |     purposes.
 |
 |  Input Description:
 |	miStructPtr	pStruct;
 |	int		strLevel	    - amount of struct info to display
 |  Output Description:
 |	Switch strLevel :
 |	    case 0 :
 |		don't do anything.
 |          case 1 :
 |      	print structure header and nothing more
 |          case 2 :
 |      	print structure header and affil. structs and wks
 |
 --*/

static void     printWorkstations(), printStructures();

void
miPrintStructure(S, strLevel)
	diStructHandle  S;
	int             strLevel;
{
	miStructPtr     s = (miStructPtr) S->deviceData;

	if (strLevel > 0) {

		ErrorF("\n\n\n**********************************\n");
		ErrorF("* Printing Structure at 0x%x *\n", s);
		ErrorF("**********************************\n");
		ErrorF("ID = %ld\n", S->id);
		ErrorF("Edit Mode = %s\n", (s->editMode == PEXStructureReplace) ?
		       "REPLACE" : "INSERT");
		ErrorF("Num Elements = %ld\nTotal Size in 4 byte units = %ld\n",
		       s->numElements, s->totalSize);
		ErrorF("Curr Offset = %ld\nCurr Elt Ptr = 0x%x\n",
		       s->currElementOffset, s->pCurrElement);
		ErrorF("Zero El Ptr = 0x%x\nLast El Ptr = 0x%x\n",
		       s->pZeroElement, s->pLastElement);

		if (strLevel == 2) {
			ErrorF("\nParent Structures :\n");
			printStructures(s->parents);
			ErrorF("\nChild Structures :\n");
			printStructures(s->children);
			ErrorF("\nWKS posted to:\n");
			printWorkstations(s->wksPostedTo);
			ErrorF("\nWKS appearing on:\n");
			printWorkstations(s->wksAppearOn);
		}
	}
}

static void
printStructures(list)
	listofObj      *list;
{
	int             i;
	diStructHandle *str;

	str = (diStructHandle *) list->pList;
	for (i = 0; i < list->numObj; i++, str++) {
		ErrorF("\tStruct Address: 0x%x\t\tId: %ld\n",
		       (*str)->deviceData, (*str)->id);
	}
}

static void
printWorkstations(list)
	listofObj      *list;
{
	int             i;
	diWKSHandle    *wks;

	wks = (diWKSHandle *) list->pList;
	for (i = 0; i < list->numObj; i++, wks++) {
		ErrorF("\tWks Address: 0x%x\t\tId: %ld\n",
		       (*wks)->deviceData, (*wks)->id);
	}
}


/*++
 |
 |  Function Name:	ValidateStructurePath
 |
 |  Function Description:
	Follows the given search or pick path to see if it's valid
 |
 --*/

ddpex4rtn
ValidateStructurePath(pPath)
    listofObj      *pPath;
{
    miGenericElementPtr p_element;
    diStructHandle  pStruct, pNextStruct;
    miStructPtr     pstruct;
    ddULONG         offset;
    int             i, j;

    if (pPath->type == DD_ELEMENT_REF) {
	ddElementRef   *pSCPath;

	pSCPath = (ddElementRef *) pPath->pList;
	pNextStruct = pSCPath->structure;

	for (i = pPath->numObj; i > 0; i--, pSCPath++) {
	    pStruct = pSCPath->structure;
	    if (pNextStruct != pStruct)	return (PEXERR(PEXPathError));

	    pstruct = (miStructPtr) pStruct->deviceData;

	    offset = pSCPath->offset;
	    if (offset > MISTR_NUM_EL(pstruct)) return (PEXERR(PEXPathError));

	    /* dont' check what the last element is */
	    if (i == 1) break;

	    MISTR_FIND_EL(pstruct, offset, p_element);
	    if (MISTR_EL_TYPE(p_element) != PEXOCExecuteStructure)
		return (PEXERR(PEXPathError));

	    pNextStruct = (diStructHandle) MISTR_GET_EXSTR_STR(p_element);
	}
    } else {
	ddPickPath     *pPickPath;
	ddULONG         pickId;

	/*
	 * pick has to step through each element to check pick id also
	 */
	pPickPath = (ddPickPath *) pPath->pList;
	pNextStruct = pPickPath->structure;
	pickId = 0;

	for (i = pPath->numObj; i > 0; i--, pPickPath++) {

	    pStruct = pPickPath->structure;
	    if (pNextStruct != pStruct) return (PEXERR(PEXPathError));

	    pstruct = (miStructPtr) pStruct->deviceData;

	    offset = pPickPath->offset;
	    if (offset > MISTR_NUM_EL(pstruct)) return (PEXERR(PEXPathError));

	    /*
	     * start at the first element and look at each
	     * element until the offset is reached
	     */
	    MISTR_FIND_EL(pstruct, 1, p_element);

	    for (j = 1; j <  offset; j++ ) {
		if (MISTR_EL_TYPE(p_element) == PEXOCPickId)
		    pickId = MISTR_GET_PICK_ID(p_element);
		p_element = MISTR_NEXT_EL(p_element);
	    }

	    if (pickId != pPickPath->pickid) return (PEXERR(PEXPathError));

	    /* dont' check what the last element is */
	    if (i == 1) break;

	    if (MISTR_EL_TYPE(p_element) != PEXOCExecuteStructure)
		return (PEXERR(PEXPathError));

	    pNextStruct = (diStructHandle) MISTR_GET_EXSTR_STR(p_element);
	}
    }
    return (Success);
}