summaryrefslogtreecommitdiffstats
path: root/ast/region.c
blob: a08c55c3696bf30c69ae61237ca55ddb652e1232 (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
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
/*
*class++
*  Name:
*     Region

*  Purpose:
*     Represents a region within a coordinate system.

*  Constructor Function:
*     None.

*  Description:
*     This class provides the basic facilities for describing a region within
*     a specified coordinate system. However, the Region class does not
*     have a constructor function of its own, as it is simply a container
*     class for a family of specialised sub-classes such as Circle, Box, etc,
*     which implement Regions with particular shapes.
*
*     All sub-classes of Region require a Frame to be supplied when the Region
*     is created. This Frame describes the coordinate system in which the
*     Region is defined, and is referred to as the "encapsulated Frame" below.
*     Constructors will also typically required one or more positions to be
*     supplied which define the location and extent of the region. These
*     positions must be supplied within the encapsulated Frame.
*
*     The Region class inherits from the Frame class, and so a Region can be
*     supplied where-ever a Frame is expected. In these cases, supplying a
*     Region is equivalent to supplying a reference to its encapsulated Frame.
*     Thus all the methods of the Frame class can be used on the Region class.
*     For instance, the
c     astFormat function
f     AST_FORMAT routine
*     may be used on a Region to format an axis value.
*
*     In addition, since Frame inherits from Mapping, a Region is also a sort
*     of Mapping. Transforming positions by supplying a Region to one of the
c     astTran<X> functions
f     AST_TRAN<X> routines
*     is the way to determine if a given position is inside or outside the
*     Region. When used as a Mapping, most classes of Frame are equivalent to
*     a UnitMap. However, the Region class modifies this behaviour so that a
*     Region acts like a UnitMap only for input positions which are within the
*     area represented by the Region. Input positions which are outside the
*     area produce bad output values (i.e. the output values are equal to
*     AST__BAD). This behaviour is the same for both the forward and the
*     inverse transformation. In this sense the "inverse transformation"
*     is not a true inverse of the forward transformation, since applying
*     the forward transformation to a point outside the Region, and then
*     applying the inverse transformation results, in a set of AST__BAD axis
*     values rather than the original axis values. If required, the
c     astRemoveRegions
f     AST_REMOVEREGIONS
*     function can be used to remove the "masking" effect of any Regions
*     contained within a compound Mapping or FrameSet. It does this by
*     replacing each Region with a UnitMap or equivalent Frame (depending
*     on the context in which the Region is used).
*
*     If the coordinate system represented by the Region is changed (by
*     changing the values of one or more of the attribute which the Region
*     inherits from its encapsulated Frame), the area represented by
*     the Region is mapped into the new coordinate system. For instance, let's
*     say a Circle (a subclass of Region) is created, a SkyFrame being
*     supplied to the constructor so that the Circle describes a circular
*     area on the sky in FK4 equatorial coordinates. Since Region inherits
*     from Frame, the Circle will have a System attribute and this attribute
*     will be set to "FK4". If the System attribute of the Region is then
*     changed from FK4 to FK5, the circular area represented by the Region
*     will automatically be mapped from the FK4 system into the FK5 system.
*     In general, changing the coordinate system in this way may result in the
*     region changing shape - for instance, a circle may change into an
*     ellipse if the transformation from the old to the new coordinate system
*     is linear but with different scales on each axis. Thus the specific
*     class of a Region cannot be used as a guarantee of the shape in any
*     particular coordinate system. If the
c     astSimplify function
f     AST_SIMPLIFY routine
*     is used on a Region, it will endeavour to return a new Region of
*     a sub-class which accurately describes the shape in the current
*     coordinate system of the Region (but this may not always be possible).
*
*     It is possible to negate an existing Region so that it represents all
*     areas of the encapsulated Frame except for the area specified when
*     the Region was created.

*  Inheritance:
*     The Region class inherits from the Frame class.

*  Attributes:
*     In addition to those attributes common to all Frames, every
*     Region also has the following attributes:
*
*     - Adaptive: Should the area adapt to changes in the coordinate system?
*     - Negated: Has the original region been negated?
*     - Closed: Should the boundary be considered to be inside the region?
*     - MeshSize: Number of points used to create a mesh covering the Region
*     - FillFactor: Fraction of the Region which is of interest
*     - Bounded: Is the Region bounded?
*
*     Every Region also inherits any further attributes that belong
*     to the encapsulated Frame, regardless of that Frame's class. (For
*     example, the Equinox attribute, defined by the SkyFrame class, is
*     inherited by any Region which represents a SkyFrame.)

*  Functions:
c     In addition to those functions applicable to all Frames, the
c     following functions may also be applied to all Regions:
f     In addition to those routines applicable to all Frames, the
f     following routines may also be applied to all Regions:
*
c     - astGetRegionBounds: Get the bounds of a box containing a Region
f     - AST_GETREGIONBOUNDS: Get the bounds of a box containing a Region
c     - astGetRegionFrame: Get a copy of the Frame represent by a Region
f     - AST_GETREGIONFRAME: Get a copy of the Frame represent by a Region
c     - astGetRegionFrameSet: Get a copy of the Frameset encapsulated by a Region
f     - AST_GETREGIONFRAMESET: Get a copy of the Frameset encapsulated by a Region
c     - astGetRegionMesh: Get a mesh of points covering a Region
f     - AST_GETREGIONMESH: Get a mesh of points covering a Region
c     - astGetRegionPoints: Get the positions that define a Region
f     - AST_GETREGIONPOINTS: Get the positions that define a Region
c     - astGetUnc: Obtain uncertainty information from a Region
c     - astGetRegionDisc: Get the bounds of disc containing a Region
f     - AST_GETREGIONDISC: Get the bounds of disc containing a Region
f     - AST_GETUNC: Obtain uncertainty information from a Region
c     - astMapRegion: Transform a Region into a new coordinate system
f     - AST_MAPREGION: Transform a Region into a new coordinate system
c     - astNegate: Toggle the value of the Negated attribute
f     - AST_NEGATE: Toggle the value of the Negated attribute
c     - astOverlap: Determines the nature of the overlap between two Regions
f     - AST_OVERLAP: Determines the nature of the overlap between two Regions
c     - astMask<X>: Mask a region of a data grid
f     - AST_MASK<X>: Mask a region of a data grid
c     - astSetUnc: Associate a new uncertainty with a Region
f     - AST_SETUNC: Associate a new uncertainty with a Region
c     - astShowMesh: Display a mesh of points on the surface of a Region
f     - AST_SHOWMESH: Display a mesh of points on the surface of a Region

*  Copyright:
*     Copyright (C) 1997-2006 Council for the Central Laboratory of the
*     Research Councils
*     Copyright (C) 2009 Science & Technology Facilities Council.
*     All Rights Reserved.

*  Licence:
*     This program is free software: you can redistribute it and/or
*     modify it under the terms of the GNU Lesser General Public
*     License as published by the Free Software Foundation, either
*     version 3 of the License, or (at your option) any later
*     version.
*
*     This program is distributed in the hope that it will be useful,
*     but WITHOUT ANY WARRANTY; without even the implied warranty of
*     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*     GNU Lesser General Public License for more details.
*
*     You should have received a copy of the GNU Lesser General
*     License along with this program.  If not, see
*     <http://www.gnu.org/licenses/>.

*  Authors:
*     DSB: David S. Berry (STARLINK)

*  History:
*     3-DEC-2003 (DSB):
*        Original version.
*     12-MAY-2005 (DSB):
*        Override astNormBox method.
*     12-AUG-2005 (DSB):
*        Override ObsLat and ObsLon accessor methods.
*     14-FEB-2006 (DSB):
*        Override astGetObjSize.
*     2-MAR-2006 (DSB):
*        Changed AST_LONG_DOUBLE to HAVE_LONG_DOUBLE.
*     14-MAR-2006 (DSB):
*        Added astGetRefFS.
*     28-MAY-2007 (DSB):
*        - Added protected function astBndMesh.
*     14-JAN-2009 (DSB):
*        Override the astIntersect method.
*     20-JAN-2009 (DSB):
*        Change astPickAxes so that it returns a Region rather than a
*        Frame if possible. This included adding method astRegBasePick.
*     9-FEB-2009 (DSB):
*        Move PointList methods astGetEnclosure and astSetEnclosure to
*        Region.
*     18-FEB-2009 (DSB):
*        Remove methods astGetEnclosure and astSetEnclosure.
*     15-JUN-2009 (DSB):
*        Modify MapRegion to use FrameSets properly.
*     18-JUN-2009 (DSB):
*        Override ObsAlt accessor methods.
*     7-SEP-2009 (DSB):
*        Fix astMask to avoid reading variance values from the data array.
*     8-SEP-2009 (DSB):
*        Fix bugs in astOverlap that could result in wrong results if
*        either region is unbounded.
*     4-JAN-2010 (DSB):
*        Fix bug in GetRegionBounds (it was assumed implicitly that the base
*        Frame had the same number of axes as the current Frame).
*     18-MAR-2011 (DSB):
*        Added astGetRegionMesh public method.
*     22-MAR-2011 (DSB):
*        Improve uniformity of points produced by astRegBaseGrid method.
*     29-APR-2011 (DSB):
*        Prevent astFindFrame from matching a subclass template against a
*        superclass target.
*     17-MAY-2011 (DSB):
*        In RegBaseGrid, accept the final try even if it is not within 5%
*        of the required meshsize.
*     27-APR-2012 (DSB):
*        Store a negated copy of itself with each Region. Changing the Negated
*        attribute of a Region causes the cached information to be reset, and
*        re-calculating it can be an expensive operation. So instead of changing
*        "Negatated" in "this", access the negated copy of "this" using the
*        new protected method astGetNegation.
*     7-JUN-2012 (DSB):
*        Added protected astRegSplit method to split a Region into disjoint
*        component regions.
*     15-JUN-2012 (DSB):
*        Guard against division by zero in RegBase Grid if "ipr" is zero.
*     7-NOV-2013 (DSB):
*        Added method astGetRegionFrameSet.
*     3-FEB-2014 (DSB):
*        Fix bug masking regions that have no overlap with the supplied array.
*     17-APR-2015 (DSB):
*        Added Centre.
*     26-OCT-2016 (DSB):
*        - Override the astAxNorm method.
*        - Use astAxNorm to fix a bug in astGetRegionBounds for cases where
*        the Region cross a longitude=0 singularity.
*     11-NOV-2016 (DSB):
*        When loading a Region, use the dimensionality of the base Frame
*        of the FrameSet (rather than the current Frame as it used to be)
*        to define the number of axes required in the PointSet.
*     1-DEC-2016 (DSB):
*        Changed MapRegion to remove any unnecessary base frame axes in
*        the returned Region.
*     15-NOV-2018 (DSB):
*        Use error code AST__NOIMP instead of AST__INTER when reporting
*        an error about an abstract method not being implemented.
*     4-DEC-2018 (DSB):
*        Change GetBounded so that Regions defined within SkyFrames are
*        always bounded, whether negated or not.
*     11-DEC-2018 (DSB):
*        Add astGetRegionDisc.
*     16-JAN-2019 (DSB):
*        Change Conv() so that it aligns in the current Frame of "to". Without this, 
*        it is possible for uncertainty regions to be mapped incorrectly into the 
*        frame of the new region when creating new regions.
*class--

*  Implementation Notes:
*     - All sub-classes must over-ride the following abstract methods
*     declared in this class: astRegBaseBox, astRegBaseMesh, astRegPins,
*     astRegTrace. They must also extend the astTransform method. In addition
*     they should usually extend astSimplify and astRegCentre.

*/

/* Module Macros. */
/* ============== */
/* Set the name of the class we are implementing. This indicates to
   the header files that define class interfaces that they should make
   "protected" symbols available. */
#define astCLASS Region

/* Value for Ident attribute of of an encapsulated FrameSet which
   indicates that it is a dummy FrameSet (see astRegDummy). */
#define DUMMY_FS "ASTREGION-DUMMY"

/*
*  Name:
*     MAKE_CLEAR

*  Purpose:
*     Define a function to clear an attribute value for a Region.

*  Type:
*     Private macro.

*  Synopsis:
*     #include "region.h"
*     MAKE_CLEAR(attribute)

*  Class Membership:
*     Defined by the Region class.

*  Description:
*     This macro expands to an implementation of a private member function
*     of the form:
*
*        static void Clear<Attribute>( AstFrame *this )
*
*     that clears the value of a specified attribute for the encapsulated
*     FrameSet within a Region (this). This function is intended to over-ride
*     the astClear<Attribute> method inherited from the Frame class.

*  Parameters:
*     attribute
*        Name of the attribute, as it appears in the function name.
*/

/* Define the macro. */
#define MAKE_CLEAR(attribute) \
static void Clear##attribute( AstFrame *this_frame, int *status ) { \
\
/* Local Variables: */ \
   AstRegion *this;            /* Pointer to the Region structure */ \
\
/* Check the global error status. */ \
   if ( !astOK ) return; \
\
/* Obtain a pointer to the Region structure. */ \
   this = (AstRegion *) this_frame; \
\
/* Obtain a pointer to the encapsulated FrameSet and invoke its \
   astClear method. The protected astClear##attribute method is not used \
   because we want the current Frame of the FrameSet tp be re-mapped if \
   necessary. */ \
   astClear( this->frameset, #attribute ); \
}

/*
*  Name:
*     MAKE_CLEAR_AXIS

*  Purpose:
*     Define a function to clear an attribute value for a Region axis.

*  Type:
*     Private macro.

*  Synopsis:
*     #include "region.h"
*     MAKE_CLEAR_AXIS(attribute)

*  Class Membership:
*     Defined by the Region class.

*  Description:
*     This macro expands to an implementation of a private member function
*     of the form:
*
*        static void Clear<Attribute>( AstFrame *this, int axis )
*
*     that clears the value of a specified attribute for an axis of
*     the encapsulated FrameSet within a Region (this). This function is
*     intended to over-ride the astClear<Attribute> method inherited
*     from the Frame class.

*  Parameters:
*     attribute
*        Name of the attribute, as it appears in the function name.
*/

/* Define the macro. */
#define MAKE_CLEAR_AXIS(attribute) \
static void Clear##attribute( AstFrame *this_frame, int axis, int *status ) { \
\
/* Local Variables: */ \
   AstRegion *this;            /* Pointer to the Region structure */ \
   char buf[100];              /* Buffer for attribute name */ \
\
/* Check the global error status. */ \
   if ( !astOK ) return; \
\
/* Obtain a pointer to the Region structure. */ \
   this = (AstRegion *) this_frame; \
\
/* Validate the axis index supplied. */ \
   (void) astValidateAxis( this, axis, 1, "astClear" #attribute ); \
\
/* We use the public astSetx method rather than the protected \
   astSet#attribute method so that the current Frame in the encapsulated \
   FrameSet will be re-mapped if necessary. Construct the attribute name. */ \
   sprintf( buf, "%s(%d)", #attribute, axis + 1 ); \
\
/* Obtain a pointer to the Region's encapsulated FrameSet and invoke its \
   astClear method. The protected astClear#attribute method is notused \
   since we want the current Frame of the encapsulated FrameSet to be \
   remapped if required. */ \
   astClear( this->frameset, buf ); \
}

/*
*  Name:
*     MAKE_GET

*  Purpose:
*     Define a function to get an attribute value for a Region.

*  Type:
*     Private macro.

*  Synopsis:
*     #include "region.h"
*     MAKE_GET(attribute,type)

*  Class Membership:
*     Defined by the Region class.

*  Description:
*     This macro expands to an implementation of a private member function
*     of the form:
*
*        static <type> Get<Attribute>( AstFrame *this )
*
*     that gets the value of a specified attribute for the encapsulated
*     FrameSet of a Region (this). This function is intended to over-ride
*     the astGet<Attribute> method inherited from the Frame class.

*  Parameters:
*     attribute
*        Name of the attribute, as it appears in the function name.
*     type
*        The C type of the attribute.
*/

/* Define the macro. */
#define MAKE_GET(attribute,type) \
static type Get##attribute( AstFrame *this_frame, int *status ) { \
\
/* Local Variables: */ \
   AstRegion *this;            /* Pointer to the Region structure */ \
   type result;                /* Value to return */ \
\
/* Check the global error status. */ \
   if ( !astOK ) return (type) 0; \
\
/* Obtain a pointer to the Region structure. */ \
   this = (AstRegion *) this_frame; \
\
/* Obtain a pointer to the encapsulated FrameSet and invoke its \
   astGet<Attribute> method.  */ \
   result = astGet##attribute( this->frameset ); \
\
/* If an error occurred, clear the result value. */ \
   if ( !astOK ) result = (type) 0; \
\
/* Return the result. */ \
   return result; \
}

/*
*  Name:
*     MAKE_GET_AXIS

*  Purpose:
*     Define a function to get an attribute value for a Region axis.

*  Type:
*     Private macro.

*  Synopsis:
*     #include "region.h"
*     MAKE_GET_AXIS(attribute,type)

*  Class Membership:
*     Defined by the Region class.

*  Description:
*     This macro expands to an implementation of a private member function
*     of the form:
*
*        static <type> Get<Attribute>( AstFrame *this, int axis )
*
*     that gets the value of a specified attribute for an axis of the
*     encapsulated FrameSet within a Region (this). This function is intended
*     to over-ride the astGet<Attribute> method inherited from the Frame
*     class.

*  Parameters:
*     attribute
*        Name of the attribute, as it appears in the function name.
*     type
*        The C type of the attribute.
*/

/* Define the macro. */
#define MAKE_GET_AXIS(attribute,type) \
static type Get##attribute( AstFrame *this_frame, int axis, int *status ) { \
\
/* Local Variables: */ \
   AstRegion *this;            /* Pointer to the Region structure */ \
   type result;                /* Value to return */ \
\
/* Check the global error status. */ \
   if ( !astOK ) return (type) 0; \
\
/* Obtain a pointer to the Region structure. */ \
   this = (AstRegion *) this_frame; \
\
/* Validate the axis index supplied. */ \
   (void) astValidateAxis( this, axis, 1, "astGet" #attribute ); \
\
/* Obtain a pointer to the Region's encapsulated FrameSet and invoke its \
   astGet<Attribute> method.  */ \
   result = astGet##attribute( this->frameset, axis ); \
\
/* If an error occurred, clear the result value. */ \
   if ( !astOK ) result = (type) 0; \
\
/* Return the result. */ \
   return result; \
}

/*
*  Name:
*     MAKE_SET_SYSTEM

*  Purpose:
*     Define a function to set a System attribute value for a Region.

*  Type:
*     Private macro.

*  Synopsis:
*     #include "region.h"
*     MAKE_SET_SYSTEM(attribute)

*  Class Membership:
*     Defined by the Region class.

*  Description:
*     This macro expands to an implementation of a private member function
*     of the form:
*
*        static void Set<Attribute>( AstFrame *this, AstSystemType value )
*
*     that sets the value of a specified attribute for the encapsulated
*     FrameSet of a Region (this). This function is intended to over-ride the
*     astSet<Attribute> method inherited from the Frame class.

*  Parameters:
*     attribute
*        Name of the attribute, as it appears in the function name.
*/

/* Define the macro. */
#define MAKE_SET_SYSTEM(attribute) \
static void Set##attribute( AstFrame *this_frame, AstSystemType value, int *status ) { \
\
/* Local Variables: */ \
   AstRegion *this;            /* Pointer to the Region structure */ \
   const char *text;           /* Pointer to system string */ \
\
/* Check the global error status. */ \
   if ( !astOK ) return; \
\
/* Obtain a pointer to the Region structure. */ \
   this = (AstRegion *) this_frame; \
\
/* Convert the supplied value to a string using the astSystemString
   method of the current Frame in the encapsulated FrameSet. */ \
   text = astSystemString( this->frameset, value ); \
\
/* Set the value by invoking the public astSetC method on the encapusulated \
   FrameSet. This ensures that the current Frame of the encapsulated \
   FrameSet is re-mapped if necessary. */ \
   astSetC( this->frameset, #attribute, text ); \
}

/*
*  Name:
*     MAKE_SET

*  Purpose:
*     Define a function to set an attribute value for a Region.

*  Type:
*     Private macro.

*  Synopsis:
*     #include "region.h"
*     MAKE_SET(attribute,type,x)

*  Class Membership:
*     Defined by the Region class.

*  Description:
*     This macro expands to an implementation of a private member function
*     of the form:
*
*        static void Set<Attribute>( AstFrame *this, <type> value )
*
*     that sets the value of a specified attribute for the encapsulated
*     FrameSet of a Region (this). This function is intended to over-ride the
*     astSet<Attribute> method inherited from the Frame class.

*  Parameters:
*     attribute
*        Name of the attribute, as it appears in the function name.
*     type
*        The C type of the attribute.
*     x
*        The single character code for the astSetx function for the given C
*        type.
*/

/* Define the macro. */
#define MAKE_SET(attribute,type,x) \
static void Set##attribute( AstFrame *this_frame, type value, int *status ) { \
\
/* Local Variables: */ \
   AstRegion *this;            /* Pointer to the Region structure */ \
\
/* Check the global error status. */ \
   if ( !astOK ) return; \
\
/* Obtain a pointer to the Region structure. */ \
   this = (AstRegion *) this_frame; \
\
/* Set the value by invoking the public astSetx method on the encapusulated \
   FrameSet. This ensures that the current Frame of the encapsulated \
   FrameSet is re-mapped if necessary. */ \
   astSet##x( this->frameset, #attribute, value ); \
}

/*
*  Name:
*     MAKE_SET_AXIS

*  Purpose:
*     Define a function to set an attribute value for a Region axis.

*  Type:
*     Private macro.

*  Synopsis:
*     #include "region.h"
*     MAKE_SET_AXIS(attribute,type,x)

*  Class Membership:
*     Defined by the Region class.

*  Description:
*     This macro expands to an implementation of a private member function
*     of the form:
*
*        static void Set<Attribute>( AstFrame *this, int axis, <type> value )
*
*     that sets the value of a specified attribute for an axis of the
*     encapsulated FrameSet within a Region (this). This function is intended
*     to over-ride the astSet<Attribute> method inherited from the Frame
*     class.

*  Parameters:
*     attribute
*        Name of the attribute, as it appears in the function name.
*     type
*        The C type of the attribute.
*     x
*        The single character code for the astSetx function for the given C
*        type.
*/

/* Define the macro. */
#define MAKE_SET_AXIS(attribute,type,x) \
static void Set##attribute( AstFrame *this_frame, int axis, type value, int *status ) { \
\
/* Local Variables: */ \
   AstRegion *this;            /* Pointer to the Region structure */ \
   char buf[100];              /* Buffer for attribute name */ \
\
/* Check the global error status. */ \
   if ( !astOK ) return; \
\
/* Obtain a pointer to the Region structure. */ \
   this = (AstRegion *) this_frame; \
\
/* Validate the axis index supplied. */ \
   (void) astValidateAxis( this, axis, 1, "astSet" #attribute ); \
\
/* We use the public astSetx method rather than the protected \
   astSet#attribute method so that the current Frame in the encapsulated \
   FrameSet will be re-mapped if necessary. Construct the attribute name. */ \
   sprintf( buf, "%s(%d)", #attribute, axis + 1 ); \
\
/* Obtain a pointer to the Region's encapsulated FrameSet and invoke its \
   astSet<x> method.  */ \
   astSet##x( this->frameset, buf, value ); \
}

/*
*  Name:
*     MAKE_TEST

*  Purpose:
*     Define a function to test if an attribute value is set for a Region.

*  Type:
*     Private macro.

*  Synopsis:
*     #include "region.h"
*     MAKE_TEST(attribute)

*  Class Membership:
*     Defined by the Region class.

*  Description:
*     This macro expands to an implementation of a private member function
*     of the form:
*
*        static int Test<Attribute>( AstFrame *this )
*
*     that returns a boolean result (0 or 1) to indicate if the value
*     of a specified attribute for the encapsulated FrameSet within a
*     Region (this) is set. This function is intended to over-ride the
*     astTest<Attribute> method inherited from the Frame class.

*  Parameters:
*     attribute
*        Name of the attribute, as it appears in the function name.
*/

/* Define the macro. */
#define MAKE_TEST(attribute) \
static int Test##attribute( AstFrame *this_frame, int *status ) { \
\
/* Local Variables: */ \
   AstRegion *this;            /* Pointer to Region structure */ \
   int result;                 /* Result to return */ \
\
/* Check the global error status. */ \
   if ( !astOK ) return 0; \
\
/* Obtain a pointer to the Region structure. */ \
   this = (AstRegion *) this_frame; \
\
/* Obtain a pointer to the Region's encapsulated FrameSet and invoke its \
   astTest<Attribute> method.  */ \
   result = astTest##attribute( this->frameset ); \
\
/* If an error occurred, clear the result value. */ \
   if ( !astOK ) result = 0; \
\
/* Return the result. */ \
   return result; \
}

/*
*  Name:
*     MAKE_TEST_AXIS

*  Purpose:
*     Define a function to test if an attribute value is set for a Region
*     axis.

*  Type:
*     Private macro.

*  Synopsis:
*     #include "region.h"
*     MAKE_TEST_AXIS(attribute)

*  Class Membership:
*     Defined by the Region class.

*  Description:
*     This macro expands to an implementation of a private member function
*     of the form:
*
*        static int Test<Attribute>( AstFrame *this, int axis )
*
*     that returns a boolean result (0 or 1) to indicate if the value
*     of a specified attribute for an axis of the encapsulated FrameSet
*     within a Region (this) is set. This function is intended to over-ride
*     the astTest<Attribute> method inherited from the Frame class.

*  Parameters:
*     attribute
*        Name of the attribute, as it appears in the function name.
*/

/* Define the macro. */
#define MAKE_TEST_AXIS(attribute) \
static int Test##attribute( AstFrame *this_frame, int axis, int *status ) { \
\
/* Local Variables: */ \
   AstRegion *this;              /* Pointer to the Region structure */ \
   int result;                   /* Value to return */ \
\
/* Check the global error status. */ \
   if ( !astOK ) return 0; \
\
/* Obtain a pointer to the Region structure. */ \
   this = (AstRegion *) this_frame; \
\
/* Validate the axis index supplied. */ \
   (void) astValidateAxis( this, axis, 1, "astTest" #attribute ); \
\
/* Obtain a pointer to the Region's encapsulated FrameSet and invoke its \
   astTest<Attribute> method.  */ \
   result = astTest##attribute( this->frameset, axis ); \
\
/* If an error occurred, clear the result value. */ \
   if ( !astOK ) result = 0; \
\
/* Return the result. */ \
   return result; \
}

/* Header files. */
/* ============= */
/* Interface definitions. */
/* ---------------------- */

#include "globals.h"             /* Thread-safe global data access */
#include "error.h"               /* Error reporting facilities */
#include "memory.h"              /* Memory allocation facilities */
#include "object.h"              /* Base Object class */
#include "mapping.h"             /* Coordinate Mappings */
#include "unitmap.h"             /* Unit Mappings */
#include "permmap.h"             /* Coordinate permutation Mappings */
#include "cmpmap.h"              /* Compound Mappings */
#include "frame.h"               /* Parent Frame class */
#include "skyframe.h"            /* Celestial coordinate frames */
#include "frameset.h"            /* Interconnected coordinate systems */
#include "region.h"              /* Interface definition for this class */
#include "circle.h"              /* Circular regions */
#include "box.h"                 /* Box regions */
#include "cmpregion.h"           /* Compound regions */
#include "wcsmap.h"              /* For AST__DPI */
#include "ellipse.h"             /* Elliptical regions */
#include "pointset.h"            /* Sets of points */
#include "globals.h"             /* Thread-safe global data access */

/* Error code definitions. */
/* ----------------------- */
#include "ast_err.h"             /* AST error codes */

/* C header files. */
/* --------------- */
#include <ctype.h>
#include <limits.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>

/* Module Variables. */
/* ================= */

/* Address of this static variable is used as a unique identifier for
   member of this class. */
static int class_check;

/* Pointers to parent class methods which are extended by this class. */
static int (* parent_getobjsize)( AstObject *, int * );
static int (* parent_getusedefs)( AstObject *, int * );

#if defined(THREAD_SAFE)
static int (* parent_managelock)( AstObject *, int, int, AstObject **, int * );
#endif

/* Define macros for accessing each item of thread specific global data. */
#ifdef THREAD_SAFE

/* Define how to initialise thread-specific globals. */
#define GLOBAL_inits \
   globals->Class_Init = 0; \
   globals->GetAttrib_Buff[ 0 ] = 0;

/* Create the function that initialises global data for this module. */
astMAKE_INITGLOBALS(Region)

/* Define macros for accessing each item of thread specific global data. */
#define class_init astGLOBAL(Region,Class_Init)
#define class_vtab astGLOBAL(Region,Class_Vtab)
#define getattrib_buff astGLOBAL(Region,GetAttrib_Buff)



/* If thread safety is not needed, declare and initialise globals at static
   variables. */
#else

static char getattrib_buff[ 101 ];


/* Define the class virtual function table and its initialisation flag
   as static variables. */
static AstRegionVtab class_vtab;   /* Virtual function table */
static int class_init = 0;       /* Virtual function table initialised? */

#endif

/* Prototypes for Private Member Functions. */
/* ======================================== */
#if HAVE_LONG_DOUBLE     /* Not normally implemented */
static int MaskLD( AstRegion *, AstMapping *, int, int, const int[], const int ubnd[], long double [], long double, int * );
#endif
static int MaskB( AstRegion *, AstMapping *, int, int, const int[], const int[], signed char[], signed char, int * );
static int MaskD( AstRegion *, AstMapping *, int, int, const int[], const int[], double[], double, int * );
static int MaskF( AstRegion *, AstMapping *, int, int, const int[], const int[], float[], float, int * );
static int MaskI( AstRegion *, AstMapping *, int, int, const int[], const int[], int[], int, int * );
static int MaskL( AstRegion *, AstMapping *, int, int, const int[], const int[], long int[], long int, int * );
static int MaskS( AstRegion *, AstMapping *, int, int, const int[], const int[], short int[], short int, int * );
static int MaskUB( AstRegion *, AstMapping *, int, int, const int[], const int[], unsigned char[], unsigned char, int * );
static int MaskUI( AstRegion *, AstMapping *, int, int, const int[], const int[], unsigned int[], unsigned int, int * );
static int MaskUL( AstRegion *, AstMapping *, int, int, const int[], const int[], unsigned long int[], unsigned long int, int * );
static int MaskUS( AstRegion *, AstMapping *, int, int, const int[], const int[], unsigned short int[], unsigned short int, int * );

static AstAxis *GetAxis( AstFrame *, int, int * );
static AstFrame *GetRegionFrame( AstRegion *, int * );
static AstFrameSet *GetRegionFrameSet( AstRegion *, int * );
static AstFrame *PickAxes( AstFrame *, int, const int[], AstMapping **, int * );
static AstFrame *RegFrame( AstRegion *, int * );
static AstFrameSet *Conv( AstFrameSet *, AstFrameSet *, int * );
static AstFrameSet *Convert( AstFrame *, AstFrame *, const char *, int * );
static AstFrameSet *ConvertX( AstFrame *, AstFrame *, const char *, int * );
static AstFrameSet *FindFrame( AstFrame *, AstFrame *, const char *, int * );
static AstFrameSet *GetRegFS( AstRegion *, int * );
static AstLineDef *LineDef( AstFrame *, const double[2], const double[2], int * );
static AstMapping *RegMapping( AstRegion *, int * );
static AstMapping *RemoveRegions( AstMapping *, int * );
static AstMapping *Simplify( AstMapping *, int * );
static AstObject *Cast( AstObject *, AstObject *, int * );
static AstPointSet *BTransform( AstRegion *, AstPointSet *, int, AstPointSet *, int * );
static AstPointSet *BndBaseMesh( AstRegion *, double *, double *, int * );
static AstPointSet *BndMesh( AstRegion *, double *, double *, int * );
static AstPointSet *GetSubMesh( int *, AstPointSet *, int * );
static AstPointSet *RegBaseGrid( AstRegion *, int * );
static AstPointSet *RegBaseMesh( AstRegion *, int * );
static AstPointSet *RegGrid( AstRegion *, int * );
static AstPointSet *RegMesh( AstRegion *, int * );
static AstPointSet *RegTransform( AstRegion *, AstPointSet *, int, AstPointSet *, AstFrame **, int * );
static AstPointSet *ResolvePoints( AstFrame *, const double [], const double [], AstPointSet *, AstPointSet *, int * );
static AstRegion *MapRegion( AstRegion *, AstMapping *, AstFrame *, int * );
static AstRegion *RegBasePick( AstRegion *, int, const int *, int * );
static AstRegion **RegSplit( AstRegion *, int *, int * );
static AstSystemType SystemCode( AstFrame *, const char *, int * );
static AstSystemType ValidateSystem( AstFrame *, AstSystemType, const char *, int * );
static const char *Abbrev( AstFrame *, int, const char *, const char *, const char *, int * );
static const char *Format( AstFrame *, int, double, int * );
static const char *SystemString( AstFrame *, AstSystemType, int * );
static const int *GetPerm( AstFrame *, int * );
static double *RegCentre( AstRegion *, double *, double **, int, int, int * );
static double Angle( AstFrame *, const double[], const double[], const double[], int * );
static double AxAngle( AstFrame *, const double[], const double[], int, int * );
static double AxDistance( AstFrame *, int, double, double, int * );
static double AxOffset( AstFrame *, int, double, double, int * );
static double Distance( AstFrame *, const double[], const double[], int * );
static double Centre( AstFrame *, int, double, double, int * );
static double Gap( AstFrame *, int, double, int *, int * );
static double Offset2( AstFrame *, const double[2], double, double, double[2], int * );
static int Equal( AstObject *, AstObject *, int * );
static int GetNaxes( AstFrame *, int * );
static int GetObjSize( AstObject *, int * );
static int GetUseDefs( AstObject *, int * );
static int IsUnitFrame( AstFrame *, int * );
static int LineContains( AstFrame *, AstLineDef *, int, double *, int * );
static int LineCrossing( AstFrame *, AstLineDef *, AstLineDef *, double **, int * );
static int Match( AstFrame *, AstFrame *, int, int **, int **, AstMapping **, AstFrame **, int * );
static int Overlap( AstRegion *, AstRegion *, int * );
static int OverlapX( AstRegion *, AstRegion *, int * );
static int RegDummyFS( AstRegion *, int * );
static int RegPins( AstRegion *, AstPointSet *, AstRegion *, int **, int * );
static int SubFrame( AstFrame *, AstFrame *, int, const int *, const int *, AstMapping **, AstFrame **, int * );
static int RegTrace( AstRegion *, int, double *, double **, int * );
static int Unformat( AstFrame *, int, const char *, double *, int * );
static int ValidateAxis( AstFrame *, int, int, const char *, int * );
static void AxNorm( AstFrame *, int, int, int, double *, int * );
static void CheckPerm( AstFrame *, const int *, const char *, int * );
static void Copy( const AstObject *, AstObject *, int * );
static void Delete( AstObject *, int * );
static void Dump( AstObject *, AstChannel *, int * );
static void GetRegionBounds( AstRegion *, double *, double *, int * );
static void GetRegionBounds2( AstRegion *, double *, double *, int * );
static void GetRegionMesh( AstRegion *, int, int, int, int *, double *, int * );
static void GetRegionPoints( AstRegion *, int, int, int *, double *, int * );
static void GetRegionDisc( AstRegion *, double[2], double *, int * );
static void Intersect( AstFrame *, const double[2], const double[2], const double[2], const double[2], double[2], int * );
static void LineOffset( AstFrame *, AstLineDef *, double, double, double[2], int * );
static void MatchAxes( AstFrame *, AstFrame *, int *, int * );
static void MatchAxesX( AstFrame *, AstFrame *, int *, int * );
static void Negate( AstRegion *, int * );
static void Norm( AstFrame *, double[], int * );
static void NormBox( AstFrame *, double[], double[], AstMapping *, int * );
static void Offset( AstFrame *, const double[], const double[], double, double[], int * );
static void Overlay( AstFrame *, const int *, AstFrame *, int * );
static void PermAxes( AstFrame *, const int[], int * );
static void RegBaseBox( AstRegion *, double *, double *, int * );
static void RegBaseBox2( AstRegion *, double *, double *, int * );
static void RegClearAttrib( AstRegion *, const char *, char **, int * );
static void RegOverlay( AstRegion *, AstRegion *, int, int * );
static void RegSetAttrib( AstRegion *, const char *, char **, int * );
static void ReportPoints( AstMapping *, int, AstPointSet *, AstPointSet *, int * );
static void ResetCache( AstRegion *, int * );
static void Resolve( AstFrame *, const double [], const double [], const double [], double [], double *, double *, int * );
static void SetAxis( AstFrame *, int, AstAxis *, int * );
static void SetRegFS( AstRegion *, AstFrame *, int * );
static void ShowMesh( AstRegion *, int, const char *, int * );
static void ValidateAxisSelection( AstFrame *, int, const int *, const char *, int * );
static AstRegion *GetNegation( AstRegion *, int * );

static int GetBounded( AstRegion *, int * );
static AstRegion *GetDefUnc( AstRegion *, int * );

static AstRegion *GetUncFrm( AstRegion *, int, int * );
static AstRegion *GetUnc( AstRegion *, int, int * );
static int TestUnc( AstRegion *, int * );
static void ClearUnc( AstRegion *, int * );
static void SetUnc( AstRegion *, AstRegion *, int * );

static const char *GetDomain( AstFrame *, int * );
static int TestDomain( AstFrame *, int * );
static void ClearDomain( AstFrame *, int * );
static void SetDomain( AstFrame *, const char *, int * );

static const char *GetFormat( AstFrame *, int, int * );
static int TestFormat( AstFrame *, int, int * );
static void ClearFormat( AstFrame *, int, int * );
static void SetFormat( AstFrame *, int, const char *, int * );

static const char *GetLabel( AstFrame *, int, int * );
static int TestLabel( AstFrame *, int, int * );
static void ClearLabel( AstFrame *, int, int * );
static void SetLabel( AstFrame *, int, const char *, int * );

static const char *GetSymbol( AstFrame *, int, int * );
static int TestSymbol( AstFrame *, int, int * );
static void ClearSymbol( AstFrame *, int, int * );
static void SetSymbol( AstFrame *, int, const char *, int * );

static const char *GetTitle( AstFrame *, int * );
static void SetTitle( AstFrame *, const char *, int * );
static void ClearTitle( AstFrame *, int * );
static int TestTitle( AstFrame *, int * );

static const char *GetUnit( AstFrame *, int, int * );
static int TestUnit( AstFrame *, int, int * );
static void ClearUnit( AstFrame *, int, int * );
static void SetUnit( AstFrame *, int, const char *, int * );

static int GetDigits( AstFrame *, int * );
static int TestDigits( AstFrame *, int * );
static void ClearDigits( AstFrame *, int * );
static void SetDigits( AstFrame *, int, int * );

static int GetDirection( AstFrame *, int, int * );
static int TestDirection( AstFrame *, int, int * );
static void ClearDirection( AstFrame *, int, int * );
static void SetDirection( AstFrame *, int, int, int * );

static int GetActiveUnit( AstFrame *, int * );
static int TestActiveUnit( AstFrame *, int * );
static void SetActiveUnit( AstFrame *, int, int * );

static int GetMatchEnd( AstFrame *, int * );
static int TestMatchEnd( AstFrame *, int * );
static void ClearMatchEnd( AstFrame *, int * );
static void SetMatchEnd( AstFrame *, int, int * );

static int GetMaxAxes( AstFrame *, int * );
static int TestMaxAxes( AstFrame *, int * );
static void ClearMaxAxes( AstFrame *, int * );
static void SetMaxAxes( AstFrame *, int, int * );

static int GetMinAxes( AstFrame *, int * );
static int TestMinAxes( AstFrame *, int * );
static void ClearMinAxes( AstFrame *, int * );
static void SetMinAxes( AstFrame *, int, int * );

static int GetPermute( AstFrame *, int * );
static int TestPermute( AstFrame *, int * );
static void ClearPermute( AstFrame *, int * );
static void SetPermute( AstFrame *, int, int * );

static int GetPreserveAxes( AstFrame *, int * );
static int TestPreserveAxes( AstFrame *, int * );
static void ClearPreserveAxes( AstFrame *, int * );
static void SetPreserveAxes( AstFrame *, int, int * );

static double GetBottom( AstFrame *, int, int * );
static int TestBottom( AstFrame *, int, int * );
static void ClearBottom( AstFrame *, int, int * );
static void SetBottom( AstFrame *, int, double, int * );

static double GetTop( AstFrame *, int, int * );
static int TestTop( AstFrame *, int, int * );
static void ClearTop( AstFrame *, int, int * );
static void SetTop( AstFrame *, int, double, int * );

static double GetEpoch( AstFrame *, int * );
static int TestEpoch( AstFrame *, int * );
static void ClearEpoch( AstFrame *, int * );
static void SetEpoch( AstFrame *, double, int * );

static double GetObsAlt( AstFrame *, int * );
static int TestObsAlt( AstFrame *, int * );
static void ClearObsAlt( AstFrame *, int * );
static void SetObsAlt( AstFrame *, double, int * );

static double GetObsLat( AstFrame *, int * );
static int TestObsLat( AstFrame *, int * );
static void ClearObsLat( AstFrame *, int * );
static void SetObsLat( AstFrame *, double, int * );

static double GetObsLon( AstFrame *, int * );
static int TestObsLon( AstFrame *, int * );
static void ClearObsLon( AstFrame *, int * );
static void SetObsLon( AstFrame *, double, int * );

static AstSystemType GetSystem( AstFrame *, int * );
static int TestSystem( AstFrame *, int * );
static void ClearSystem( AstFrame *, int * );
static void SetSystem( AstFrame *, AstSystemType, int * );

static AstSystemType GetAlignSystem( AstFrame *, int * );
static int TestAlignSystem( AstFrame *, int * );
static void ClearAlignSystem( AstFrame *, int * );
static void SetAlignSystem( AstFrame *, AstSystemType, int * );

static const char *GetAttrib( AstObject *, const char *, int * );
static int TestAttrib( AstObject *, const char *, int * );
static void ClearAttrib( AstObject *, const char *, int * );
static void SetAttrib( AstObject *, const char *, int * );

static int GetNegated( AstRegion *, int * );
static int TestNegated( AstRegion *, int * );
static void ClearNegated( AstRegion *, int * );
static void SetNegated( AstRegion *, int, int * );

static int GetClosed( AstRegion *, int * );
static int TestClosed( AstRegion *, int * );
static void ClearClosed( AstRegion *, int * );
static void SetClosed( AstRegion *, int, int * );

static int GetMeshSize( AstRegion *, int * );
static int TestMeshSize( AstRegion *, int * );
static void ClearMeshSize( AstRegion *, int * );
static void SetMeshSize( AstRegion *, int, int * );

static double GetFillFactor( AstRegion *, int * );
static int TestFillFactor( AstRegion *, int * );
static void ClearFillFactor( AstRegion *, int * );
static void SetFillFactor( AstRegion *, double, int * );

static int GetRegionFS( AstRegion *, int * );
static int TestRegionFS( AstRegion *, int * );
static void ClearRegionFS( AstRegion *, int * );
static void SetRegionFS( AstRegion *, int, int * );

static int GetAdaptive( AstRegion *, int * );
static int TestAdaptive( AstRegion *, int * );
static void ClearAdaptive( AstRegion *, int * );
static void SetAdaptive( AstRegion *, int, int * );

#if defined(THREAD_SAFE)
static int ManageLock( AstObject *, int, int, AstObject **, int * );
#endif


/* Member functions. */
/* ================= */

static const char *Abbrev( AstFrame *this_frame, int axis, const char *fmt,
                           const char *str1, const char *str2, int *status ) {
/*
*  Name:
*     Abbrev

*  Purpose:
*     Abbreviate a formatted Region axis value by skipping leading fields.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     const char *Abbrev( AstFrame *this, int axis, const char *fmt,
*                         const char *str1, const char *str2, int *status )

*  Class Membership:
*     Region member function (over-rides the protected astAbbrev
*     method inherited from the Frame class).

*  Description:
*     This function compares two Region axis values that have been
*     formatted (using astFormat) and determines if they have any
*     redundant leading fields (i.e. leading fields in common which
*     can be suppressed when tabulating the values or plotting them on
*     the axis of a graph).

*  Parameters:
*     this
*        Pointer to the Region
*     axis
*        The number of the Region axis for which the values have
*        been formatted (axis numbering starts at zero for the first
*        axis).
*     fmt
*        Pointer to a constant null-terminated string containing the
*        format specification used to format the two values.
*     str1
*        Pointer to a constant null-terminated string containing the
*        first formatted value.
*     str1
*        Pointer to a constant null-terminated string containing the
*        second formatted value.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     A pointer into the "str2" string which locates the first
*     character in the first field that differs between the two
*     formatted values.
*
*     If the two values have no leading fields in common, the returned
*     value will point at the start of string "str2". If the two
*     values are equal, it will point at the terminating null at the
*     end of this string.

*  Notes:
*     - This function assumes that the format specification used was
*     the same when both values were formatted and that they both
*     apply to the same Region axis.
*     - A pointer to the start of "str2" will be returned if this
*     function is invoked with the global error status set, or if it
*     should fail for any reason.
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to current Frame */
   AstRegion *this;              /* Pointer to the Region structure */
   const char *result;           /* Pointer value to return */

/* Check the global error status. */
   if ( !astOK ) return str2;

/* Obtain a pointer to the Region structure. */
   this = (AstRegion *) this_frame;

/* Validate the axis index. */
   (void) astValidateAxis( this, axis, 1, "astAbbrev" );

/* Obtain a pointer to the Region's current Frame and invoke this
   Frame's astAbbrev method to perform the processing. Annul the Frame
   pointer afterwards. */
   fr = astGetFrame( this->frameset, AST__CURRENT );
   result = astAbbrev( fr, axis, fmt, str1, str2 );
   fr = astAnnul( fr );

/* If an error occurred, clear the result. */
   if ( !astOK ) result = str2;

/* Return the result. */
   return result;
}

static double Angle( AstFrame *this_frame, const double a[],
                     const double b[], const double c[], int *status ) {
/*
*  Name:
*     Angle

*  Purpose:
*     Calculate the angle subtended by two points at a third point.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     double Angle( AstFrame *this, const double a[], const double b[],
*                   const double c[], int *status )

*  Class Membership:
*     Region member function (over-rides the protected astAngle
*     method inherited from the Frame class).

*  Description:
*     This function finds the angle at point B between the line joining points
*     A and B, and the line joining points C and B. These lines will in fact be
*     geodesic curves appropriate to the Frame in use. For instance, in
*     SkyFrame, they will be great circles.

*  Parameters:
*     this
*        Pointer to the Frame.
*     a
*        An array of double, with one element for each Frame axis
*        (Naxes attribute) containing the coordinates of the first point.
*     b
*        An array of double, with one element for each Frame axis
*        (Naxes attribute) containing the coordinates of the second point.
*     c
*        An array of double, with one element for each Frame axis
*        (Naxes attribute) containing the coordinates of the third point.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     astAngle
*        The angle in radians, from the line AB to the line CB. If the
*        Frame is 2-dimensional, it will be in the range $\pm \pi$,
*        and positive rotation is in the same sense as rotation from
*        the positive direction of axis 2 to the positive direction of
*        axis 1. If the Frame has more than 2 axes, a positive value will
*        always be returned in the range zero to $\pi$.

*  Notes:
*     - A value of AST__BAD will also be returned if points A and B are
*     co-incident, or if points B and C are co-incident.
*     - A value of AST__BAD will also be returned if this function is
*     invoked with the AST error status set, or if it should fail for
*     any reason.
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to current Frame */
   AstRegion *this;              /* Pointer to the Region structure */
   double result;                /* Value to return */

/* Check the global error status. */
   if ( !astOK ) return AST__BAD;

/* Obtain a pointer to the FrameSet structure. */
   this = (AstRegion *) this_frame;

/* Obtain a pointer to the Region's encapsulated Frame and invoke this
   Frame's astAngle method. Annul the Frame pointer afterwards. */
   fr = astGetFrame( this->frameset, AST__CURRENT );
   result = astAngle( fr, a, b, c );
   fr = astAnnul( fr );

/* If an error occurred, clear the result. */
   if ( !astOK ) result = AST__BAD;

/* Return the result. */
   return result;
}

static double AxAngle( AstFrame *this_frame, const double a[], const double b[], int axis, int *status ) {
/*
*  Name:
*     AxAngle

*  Purpose:
*     Returns the angle from an axis, to a line through two points.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     double AxAngle( AstFrame *this, const double a[], const double b[], int axis, int *status )

*  Class Membership:
*     Region member function (over-rides the protected astAxAngle
*     method inherited from the Frame class).

*  Description:
*     This function finds the angle, as seen from point A, between the positive
*     direction of a specified axis, and the geodesic curve joining point
*     A to point B.

*  Parameters:
*     this
*        Pointer to the Frame.
*     a
*        An array of double, with one element for each Frame axis
*        (Naxes attribute) containing the coordinates of the first point.
*     b
*        An array of double, with one element for each Frame axis
*        (Naxes attribute) containing the coordinates of the second point.
*     axis
*        The number of the Frame axis from which the angle is to be
*        measured (one-based)
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*        The angle in radians, from the positive direction of the
*        specified axis, to the line AB. If the Frame is 2-dimensional,
*        it will be in the range $\pm \pi$, and positive rotation is in
*        the same sense as rotation from the positive direction of axis 2
*        to the positive direction of axis 1. If the Frame has more than 2
*        axes, a positive value will always be returned in the range zero
*        to $\pi$.

*  Notes:
*     - The geodesic curve used by this function is the path of
*     shortest distance between two points, as defined by the
*     astDistance function.
*     - This function will return "bad" coordinate values (AST__BAD)
*     if any of the input coordinates has this value, or if the require
*     position angle is undefined.
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to current Frame */
   AstRegion *this;              /* Pointer to the Region structure */
   double result;                /* Value to return */

/* Check the global error status. */
   if ( !astOK ) return AST__BAD;

/* Obtain a pointer to the FrameSet structure. */
   this = (AstRegion *) this_frame;

/* Validate the axis index. */
   (void) astValidateAxis( this, axis - 1, 1, "astAxAngle" );

/* Obtain a pointer to the Region's encapsulated Frame and invoke the
   astAxAngle method for this Frame. Annul the Frame pointer
   afterwards. */
   fr = astGetFrame( this->frameset, AST__CURRENT );
   result = astAxAngle( fr, a, b, axis );
   fr = astAnnul( fr );

/* If an error occurred, clear the result value. */
   if ( !astOK ) result = AST__BAD;

/* Return the result. */
   return result;
}

static double AxDistance( AstFrame *this_frame, int axis, double v1, double v2, int *status ) {
/*
*  Name:
*     AxDistance

*  Purpose:
*     Find the distance between two axis values.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     double AxDistance( AstFrame *this, int axis, double v1, double v2, int *status )

*  Class Membership:
*     Region member function (over-rides the protected astAxDistance
*     method inherited from the Frame class).

*  Description:
*     This function returns a signed value representing the axis increment
*     from axis value v1 to axis value v2.
*
*     For a simple Frame, this is a trivial operation returning the
*     difference between the two axis values. But for other derived classes
*     of Frame (such as a SkyFrame) this is not the case.

*  Parameters:
*     this
*        Pointer to the Frame.
*     axis
*        The index of the axis to which the supplied values refer. The
*        first axis has index 1.
*     v1
*        The first axis value.
*     v2
*        The second axis value.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     The distance between the two axis values.

*  Notes:
*     - This function will return a "bad" result value (AST__BAD) if
*     any of the input vaues has this value.
*     - A "bad" value will also be returned if this function is
*     invoked with the AST error status set, or if it should fail for
*     any reason.
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to current Frame */
   AstRegion *this;              /* Pointer to the Region structure */
   double result;                /* Value to return */

/* Check the global error status. */
   if ( !astOK ) return AST__BAD;

/* Obtain a pointer to the FrameSet structure. */
   this = (AstRegion *) this_frame;

/* Validate the axis index. */
   (void) astValidateAxis( this, axis - 1, 1, "astAxDistance" );

/* Obtain a pointer to the Region's encapsulated Frame and invoke the
   astAxDistance method for this Frame. Annul the Frame pointer
   afterwards. */
   fr = astGetFrame( this->frameset, AST__CURRENT );
   result = astAxDistance( fr, axis, v1, v2 );
   fr = astAnnul( fr );

/* If an error occurred, clear the result value. */
   if ( !astOK ) result = AST__BAD;

/* Return the result. */
   return result;
}

static void AxNorm( AstFrame *this_frame, int axis, int oper, int nval,
                    double *values, int *status ){
/*
*  Name:
*     AxNorm

*  Purpose:
*     Normalise an array of axis values.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     void AxNorm( AstFrame *this, int axis, int oper, int nval,
*                  double *values, int *status )

*  Class Membership:
*     FrameSet member function (over-rides the protected astAxNorm
*     method inherited from the Frame class).

*  Description:
*     This function modifies a supplied array of axis values so that
*     they are normalised in the manner indicated by parameter "oper".
*
*     No normalisation is possible for a simple Frame and so the supplied
*     values are returned unchanged. However, this may not be the case for
*     specialised sub-classes of Frame. For instance, a SkyFrame has a
*     discontinuity at zero longitude and so a longitude value can be
*     expressed in the range [-Pi,+PI] or the range [0,2*PI].

*  Parameters:
*     this
*        Pointer to the Frame.
*     axis
*        The index of the axis to which the supplied values refer. The
*        first axis has index 1.
*     oper
*        Indicates the type of normalisation to be applied. If zero is
*        supplied, the normalisation will be the same as that performed by
*        function astNorm. If 1 is supplied, the normalisation will be
*        chosen automatically so that the resulting list has the smallest
*        range.
*     nval
*        The number of points in the values array.
*     values
*        On entry, the axis values to be normalised. Modified on exit to
*        hold the normalised values.
*     status
*        Pointer to the inherited status variable.

*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to current Frame */
   AstRegion *this;              /* Pointer to the Region structure */

/* Check the global error status. */
   if ( !astOK ) return;

/* Obtain a pointer to the Region structure. */
   this = (AstRegion *) this_frame;

/* Validate the axis index. */
   (void) astValidateAxis( this, axis - 1, 1, "astAxNorm" );

/* Obtain a pointer to the Region's encapsulated Frame and invoke
   the astAxNorm method for this Frame. Annul the Frame pointer
   afterwards. */
   fr = astGetFrame( this->frameset, AST__CURRENT );
   astAxNorm( fr, axis, oper, nval, values );
   fr = astAnnul( fr );
}

static double AxOffset( AstFrame *this_frame, int axis, double v1, double dist, int *status ) {
/*
*  Name:
*     AxOffset

*  Purpose:
*     Add an increment onto a supplied axis value.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     double AxOffset( AstFrame *this, int axis, double v1, double dist, int *status )

*  Class Membership:
*     Region member function (over-rides the protected astAxOffset
*     method inherited from the Frame class).

*  Description:
*     This function returns an axis value formed by adding a signed axis
*     increment onto a supplied axis value.
*
*     For a simple Frame, this is a trivial operation returning the
*     sum of the two supplied values. But for other derived classes
*     of Frame (such as a SkyFrame) this is not the case.

*  Parameters:
*     this
*        Pointer to the Frame.
*     axis
*        The index of the axis to which the supplied values refer. The
*        first axis has index 1.
*     v1
*        The original axis value.
*     dist
*        The axis increment to add to the original axis value.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     The incremented axis value.

*  Notes:
*     - This function will return a "bad" result value (AST__BAD) if
*     any of the input vaues has this value.
*     - A "bad" value will also be returned if this function is
*     invoked with the AST error status set, or if it should fail for
*     any reason.
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to current Frame */
   AstRegion *this;              /* Pointer to the Region structure */
   double result;                /* Value to return */

/* Check the global error status. */
   if ( !astOK ) return AST__BAD;

/* Obtain a pointer to the FrameSet structure. */
   this = (AstRegion *) this_frame;

/* Validate the axis index. */
   (void) astValidateAxis( this, axis - 1, 1, "astAxOffset" );

/* Obtain a pointer to the Region's encapsulated Frame and invoke the
   astAxOffset method for this Frame. Annul the Frame pointer
   afterwards. */
   fr = astGetFrame( this->frameset, AST__CURRENT );
   result = astAxOffset( fr, axis, v1, dist );
   fr = astAnnul( fr );

/* If an error occurred, clear the result value. */
   if ( !astOK ) result = AST__BAD;

/* Return the result. */
   return result;
}

static AstPointSet *BndBaseMesh( AstRegion *this, double *lbnd, double *ubnd, int *status ){
/*
*+
*  Name:
*     astBndBaseMesh

*  Purpose:
*     Return a PointSet containing points spread around part of the boundary
*     of a Region, in the base Frame.

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     AstPointSet *astBndBaseMesh( AstRegion *this, double *lbnd, double *ubnd )

*  Class Membership:
*     Region virtual function.

*  Description:
*     This function returns a PointSet containing a set of points on the
*     boundary of the intersection between the supplied Region and the
*     supplied (current Frame) box. The mesh points refer to the base
*     Frame. If the boundary of the supplied Region does not intersect the
*     supplied box, then a PointSet containing a single bad point is
*     returned.

*  Parameters:
*     this
*        Pointer to the Region.
*     lbnd
*        Pointer to an array holding the lower limits of the axis values
*        within the required box. Defined in the current Frame of the Region.
*     ubnd
*        Pointer to an array holding the upper limits of the axis values
*        within the required box. Defined in the current Frame of the Region.

*  Returned Value:
*     Pointer to the PointSet holding the base Frame mesh. The axis values
*     in this PointSet will have associated accuracies derived from the
*     uncertainties which were supplied when the Region was created.
*
*     If the Region does not intersect the supplied box, the returned
*     PointSet will contain a single point with a value of AST__BAD on
*     every axis.

*  Notes:
*    - A NULL pointer is returned if an error has already occurred, or if
*    this function should fail for any reason.
*-
*/

/* Local Variables: */
   AstBox *box;
   AstCmpRegion *cmpreg;
   AstPointSet *result;
   double **ptr;
   int ic;
   int nc;

/* Check the local error status. */
   if ( !astOK ) return NULL;

/* Form a Box describing the required box. */
   box = astBox( this, 1, lbnd, ubnd, NULL, "", status );

/* Check there is partial overlap between the Regions.*/
   if( astOverlap( this, box ) > 3 ) {

/* Form a CmpRegion representing the intersection between the supplied
   Region and the above box. */
      cmpreg = astCmpRegion( this, box, AST__AND, "", status );

/* Get the boundary mesh. */
      result = astRegBaseMesh( cmpreg );

/* Free resources. */
      cmpreg = astAnnul( cmpreg );

/* If the boundary of the supplied Region does not intersect the box,
   return a PointSet containing a single bad position. */
   } else {
      nc = astGetNin( this->frameset );
      result = astPointSet( 1, nc, "", status );
      ptr = astGetPoints( result );
      if( ptr ) {
         for( ic = 0; ic < nc; ic++ ) ptr[ ic ][ 0 ] = AST__BAD;
      }
   }

/* Free resources. */
   box = astAnnul( box );

/* Return NULL if an error occurred. */
   if( !astOK ) result = astAnnul( result );

/* Return the required pointer. */
   return result;
}

static AstPointSet *BndMesh( AstRegion *this, double *lbnd, double *ubnd, int *status ){
/*
*+
*  Name:
*     astBndMesh

*  Purpose:
*     Return a PointSet containing points spread around part of the boundary
*     of a Region, in the current Frame.

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     AstPointSet *astBndMesh( AstRegion *this, double *lbnd, double *ubnd )

*  Class Membership:
*     Region virtual function.

*  Description:
*     This function returns a PointSet containing a set of points on the
*     boundary of the intersection between the supplied Region and the
*     supplied box. The points refer to the current Frame of the
*     encapsulated FrameSet. If the boundary of the supplied Region does
*     not intersect the supplied box, then a PointSet containing a single
*     bad point is returned.

*  Parameters:
*     this
*        Pointer to the Region.
*     lbnd
*        Pointer to an array holding the lower limits of the axis values
*        within the required box. Defined in the current Frame of the Region.
*     ubnd
*        Pointer to an array holding the upper limits of the axis values
*        within the required box. Defined in the current base Frame of the
*        Region.

*  Returned Value:
*     Pointer to the PointSet. The axis values in this PointSet will have
*     associated accuracies derived from the uncertainties which were
*     supplied when the Region was created.
*
*    If the Region does not intersect the supplied box, the returned
*    PointSet will contain a single point with a value of AST__BAD on
*    every axis.

*  Notes:
*    - A NULL pointer is returned if an error has already occurred, or if
*    this function should fail for any reason.
*-
*/

/* Local Variables: */
   AstMapping *map;
   AstPointSet *ps1;
   AstPointSet *result;

/* Initialise */
   result = NULL;

/* Check the local error status. */
   if ( !astOK ) return result;

/* Get the current->base Mapping from the Region. */
   map = astGetMapping( this->frameset, AST__CURRENT, AST__BASE );

/* Use astBndBaseMesh to get a mesh of base Frame points within this base
   Frame bounding box. */
   ps1 = astBndBaseMesh( this, lbnd, ubnd );

/* Transform it into the current Frame. */
   if( ps1 ) result = astTransform( map, ps1, 0, NULL );

/* Free resources. */
   map = astAnnul( map );
   ps1 = astAnnul( ps1 );

/* Return NULL if an error occurred. */
   if( !astOK ) result = astAnnul( result );

/* Return the required pointer. */
   return result;
}

static AstPointSet *BTransform( AstRegion *this, AstPointSet *in,
                                int forward, AstPointSet *out, int *status ) {
/*
*+
*  Name:
*     astBTransform

*  Purpose:
*     Use a Region to transform a set of points in the base Frame.

*  Type:
*     Protected virtual function.

*  Synopsis:
*     #include "circle.h"
*     AstPointSet *astBTransform( AstRegion *this, AstPointSet *in,
                                  int forward, AstPointSet *out )

*  Class Membership:
*     Region member function

*  Description:
*     This function takes a Region and a set of points within the base
*     Frame of the Region, and transforms the points by setting axis values
*     to AST__BAD for all points which are outside the region. Points inside
*     the region are copied unchanged from input to output.

*  Parameters:
*     this
*        Pointer to the Region.
*     in
*        Pointer to the PointSet holding the input coordinate data.
*     forward
*        A non-zero value indicates that the forward coordinate transformation
*        should be applied, while a zero value requests the inverse
*        transformation.
*     out
*        Pointer to a PointSet which will hold the transformed (output)
*        coordinate values. A NULL value may also be given, in which case a
*        new PointSet will be created by this function.

*  Returned Value:
*     Pointer to the output (possibly new) PointSet.

*  Notes:
*     -  This is identical to the astTransform method for a Region except
*     that the supplied and returned points refer to the base Frame of
*     the Region, rather than the current Frame.
*-
*/

/* Local Variables: */
   AstPointSet *result;          /* Pointer to output PointSet */
   int old;                      /* Origial value of "nomap" flag */

/* Check the global error status. */
   if ( !astOK ) return NULL;

/* Save the current value of the "nomap" flag for this Region,and then
   set it. Doing this tells the astRegMapping function (called by
   astRegTransform) to assume a unit map connects base and current Frame. */
   old = this->nomap;
   this->nomap = 1;

/* Invoke the usual astTransform method. The above setting of the "nomap"
   flag will cause the astTransform method to treat the base Frame as the
   current Frame. */
   result = astTransform( this, in, forward, out );

/* Reset the "nomap" flag. */
   this->nomap = old;

/* Return a pointer to the output PointSet. */
   return result;
}

static AstObject *Cast( AstObject *this_object, AstObject *obj, int *status ) {
/*
*  Name:
*     Cast

*  Purpose:
*     Cast an Object into an instance of a sub-class.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     AstObject *Cast( AstObject *this, AstObject *obj, int *status )

*  Class Membership:
*     Region member function (over-rides the protected astCast
*     method inherited from the Frame class).

*  Description:
*     This function returns a deep copy of an ancestral component of the
*     supplied object. The required class of the ancestral component is
*     specified by another object. Specifically, if "this" and "new" are
*     of the same class, a copy of "this" is returned. If "this" is an
*     instance of a subclass of "obj", then a copy of the component
*     of "this" that matches the class of "obj" is returned. Otherwise,
*     a NULL pointer is returned without error.

*  Parameters:
*     this
*        Pointer to the Object to be cast.
*     obj
*        Pointer to an Object that defines the class of the returned Object.
*        The returned Object will be of the same class as "obj".

*  Returned Value:
*     A pointer to the new Object. NULL if "this" is not a sub-class of
*     "obj", or if an error occurs.

*  Notes:
*     - A NULL pointer will be returned if this function is invoked
*     with the global error status set, or if it should fail for any
*     reason.
*/

/* Local Variables; */
   AstFrame *cfrm;
   AstObject *new;
   astDECLARE_GLOBALS
   int generation_gap;

/* Initialise */
   new = NULL;

/* Check inherited status */
   if( !astOK ) return new;

/* Get a pointer to the thread specific global data structure. */
   astGET_GLOBALS(NULL);

/* See how many steps up the class inheritance ladder it is from "obj"
   to this class (Region). A positive value is returned if Region is
   a sub-class of "obj". A negative value is returned if "obj" is a
   sub-class of Region. Zero is returned if "obj" is a Region.
   AST__COUSIN is returned if "obj" is not on the same line of descent
   as Region. */
   generation_gap = astClassCompare( (AstObjectVtab *) &class_vtab,
                                     astVTAB( obj ) );

/* If "obj" is a Region or a sub-class of Region, we can cast by
   truncating the vtab for "this" so that it matches the vtab of "obJ",
   and then taking a deep copy of "this". */
   if( generation_gap <= 0 && generation_gap != AST__COUSIN ) {
      new = astCastCopy( this_object, obj );

/* If "obj" is not a Region or a sub-class of Region (e.g. a Frame or
   some sub-class of Frame), we attempt to cast the current Frame of the
   encapsulated FrameSet into the class indicated by "obj". */
   } else {
      cfrm = astGetFrame( ((AstRegion *) this_object)->frameset, AST__CURRENT );
      new = astCast( cfrm, obj );
      cfrm = astAnnul( cfrm );
   }

/* Return the new pointer. */
   return new;
}

static double Centre( AstFrame *this_frame, int axis, double value, double gap, int *status ) {
/*
*  Name:
*     Centre

*  Purpose:
*     Find a "nice" central value for tabulating Frame axis values.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     double  Centre( AstFrame *this_frame, int axis, double value,
*                     double gap, int *status )

*  Class Membership:
*     Region member function (over-rides the protected astCentre method
*     inherited from the Frame class).

*  Description:
*     This function returns an axis value which produces a nice formatted
*     value suitable for a major tick mark on a plot axis, close to the
*     supplied axis value.

*  Parameters:
*     this
*        Pointer to the Frame.
*     axis
*        The number of the axis (zero-based) for which a central value
*        is to be found.
*     value
*        An arbitrary axis value in the section that is being plotted.
*     gap
*        The gap size.

*  Returned Value:
*     The nice central axis value.

*  Notes:
*     - A value of zero is returned if the supplied gap size is zero.
*     - A value of zero will be returned if this function is invoked
*     with the global error status set, or if it should fail for any
*     reason.
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to current Frame */
   AstRegion *this;              /* Pointer to the Region structure */
   double result;                /* Value to return */

/* Check the global error status. */
   if ( !astOK ) return 0.0;

/* Obtain a pointer to the Region structure. */
   this = (AstRegion *) this_frame;

/* Validate the axis index. */
   (void) astValidateAxis( this, axis, 1, "astCentre" );

/* Obtain a pointer to the Region's current Frame and invoke this
   Frame's astCentre method to obtain the required value. Annul the
   Frame pointer afterwards. */
   fr = astGetFrame( this->frameset, AST__CURRENT );
   result = astCentre( fr, axis, value, gap );
   fr = astAnnul( fr );

/* If an error occurred, clear the result. */
   if ( !astOK ) result = 0.0;

/* Return the result. */
   return result;
}

static void CheckPerm( AstFrame *this_frame, const int *perm, const char *method, int *status ) {
/*
*  Name:
*     CheckPerm

*  Purpose:
*     Check that an array contains a valid permutation.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     void CheckPerm( AstFrame *this, const int *perm, const char *method, int *status )

*  Class Membership:
*     Region member function (over-rides the protected astCheckPerm
*     method inherited from the Frame class).

*  Description:
*     This function checks the validity of a permutation array that
*     will be used to permute the order of a Frame's axes. If the
*     permutation specified by the array is not valid, an error is
*     reported and the global error status is set. Otherwise, the
*     function returns without further action.

*  Parameters:
*     this
*        Pointer to the Frame.
*     perm
*        Pointer to an array of integers with the same number of
*        elements as there are axes in the Frame. For each axis, the
*        corresponding integer gives the (zero based) axis index to be
*        used to identify the information for that axis (using the
*        un-permuted axis numbering). To be valid, the integers in
*        this array should therefore all lie in the range zero to
*        (naxes-1) inclusive, where "naxes" is the number of Frame
*        axes, and each value should occur exactly once.
*     method
*        Pointer to a constant null-terminated character string
*        containing the name of the method that invoked this function
*        to validate a permutation array. This method name is used
*        solely for constructing error messages.
*     status
*        Pointer to the inherited status variable.

*  Notes:
*     - Error messages issued by this function refer to the external
*     (public) numbering system used for axes (which is one-based),
*     whereas zero-based axis indices are used internally.
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to current Frame */
   AstRegion *this;              /* Pointer to the Region structure */

/* Check the global error status. */
   if ( !astOK ) return;

/* Obtain a pointer to the FrameSet structure. */
   this = (AstRegion *) this_frame;

/* Obtain a pointer to the Region's encapsulated Frame and invoke this
   Frame's astCheckPerm method. Annul the Frame pointer afterwards. */
   fr = astGetFrame( this->frameset, AST__CURRENT );
   astCheckPerm( fr, perm, method );
   fr = astAnnul( fr );

}

static void ClearAttrib( AstObject *this_object, const char *attrib, int *status ) {
/*
*  Name:
*     ClearAttrib

*  Purpose:
*     Clear an attribute value for a Region.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     void ClearAttrib( AstObject *this, const char *attrib, int *status )

*  Class Membership:
*     Region member function (over-rides the astClearAttrib protected
*     method inherited from the Frame class).

*  Description:
*     This function clears the value of a specified attribute for a
*     Region, so that the default value will subsequently be used.

*  Parameters:
*     this
*        Pointer to the Region.
*     attrib
*        Pointer to a null terminated string specifying the attribute
*        name.  This should be in lower case with no surrounding white
*        space.
*     status
*        Pointer to the inherited status variable.
*/

/* Local Variables: */
   AstRegion *this;            /* Pointer to the Region structure */

/* Check the global error status. */
   if ( !astOK ) return;

/* Obtain a pointer to the Region structure. */
   this = (AstRegion *) this_object;

/* Check the attribute name and clear the appropriate attribute. */

/* We first handle attributes that apply to the Region as a whole
   (rather than to the encapsulated FrameSet). */

/* Negated */
/* ------- */
   if ( !strcmp( attrib, "negated" ) ) {
      astClearNegated( this );

/* Closed */
/* ------ */
   } else if ( !strcmp( attrib, "closed" ) ) {
      astClearClosed( this );

/* FillFactor */
/* ---------- */
   } else if ( !strcmp( attrib, "fillfactor" ) ) {
      astClearFillFactor( this );

/* MeshSize */
/* -------- */
   } else if ( !strcmp( attrib, "meshsize" ) ) {
      astClearMeshSize( this );

/* Adaptive */
/* -------- */
   } else if ( !strcmp( attrib, "adaptive" ) ) {
      astClearAdaptive( this );


/* We now check for atttributes of superclasses which apply to the Region
   as a whole. We do not want to pass these on to the encapsulated FrameSet. */

/* ID. */
/* --- */
   } else if ( !strcmp( attrib, "id" ) ) {
      astClearID( this );

/* Ident. */
/* ------ */
   } else if ( !strcmp( attrib, "ident" ) ) {
      astClearIdent( this );

/* Invert. */
/* ------- */
   } else if ( !strcmp( attrib, "invert" ) ) {
      astClearInvert( this );

/* Report. */
/* ------- */
   } else if ( !strcmp( attrib, "report" ) ) {
      astClearReport( this );


/* If the name was not recognised, test if it matches any of the
   read-only attributes of this class (including those of all superclasses).
   If it does, then report an error. */
   } else if ( !strcmp( attrib, "class" ) ||
               !strcmp( attrib, "nin" ) ||
               !strcmp( attrib, "nobject" ) ||
               !strcmp( attrib, "nout" ) ||
               !strcmp( attrib, "bounded" ) ||
               !strcmp( attrib, "refcount" ) ||
               !strcmp( attrib, "tranforward" ) ||
               !strcmp( attrib, "traninverse" ) ) {
      astError( AST__NOWRT, "astClear: Invalid attempt to clear the \"%s\" "
                "value for a %s.", status, attrib, astGetClass( this ) );
      astError( AST__NOWRT, "This is a read-only attribute." , status);

/* Pass unrecognised attributes on to the Region's encapsulated FrameSet for
   further interpretation. Do not pass on FrameSet attributes since we
   pretend to the outside world that the encapsulated FrameSet is actually a
   Frame. */
   } else if ( strcmp( attrib, "base" ) &&
               strcmp( attrib, "current" ) &&
               strcmp( attrib, "nframe" ) ) {

/* If the Region is to adapt to coordinate system chanmges, use the public
   astClear method so that the current Frame in the encapsulated FrameSet will
   be re-mapped if the attribute changes require it. */
      if( astGetAdaptive( this ) ) {
         astClear( this->frameset, attrib );

/* If the Region is not to adapt to coordinate system chanmges, use the
   astRegSetAttrib method which assigns the attribute setting to both
   current and base Frames in the FrameSet without causing any remapping to
   be performed. */
      } else {
         astRegClearAttrib( this, attrib, NULL );
      }
   }
}

static AstFrameSet *Conv( AstFrameSet *from, AstFrameSet *to, int *status ){
/*
*  Name:
*     Conv

*  Purpose:
*     Find Mapping between Frames

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     AstFrameSet *Conv( AstFrameSet *from, AstFrameSet *to, int *status );

*  Class Membership:
*     Region member function

*  Description:
*     This function provides a convenient interface for astConvert.
*     It is like astConvert except it does not alter the base Frames of
*     the supplied FrameSets and does not require a Domain list.
*
*     It aligns in the current Frame of "to".

*  Parameters:
*     from
*        Pointer to the source FrameSet.
*     to
*        Pointer to the source FrameSet.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*        The conversion FrameSet (see astConvert).

*/

/* Local Variables: */
   AstFrameSet *result;        /* FrameSet to return */
   const char *dom;            /* Domain in which to align */
   int from_base;              /* Index of original base Frame in "from" */
   int to_base;                /* Index of original base Frame in "to" */

/* Check the global error status. */
   if( !astOK ) return NULL;

/* Note the indices of the base Frames in the FrameSets. */
   to_base = astGetBase( to );
   from_base = astGetBase( from );

/* Get the domain of the currentFrame of "to". */
   dom = astGetDomain( to );

/* Invoke astConvert. */
   result = astConvert( from, to, dom );

/* Re-instate original base Frames. */
   astSetBase( to, to_base );
   astSetBase( from, from_base );

/* Return the result. */
   return result;
}

static AstFrameSet *Convert( AstFrame *from, AstFrame *to,
                             const char *domainlist, int *status ) {
/*
*  Name:
*     Convert

*  Purpose:
*     Determine how to convert between two coordinate systems.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     AstFrameSet *Convert( AstFrame *from, AstFrame *to,
*                           const char *domainlist, int *status )

*  Class Membership:
*     Region member function (over-rides the public astConvert
*     method inherited fromm the Frame class).

*  Description:
*     This function compares two Regions and determines whether it
*     is possible to convert between the coordinate systems which
*     their current Frames represent. If conversion is possible, it
*     returns a FrameSet which describes the conversion and which may
*     be used (as a Mapping) to transform coordinate values in either
*     direction.

*  Parameters:
*     from
*        Pointer to a Region whose current Frame represents the
*        "source" coordinate system.  Note that the Base attribute of
*        the Region may be modified by this function.
*     to
*        Pointer to a Region whose current Frame represents the
*        "destination" coordinate system.  Note that the Base
*        attribute of the Region may be modified by this function.
*     domainlist
*        Pointer to a null-terminated character string containing a
*        comma-separated list of Frame domains. This may be used to
*        define a priority order for the different intermediate
*        coordinate systems that might be used to perform the
*        conversion.
*
*        The function will first try to obtain a conversion by making
*        use only of intermediate Frames whose Domain attribute
*        matches the first domain in this list. If this fails, the
*        second domain in the list will be used, and so on, until
*        conversion is achieved. A blank domain (e.g. two consecutive
*        commas) indicates that all Frames should be considered,
*        regardless of their Domain attributes. The list is
*        case-insensitive and all white space is ignored.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*        If the requested coordinate conversion is possible, the
*        function returns a pointer to a FrameSet which describes the
*        conversion. Otherwise, a null Object pointer (AST__NULL) is
*        returned without error.
*
*        If a FrameSet is returned, it will contain two Frames. Frame
*        number 1 (its base Frame) will describe the source coordinate
*        system, corresponding to the "from" parameter. Frame number 2
*        (its current Frame) will describe the destination coordinate
*        system, corresponding to the "to" parameter. The Mapping
*        which inter-relates these Frames will perform the required
*        conversion between the two coordinate systems.

*  Notes:
*     - The returned FrameSet will not contain any Regions. If one or
*     more of the supplied Frames are in fact Regions, the corresponding
*     Frames in any returned FrameSet will described the encapsulated
*     Frame, without any region information.
*     - A NULL pointer will be returned if this function is invoked
*     with the global error status set, or if it should fail for any
*     reason.
*/

/* Local Variables: */
   AstFrameSet *result;       /* Returned FrameSet */

/* Check the inherited status. */
   if ( !astOK ) return NULL;

/* If the "from" pointer is a Region, get a pointer to the current Frame of
   the encapsulated FrameSet and use it instead of the supplied pointer. */
   if( astIsARegion( from ) ) {
      from = astGetFrame( ((AstRegion *) from)->frameset, AST__CURRENT );
   } else {
      from = astClone( from );
   }

/* If the "to" pointer is a Region, get a pointer to the current Frame of
   the encapsulated FrameSet and use it instead of the supplied pointer. */
   if( astIsARegion( to ) ) {
      to = astGetFrame( ((AstRegion *) to)->frameset, AST__CURRENT );
   } else {
      to = astClone( to );
   }

/* Now invoke astConvert on the above Frames. */
   result = astConvert( from, to, domainlist );

/* Annul the pointers used above. */
   from = astAnnul( from );
   to = astAnnul( to );

/* Return the result */
   return result;
}

static AstFrameSet *ConvertX( AstFrame *to, AstFrame *from,
                              const char *domainlist, int *status ) {
/*
*  Name:
*     ConvertX

*  Purpose:
*     Determine how to convert between two coordinate systems.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     AstFrameSet *astConvertX( AstFrame *to, AstFrame *from,
*                               const char *domainlist )

*  Class Membership:
*     Region member function (over-rides the protected astConvertX
*     method inherited from the Frame class).

*  Description:
*     This function performs the processing for the public astConvert
*     method and has exactly the same interface except that the order
*     of the first two arguments is swapped. This is a trick to allow
*     the astConvert method to be over-ridden by derived classes on
*     the basis of the class of either of its first two arguments.
*
*     See the astConvert method for details of the interface.
*-
*/

/* Local Variables: */
   AstFrameSet *result;       /* Returned FrameSet */

/* Check the inherited status. */
   if ( !astOK ) return NULL;

/* If the "to" pointer is a Region, get a pointer to the current Frame of
   the encapsulated FrameSet and use it instead of the supplied pointer. */
   if( astIsARegion( to ) ) {
      to = astGetFrame( ((AstRegion *) to)->frameset, AST__CURRENT );
   } else {
      to = astClone( to );
   }

/* If the "from" pointer is a Region, get a pointer to the current Frame of
   the encapsulated FrameSet and use it instead of the supplied pointer. */
   if( astIsARegion( from ) ) {
      from = astGetFrame( ((AstRegion *) from)->frameset, AST__CURRENT );
   } else {
      from = astClone( from );
   }

/* Now invoke astConvertX on the above Frames. */
   result = astConvertX( to, from, domainlist );

/* Annul the pointers used above. */
   from = astAnnul( from );
   to = astAnnul( to );

/* Return the result */
   return result;
}

static double Distance( AstFrame *this_frame, const double point1[],
                        const double point2[], int *status ) {
/*
*  Name:
*     Distance

*  Purpose:
*     Calculate the distance between two points.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     double Distance( AstFrame *this, const double point1[],
*                      const double point2[], int *status )

*  Class Membership:
*     Region member function (over-rides the protected astDistance
*     method inherited from the Frame class).

*  Description:
*     This function finds the distance between two points whose
*     Region coordinates are given. The distance calculated is that
*     along the geodesic curve that joins the two points.

*  Parameters:
*     this
*        Pointer to the Region.
*     point1
*        An array of double, with one element for each Region axis
*        containing the coordinates of the first point.
*     point2
*        An array of double, with one element for each Region axis
*        containing the coordinates of the second point.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     The distance between the two points.

*  Notes:
*     - This function will return a "bad" result value (AST__BAD) if
*     any of the input coordinates has this value.
*     - A "bad" value will also be returned if this function is
*     invoked with the AST error status set or if it should fail for
*     any reason.
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to current Frame */
   AstRegion *this;              /* Pointer to the Region structure */
   double result;                /* Value to return */

/* Check the global error status. */
   if ( !astOK ) return AST__BAD;

/* Obtain a pointer to the Region structure. */
   this = (AstRegion *) this_frame;

/* Obtain a pointer to the Region's current Frame and invoke this
   Frame's astDistance method. Annul the Frame pointer afterwards. */
   fr = astGetFrame( this->frameset, AST__CURRENT );
   result = astDistance( fr, point1, point2 );
   fr = astAnnul( fr );

/* If an error occurred, clear the result. */
   if ( !astOK ) result = AST__BAD;

/* Return the result. */
   return result;
}

static int Equal( AstObject *this_object, AstObject *that_object, int *status ) {
/*
*  Name:
*     Equal

*  Purpose:
*     Test if two Objects are equivalent.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     int Equal( AstObject *this_object, AstObject *that_object, int *status )

*  Class Membership:
*     Region member function (over-rides the astEqual protected
*     method inherited from the Frame class).

*  Description:
*     This function returns a boolean result (0 or 1) to indicate whether
*     two Regions are equivalent.

*  Parameters:
*     this
*        Pointer to the first Region.
*     that
*        Pointer to the second Region.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     One if the Regions are equivalent, zero otherwise.

*  Notes:
*     - The Regions are equivalent if they are of the same class, have
*     equal PointSets, have equal base Frames, have equal current Frames,
*     and if the Mapping between base Frames is a UnitMap. In addition, the
*     Negated attribute must have the same value in both Regions, as must
*     the Closed attribute.
*     - A value of zero will be returned if this function is invoked
*     with the global status set, or if it should fail for any reason.
*/

/* Local Variables: */
   AstFrame *bf1;
   AstFrame *bf2;
   AstFrame *cf1;
   AstFrame *cf2;
   AstMapping *m1;
   AstMapping *m2;
   AstRegion *that;
   AstRegion *this;
   const char *class1;
   const char *class2;
   int result;

/* Initialise. */
   result = 0;

/* Check the global error status. */
   if ( !astOK ) return result;

/* Check that the two objects have the same class. */
   class1 = astGetClass( this_object );
   class2 = astGetClass( that_object );
   if( astOK && !strcmp( class1, class2 ) ) {

/* Obtain pointers to the two Region structures. */
      this = (AstRegion *) this_object;
      that = (AstRegion *) that_object;

/* Test their PointSets for equality. */
      if( astEqual( this->points, that->points ) ){

/* Test their base Frames for equality. */
         bf1 = astGetFrame( this->frameset, AST__BASE );
         bf2 = astGetFrame( that->frameset, AST__BASE );
         if( astEqual( bf1, bf2 ) ){

/* Test their current Frames for equality. */
            cf1 = astGetFrame( this->frameset, AST__CURRENT );
            cf2 = astGetFrame( that->frameset, AST__CURRENT );
            if( astEqual( cf1, cf2 ) ){

/* Get the two Mappings and check that they are equal */
               m1 = astGetMapping( this->frameset, AST__BASE, AST__CURRENT );
               m2 = astGetMapping( that->frameset, AST__BASE, AST__CURRENT );
               if( astEqual( m1, m2 ) ) {

/* Test the Negated and Closed flags are equal */
                  if( astGetNegated( this ) == astGetNegated( that ) &&
                       astGetClosed( this ) == astGetClosed( that ) ) {
                     result = 1;
                  }
               }

/* Free resources. */
               m1 = astAnnul( m1 );
               m2 = astAnnul( m2 );
            }

            cf1 = astAnnul( cf1 );
            cf2 = astAnnul( cf2 );
         }

         bf1 = astAnnul( bf1 );
         bf2 = astAnnul( bf2 );
      }
   }

/* If an error occurred, clear the result value. */
   if ( !astOK ) result = 0;

/* Return the result, */
   return result;
}

static void ClearUnc( AstRegion *this, int *status ){
/*
*+
*  Name:
*     astClearUnc

*  Purpose:
*     Erase any uncertainty information in a Region.

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     void astClearUnc( AstRegion *this )

*  Class Membership:
*     Region virtual function.

*  Description:
*     This function erases all uncertainty information, whether default
*     or not, from a Region.

*  Parameters:
*     this
*        Pointer to the Region.

*-
*/

/* Check the inherited status. */
   if( !astOK ) return;

/* Annul any user-supplied uncertainty. Also indicate that cached
   information may now be out of date. */
   if( this->unc ) {
      this->unc = astAnnul( this->unc );
      astResetCache( this );
   }

/* Annul any default uncertainty. */
   if( this->defunc ) this->defunc = astAnnul( this->defunc );

}

static AstFrameSet *FindFrame( AstFrame *target_frame, AstFrame *template,
                               const char *domainlist, int *status ) {
/*
*  Name:
*     FindFrame

*  Purpose:
*     Find a coordinate system with specified characteristics.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     AstFrameSet *FindFrame( AstFrame *target, AstFrame *template,
*                             const char *domainlist, int *status )

*  Class Membership:
*     Region member function (over-rides the astFindFrame method
*     inherited from the Frame class).

*  Description:
*     This function uses a "template" Frame to search a Region to
*     identify a coordinate system which has a specified set of
*     characteristics. If a suitable coordinate system can be found,
*     the function returns a pointer to a FrameSet which describes the
*     required coordinate system and how to convert coordinates to and
*     from it.

*  Parameters:
*     target
*        Pointer to the target Region.
*     template
*        Pointer to the template Frame, which should be an instance of
*        the type of Frame you wish to find.
*     domainlist
*        Pointer to a null-terminated character string containing a
*        comma-separated list of Frame domains. This may be used to
*        establish a priority order for the different types of
*        coordinate system that might be found.
*
*        The function will first try to find a suitable coordinate
*        system whose Domain attribute equals the first domain in this
*        list. If this fails, the second domain in the list will be
*        used, and so on, until a result is obtained. A blank domain
*        (e.g. two consecutive commas) indicates that any coordinate
*        system is acceptable (subject to the template) regardless of
*        its domain.
*
*        This list is case-insensitive and all white space is ignored.
*        If you do not wish to restrict the domain in this way, you
*        should supply an empty string.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     If the search is successful, the function returns a pointer to a
*     FrameSet which contains the Frame found and a description of how
*     to convert to (and from) the coordinate system it
*     represents. Otherwise, a null Object pointer (AST__NULL) is
*     returned without error.
*
*     If a FrameSet is returned, it will contain two Frames. Frame
*     number 1 (its base Frame) represents the target coordinate
*     system and will be the same as the target. Frame number 2 (its
*     current Frame) will be a Frame representing the coordinate system
*     which the function found. The Mapping which inter-relates these two
*     Frames will describe how to convert between their respective coordinate
*     systems. Note, the Frames in this FrameSet will not be Regions -
*     that is, they will be simple Frames or other derived classes.

*  Notes:
*     - A null Object pointer (AST__NULL) will be returned if this
*     function is invoked with the AST error status set, or if it
*     should fail for any reason.
*/

/* Local Variables: */
   AstFrameSet *result;          /* Pointer to result FrameSet */
   AstFrame *fr;                 /* Pointer to encapsulated Frame */

/* Initialise. */
   result = NULL;

/* Check the global error status. */
   if ( !astOK ) return result;

/* Invoke the astFindFrame method on the current Frame of the
   encapsulated FrameSet within the target Region. */
   fr = astGetFrame( ((AstRegion *) target_frame)->frameset, AST__CURRENT );
   result = astFindFrame( fr, template, domainlist );
   fr = astAnnul( fr );

/* Return the result. */
   return result;
}

static const char *Format( AstFrame *this_frame, int axis, double value, int *status ) {
/*
*  Name:
*     Format

*  Purpose:
*     Format a coordinate value for a Region axis.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     const char *Format( AstFrame *this, int axis, double value, int *status )

*  Class Membership:
*     Region member function (over-rides the astFormat method
*     inherited from the Frame class).

*  Description:
*     This function returns a pointer to a string containing the
*     formatted (character) version of a coordinate value for a
*     Region axis. The formatting applied is that specified by a
*     previous invocation of the astSetFormat method. A suitable
*     default format is applied if necessary.

*  Parameters:
*     this
*        Pointer to the Region.
*     axis
*        The number of the axis (zero-based) for which formatting is
*        to be performed.
*     value
*        The coordinate value to be formatted.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     A pointer to a null-terminated string containing the formatted
*     value.

*  Notes:
*     - The returned string pointer may point at memory allocated
*     within the Region object, or at static memory. The contents of
*     the string may be over-written or the pointer may become invalid
*     following a further invocation of the same function or deletion
*     of the Region. A copy of the string should therefore be made
*     if necessary.
*     - A NULL pointer will be returned if this function is invoked
*     with the global error status set, or if it should fail for any
*     reason.
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to current Frame */
   AstRegion *this;              /* Pointer to the Region structure */
   const char *result;           /* Pointer value to return */

/* Check the global error status. */
   if ( !astOK ) return NULL;

/* Obtain a pointer to the Region structure. */
   this = (AstRegion *) this_frame;

/* Validate the axis index. */
   (void) astValidateAxis( this, axis, 1, "astFormat" );

/* Obtain a pointer to the Region's current Frame and invoke the
   astFormat method for this Frame. Annul the Frame pointer
   afterwards. */
   fr = astGetFrame( this->frameset, AST__CURRENT );
   result = astFormat( fr, axis, value );
   fr = astAnnul( fr );

/* If an error occurred, clear the result value. */
   if ( !astOK ) result = NULL;

/* Return the result. */
   return result;
}

static double Gap( AstFrame *this_frame, int axis, double gap, int *ntick, int *status ) {
/*
*  Name:
*     Gap

*  Purpose:
*     Find a "nice" gap for tabulating Region axis values.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     double Gap( AstFrame *this, int axis, double gap, int *ntick, int *status )

*  Class Membership:
*     Region member function (over-rides the protected astGap method
*     inherited from the Frame class).

*  Description:
*     This function returns a gap size which produces a nicely spaced
*     series of formatted values for a Region axis, the returned gap
*     size being as close as possible to the supplied target gap
*     size. It also returns a convenient number of divisions into
*     which the gap can be divided.

*  Parameters:
*     this
*        Pointer to the Region.
*     axis
*        The number of the axis (zero-based) for which a gap is to be found.
*     gap
*        The target gap size.
*     ntick
*        Address of an int in which to return a convenient number of
*        divisions into which the gap can be divided.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     The nice gap size.

*  Notes:
*     - A value of zero is returned if the target gap size is zero.
*     - A negative gap size is returned if the supplied gap size is negative.
*     - A value of zero will be returned if this function is invoked
*     with the global error status set, or if it should fail for any
*     reason.
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to current Frame */
   AstRegion *this;              /* Pointer to the Region structure */
   double result;                /* Gap value to return */

/* Check the global error status. */
   if ( !astOK ) return 0.0;

/* Obtain a pointer to the Region structure. */
   this = (AstRegion *) this_frame;

/* Validate the axis index. */
   (void) astValidateAxis( this, axis, 1, "astGap" );

/* Obtain a pointer to the Region's current Frame and invoke this
   Frame's astGap method to obtain the required gap value. Annul the
   Frame pointer afterwards. */
   fr = astGetFrame( this->frameset, AST__CURRENT );
   result = astGap( fr, axis, gap, ntick );
   fr = astAnnul( fr );

/* If an error occurred, clear the result. */
   if ( !astOK ) result = 0.0;

/* Return the result. */
   return result;
}

static int GetObjSize( AstObject *this_object, int *status ) {
/*
*  Name:
*     GetObjSize

*  Purpose:
*     Return the in-memory size of an Object.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     int GetObjSize( AstObject *this, int *status )

*  Class Membership:
*     Region member function (over-rides the astGetObjSize protected
*     method inherited from the parent class).

*  Description:
*     This function returns the in-memory size of the supplied Region,
*     in bytes.

*  Parameters:
*     this
*        Pointer to the Region.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     The Object size, in bytes.

*  Notes:
*     - A value of zero will be returned if this function is invoked
*     with the global status set, or if it should fail for any reason.
*/

/* Local Variables: */
   AstRegion *this;         /* Pointer to Region structure */
   int result;                /* Result value to return */

/* Initialise. */
   result = 0;

/* Check the global error status. */
   if ( !astOK ) return result;

/* Obtain a pointers to the Region structure. */
   this = (AstRegion *) this_object;

/* Invoke the GetObjSize method inherited from the parent class, and then
   add on any components of the class structure defined by thsi class
   which are stored in dynamically allocated memory. */
   result = (*parent_getobjsize)( this_object, status );

   result += astGetObjSize( this->frameset );
   result += astGetObjSize( this->points );
   result += astGetObjSize( this->basemesh );
   result += astGetObjSize( this->basegrid );
   result += astGetObjSize( this->unc );
   result += astGetObjSize( this->negation );
   result += astGetObjSize( this->defunc );

/* If an error occurred, clear the result value. */
   if ( !astOK ) result = 0;

/* Return the result, */
   return result;
}

static const char *GetAttrib( AstObject *this_object, const char *attrib, int *status ) {
/*
*  Name:
*     GetAttrib

*  Purpose:
*     Get the value of a specified attribute for a Region.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     const char *GetAttrib( AstObject *this, const char *attrib, int *status )

*  Class Membership:
*     Region member function (over-rides the protected astGetAttrib
*     method inherited from the Frame class).

*  Description:
*     This function returns a pointer to the value of a specified
*     attribute for a Region, formatted as a character string.

*  Parameters:
*     this
*        Pointer to the Region.
*     attrib
*        Pointer to a null-terminated string containing the name of
*        the attribute whose value is required. This name should be in
*        lower case, with all white space removed.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     - Pointer to a null-terminated string containing the attribute
*     value.

*  Notes:
*     - The returned string pointer may point at memory allocated
*     within the Region, or at static memory. The contents of the
*     string may be over-written or the pointer may become invalid
*     following a further invocation of the same function or any
*     modification of the Region. A copy of the string should
*     therefore be made if necessary.
*     - A NULL pointer will be returned if this function is invoked
*     with the global error status set, or if it should fail for any
*     reason.
*/

/* Local Variables: */
   astDECLARE_GLOBALS           /* Pointer to thread-specific global data */
   AstRegion *this;              /* Pointer to the Region structure */
   const char *result;           /* Pointer value to return */
   double dval;                  /* Floating point attribute value */
   int ival;                     /* Integer attribute value */

/* Initialise. */
   result = NULL;

/* Check the global error status. */
   if ( !astOK ) return result;

/* Get a pointer to the thread specific global data structure. */
   astGET_GLOBALS(this_object);

/* Obtain a pointer to the Region structure. */
   this = (AstRegion *) this_object;

/* Compare "attrib" with each recognised attribute name in turn,
   obtaining the value of the required attribute. If necessary, write
   the value into "getattrib_buff" as a null-terminated string in an appropriate
   format.  Set "result" to point at the result string. */

/* We first handle attributes that apply to the Region as a whole
   (rather than to the encapsulated FrameSet). */

/* Negated */
/* ------- */
   if ( !strcmp( attrib, "negated" ) ) {
      ival = astGetNegated( this );
      if ( astOK ) {
         (void) sprintf( getattrib_buff, "%d", ival );
         result = getattrib_buff;
      }

/* Closed */
/* ------ */
   } else if ( !strcmp( attrib, "closed" ) ) {
      ival = astGetClosed( this );
      if ( astOK ) {
         (void) sprintf( getattrib_buff, "%d", ival );
         result = getattrib_buff;
      }

/* Adaptive */
/* -------- */
   } else if ( !strcmp( attrib, "adaptive" ) ) {
      ival = astGetAdaptive( this );
      if ( astOK ) {
         (void) sprintf( getattrib_buff, "%d", ival );
         result = getattrib_buff;
      }

/* FillFactor */
/* ---------- */
   } else if ( !strcmp( attrib, "fillfactor" ) ) {
      dval = astGetFillFactor( this );
      if ( astOK ) {
         (void) sprintf( getattrib_buff, "%.*g", AST__DBL_DIG, dval );
         result = getattrib_buff;
      }

/* MeshSize */
/* -------- */
   } else if ( !strcmp( attrib, "meshsize" ) ) {
      ival = astGetMeshSize( this );
      if ( astOK ) {
         (void) sprintf( getattrib_buff, "%d", ival );
         result = getattrib_buff;
      }

/* Bounded */
/* ------- */
   } else if ( !strcmp( attrib, "bounded" ) ) {
      ival = astGetBounded( this );
      if ( astOK ) {
         (void) sprintf( getattrib_buff, "%d", ival );
         result = getattrib_buff;
      }

/* Now get the values of attributes inherited from parent classes. We do
   this to avoid the request being passed on to the encapsulated FrameSet
   below. */

/* Class. */
/* ------ */
   } else if ( !strcmp( attrib, "class" ) ) {
      result = astGetClass( this );

/* ID. */
/* --- */
   } else if ( !strcmp( attrib, "id" ) ) {
      result = astGetID( this );

/* Ident. */
/* ------ */
   } else if ( !strcmp( attrib, "ident" ) ) {
      result = astGetIdent( this );

/* Invert. */
/* ------- */
   } else if ( !strcmp( attrib, "invert" ) ) {
      ival = astGetInvert( this );
      if ( astOK ) {
         (void) sprintf( getattrib_buff, "%d", ival );
         result = getattrib_buff;
      }

/* Nin. */
/* ---- */
   } else if ( !strcmp( attrib, "nin" ) ) {
      ival = astGetNin( this );
      if ( astOK ) {
         (void) sprintf( getattrib_buff, "%d", ival );
         result = getattrib_buff;
      }

/* Nobject. */
/* -------- */
   } else if ( !strcmp( attrib, "nobject" ) ) {
      ival = astGetNobject( this );
      if ( astOK ) {
         (void) sprintf( getattrib_buff, "%d", ival );
         result = getattrib_buff;
      }

/* Nout. */
/* ----- */
   } else if ( !strcmp( attrib, "nout" ) ) {
      ival = astGetNout( this );
      if ( astOK ) {
         (void) sprintf( getattrib_buff, "%d", ival );
         result = getattrib_buff;
      }

/* RefCount. */
/* --------- */
   } else if ( !strcmp( attrib, "refcount" ) ) {
      ival = astGetRefCount( this );
      if ( astOK ) {
         (void) sprintf( getattrib_buff, "%d", ival );
         result = getattrib_buff;
      }

/* Report. */
/* ------- */
   } else if ( !strcmp( attrib, "report" ) ) {
      ival = astGetReport( this );
      if ( astOK ) {
         (void) sprintf( getattrib_buff, "%d", ival );
         result = getattrib_buff;
      }

/* TranForward. */
/* ------------ */
   } else if ( !strcmp( attrib, "tranforward" ) ) {
      ival = astGetTranForward( this );
      if ( astOK ) {
         (void) sprintf( getattrib_buff, "%d", ival );
         result = getattrib_buff;
      }

/* TranInverse. */
/* ------------ */
   } else if ( !strcmp( attrib, "traninverse" ) ) {
      ival = astGetTranInverse( this );
      if ( astOK ) {
         (void) sprintf( getattrib_buff, "%d", ival );
         result = getattrib_buff;
      }

/* Pass unrecognised attributes on to the Region's encapsulated FrameSet for
   further interpretation. Do not pass on FrameSet attributes since we
   pretend to the outside world that the encapsulated FrameSet is actually a
   Frame. */
   } else if ( strcmp( attrib, "base" ) &&
               strcmp( attrib, "current" ) &&
               strcmp( attrib, "nframe" ) ) {
      result = astGetAttrib( this->frameset, attrib );
   }

/* If an error occurred, clear the result value. */
   if ( !astOK ) result = NULL;

/* Return the result. */
   return result;
}

static int GetBounded( AstRegion *this, int *status ) {
/*
*+
*  Name:
*     astGetBounded

*  Purpose:
*     Is the Region bounded?

*  Type:
*     Protected function.

*  Synopsis:
*     int astGetBounded( AstRegion *this )

*  Class Membership:
*     Region virtual function.

*  Description:
*     This function returns a flag indicating if the Region is bounded.
*     The implementation provided by the base Region class is suitable
*     for Region sub-classes representing the inside of a single closed
*     curve (e.g. Circle, Ellipse, Box, etc). Other sub-classes (such as
*     CmpRegion, PointList, etc ) may need to provide their own
*     implementations.

*  Parameters:
*     this
*        Pointer to the Region.

*  Returned Value:
*     Non-zero if the Region is bounded. Zero otherwise.

*-
*/

/* Local Variables: */
   int result;
   AstFrame *bfrm;

/* Check inherited status */
   if( !astOK ) return 0;

/* For Regions which are defined by one or more closed curves such as Circles,
   Boxes, etc, the Region is bounded so long as it has not been negated.
   Classes for which this is not true should over-ride this implementation.
   Note, Regions defined within SkyFrames (i.e. on a sphere) are always
   bounded, since a finite region has a finite negation. */
   bfrm = astGetFrame( this->frameset, AST__BASE );
   if( astIsASkyFrame( bfrm ) ) {
      result = 1;
   } else {
      result = !astGetNegated( this );
   }
   bfrm = astAnnul( bfrm );

   return result;
}

static AstAxis *GetAxis( AstFrame *this_frame, int axis, int *status ) {
/*
*  Name:
*     GetAxis

*  Purpose:
*     Obtain a pointer to a specified Axis from a Region.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     AstAxis *GetAxis( AstFrame *this, int axis, int *status )

*  Class Membership:
*     Region member function (over-rides the astGetAxis method
*     inherited from the Frame class).

*  Description:
*     This function returns a pointer to the Axis object associated
*     with one of the axes of the current Frame of a Region. This
*     object describes the quantity which is represented along that
*     axis.

*  Parameters:
*     this
*        Pointer to the Region.
*     axis
*        The number of the axis (zero-based) for which an Axis pointer
*        is required.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     A pointer to the requested Axis object.

*  Notes:
*     - The reference count of the requested Axis object will be
*     incremented by one to reflect the additional pointer returned by
*     this function.
*     - A NULL pointer will be returned if this function is invoked
*     with the global error status set, or if it should fail for any
*     reason.
*/

/* Local Variables: */
   AstAxis *result;              /* Pointer to Axis */
   AstRegion *this;              /* Pointer to the Region structure */

/* Check the global error status. */
   if ( !astOK ) return NULL;

/* Obtain a pointer to the Region structure. */
   this = (AstRegion *) this_frame;

/* Validate the axis index. */
   (void) astValidateAxis( this, axis, 1, "astGetAxis" );

/* Obtain a pointer to the Region's encapsulated FrameSet and invoke
   this FrameSet's astGetAxis method to obtain the required Axis
   pointer. */
   result = astGetAxis( this->frameset, axis );

/* If an error occurred, annul the result. */
   if ( !astOK ) result = astAnnul( result );

/* Return the result. */
   return result;
}

static AstRegion *GetDefUnc( AstRegion *this, int *status ) {
/*
*+
*  Name:
*     astGetDefUnc

*  Purpose:
*     Obtain a pointer to the default uncertainty Region for a given Region.

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     AstRegion *astGetDefUnc( AstRegion *this )

*  Class Membership:
*     Region virtual function.

*  Description:
*     This function returns a pointer to a Region which represents the
*     default uncertainty associated with a position on the boundary of the
*     given  Region. The returned Region refers to the base Frame within the
*     FrameSet encapsulated by the supplied Region.

*  Parameters:
*     this
*        Pointer to the Region.

*  Returned Value:
*     A pointer to the Region. This should be annulled (using astAnnul)
*     when no longer needed.

*  Notes:
*     - A NULL pointer will be returned if this function is invoked
*     with the global error status set, or if it should fail for any
*     reason.
*-
*/

/* Local Variables: */
   AstFrame *bfrm;            /* Base Frame of supplied Region */
   AstRegion *result;         /* Returned pointer */
   double *lbnd;              /* Ptr. to array holding axis lower bounds */
   double *ubnd;              /* Ptr. to array holding axis upper bounds */
   double c;                  /* Central axis value */
   double hw;                 /* Half width of uncertainty interval */
   int i;                     /* Axis index */
   int nax;                   /* Number of base Frame axes */

/* Initialise */
   result = NULL;

/* Check the global error status. */
   if ( !astOK ) return result;

/* Get a pointer to the base Frame in the supplied Region. */
   bfrm = astGetFrame( this->frameset, AST__BASE );

/* Get the number of base Frame axes. */
   nax = astGetNaxes( bfrm );

/* Get the base frame bounding box of the supplied Region. The astRegBaseBox
   assumes the supplied Region has not been inverted. But if the Region
   contains other Regions (e.g. a Prism or CmpRegion, etc) then this
   assumption needs to be propagated to the component Regions, which
   astRegBaseBox does not do. For this reason we use astRegBaseBox2
   instead. */
   lbnd = astMalloc( sizeof( double)*(size_t) nax );
   ubnd = astMalloc( sizeof( double)*(size_t) nax );
   astRegBaseBox2( this, lbnd, ubnd );

/* Create a Box covering 1.0E-6 of this bounding box, centred on the
   centre of the box. */
   if( astOK ) {
      for( i = 0; i < nax; i++ ) {
         if( ubnd[ i ] != DBL_MAX && lbnd[ i ] != -DBL_MAX ) {
            hw = fabs( 0.5E-6*(  ubnd[ i ] - lbnd[ i ] ) );
            c = 0.5*(  ubnd[ i ] + lbnd[ i ] );
            if( hw == 0.0 ) hw = c*0.5E-6;
            ubnd[ i ] = c + hw;
            lbnd[ i ] = c - hw;
         } else {
            ubnd[ i ] = 0.0;
            lbnd[ i ] = 0.0;
         }
      }
      result = (AstRegion *) astBox( bfrm, 1, lbnd, ubnd, NULL, "", status );
   }

/* Free resources. */
   lbnd = astFree( lbnd );
   ubnd = astFree( ubnd );
   bfrm = astAnnul( bfrm );

/* Return NULL if an error occurred. */
   if( !astOK ) result = astAnnul( result );

/* Return the required pointer. */
   return result;
}

static AstRegion *GetNegation( AstRegion *this, int *status ) {
/*
*+
*  Name:
*     astGetNegation

*  Purpose:
*     Obtain a pointer to a negated copy of the supplied Region.

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     AstRegion *GetNegation( AstRegion *this, int *status )

*  Class Membership:
*     Region virtual function.

*  Description:
*     This function returns a pointer to a Region which is a negated
*     copy of "this". The copy is cached in the Region structure for
*     future use.

*  Parameters:
*     this
*        Pointer to the Region.

*  Returned Value:
*     A pointer to the Region. This should be annulled (using astAnnul)
*     when no longer needed.

*  Notes:
*     - A NULL pointer will be returned if this function is invoked
*     with the global error status set, or if it should fail for any
*     reason.
*-
*/

/* Check the global error status. */
   if ( !astOK ) return NULL;

/* If the Region struture does not contain a pointer to a negated copy of
   itself, create one now. */
   if( ! this->negation ) {
      this->negation = astCopy( this );
      astNegate( this->negation );
   }

/* Return a clone of the negation pointer. */
   return astClone( this->negation );
}

static AstFrameSet *GetRegFS( AstRegion *this, int *status ) {
/*
*+
*  Name:
*     astGetRegFS

*  Purpose:
*     Obtain a pointer to the FrameSet encapsulated within a Region.

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     AstFrameSet *astGetRegFS( AstRegion *this )

*  Class Membership:
*     Region virtual function

*  Description:
*     This function returns a pointer to the FrameSet encapsulated by the
*     Region. This is a clone, not a deep copy, of the pointer stored
*     in the Region.

*  Parameters:
*     this
*        Pointer to the Region.

*  Returned Value:
*     A pointer to the FrameSet.

*  Notes:
*     - A NULL pointer will be returned if this function is invoked
*     with the global error status set, or if it should fail for any
*     reason.
*-
*/

/* Check the global error status. */
   if ( !astOK ) return NULL;

/* Return the required pointer. */
   return astClone( this->frameset );
}

static AstPointSet *GetSubMesh( int *mask, AstPointSet *in, int *status ) {
/*
*  Name:
*     GetSubMesh

*  Purpose:
*     Extract a selection of points from a PointSet.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     AstPointSet *GetSubMesh( int *mask, AstPointSet *in, int *status )

*  Class Membership:
*     Region member function

*  Description:
*     This function creates a new PointSet holding points selected from a
*     supplied PointSet. An integer mask is supplied to indicate which
*     points should be selected.

*  Parameters:
*     mask
*        Pointer to a mask array, Its size should be equal to the number
*        of points in the supplied PointSet. Each corresponding point will
*        be copied if the mask value is zero.
*     in
*        Pointer to the PointSet holding the input positions.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     Pointer to the output PointSet.

*  Notes:
*     - A null pointer will be returned if this function is invoked
*     with the global error status set, or if it should fail for any
*     reason.
*/

/* Local Variables: */
   AstPointSet *result;          /* Pointer to output PointSet */
   double **ptr_in;              /* Pointers to input axis values */
   double **ptr_out;             /* Pointers to output axis values */
   double *pin;                  /* Pointer to next input axis value */
   double *pout;                 /* Pointer to next output axis value */
   int *m;                       /* Pointer to next mask element */
   int ic;                       /* Axis index */
   int ip;                       /* Point index */
   int nc;                       /* Number of axes in both PointSets */
   int npin;                     /* Number of points in input PointSet */
   int npout;                    /* Number of points in output PointSet */

/* Initialise. */
   result = NULL;

/* Check the global error status. */
   if ( !astOK ) return result;

/* Get the length of the mask. */
   npin = astGetNpoint( in );

/* Count the number of zeros in the mask. */
   npout = 0;
   m = mask;
   for( ip = 0; ip < npin; ip++ ) {
      if( *(m++) == 0 ) npout++;
   }

/* Create the output PointSet and get pointers to its data arrays. */
   nc = astGetNcoord( in );
   result = astPointSet( npout, nc, "", status );
   ptr_in = astGetPoints( in );
   ptr_out = astGetPoints( result );

/* Check pointers can be dereferenced safely. */
   if( astOK ) {

/* Copy the required axis values from the input to the output. */
      for( ic = 0; ic < nc; ic++ ) {
         pin = ptr_in[ ic ];
         pout = ptr_out[ ic ];
         m = mask;
         for( ip = 0; ip < npin; ip++, pin++, m++ ) {
            if( *m == 0 ) *(pout++) = *pin;
         }
      }
   }

/* Return a pointer to the output PointSet. */
   return result;

}

static AstRegion *GetUnc( AstRegion *this, int def, int *status ){
/*
*++
*  Name:
c     astGetUnc
f     AST_GETUNC

*  Purpose:
*     Obtain uncertainty information from a Region.

*  Type:
*     Public virtual function.

*  Synopsis:
c     #include "region.h"
c     AstRegion *astGetUnc( AstRegion *this, int def )
f     RESULT = AST_GETUNC( THIS, DEF, STATUS )

*  Class Membership:
*     Region method.

*  Description:
*     This function returns a Region which represents the uncertainty
*     associated with positions within the supplied Region. See
c     astSetUnc
f     AST_SETUNC
*     for more information about Region uncertainties and their use.

*  Parameters:
c     this
f     THIS = INTEGER (Given)
*        Pointer to the Region.
c     def
f     DEF = LOGICAL (Given)
*        Controls what is returned if no uncertainty information has been
*        associated explicitly with the supplied Region. If
c        a non-zero value
f        .TRUE.
*        is supplied, then the default uncertainty Region used internally
*        within AST is returned (see "Applicability" below). If
c        zero is supplied, then NULL
f        .FALSE. is supplied, then AST__NULL
*        will be returned (without error).
f     STATUS = INTEGER (Given and Returned)
f        The global status.

*  Returned Value:
c     astGetUnc()
f     AST_GETUNC = INTEGER
*        A pointer to a Region describing the uncertainty in the supplied
*        Region.

*  Applicability:
*     CmpRegion
*        The default uncertainty for a CmpRegion is taken from one of the
*        two component Regions. If the first component Region has a
*        non-default uncertainty, then it is used as the default uncertainty
*        for the parent CmpRegion. Otherwise, if the second component Region
*        has a non-default uncertainty, then it is used as the default
*        uncertainty for the parent CmpRegion. If neither of the
*        component Regions has non-default uncertainty, then the default
*        uncertainty for the CmpRegion is 1.0E-6 of the bounding box of
*        the CmpRegion.
*     Prism
*        The default uncertainty for a Prism is formed by combining the
*        uncertainties from the two component Regions. If a component
*        Region does not have a non-default uncertainty, then its default
*        uncertainty will be used to form the default uncertainty of the
*        parent Prism.
*     Region
*        For other classes of Region, the default uncertainty is 1.0E-6
*        of the bounding box of the Region. If the bounding box has zero
*        width on any axis, then the uncertainty will be 1.0E-6 of the
*        axis value.

*  Notes:
*     - If uncertainty information is associated with a Region, and the
*     coordinate system described by the Region is subsequently changed
*     (e.g. by changing the value of its System attribute, or using the
c     astMapRegion
f     AST_MAPREGION
*     function), then the uncertainty information returned by this function
*     will be modified so that it refers to the coordinate system currently
*     described by the supplied Region.
f     - A null Object pointer (AST__NULL) will be returned if this
f     function is invoked with STATUS set to an error value, or if it
c     - A null Object pointer (NULL) will be returned if this
c     function is invoked with the AST error status set, or if it
*     should fail for any reason.

*--
*/

/* Local Variables: */
   AstRegion *result;       /* Pointer to returned uncertainty Region */
   AstRegion *unc;          /* Pointer to original uncertainty Region */

/* Initialise */
   result = NULL;

/* Check inherited status */
   if( !astOK ) return result;

/* Check that we have an uncertainty Region to return (either assigned or
   default). */
   if( def || astTestUnc( this ) ) {

/* Obtain the uncertainty Region and take a copy so that we can modify it
   without affecting the supplied Region. */
      unc = astGetUncFrm( this, AST__CURRENT );
      result = astCopy( unc );
      unc = astAnnul( unc );

/* In its current context, the uncertainty region is known to refer to
   the Frame of the supplied Region and so its RegionFS attribute will be
   set to zero, indicating that the uncertainty FrameSet need not be
   dumped. However, outside of AST this information cannot be implied, so
   clear the RegionFS attribute so that the returned pointer will include
   Frame information if it is dumped to a Channel. */
      astClearRegionFS( result );

   }

/* Return the result. */
   return result;

}

static AstRegion *GetUncFrm( AstRegion *this, int ifrm, int *status ) {
/*
*+
*  Name:
*     astGetUncFrm

*  Purpose:
*     Obtain a pointer to the uncertainty Region for a given Region.

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     AstRegion *astGetUncFrm( AstRegion *this, int ifrm )

*  Class Membership:
*     Region virtual function.

*  Description:
*     This function returns a pointer to a Region which represents the
*     uncertainty associated with a position on the boundary of the given
*     Region. The returned Region can refer to the either the base or
*     the current Frame within the FrameSet encapsulated by the supplied
*     Region as specified by the "ifrm" parameter. If the returned Region is
*     re-centred at some point on the boundary of the supplied Region, then
*     the re-centred Region will represent the region in which the true
*     boundary position could be.

*  Parameters:
*     this
*        Pointer to the Region.
*     ifrm
*        The index of a Frame within the FrameSet encapsulated by "this".
*        The returned Region will refer to the requested Frame. It should
*        be either AST__CURRENT or AST__BASE.

*  Returned Value:
*     A pointer to the Region. This should be annulled (using astAnnul)
*     when no longer needed.

*  Notes:
*     - A default uncertainty Region will be created if the supplied Region
*     does not have an uncertainty Region.
*     - A NULL pointer will be returned if this function is invoked
*     with the global error status set, or if it should fail for any
*     reason.
*-
*/

/* Local Variables: */
   AstFrame *frm;             /* Current Frame from supplied Region */
   AstMapping *map;           /* Supplied to uncertainty Mapping */
   AstRegion *result;         /* Returned pointer */
   AstRegion *unc;            /* Base frame uncertainty Region to use */

/* Initialise */
   result = NULL;

/* Check the global error status. */
   if ( !astOK ) return result;

/* If the Region has an explicitly assigned base-frame uncertainty Region,
   use it. */
   if( this->unc ) {
      unc = this->unc;

/* If not, use the default base-frame uncertainty Region, creating it if
   necessary. */
   } else {
      if( !this->defunc ) this->defunc = astGetDefUnc( this );
      unc = this->defunc;
   }

/* If the uncertainty Region is the base Frame is required, just return a
   clone of the uncertainty Region pointer. The Frame represented by an
   uncertainty Region will always (barring bugs!) be the base Frame of
   its parent Region. */
   if( ifrm == AST__BASE ) {
      result = astClone( unc );

/* If the uncertainty Region is the current Frame is required... */
   } else {

/* Get a Mapping from the Frame represented by the uncertainty Region
   (the Region base Frame) to the Region current Frame. */
      map = astGetMapping( this->frameset, AST__BASE, AST__CURRENT );

/* If this is a UnitMap, the uncertainty Region is already in the correct
   Frame, so just return the stored pointer. */
      if( astIsAUnitMap( map ) ) {
         result = astClone( unc );

/* Otherwise, use this Mapping to map the uncertainty Region into the current
   Frame. */
      } else {
         frm = astGetFrame( this->frameset, AST__CURRENT );
         result = astMapRegion( unc, map, frm );

/* Free resources. */
         frm = astAnnul( frm );
      }

      map = astAnnul( map );
   }

/* Return NULL if an error occurred. */
   if( !astOK ) result = astAnnul( result );

/* Return the required pointer. */
   return result;
}

static int GetUseDefs( AstObject *this_object, int *status ) {
/*
*  Name:
*     GetUseDefs

*  Purpose:
*     Get the value of the UseDefs attribute for a Region.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     int GetUseDefs( AstObject *this_object, int *status ) {

*  Class Membership:
*     Region member function (over-rides the protected astGetUseDefs
*     method inherited from the Frame class).

*  Description:
*     This function returns the value of the UseDefs attribute for a
*     Region. supplying a suitable default.

*  Parameters:
*     this
*        Pointer to the Region.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     - The USeDefs value.
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to current Frame */
   AstRegion *this;              /* Pointer to the Region structure */
   int result;                   /* Value to return */

/* Initialise. */
   result = 0;

/* Check the global error status. */
   if ( !astOK ) return result;

/* Obtain a pointer to the Region structure. */
   this = (AstRegion *) this_object;

/* If the UseDefs value for the Region has been set explicitly, use the
   Get method inherited from the parent Frame class to get its value. */
   if( astTestUseDefs( this ) ) {
      result = (*parent_getusedefs)( this_object, status );

/* Otherwise, supply a default value equal to the UseDefs value of the
   encapsulated Frame. */
   } else {
      fr = astGetFrame( this->frameset, AST__CURRENT );
      result = astGetUseDefs( fr );
      fr = astAnnul( fr );
   }

/* Return the result. */
   return result;
}

static int TestUnc( AstRegion *this, int *status ) {
/*
*+
*  Name:
*     astTestUnc

*  Purpose:
*     Does the Region contain non-default uncertainty information?

*  Type:
*     Protected function.

*  Synopsis:
*     int astTestUnc( AstRegion *this )

*  Class Membership:
*     Region virtual function.

*  Description:
*     This function returns a flag indicating if the uncertainty Region in
*     the supplied Region was supplied explicit (i.e. is not a default
*     uncertainty Region).

*  Parameters:
*     this
*        Pointer to the Region.

*  Returned Value:
*     Non-zero if the uncertainty Region was supplied explicitly.
*     Zero otherwise.

*  Notes:
*     - Classes of Region that encapsulate two or more other Regions
*     inherit their default uncertainty from the encapsulated Regions.
*     Non-default uncertainty in the component Regions does not imply
*     that the parent Region has non-default uncertainty.
*-
*/

/* Check the global error status. */
   if ( !astOK ) return 0;

   return ( this->unc != NULL );
}

static AstFrame *RegFrame( AstRegion *this, int *status ) {
/*
*+
*  Name:
*     astRegFrame

*  Purpose:
*     Obtain a pointer to the current Frame for a Region.

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     AstFrame *astRegFrame( AstRegion *this )

*  Class Membership:
*     Region virtual function

*  Description:
*     This function returns a pointer to the current Frame in the encapsulated
*     FrameSet. This is a clone, not a deep copy, of the pointer stored
*     in the FrameSet. For a deep copy, use astGetRegionFrame.

*  Parameters:
*     this
*        Pointer to the Region.

*  Returned Value:
*     A pointer to the Frame.

*  Notes:
*     - A NULL pointer will be returned if this function is invoked
*     with the global error status set, or if it should fail for any
*     reason.
*-
*/

/* Check the global error status. */
   if ( !astOK ) return NULL;

/* Return the required pointer. */
   return astGetFrame( this->frameset, AST__CURRENT );
}

static AstMapping *RegMapping( AstRegion *this, int *status ) {
/*
*+
*  Name:
*     astRegMapping

*  Purpose:
*     Obtain a pointer to the simplified base->current Mapping for a Region.

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     AstMapping *astRegMapping( AstRegion *this )

*  Class Membership:
*     Region member function

*  Description:
*     This function returns a pointer to the Mapping from the base to the
*     current Frame int he encapsulated FrameSet. The returned Mapping is
*     simplified before being returned.

*  Parameters:
*     this
*        Pointer to the Region.

*  Returned Value:
*     A pointer to the Mapping.

*  Notes:
*     - A NULL pointer will be returned if this function is invoked
*     with the global error status set, or if it should fail for any
*     reason.
*-
*/

/* Local Variables: */
   AstMapping *map;           /* Unsimplified Mapping */
   AstMapping *result;        /* Simplified Mapping */

/* Initialise */
   result = NULL;

/* Check the global error status. */
   if ( !astOK ) return result;

/* If the "nomap" flag is set in the Region structure, re return a
   UnitMap. */
   if( this->nomap ) {
      result = (AstMapping *) astUnitMap( astGetNin( this->frameset ), "", status );

/* Otherwise use the Mapping from the Region's FrameSet. */
   } else {

/* Get the Mapping */
      map = astGetMapping( this->frameset, AST__BASE, AST__CURRENT );

/* Simplify it. */
      result = astSimplify( map );

/* Annul the pointer to the unsimplified Mapping */
      map = astAnnul( map );
   }

/* Return the required pointer. */
   return result;
}

static int GetNaxes( AstFrame *this_frame, int *status ) {
/*
*  Name:
*     GetNaxes

*  Purpose:
*     Determine how many axes a Region has.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     int GetNaxes( AstFrame *this, int *status )

*  Class Membership:
*     Region member function (over-rides the astGetNaxes method
*     inherited from the Frame class).

*  Description:
*     This function returns the number of axes for a Region. This is equal
*     to the number of axes in its current Frame.

*  Parameters:
*     this
*        Pointer to the Region.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     The number of Region axes (zero or more).

*  Notes:
*     - A value of zero will be returned if this function is invoked
*     with the global error status set, or if it should fail for any
*     reason.
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to current Frame */
   AstRegion *this;              /* Pointer to the Region structure */
   int result;                   /* Result to be returned */

/* Check the global error status. */
   if ( !astOK ) return 0;

/* Obtain a pointer to the Region structure. */
   this = (AstRegion *) this_frame;

/* Obtain a pointer to the Region's current Frame. */
   fr = astGetFrame( this->frameset, AST__CURRENT );

/* Obtain the number of axes in this Frame. */
   result = astGetNaxes( fr );

/* Annul the current Frame pointer. */
   fr = astAnnul( fr );

/* If an error occurred, clear the result value. */
   if ( !astOK ) result = 0;

/* Return the result. */
   return result;
}

static const int *GetPerm( AstFrame *this_frame, int *status ) {
/*
*  Name:
*     GetPerm

*  Purpose:
*     Access the axis permutation array for the current Frame of a Region.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     const int *GetPerm( AstFrame *this, int *status )

*  Class Membership:
*     Region member function (over-rides the astGetPerm protected
*     method inherited from the Frame class).

*  Description:
*     This function returns a pointer to the axis permutation array
*     for the current Frame of a Region. This array constitutes a
*     lookup-table that converts between an axis number supplied
*     externally and the corresponding index in the Frame's internal
*     axis arrays.

*  Parameters:
*     this
*        Pointer to the Region.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     Pointer to the current Frame's axis permutation array (a
*     constant array of int).  Each element of this contains the
*     (zero-based) internal axis index to be used in place of the
*     external index which is used to address the permutation
*     array. If the current Frame has zero axes, this pointer will be
*     NULL.

*  Notes:
*     - The pointer returned by this function gives direct access to
*     data internal to the Frame object. It remains valid only so long
*     as the Frame exists. The permutation array contents may be
*     modified by other functions which operate on the Frame and this
*     may render the returned pointer invalid.
*     - A NULL pointer will be returned if this function is invoked
*     with the global error status set, or if it should fail for any
*     reason.
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to current Frame */
   AstRegion *this;              /* Pointer to Region structure */
   const int *result;            /* Result pointer value */

/* Check the global error status. */
   if ( !astOK ) return NULL;

/* Obtain a pointer to the Region structure. */
   this = (AstRegion *) this_frame;

/* Obtain a pointer to the Region's current Frame and then obtain a
   pointer to its axis permutation array. Annul the Frame pointer
   afterwards. */
   fr = astGetFrame( this->frameset, AST__CURRENT );
   result = astGetPerm( fr );
   fr = astAnnul( fr );

/* If an error occurred, clear the result value. */
   if ( !astOK ) result = NULL;

/* Return the result. */
   return result;
}

static AstFrame *GetRegionFrame( AstRegion *this, int *status ) {
/*
*++
*  Name:
c     astGetRegionFrame
f     AST_GETREGIONFRAME

*  Purpose:
*     Obtain a pointer to the encapsulated Frame within a Region.

*  Type:
*     Public virtual function.

*  Synopsis:
c     #include "region.h"
c     AstFrame *astGetRegionFrame( AstRegion *this )
f     RESULT = AST_GETREGIONFRAME( THIS, STATUS )

*  Class Membership:
*     Region method.

*  Description:
*     This function returns a pointer to the Frame represented by a
*     Region.

*  Parameters:
c     this
f     THIS = INTEGER (Given)
*        Pointer to the Region.
f     STATUS = INTEGER (Given and Returned)
f        The global status.

*  Returned Value:
c     astGetRegionFrame()
f     AST_GETREGIONFRAME = INTEGER
*        A pointer to a deep copy of the Frame represented by the Region.
*        Using this pointer to modify the Frame will have no effect on
*        the Region. To modify the Region, use the Region pointer directly.

*  Notes:
*     - A null Object pointer (AST__NULL) will be returned if this
c     function is invoked with the AST error status set, or if it
f     function is invoked with STATUS set to an error value, or if it
*     should fail for any reason.
*--
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to current Frame */
   AstFrame *result;             /* Pointer value to return */

/* Initialise. */
   result = NULL;

/* Check the global error status. */
   if ( !astOK ) return result;

/* Get a pointer to the current Frame of the encapsulated FrameSet. */
   fr = astGetFrame( this->frameset, AST__CURRENT );

/* Take a deep copy of it, and then annul the original pointer. */
   result = astCopy( fr );
   fr = astAnnul( fr );

/* If not OK, annul the returned pointer. */
   if( !astOK ) result = astAnnul( result );

/* Return the result. */
   return result;
}

static AstFrameSet *GetRegionFrameSet( AstRegion *this, int *status ) {
/*
*++
*  Name:
c     astGetRegionFrameSet
f     AST_GETREGIONFRAMESET

*  Purpose:
*     Obtain a pointer to the encapsulated FrameSet within a Region.

*  Type:
*     Public virtual function.

*  Synopsis:
c     #include "region.h"
c     AstFrame *astGetRegionFrameSet( AstRegion *this )
f     RESULT = AST_GETREGIONFRAMESET( THIS, STATUS )

*  Class Membership:
*     Region method.

*  Description:
*     This function returns a pointer to the FrameSet encapsulated by a
*     Region. The base Frame is the Frame in which the box was originally
*     defined, and the current Frame is the Frame into which the Region
*     is currently mapped (i.e. it will be the same as the Frame returned
c     by astGetRegionFrame).
f     by AST_GETREGIONFRAME).

*  Parameters:
c     this
f     THIS = INTEGER (Given)
*        Pointer to the Region.
f     STATUS = INTEGER (Given and Returned)
f        The global status.

*  Returned Value:
c     astGetRegionFrameSet()
f     AST_GETREGIONFRAMESET = INTEGER
*        A pointer to a deep copy of the FrameSet represented by the Region.
*        Using this pointer to modify the FrameSet will have no effect on
*        the Region.

*  Notes:
*     - A null Object pointer (AST__NULL) will be returned if this
c     function is invoked with the AST error status set, or if it
f     function is invoked with STATUS set to an error value, or if it
*     should fail for any reason.
*--
*/

/* Check the global error status. */
   if ( !astOK ) return NULL;

/* Return a deep copy of the encapsulated FrameSet. */
   return astCopy( this->frameset );
}

void astInitRegionVtab_(  AstRegionVtab *vtab, const char *name, int *status ) {
/*
*+
*  Name:
*     astInitRegionVtab

*  Purpose:
*     Initialise a virtual function table for a Region.

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     void astInitRegionVtab( AstRegionVtab *vtab, const char *name )

*  Class Membership:
*     Region vtab initialiser.

*  Description:
*     This function initialises the component of a virtual function
*     table which is used by the Region class.

*  Parameters:
*     vtab
*        Pointer to the virtual function table. The components used by
*        all ancestral classes will be initialised if they have not already
*        been initialised.
*     name
*        Pointer to a constant null-terminated character string which contains
*        the name of the class to which the virtual function table belongs (it
*        is this pointer value that will subsequently be returned by the Object
*        astClass function).
*-
*/

/* Local Variables: */
   astDECLARE_GLOBALS            /* Pointer to thread-specific global data */
   AstFrameVtab *frame;          /* Pointer to Frame component of Vtab */
   AstMappingVtab *mapping;      /* Pointer to Mapping component of Vtab */
   AstObjectVtab *object;        /* Pointer to Object component of Vtab */

/* Check the local error status. */
   if ( !astOK ) return;

/* Get a pointer to the thread specific global data structure. */
   astGET_GLOBALS(NULL);

/* Initialize the component of the virtual function table used by the
   parent class. */
   astInitFrameVtab( (AstFrameVtab *) vtab, name );

/* Store a unique "magic" value in the virtual function table. This
   will be used (by astIsARegion) to determine if an object belongs
   to this class.  We can conveniently use the address of the (static)
   class_check variable to generate this unique value. */
   vtab->id.check = &class_check;
   vtab->id.parent = &(((AstFrameVtab *) vtab)->id);

/* Initialise member function pointers. */
/* ------------------------------------ */

/* Store pointers to the member functions (implemented here) that
   provide virtual methods for this class. */
   vtab->ClearNegated = ClearNegated;
   vtab->GetNegated = GetNegated;
   vtab->SetNegated = SetNegated;
   vtab->TestNegated = TestNegated;

   vtab->ClearRegionFS = ClearRegionFS;
   vtab->GetRegionFS = GetRegionFS;
   vtab->SetRegionFS = SetRegionFS;
   vtab->TestRegionFS = TestRegionFS;

   vtab->ClearClosed = ClearClosed;
   vtab->GetClosed = GetClosed;
   vtab->SetClosed = SetClosed;
   vtab->TestClosed = TestClosed;

   vtab->ClearMeshSize = ClearMeshSize;
   vtab->GetMeshSize = GetMeshSize;
   vtab->SetMeshSize = SetMeshSize;
   vtab->TestMeshSize = TestMeshSize;

   vtab->ClearAdaptive = ClearAdaptive;
   vtab->GetAdaptive = GetAdaptive;
   vtab->SetAdaptive = SetAdaptive;
   vtab->TestAdaptive = TestAdaptive;

   vtab->ClearFillFactor = ClearFillFactor;
   vtab->GetFillFactor = GetFillFactor;
   vtab->SetFillFactor = SetFillFactor;
   vtab->TestFillFactor = TestFillFactor;

   vtab->ResetCache = ResetCache;
   vtab->RegTrace = RegTrace;
   vtab->GetBounded = GetBounded;
   vtab->TestUnc = TestUnc;
   vtab->ClearUnc = ClearUnc;
   vtab->GetRegionFrame = GetRegionFrame;
   vtab->GetRegionFrameSet = GetRegionFrameSet;
   vtab->MapRegion = MapRegion;
   vtab->Overlap = Overlap;
   vtab->OverlapX = OverlapX;
   vtab->Negate = Negate;
   vtab->BndMesh = BndMesh;
   vtab->BndBaseMesh = BndBaseMesh;
   vtab->RegBaseGrid = RegBaseGrid;
   vtab->RegBaseMesh = RegBaseMesh;
   vtab->RegSplit = RegSplit;
   vtab->RegBaseBox = RegBaseBox;
   vtab->RegBaseBox2 = RegBaseBox2;
   vtab->RegBasePick = RegBasePick;
   vtab->RegCentre = RegCentre;
   vtab->RegGrid = RegGrid;
   vtab->RegMesh = RegMesh;
   vtab->RegClearAttrib = RegClearAttrib;
   vtab->RegSetAttrib = RegSetAttrib;
   vtab->GetDefUnc = GetDefUnc;
   vtab->GetNegation = GetNegation;
   vtab->GetUncFrm = GetUncFrm;
   vtab->SetUnc = SetUnc;
   vtab->GetUnc = GetUnc;
   vtab->ShowMesh = ShowMesh;
   vtab->GetRegionBounds = GetRegionBounds;
   vtab->GetRegionBounds2 = GetRegionBounds2;
   vtab->GetRegionMesh = GetRegionMesh;
   vtab->GetRegionPoints = GetRegionPoints;
   vtab->GetRegionDisc = GetRegionDisc;
   vtab->RegOverlay = RegOverlay;
   vtab->RegFrame = RegFrame;
   vtab->RegDummyFS = RegDummyFS;
   vtab->RegMapping = RegMapping;
   vtab->RegPins = RegPins;
   vtab->RegTransform = RegTransform;
   vtab->BTransform = BTransform;
   vtab->GetRegFS = GetRegFS;
   vtab->SetRegFS = SetRegFS;
   vtab->MaskB = MaskB;
   vtab->MaskD = MaskD;
   vtab->MaskF = MaskF;
   vtab->MaskI = MaskI;
   vtab->MaskL = MaskL;
   vtab->MaskS = MaskS;
   vtab->MaskUB = MaskUB;
   vtab->MaskUI = MaskUI;
   vtab->MaskUL = MaskUL;
   vtab->MaskUS = MaskUS;
#if HAVE_LONG_DOUBLE     /* Not normally implemented */
   vtab->MaskLD = MaskLD;
#endif

/* Save the inherited pointers to methods that will be extended, and store
   replacement pointers for methods which will be over-ridden by new member
   functions implemented here. */
   object = (AstObjectVtab *) vtab;
   mapping = (AstMappingVtab *) vtab;
   frame = (AstFrameVtab *) vtab;

   parent_getobjsize = object->GetObjSize;
   object->GetObjSize = GetObjSize;

   parent_getusedefs = object->GetUseDefs;
   object->GetUseDefs = GetUseDefs;

#if defined(THREAD_SAFE)
   parent_managelock = object->ManageLock;
   object->ManageLock = ManageLock;
#endif

   object->Cast = Cast;
   object->Equal = Equal;
   object->ClearAttrib = ClearAttrib;
   object->GetAttrib = GetAttrib;
   object->SetAttrib = SetAttrib;
   object->TestAttrib = TestAttrib;

   mapping->ReportPoints = ReportPoints;
   mapping->RemoveRegions = RemoveRegions;
   mapping->Simplify = Simplify;

   frame->Abbrev = Abbrev;
   frame->Angle = Angle;
   frame->AxAngle = AxAngle;
   frame->AxDistance = AxDistance;
   frame->AxNorm = AxNorm;
   frame->AxOffset = AxOffset;
   frame->CheckPerm = CheckPerm;
   frame->ClearDigits = ClearDigits;
   frame->ClearDirection = ClearDirection;
   frame->ClearDomain = ClearDomain;
   frame->ClearFormat = ClearFormat;
   frame->ClearLabel = ClearLabel;
   frame->ClearMatchEnd = ClearMatchEnd;
   frame->ClearMaxAxes = ClearMaxAxes;
   frame->ClearMinAxes = ClearMinAxes;
   frame->ClearPermute = ClearPermute;
   frame->ClearPreserveAxes = ClearPreserveAxes;
   frame->ClearSymbol = ClearSymbol;
   frame->ClearTitle = ClearTitle;
   frame->ClearUnit = ClearUnit;
   frame->Convert = Convert;
   frame->ConvertX = ConvertX;
   frame->Distance = Distance;
   frame->FindFrame = FindFrame;
   frame->Format = Format;
   frame->Centre = Centre;
   frame->Gap = Gap;
   frame->GetAxis = GetAxis;
   frame->GetDigits = GetDigits;
   frame->GetDirection = GetDirection;
   frame->GetDomain = GetDomain;
   frame->GetFormat = GetFormat;
   frame->GetLabel = GetLabel;
   frame->GetMatchEnd = GetMatchEnd;
   frame->GetMaxAxes = GetMaxAxes;
   frame->GetMinAxes = GetMinAxes;
   frame->GetNaxes = GetNaxes;
   frame->GetPerm = GetPerm;
   frame->GetPermute = GetPermute;
   frame->GetPreserveAxes = GetPreserveAxes;
   frame->GetSymbol = GetSymbol;
   frame->GetTitle = GetTitle;
   frame->GetUnit = GetUnit;
   frame->Intersect = Intersect;
   frame->IsUnitFrame = IsUnitFrame;
   frame->Match = Match;
   frame->Norm = Norm;
   frame->NormBox = NormBox;
   frame->Offset = Offset;
   frame->Offset2 = Offset2;
   frame->Overlay = Overlay;
   frame->PermAxes = PermAxes;
   frame->PickAxes = PickAxes;
   frame->Resolve = Resolve;
   frame->ResolvePoints = ResolvePoints;
   frame->SetAxis = SetAxis;
   frame->SetDigits = SetDigits;
   frame->SetDirection = SetDirection;
   frame->SetDomain = SetDomain;
   frame->SetFormat = SetFormat;
   frame->SetLabel = SetLabel;
   frame->SetMatchEnd = SetMatchEnd;
   frame->SetMaxAxes = SetMaxAxes;
   frame->SetMinAxes = SetMinAxes;
   frame->SetPermute = SetPermute;
   frame->SetPreserveAxes = SetPreserveAxes;
   frame->SetSymbol = SetSymbol;
   frame->SetTitle = SetTitle;
   frame->SetUnit = SetUnit;
   frame->SubFrame = SubFrame;
   frame->SystemCode = SystemCode;
   frame->SystemString = SystemString;
   frame->TestDigits = TestDigits;
   frame->TestDirection = TestDirection;
   frame->TestDomain = TestDomain;
   frame->TestFormat = TestFormat;
   frame->TestLabel = TestLabel;
   frame->TestMatchEnd = TestMatchEnd;
   frame->TestMaxAxes = TestMaxAxes;
   frame->TestMinAxes = TestMinAxes;
   frame->TestPermute = TestPermute;
   frame->TestPreserveAxes = TestPreserveAxes;
   frame->TestSymbol = TestSymbol;
   frame->TestTitle = TestTitle;
   frame->TestUnit = TestUnit;
   frame->Unformat = Unformat;
   frame->ValidateAxis = ValidateAxis;
   frame->ValidateAxisSelection = ValidateAxisSelection;
   frame->ValidateSystem = ValidateSystem;
   frame->LineDef = LineDef;
   frame->LineContains = LineContains;
   frame->LineCrossing = LineCrossing;
   frame->LineOffset = LineOffset;
   frame->MatchAxes = MatchAxes;
   frame->MatchAxesX = MatchAxesX;

   frame->GetActiveUnit = GetActiveUnit;
   frame->SetActiveUnit = SetActiveUnit;
   frame->TestActiveUnit = TestActiveUnit;

   frame->GetTop = GetTop;
   frame->SetTop = SetTop;
   frame->TestTop = TestTop;
   frame->ClearTop = ClearTop;

   frame->GetBottom = GetBottom;
   frame->SetBottom = SetBottom;
   frame->TestBottom = TestBottom;
   frame->ClearBottom = ClearBottom;

   frame->GetEpoch = GetEpoch;
   frame->SetEpoch = SetEpoch;
   frame->TestEpoch = TestEpoch;
   frame->ClearEpoch = ClearEpoch;

   frame->ClearObsAlt = ClearObsAlt;
   frame->TestObsAlt = TestObsAlt;
   frame->GetObsAlt = GetObsAlt;
   frame->SetObsAlt = SetObsAlt;

   frame->ClearObsLat = ClearObsLat;
   frame->TestObsLat = TestObsLat;
   frame->GetObsLat = GetObsLat;
   frame->SetObsLat = SetObsLat;

   frame->ClearObsLon = ClearObsLon;
   frame->TestObsLon = TestObsLon;
   frame->GetObsLon = GetObsLon;
   frame->SetObsLon = SetObsLon;

   frame->GetSystem = GetSystem;
   frame->SetSystem = SetSystem;
   frame->TestSystem = TestSystem;
   frame->ClearSystem = ClearSystem;

   frame->GetAlignSystem = GetAlignSystem;
   frame->SetAlignSystem = SetAlignSystem;
   frame->TestAlignSystem = TestAlignSystem;
   frame->ClearAlignSystem = ClearAlignSystem;

/* Declare the copy constructor, destructor and class dump
   functions. */
   astSetDelete( vtab, Delete );
   astSetCopy( vtab, Copy );
   astSetDump( vtab, Dump, "Region",
               "An area within a coordinate system" );

/* If we have just initialised the vtab for the current class, indicate
   that the vtab is now initialised, and store a pointer to the class
   identifier in the base "object" level of the vtab. */
   if( vtab == &class_vtab ) {
      class_init = 1;
      astSetVtabClassIdentifier( vtab, &(vtab->id) );
   }
}

static void Intersect( AstFrame *this_frame, const double a1[2],
                       const double a2[2], const double b1[2],
                       const double b2[2], double cross[2],
                       int *status ) {
/*
*  Name:
*     Intersect

*  Purpose:
*     Find the point of intersection between two geodesic curves.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     void Intersect( AstFrame *this_frame, const double a1[2],
*                      const double a2[2], const double b1[2],
*                      const double b2[2], double cross[2],
*                      int *status )

*  Class Membership:
*     Region member function (over-rides the astIntersect method
*     inherited from the Frame class).

*  Description:
*     This function finds the coordinate values at the point of
*     intersection between two geodesic curves. Each curve is specified
*     by two points on the curve.

*  Parameters:
*     this
*        Pointer to the SkyFrame.
*     a1
*        An array of double, with one element for each Frame axis.
*        This should contain the coordinates of a point on the first
*        geodesic curve.
*     a2
*        An array of double, with one element for each Frame axis.
*        This should contain the coordinates of a second point on the
*        first geodesic curve.
*     b1
*        An array of double, with one element for each Frame axis.
*        This should contain the coordinates of a point on the second
*        geodesic curve.
*     b2
*        An array of double, with one element for each Frame axis.
*        This should contain the coordinates of a second point on
*        the second geodesic curve.
*     cross
*        An array of double, with one element for each Frame axis
*        in which the coordinates of the required intersection
*        point will be returned. These will be AST__BAD if the curves do
*        not intersect.
*     status
*        Pointer to the inherited status variable.

*  Notes:
*     - The geodesic curve used by this function is the path of
*     shortest distance between two points, as defined by the
*     astDistance function.
*     - This function will return "bad" coordinate values (AST__BAD)
*     if any of the input coordinates has this value.
*     - For SkyFrames each curve will be a great circle, and in general
*     each pair of curves will intersect at two diametrically opposite
*     points on the sky. The returned position is the one which is
*     closest to point "a1".
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to current Frame */
   AstRegion *this;              /* Pointer to the Region structure */

/* Check the global error status. */
   if ( !astOK ) return;

/* Obtain a pointer to the FrameSet structure. */
   this = (AstRegion *) this_frame;

/* Obtain a pointer to the Region's encapsulated Frame and invoke the
   astIntersect method for this Frame. Annul the Frame pointer
   afterwards. */
   fr = astGetFrame( this->frameset, AST__CURRENT );
   astIntersect( fr, a1, a2, b1, b2, cross );
   fr = astAnnul( fr );
}

static int IsUnitFrame( AstFrame *this, int *status ){
/*
*  Name:
*     IsUnitFrame

*  Purpose:
*     Is this Frame equivalent to a UnitMap?

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     int IsUnitFrame( AstFrame *this, int *status )

*  Class Membership:
*     Region member function (over-rides the protected astIsUnitFrame
*     method inherited from the Frame class).

*  Description:
*     This function returns a flag indicating if the supplied Frame is
*     equivalent to a UnitMap when treated as a Mapping (note, the Frame
*     class inherits from Mapping and therefore every Frame is also a Mapping).

*  Parameters:
*     this
*        Pointer to the Frame.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     A non-zero value is returned if the supplied Frame is equivalent to
*     a UnitMap when treated as a Mapping.

*-
*/

/* Check the global error status. */
   if( !astOK ) return 0;

/* The Region class is never equivalent to a UnitMap. */
   return 0;
}

static int LineContains( AstFrame *this_frame, AstLineDef *l, int def, double *point, int *status ) {
/*
*  Name:
*     LineContains

*  Purpose:
*     Determine if a line contains a point.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     int LineContains( AstFrame *this, AstLineDef *l, int def, double *point, int *status )

*  Class Membership:
*     Region member function (over-rides the protected astLineContains
*     method inherited from the Frame class).

*  Description:
*     This function determines if the supplied point is on the supplied
*     line within the supplied Frame. The start point of the line is
*     considered to be within the line, but the end point is not. The tests
*     are that the point of closest approach of the line to the point should
*     be between the start and end, and that the distance from the point to
*     the point of closest aproach should be less than 1.0E-7 of the length
*     of the line.

*  Parameters:
*     this
*        Pointer to the Frame.
*     l
*        Pointer to the structure defining the line.
*     def
*        Should be set non-zero if the "point" array was created by a
*        call to astLineCrossing (in which case it may contain extra
*        information following the axis values),and zero otherwise.
*     point
*        Point to an array containing the axis values of the point to be
*        tested, possibly followed by extra cached information (see "def").
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     A non-zero value is returned if the line contains the point.

*  Notes:
*     - The pointer supplied for "l" should have been created using the
*     astLineDef method. These structures contained cached information about
*     the lines which improve the efficiency of this method when many
*     repeated calls are made. An error will be reported if the structure
*     does not refer to the Frame specified by "this".
*     - Zero will be returned if this function is invoked with the global
*     error status set, or if it should fail for any reason.
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to current Frame */
   int result;                   /* Returned value */

/* Initialise */
   result =0;

/* Obtain a pointer to the Region's current Frame and then invoke the
   method. Annul the Frame pointer afterwards. */
   fr = astGetFrame( ((AstRegion *) this_frame)->frameset, AST__CURRENT );
   result = astLineContains( fr, l, def, point );
   fr = astAnnul( fr );

/* Return the result. */
   return result;
}

static int LineCrossing( AstFrame *this_frame, AstLineDef *l1, AstLineDef *l2,
                         double **cross, int *status ) {
/*
*  Name:
*     LineCrossing

*  Purpose:
*     Determine if two lines cross.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     int LineCrossing( AstFrame *this, AstLineDef *l1, AstLineDef *l2,
*                       double **cross, int *status )

*  Class Membership:
*     Region member function (over-rides the protected astLineCrossing
*     method inherited from the Frame class).

*  Description:
*     This function determines if the two suplied line segments cross,
*     and if so returns the axis values at the point where they cross.
*     A flag is also returned indicating if the crossing point occurs
*     within the length of both line segments, or outside one or both of
*     the line segments.

*  Parameters:
*     this
*        Pointer to the Frame.
*     l1
*        Pointer to the structure defining the first line.
*     l2
*        Pointer to the structure defining the second line.
*     cross
*        Pointer to a location at which to put a pointer to a dynamically
*        alocated array containing the axis values at the crossing. If
*        NULL is supplied no such array is returned. Otherwise, the returned
*        array should be freed using astFree when no longer needed. If the
*        lines are parallel (i.e. do not cross) then AST__BAD is returned for
*        all axis values. Note usable axis values are returned even if the
*        lines cross outside the segment defined by the start and end points
*        of the lines. The order of axes in the returned array will take
*        account of the current axis permutation array if appropriate. Note,
*        sub-classes such as SkyFrame may append extra values to the end
*        of the basic frame axis values. A NULL pointer is returned if an
*        error occurs.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     A non-zero value is returned if the lines cross at a point which is
*     within the [start,end) segment of both lines. If the crossing point
*     is outside this segment on either line, or if the lines are parallel,
*     zero is returned. Note, the start point is considered to be inside
*     the length of the segment, but the end point is outside.

*  Notes:
*     - The pointers supplied for "l1" and "l2" should have been created
*     using the astLineDef method. These structures contained cached
*     information about the lines which improve the efficiency of this method
*     when many repeated calls are made. An error will be reported if
*     either structure does not refer to the Frame specified by "this".
*     - Zero will be returned if this function is invoked with the global
*     error status set, or if it should fail for any reason.
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to current Frame */
   int result;                   /* Returned value */

/* Initialise */
   result =0;

/* Obtain a pointer to the Region's current Frame and then invoke the
   method. Annul the Frame pointer afterwards. */
   fr = astGetFrame( ((AstRegion *) this_frame)->frameset, AST__CURRENT );
   result = astLineCrossing( fr, l1, l2, cross );
   fr = astAnnul( fr );

/* Return the result. */
   return result;
}

static AstLineDef *LineDef( AstFrame *this_frame, const double start[2],
                            const double end[2], int *status ) {
/*
*  Name:
*     LineDef

*  Purpose:
*     Creates a structure describing a line segment in a 2D Frame.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     AstLineDef *LineDef( AstFrame *this, const double start[2],
*                             const double end[2], int *status )

*  Class Membership:
*     Region member function (over-rides the protected astLineDef
*     method inherited from the Frame class).

*  Description:
*     This function creates a structure containing information describing a
*     given line segment within the supplied 2D Frame. This may include
*     information which allows other methods such as astLineCrossing to
*     function more efficiently. Thus the returned structure acts as a
*     cache to store intermediate values used by these other methods.

*  Parameters:
*     this
*        Pointer to the Frame. Must have 2 axes.
*     start
*        An array of 2 doubles marking the start of the line segment.
*     end
*        An array of 2 doubles marking the end of the line segment.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     Pointer to the memory structure containing the description of the
*     line. This structure should be freed using astFree when no longer
*     needed. A NULL pointer is returned (without error) if any of the
*     supplied axis values are AST__BAD.

*  Notes:
*     - A null pointer will be returned if this function is invoked
*     with the global error status set, or if it should fail for any
*     reason.
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to current Frame */
   AstLineDef *result;           /* Returned value */

/* Initialise */
   result = NULL;

/* Obtain a pointer to the Region's current Frame and then invoke the
   method. Annul the Frame pointer afterwards. */
   fr = astGetFrame( ((AstRegion *) this_frame)->frameset, AST__CURRENT );
   result = astLineDef( fr, start, end );
   fr = astAnnul( fr );

/* Return the result. */
   return result;
}

static void LineOffset( AstFrame *this_frame, AstLineDef *line, double par,
                        double prp, double point[2], int *status ){
/*
*  Name:
*     LineOffset

*  Purpose:
*     Find a position close to a line.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     void LineOffset( AstFrame *this, AstLineDef *line, double par,
*                      double prp, double point[2], int *status )

*  Class Membership:
*     Region member function (over-rides the protected astLineOffset
*     method inherited from the Frame class).

*  Description:
*     This function returns a position formed by moving a given distance along
*     the supplied line, and then a given distance away from the supplied line.

*  Parameters:
*     this
*        Pointer to the Frame.
*     line
*        Pointer to the structure defining the line.
*     par
*        The distance to move along the line from the start towards the end.
*     prp
*        The distance to move at right angles to the line. Positive
*        values result in movement to the left of the line, as seen from
*        the observer, when moving from start towards the end.
*     status
*        Pointer to the inherited status variable.

*  Notes:
*     - The pointer supplied for "line" should have been created using the
*     astLineDef method. This structure contains cached information about the
*     line which improves the efficiency of this method when many repeated
*     calls are made. An error will be reported if the structure does not
*     refer to the Frame specified by "this".
*/


/* Local Variables: */
   AstFrame *fr;                 /* Pointer to current Frame */

/* Obtain a pointer to the Region's current Frame and then invoke the
   method. Annul the Frame pointer afterwards. */
   fr = astGetFrame( ((AstRegion *) this_frame)->frameset, AST__CURRENT );
   astLineOffset( fr, line, par, prp, point );
   fr = astAnnul( fr );
}


#if defined(THREAD_SAFE)
static int ManageLock( AstObject *this_object, int mode, int extra,
                       AstObject **fail, int *status ) {
/*
*  Name:
*     ManageLock

*  Purpose:
*     Manage the thread lock on an Object.

*  Type:
*     Private function.

*  Synopsis:
*     #include "object.h"
*     AstObject *ManageLock( AstObject *this, int mode, int extra,
*                            AstObject **fail, int *status )

*  Class Membership:
*     Region member function (over-rides the astManageLock protected
*     method inherited from the parent class).

*  Description:
*     This function manages the thread lock on the supplied Object. The
*     lock can be locked, unlocked or checked by this function as
*     deteremined by parameter "mode". See astLock for details of the way
*     these locks are used.

*  Parameters:
*     this
*        Pointer to the Object.
*     mode
*        An integer flag indicating what the function should do:
*
*        AST__LOCK: Lock the Object for exclusive use by the calling
*        thread. The "extra" value indicates what should be done if the
*        Object is already locked (wait or report an error - see astLock).
*
*        AST__UNLOCK: Unlock the Object for use by other threads.
*
*        AST__CHECKLOCK: Check that the object is locked for use by the
*        calling thread (report an error if not).
*     extra
*        Extra mode-specific information.
*     fail
*        If a non-zero function value is returned, a pointer to the
*        Object that caused the failure is returned at "*fail". This may
*        be "this" or it may be an Object contained within "this". Note,
*        the Object's reference count is not incremented, and so the
*        returned pointer should not be annulled. A NULL pointer is
*        returned if this function returns a value of zero.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*    A local status value:
*        0 - Success
*        1 - Could not lock or unlock the object because it was already
*            locked by another thread.
*        2 - Failed to lock a POSIX mutex
*        3 - Failed to unlock a POSIX mutex
*        4 - Bad "mode" value supplied.

*  Notes:
*     - This function attempts to execute even if an error has already
*     occurred.
*/

/* Local Variables: */
   AstRegion *this;       /* Pointer to Region structure */
   int result;            /* Returned status value */

/* Initialise */
   result = 0;

/* Check the supplied pointer is not NULL. */
   if( !this_object ) return result;

/* Obtain a pointers to the Region structure. */
   this = (AstRegion *) this_object;

/* Invoke the ManageLock method inherited from the parent class. */
   if( !result ) result = (*parent_managelock)( this_object, mode, extra,
                                                fail, status );

/* Invoke the astManageLock method on any Objects contained within
   the supplied Object. */
   if( !result ) result = astManageLock( this->frameset, mode, extra, fail );
   if( !result ) result = astManageLock( this->points, mode, extra, fail );
   if( !result ) result = astManageLock( this->unc, mode, extra, fail );
   if( !result ) result = astManageLock( this->negation, mode, extra, fail );
   if( !result ) result = astManageLock( this->defunc, mode, extra, fail );
   if( !result ) result = astManageLock( this->basemesh, mode, extra, fail );
   if( !result ) result = astManageLock( this->basegrid, mode, extra, fail );

   return result;

}
#endif

static AstRegion *MapRegion( AstRegion *this, AstMapping *map0,
                             AstFrame *frame0, int *status ) {
/*
*+
*  Name:
*     astMapRegion

*  Purpose:
*     Transform a Region into a new Frame using a given Mapping.

*  Type:
*     Protected virtual function.

*  Synopsis:
*     #include "region.h"
*     AstRegion *astMapRegion( AstRegion *this, AstMapping *map,
*                              AstFrame *frame )

*  Class Membership:
*     Region method.

*  Description:
*     This function returns a pointer to a new Region which corresponds to
*     supplied Region in some other specified coordinate system. A
*     Mapping is supplied which transforms positions between the old and new
*     coordinate systems. The new Region may not be of the same class as
*     the original region.

*  Parameters:
*     this
*        Pointer to the Region.
*     map
*        Pointer to a Mapping which transforms positions from the
*        coordinate system represented by the supplied Region to the
*        coordinate system specified by "frame". The supplied Mapping should
*        define both forward and inverse transformations, and these
*        transformations should form a genuine inverse pair. That is,
*        transforming a position using the forward transformation and then
*        using the inverse transformation should produce the original input
*        position. Some Mapping classes (such as PermMap, MathMap, SphMap)
*        can result in Mappings for which this is not true.
*     frame
*        Pointer to a Frame describing the coordinate system in which
*        the new Region is required.

*  Returned Value:
*     astMapRegion()
*        A pointer to a new Region. This Region will represent the area
*        within the coordinate system specified by "frame" which corresponds
*        to the supplied Region.

*  Notes:
*     - This is the protected implementation of this function - it does
*     not simplify the returned Region. The public implementation is
*     astMapRegionID, which simplifies the returned Region.
*     - A null Object pointer (AST__NULL) will be returned if this
*     function is invoked with the AST error status set, or if it
*     should fail for any reason.
*-
*/

/* Local Variables: */
   AstFrame *frame;
   AstFrameSet *fs;
   AstMapping *tmap;
   AstMapping *usemap;
   AstMapping *map;
   AstPointSet *ps1;
   AstPointSet *pst;
   AstPointSet *ps2;
   AstRegion *usethis;
   AstRegion *result;
   double **ptr1;
   double **ptr2;
   int *axflags;
   int *inax;
   int *keep;
   int *outax;
   int i;
   int icurr;
   int j;
   int nax1;
   int nkept;
   int nnew;
   int nold;
   int np;
   int ntotal;
   int ok;

/* Initialise returned value. */
   result = NULL;

/* Check the global error status. */
   if ( !astOK ) return result;

/* Initialise local variables */
   axflags = NULL;

/* If a FrameSet was supplied for the Mapping, use the base->current
   Mapping */
   if( astIsAFrameSet( map0 ) ) {
      map = astGetMapping( (AstFrameSet *) map0, AST__BASE, AST__CURRENT );
   } else {
      map = astClone( map0 );
   }

/* If a FrameSet was supplied for the Frame, use the current Frame. */
   if( astIsAFrameSet( frame0 ) ) {
      frame = astGetFrame( (AstFrameSet *) frame0, AST__CURRENT );
   } else {
      frame = astClone( frame0 );
   }

/* First check the Mapping is suitable. It must defined both a forward
   and an inverse Mapping. */
   if( !astGetTranInverse( map ) ) {
      astError( AST__NODEF, "astMapRegion(%s): The supplied %s does not "
                "define an inverse transformation.", status, astGetClass( this ),
                astGetClass( map ) );
   } else if( !astGetTranForward( map ) ) {
      astError( AST__NODEF, "astMapRegion(%s): The supplied %s does not "
                "define a forward transformation.", status, astGetClass( this ),
                astGetClass( map ) );
   }


/* Get the number of axes in the supplied Region. */
   nold = astGetNaxes( this );

/* Get the number of axes in the returned Region. */
   nnew = astGetNaxes( frame );

/* The forward transformation must not introduce any bad axis values. We
   can only perform this test reliably if the supplied Region has no bad
   axis values. */
   ps1 = this->points;
   if( ps1 ) {
      nax1 = astGetNcoord( ps1 );
      np = astGetNpoint( ps1 );
      ptr1 = astGetPoints( ps1 );
      if( ptr1 ) {

/* Check the axis values defining the Region are good. */
         ok = 1;
         for( i = 0; i < nax1 && ok; i++ ){
            for( j = 0; j < np; j++ ) {
               if( ptr1[ i ][ j ] == AST__BAD ){
                  ok = 0;
                  break;
               }
            }
         }
         if( ok ) {

/* Transform the points defining the supplied Region into the current Frame
   of the Region. */
            pst = astRegTransform( this, ps1, 1, NULL, NULL );

/* The use the supplied Mapping to transfom them into the new Frame. */
            ps2 = astTransform( map, pst, 1, NULL );

/* Test if any of these axis values are bad. */
            ptr2 = astGetPoints( ps2 );
            if( ptr2 ) {
               for( i = 0; i < nnew && ok; i++ ){
                  for( j = 0; j < np; j++ ) {
                     if( ptr2[ i ][ j ] == AST__BAD ){
                        ok = 0;
                        break;
                     }
                  }
               }
               if( !ok ) {
                  astError( AST__NODEF, "astMapRegion(%s): The region which "
                            "results from using the supplied %s to transform "
                            "the supplied %s is undefined.", status, astGetClass( this ),
                            astGetClass( map ), astGetClass( this ) );

/* If all axis values are good, use the inverse transformation of the
   supplied Mapping to transform them back to the Frame of the supplied
   Region. */
               } else {
                  pst = astAnnul( pst );
                  pst = astTransform( map, ps2, 0, NULL );

/* Get a flag for each input of the supplied Mapping (i.e. each axis of
   the supplied Region) which is non-zero if the inverse transformation
   of the Mapping has produced any good axis values. */
                  ptr1 = astGetPoints( pst );
                  axflags = astCalloc( nold, sizeof(int) );
                  if( astOK ) {
                     for( i = 0; i < nold; i++ ){
                        for( j = 0; j < np; j++ ) {
                           if( ptr1[ i ][ j ] != AST__BAD ){
                              axflags[ i ] = 1;
                              break;
                           }
                        }
                     }
                  }
               }
            }
            ps2 = astAnnul( ps2 );
            pst = astAnnul( pst );
         }
      }
   }

/* Assume we will be using the supplied Region (this) and Mapping (map). */
   usethis = astClone( this );
   usemap = astClone( map );

/* If the new Frame for the Region has fewer axes than the old Frame, see
   if we can discard some base-frame axes. We only do this if the inverse
   transformation would otherwise supply bad values for the unused axes.
   Using bad axis values is not a good idea as some operations cannot be
   performed if any bad values are supplied. Also having more axes than
   needed is bad as it results in fewer mesh points per axis. */
   if( nnew < nold ) {

/* First invert the Mapping since astMapSplit only allows selection of
   inputs, and we want to select outputs. */
      astInvert( map );

/* Create an array holding the indices of the required inputs. */
      inax = astMalloc( nnew*sizeof(int) );
      if( astOK ) for( i = 0; i < nnew; i++ ) inax[i] = i;

/* Attempt to split the mapping to extract a new mapping that omits any
   unnecessary outputs (i.e. outputs that are indepenent of the selected
   inputs). Check the Mapping was split successfully. */
      outax = astMapSplit( map, nnew, inax, &tmap );
      if( outax ) {

/* Get the number of old axes that have been retained in the Mapping. */
         nkept = astGetNout( tmap );

/* Now we need to ensure that any unused axes for which the Mapping
   creates non-bad values are retained (such values are significant
   since they may determine whether the new Region is null or not).
   We only need to do this if any of the outputs that were split off
   above have been found to generate good values, as indicated by the
   "axflags" array. Count the number of extra axes that need to be kept,
   over and above those that are kept by the Mapping returned by
   astMapSplit above. */
         ntotal = 0;
         keep = NULL;
         if( axflags ) {
            keep = astMalloc( nold*sizeof(int) );
            if( astOK ) {

/* Loop round each axis in the supplied Region. */
               for( i = 0; i < nold; i++ ) {

/* Search the "outax" array to see if this axis was retained by astMapSplit.
   If it was, append its index to the total list of axes to keep. */
                  ok = 0;
                  for( j = 0; j < nkept; j++ ) {
                     if( outax[ j ] == i ) {
                        keep[ ntotal++ ] = i;
                        ok = 1;
                        break;
                     }
                  }

/* If the axis was not retained by astMapSplit, but generates good axis
   values, also append its index to the total list of axes to keep. */
                  if( !ok && axflags[ i ] ) {
                     keep[ ntotal++ ] = i;
                  }
               }
            }
         }

/* If there are no extra axes to keep, then the Mapping returned by
   astMapSplit above can be used as it is. */
         if( ntotal == nkept ) {

/* The values in the "outax" array will hold the zero-based indices of
   the original old axes that are retained by the new Mapping. We need to
   create a copy of the supplied Region that includes only these axes. */
            usethis = astAnnul( usethis );
            usethis = astPickAxes( this, nkept, outax, NULL );

/* Use the temportary Mapping returned by astMapSplit in place of the
   supplied Mapping (remember to invert to undo the inversion performed
   above). */
            usemap = astAnnul( usemap );
            usemap = astClone( tmap );
            astInvert( usemap );

/* Free temporary resources. */
            tmap = astAnnul( tmap );
            outax = astFree( outax );

/* If we need to retain some extra axes because they generate good values
   (even though they are independent of the new Frame axes)... */
         } else if( ntotal > nkept ){

/* We know the old Frame axes that we want to keep, so use astMapSplit
   in the opposite direction - i.e. use it on the Mapping form old to
   new.  */
            astInvert( map );

            tmap = astAnnul( tmap );
            outax = astFree( outax );

            outax = astMapSplit( map, ntotal, keep, &tmap );
            if( outax ) {
               usethis = astAnnul( usethis );
               usethis = astPickAxes( this, ntotal, keep, NULL );

               usemap = astAnnul( usemap );
               usemap = astClone( tmap );
            }

            astInvert( map );
         }
         keep = astFree( keep );
         outax = astFree( outax );
         tmap = astAnnul( tmap );
      }
      inax = astFree( inax );

/* Invert the Mapping again to bring it back to its original state. */
      astInvert( map );
   }

/* Take a deep copy of the supplied Region. */
   result = astCopy( usethis );

/* Get a pointer to the encapsulated FrameSet. */
   if( astOK ) {
      fs = result->frameset;

/* Add in the new Frame and Mapping. First note the index of the original
   current Frame. */
      icurr = astGetCurrent( fs );
      astAddFrame( fs, AST__CURRENT, usemap, frame );

/* Remove the original current Frame. */
      astRemoveFrame( fs, icurr );

/* The base and current Frames of the resulting FrameSet are now (in
   general) different and so the Region should include its FrameSet in any
   Dump. */
      astSetRegionFS( result, 1 );
   }

/* Since the Mapping has been changed, any cached information calculated
   on the basis of the Mapping properties may no longer be up to date. */
   astResetCache( result );

/* Free resources */
   usemap = astAnnul( usemap );
   usethis = astAnnul( usethis );
   map = astAnnul( map );
   frame = astAnnul( frame );
   axflags = astFree( axflags );

/* If not OK, annul the returned pointer. */
   if( !astOK ) result = astAnnul( result );

/* Return the result. */
   return result;
}

/*
*++
*  Name:
c     astMask<X>
f     AST_MASK<X>

*  Purpose:
*     Mask a region of a data grid.

*  Type:
*     Public virtual function.

*  Synopsis:
c     #include "region.h"
c     int astMask<X>( AstRegion *this, AstMapping *map, int inside, int ndim,
c                     const int lbnd[], const int ubnd[], <Xtype> in[],
c                     <Xtype> val )
f     RESULT = AST_MASK<X>( THIS, MAP, INSIDE, NDIM, LBND, UBND, IN, VAL,
f                           STATUS )

*  Class Membership:
*     Mapping method.

*  Description:
*     This is a set of functions for masking out regions within gridded data
*     (e.g. an image). The functions modifies a given data grid by
*     assigning a specified value to all samples which are inside (or outside
c     if "inside" is zero)
f     if INSIDE is .FALSE.)
*     the specified Region.
*
*     You should use a masking function which matches the numerical
*     type of the data you are processing by replacing <X> in
c     the generic function name astMask<X> by an appropriate 1- or
f     the generic function name AST_MASK<X> by an appropriate 1- or
*     2-character type code. For example, if you are masking data
c     with type "float", you should use the function astMaskF (see
f     with type REAL, you should use the function AST_MASKR (see
*     the "Data Type Codes" section below for the codes appropriate to
*     other numerical types).

*  Parameters:
c     this
f     THIS = INTEGER (Given)
*        Pointer to a Region.
c     map
f     MAP = INTEGER (Given)
*        Pointer to a Mapping. The forward transformation should map
*        positions in the coordinate system of the supplied Region
*        into pixel coordinates as defined by the
c        "lbnd" and "ubnd" parameters. A NULL pointer
f        LBND and UBND arguments. A value of AST__NULL
*        can be supplied if the coordinate system of the supplied Region
*        corresponds to pixel coordinates. This is equivalent to
*        supplying a UnitMap.
*
*        The number of inputs for this Mapping (as given by its Nin attribute)
*        should match the number of axes in the supplied Region (as given
*        by the Naxes attribute of the Region).
*        The number of outputs for the Mapping (as given by its Nout attribute)
*        should match the number of
c        grid dimensions given by the value of "ndim"
f        grid dimensions given by the value of NDIM
*        below.
c     inside
f     INSIDE = INTEGER (Given)
*        A boolean value which indicates which pixel are to be masked. If
c        a non-zero value
f        .TRUE.
*        is supplied, then all grid pixels with centres inside the supplied
*        Region are assigned the value given by
c        "val",
f        VAL,
*        and all other pixels are left unchanged. If
c        zero
f        .FALSE.
*        is supplied, then all grid pixels with centres not inside the supplied
*        Region are assigned the value given by
c        "val",
f        VAL,
*        and all other pixels are left unchanged. Note, the Negated
*        attribute of the Region is used to determine which pixel are
*        inside the Region and which are outside. So the inside of a Region
*        which has not been negated is the same as the outside of the
*        corresponding negated Region.
*
*        For types of Region such as PointList which have zero volume,
*        pixel centres will rarely fall exactly within the Region. For
*        this reason, the inclusion criterion is changed for zero-volume
*        Regions so that pixels are included (or excluded) if any part of
*        the Region passes through the pixel. For a PointList, this means
*        that pixels are included (or excluded) if they contain at least
*        one of the points listed in the PointList.
c     ndim
f     NDIM = INTEGER (Given)
*        The number of dimensions in the input grid. This should be at
*        least one.
c     lbnd
f     LBND( NDIM ) = INTEGER (Given)
c        Pointer to an array of integers, with "ndim" elements,
f        An array
*        containing the coordinates of the centre of the first pixel
*        in the input grid along each dimension.
c     ubnd
f     UBND( NDIM ) = INTEGER (Given)
c        Pointer to an array of integers, with "ndim" elements,
f        An array
*        containing the coordinates of the centre of the last pixel in
*        the input grid along each dimension.
*
c        Note that "lbnd" and "ubnd" together define the shape
f        Note that LBND and UBND together define the shape
*        and size of the input grid, its extent along a particular
c        (j'th) dimension being ubnd[j]-lbnd[j]+1 (assuming the
c        index "j" to be zero-based). They also define
f        (J'th) dimension being UBND(J)-LBND(J)+1. They also define
*        the input grid's coordinate system, each pixel having unit
*        extent along each dimension with integral coordinate values
*        at its centre.
c     in
f     IN( * ) = <Xtype> (Given and Returned)
c        Pointer to an array, with one element for each pixel in the
f        An array, with one element for each pixel in the
*        input grid, containing the data to be masked.  The
*        numerical type of this array should match the 1- or
*        2-character type code appended to the function name (e.g. if
c        you are using astMaskF, the type of each array element
c        should be "float").
f        you are using AST_MASKR, the type of each array element
f        should be REAL).
*
*        The storage order of data within this array should be such
*        that the index of the first grid dimension varies most
*        rapidly and that of the final dimension least rapidly
c        (i.e. Fortran array indexing is used).
f        (i.e. normal Fortran array storage order).
*
*        On exit, the samples specified by
c        "inside" are set to the value of "val".
f        INSIDE are set to the value of VAL.
*        All other samples are left unchanged.
c     val
f     VAL = <Xtype> (Given)
*        This argument should have the same type as the elements of
c        the "in" array. It specifies the value used to flag the
f        the IN array. It specifies the value used to flag the
*        masked data (see
c        "inside").
f        INSIDE).
f     STATUS = INTEGER (Given and Returned)
f        The global status.

*  Returned Value:
c     astMask<X>()
f     AST_MASK<X> = INTEGER
*        The number of pixels to which a value of
c        "badval"
f        BADVAL
*        has been assigned.

*  Notes:
*     - A value of zero will be returned if this function is invoked
*     with the global error status set, or if it should fail for any
*     reason.
*     - An error will be reported if the overlap of the Region and
*     the array cannot be determined.

*  Data Type Codes:
*     To select the appropriate masking function, you should
c     replace <X> in the generic function name astMask<X> with a
f     replace <X> in the generic function name AST_MASK<X> with a
*     1- or 2-character data type code, so as to match the numerical
*     type <Xtype> of the data you are processing, as follows:
c     - D: double
c     - F: float
c     - L: long int
c     - UL: unsigned long int
c     - I: int
c     - UI: unsigned int
c     - S: short int
c     - US: unsigned short int
c     - B: byte (signed char)
c     - UB: unsigned byte (unsigned char)
f     - D: DOUBLE PRECISION
f     - R: REAL
f     - I: INTEGER
f     - UI: INTEGER (treated as unsigned)
f     - S: INTEGER*2 (short integer)
f     - US: INTEGER*2 (short integer, treated as unsigned)
f     - B: BYTE (treated as signed)
f     - UB: BYTE (treated as unsigned)
*
c     For example, astMaskD would be used to process "double"
c     data, while astMaskS would be used to process "short int"
c     data, etc.
f     For example, AST_MASKD would be used to process DOUBLE
f     PRECISION data, while AST_MASKS would be used to process
f     short integer data (stored in an INTEGER*2 array), etc.
f
f     For compatibility with other Starlink facilities, the codes W
f     and UW are provided as synonyms for S and US respectively (but
f     only in the Fortran interface to AST).

*--
*/
/* Define a macro to implement the function for a specific data
   type. */
#define MAKE_MASK(X,Xtype) \
static int Mask##X( AstRegion *this, AstMapping *map, int inside, int ndim, \
                    const int lbnd[], const int ubnd[], \
                    Xtype in[], Xtype val, int *status ) { \
\
/* Local Variables: */ \
   AstFrame *grid_frame;         /* Pointer to Frame describing grid coords */ \
   AstRegion *used_region;       /* Pointer to Region to be used by astResample */ \
   Xtype *c;                     /* Pointer to next array element */ \
   Xtype *d;                     /* Pointer to next array element */ \
   Xtype *out;                   /* Pointer to the array used for resample output */ \
   Xtype *tmp_out;               /* Pointer to temporary output array */ \
   double *lbndgd;               /* Pointer to array holding lower grid bounds */ \
   double *ubndgd;               /* Pointer to array holding upper grid bounds */ \
   int *lbndg;                   /* Pointer to array holding lower grid bounds */ \
   int *ubndg;                   /* Pointer to array holding upper grid bounds */ \
   int idim;                     /* Loop counter for coordinate dimensions */ \
   int ipix;                     /* Loop counter for pixel index */ \
   int nax;                      /* Number of Region axes */ \
   int nin;                      /* Number of Mapping input coordinates */ \
   int nout;                     /* Number of Mapping output coordinates */ \
   int npix;                     /* Number of pixels in supplied array */ \
   int npixg;                    /* Number of pixels in bounding box */ \
   int result;                   /* Result value to return */ \
\
/* Initialise. */ \
   result = 0; \
\
/* Check the global error status. */ \
   if ( !astOK ) return result; \
\
/* Obtain value for the Naxes attribute of the Region. */ \
   nax = astGetNaxes( this ); \
\
/* If supplied, obtain values for the Nin and Nout attributes of the Mapping. */ \
   if( map ) { \
      nin = astGetNin( map ); \
      nout = astGetNout( map ); \
\
/* If OK, check that the number of mapping inputs matches the \
   number of axes in the Region. Report an error if necessary. */ \
      if ( astOK && ( nax != nin ) ) { \
         astError( AST__NGDIN, "astMask"#X"(%s): Bad number of mapping " \
                   "inputs (%d).", status, astGetClass( this ), nin ); \
         astError( AST__NGDIN, "The %s given requires %d coordinate value%s " \
                   "to specify a position.", status, \
                   astGetClass( this ), nax, ( nax == 1 ) ? "" : "s" ); \
      } \
\
/* If OK, check that the number of mapping outputs matches the \
   number of grid dimensions. Report an error if necessary. */ \
      if ( astOK && ( ndim != nout ) ) { \
         astError( AST__NGDIN, "astMask"#X"(%s): Bad number of mapping " \
                   "outputs (%d).", status, astGetClass( this ), nout ); \
         astError( AST__NGDIN, "The pixel grid requires %d coordinate value%s " \
                   "to specify a position.", status, \
                   ndim, ( ndim == 1 ) ? "" : "s" ); \
      } \
\
/* Create a new Region by mapping the supplied Region with the supplied \
   Mapping. The resulting Region represents a region in grid coordinates. */ \
      grid_frame = astFrame( ndim, "Domain=grid", status ); \
      used_region = astMapRegion( this, map, grid_frame ); \
      grid_frame = astAnnul( grid_frame ); \
\
/* If no Mapping was supplied check that the number of grid dimensions \
   matches the number of axes in the Region.*/ \
   } else if ( astOK && ( ( ndim != nax ) || ( ndim < 1 ) ) ) { \
      used_region = NULL; \
      astError( AST__NGDIN, "astMask"#X"(%s): Bad number of input grid " \
                "dimensions (%d).", status, astGetClass( this ), ndim ); \
      if ( ndim != nax ) { \
         astError( AST__NGDIN, "The %s given requires %d coordinate value%s " \
                   "to specify an input position.", status, \
                   astGetClass( this ), nax, ( nax == 1 ) ? "" : "s" ); \
      } \
\
/* If no Mapping was supplied and the parameters look OK, clone the \
   supplied Region pointer for use later on. */ \
   } else { \
      used_region = astClone( this ); \
   } \
\
/* Check that the lower and upper bounds of the input grid are \
   consistent. Report an error if any pair is not. */ \
   if ( astOK ) { \
      for ( idim = 0; idim < ndim; idim++ ) { \
         if ( lbnd[ idim ] > ubnd[ idim ] ) { \
            astError( AST__GBDIN, "astMask"#X"(%s): Lower bound of " \
                      "input grid (%d) exceeds corresponding upper bound " \
                      "(%d).", status, astGetClass( this ), \
                      lbnd[ idim ], ubnd[ idim ] ); \
            astError( AST__GBDIN, "Error in input dimension %d.", status, \
                      idim + 1 ); \
            break; \
         } \
      } \
   } \
\
/* Allocate memory, and then get the bounding box of this new Region in its \
   current Frame (grid coordinates). This bounding box assumes the region \
   has not been negated. */ \
   lbndg = astMalloc( sizeof( int )*(size_t) ndim ); \
   ubndg = astMalloc( sizeof( int )*(size_t) ndim ); \
   lbndgd = astMalloc( sizeof( double )*(size_t) ndim ); \
   ubndgd = astMalloc( sizeof( double )*(size_t) ndim ); \
   if( astOK ) { \
      astGetRegionBounds( used_region, lbndgd, ubndgd ); \
\
/* We convert the floating point bounds to integer pixel bounds, and at \
   the same time expand the box by 2 pixels at each edge to ensure that \
   rounding errors etc do not cause any of the Region to fall outside (or \
   on) the box. Do not let the expanded box extend outside the supplied \
   array bounds. Also note the total number of pixels in the supplied \
   array, and in the bounding box. */ \
      npix = 1; \
      npixg = 1; \
      for ( idim = 0; idim < ndim; idim++ ) { \
         if( lbndgd[ idim ] != AST__BAD && ubndgd[ idim ] != AST__BAD ) { \
            lbndg[ idim ] = astMAX( lbnd[ idim ], (int)( lbndgd[ idim ] + 0.5 ) - 2 ); \
            ubndg[ idim ] = astMIN( ubnd[ idim ], (int)( ubndgd[ idim ] + 0.5 ) + 2 ); \
         } else { \
            lbndg[ idim ] = lbnd[ idim ]; \
            ubndg[ idim ] = ubnd[ idim ]; \
         } \
         npix *= ( ubnd[ idim ] - lbnd[ idim ] + 1 ); \
         if( npixg >= 0 ) npixg *= ( ubndg[ idim ] - lbndg[ idim ] + 1 ); \
      } \
\
/* If the bounding box is null, fill the mask with the supplied value if \
   we assigning the value to the outside of the region (do the opposite if \
   the Region has been negated). */ \
      if( npixg <= 0 && astOK ) { \
         if( ( inside != 0 ) == ( astGetNegated( used_region ) != 0 ) ) { \
            c = in; \
            for( ipix = 0; ipix < npix; ipix++ ) *(c++) = val; \
            result = npix; \
         } \
\
/* If the bounding box is null, return without action. */ \
      } else if( npixg > 0 && astOK ) { \
\
/* All points outside this box are either all inside, or all outside, the \
   Region. So we can speed up processing by setting all the points which are \
   outside the box to the supplied data value (if required). This is \
   faster than checking each point individually using the Transform method \
   of the Region. We do this by supplying an alternative output array to \
   the resampling function below, which has been pre-filled with "val" at \
   every pixel. */ \
         if( ( inside != 0 ) == ( astGetNegated( used_region ) != 0 ) ) { \
\
/* Allocate memory for the alternative output array, and fill it with \
   "val". */ \
            tmp_out = astMalloc( sizeof( Xtype )*(size_t) npix ); \
            if( tmp_out ) { \
               c = tmp_out; \
               for( ipix = 0; ipix < npix; ipix++ ) *(c++) = val; \
               result = npix - npixg; \
            } \
\
/* Indicate that we will use this temporary array rather than the \
   supplied array. */ \
            out = tmp_out; \
\
/* If the outside of the grid box is outside the region of interest it \
   will be unchanged in the resturned array. Therefore we can use the \
   supplied array as the output array below. */ \
         } else { \
            tmp_out = NULL; \
            out = in; \
         } \
\
/* Temporarily invert the Region if required. The Region Transform methods \
   leave interior points unchanged and assign AST__BAD to exterior points. \
   This is the opposite of what we want (which is to leave exterior \
   points unchanged and assign VAL to interior points), so we negate the \
   region if the inside is to be assigned the value VAL.*/ \
         if( inside ) astNegate( used_region ); \
\
/* Invoke astResample to mask just the region inside the bounding box found \
   above (specified by lbndg and ubndg), since all the points outside this \
   box will already contain their required value. */ \
         result += astResample##X( used_region, ndim, lbnd, ubnd, in, NULL, AST__NEAREST, \
                                   NULL, NULL, 0, 0.0, 100, val, ndim, \
                                   lbnd, ubnd, lbndg, ubndg, out, NULL ); \
\
/* Revert to the original setting of the Negated attribute. */ \
         if( inside ) astNegate( used_region ); \
\
/* If required, copy the output data from the temporary output array to \
   the supplied array, and then free the temporary output array. */ \
         if( tmp_out ) { \
            c = tmp_out; \
            d = in; \
            for( ipix = 0; ipix < npix; ipix++ ) *(d++) = *(c++); \
            tmp_out = astFree( tmp_out ); \
         }\
      }\
   } \
\
/* Free resources */ \
   ubndg = astFree( ubndg ); \
   lbndg = astFree( lbndg ); \
   ubndgd = astFree( ubndgd ); \
   lbndgd = astFree( lbndgd ); \
   used_region = astAnnul( used_region ); \
\
/* If an error occurred, clear the returned result. */ \
   if ( !astOK ) result = 0; \
\
/* Return the result. */ \
   return result; \
}

/* Expand the above macro to generate a function for each required
   data type. */
#if HAVE_LONG_DOUBLE     /* Not normally implemented */
MAKE_MASK(LD,long double)
#endif
MAKE_MASK(D,double)
MAKE_MASK(L,long int)
MAKE_MASK(UL,unsigned long int)
MAKE_MASK(I,int)
MAKE_MASK(UI,unsigned int)
MAKE_MASK(S,short int)
MAKE_MASK(US,unsigned short int)
MAKE_MASK(B,signed char)
MAKE_MASK(UB,unsigned char)
MAKE_MASK(F,float)

/* Undefine the macro. */
#undef MAKE_MASK



static int Match( AstFrame *this_frame, AstFrame *target, int matchsub,
                  int **template_axes, int **target_axes,
                  AstMapping **map, AstFrame **result, int *status ) {
/*
*  Name:
*     Match

*  Purpose:
*     Determine if conversion is possible between two coordinate systems.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     int Match( AstFrame *template, AstFrame *target, int matchsub,
*                int **template_axes, int **target_axes,
*                AstMapping **map, AstFrame **result, int *status )

*  Class Membership:
*     Region member function (over-rides the protected astMatch
*     method inherited from the Frame class).

*  Description:
*     This function matches the current Frame of a "template" Region
*     to a "target" frame and determines whether it is possible to
*     convert coordinates between them.  If it is, a Mapping that
*     performs the transformation is returned along with a new Frame
*     that describes the coordinate system that results when this
*     Mapping is applied to the current Frame of the target
*     Region. In addition, information is returned to allow the axes
*     in this "result" Frame to be associated with the corresponding
*     axes in the target and template Frames from which they are
*     derived.

*  Parameters:
*     template
*        Pointer to the template Region, whose current Frame
*        describes the coordinate system (or set of possible
*        coordinate systems) into which we wish to convert our
*        coordinates.
*     target
*        Pointer to the target Frame. This describes the coordinate
*        system in which we already have coordinates.
*     matchsub
*        If zero then a match only occurs if the template is of the same
*        class as the target, or of a more specialised class. If non-zero
*        then a match can occur even if this is not the case.
*     template_axes
*        Address of a location where a pointer to int will be returned
*        if the requested coordinate conversion is possible. This
*        pointer will point at a dynamically allocated array of
*        integers with one element for each axis of the "result" Frame
*        (see below). It must be freed by the caller (using astFree)
*        when no longer required.
*
*        For each axis in the result Frame, the corresponding element
*        of this array will return the index of the axis in the
*        template Region's current Frame from which it is
*        derived. If it is not derived from any template Region
*        axis, a value of -1 will be returned instead.
*     target_axes
*        Address of a location where a pointer to int will be returned
*        if the requested coordinate conversion is possible. This
*        pointer will point at a dynamically allocated array of
*        integers with one element for each axis of the "result" Frame
*        (see below). It must be freed by the caller (using astFree)
*        when no longer required.
*
*        For each axis in the result Frame, the corresponding element
*        of this array will return the index of the target Frame axis
*        from which it is derived. If it is not derived from any
*        target Frame axis, a value of -1 will be returned instead.
*     map
*        Address of a location where a pointer to a new Mapping will
*        be returned if the requested coordinate conversion is
*        possible. If returned, the forward transformation of this
*        Mapping may be used to convert coordinates between the target
*        Frame and the result Frame (see below) and the inverse
*        transformation will convert in the opposite direction.
*     result
*        Address of a location where a pointer to a new Frame will be
*        returned if the requested coordinate conversion is
*        possible. If returned, this Frame describes the coordinate
*        system that results from applying the returned Mapping
*        (above) to the "target" coordinate system. In general, this
*        Frame will combine attributes from (and will therefore be
*        more specific than) both the target Frame and the current
*        Frame of the template Region. In particular, when the
*        template allows the possibility of transformaing to any one
*        of a set of alternative coordinate systems, the "result"
*        Frame will indicate which of the alternatives was used.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     A non-zero value is returned if the requested coordinate
*     conversion is possible. Otherwise zero is returned (this will
*     not in itself result in an error condition).

*  Notes:
*     - A value of zero will be returned if this function is invoked
*     with the global error status set, or if it should fail for any
*     reason.
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to Region's current Frame */
   int match;                    /* Result to be returned */

/* Initialise the returned values. */
   *template_axes = NULL;
   *target_axes = NULL;
   *map = NULL;
   *result = NULL;
   match = 0;

/* Check the global error status. */
   if ( !astOK ) return match;

/* Invoke the parent astMatch method on the current Frame within the
   encapsulated FrameSet within the Region. */
   fr = astGetFrame( ((AstRegion *) this_frame)->frameset, AST__CURRENT );
   match = astMatch( fr, target, matchsub, template_axes, target_axes, map, result );
   fr = astAnnul( fr );

/* Return the result. */
   return match;
}

static void MatchAxes( AstFrame *frm1_frame, AstFrame *frm2, int *axes,
                       int *status ) {
/*
*  Name:
*     MatchAxes

*  Purpose:
*     Find any corresponding axes in two Frames.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     void MatchAxes( AstFrame *frm1, AstFrame *frm2, int *axes )
*                     int *status )

*  Class Membership:
*     Region member function (over-rides the protected astMatchAxes
*     method inherited from the Frame class).

*  Description:
*     This function looks for corresponding axes within two supplied
*     Frames. An array of integers is returned that contains an element
*     for each axis in the second supplied Frame. An element in this array
*     will be set to zero if the associated axis within the second Frame
*     has no corresponding axis within the first Frame. Otherwise, it
*     will be set to the index (a non-zero positive integer) of the
*     corresponding axis within the first supplied Frame.

*  Parameters:
*     frm1
*        Pointer to the first Frame.
*     frm2
*        Pointer to the second Frame.
*     axes
*        Pointer to an
*        integer array in which to return the indices of the axes (within
*        the second Frame) that correspond to each axis within the first
*        Frame. Axis indices start at 1. A value of zero will be stored
*        in the returned array for each axis in the first Frame that has
*        no corresponding axis in the second Frame.
*
*        The number of elements in this array must be greater than or
*        equal to the number of axes in the first Frame.
*     status
*        Pointer to inherited status value.

*  Notes:
*     -  Corresponding axes are identified by the fact that a Mapping
*     can be found between them using astFindFrame or astConvert. Thus,
*     "corresponding axes" are not necessarily identical. For instance,
*     SkyFrame axes in two Frames will match even if they describe
*     different celestial coordinate systems
*/

/* Local Variables: */
   AstFrame *frm1;               /* Pointer to Region's current Frame */

/* Check the global error status. */
   if ( !astOK ) return;

/* Invoke the astMatchAxesX method on frm2, passing it the current Frame
   within the encapsulated FrameSet within the Region as "frm1". */
   frm1 = astGetFrame( ((AstRegion *) frm1_frame)->frameset, AST__CURRENT );
   astMatchAxesX( frm2, frm1, axes );
   frm1 = astAnnul( frm1 );
}

static void MatchAxesX( AstFrame *frm2_frame, AstFrame *frm1, int *axes,
                        int *status ) {
/*
*  Name:
*     MatchAxesX

*  Purpose:
*     Find any corresponding axes in two Frames.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     void MatchAxesX( AstFrame *frm2, AstFrame *frm1, int *axes )
*                      int *status )

*  Class Membership:
*     Region member function (over-rides the protected astMatchAxesX
*     method inherited from the Frame class).

*     This function looks for corresponding axes within two supplied
*     Frames. An array of integers is returned that contains an element
*     for each axis in the second supplied Frame. An element in this array
*     will be set to zero if the associated axis within the second Frame
*     has no corresponding axis within the first Frame. Otherwise, it
*     will be set to the index (a non-zero positive integer) of the
*     corresponding axis within the first supplied Frame.

*  Parameters:
*     frm2
*        Pointer to the second Frame.
*     frm1
*        Pointer to the first Frame.
*     axes
*        Pointer to an integer array in which to return the indices of
*        the axes (within the first Frame) that correspond to each axis
*        within the second Frame. Axis indices start at 1. A value of zero
*        will be stored in the returned array for each axis in the second
*        Frame that has no corresponding axis in the first Frame.
*
*        The number of elements in this array must be greater than or
*        equal to the number of axes in the second Frame.
*     status
*        Pointer to inherited status value.

*  Notes:
*     -  Corresponding axes are identified by the fact that a Mapping
*     can be found between them using astFindFrame or astConvert. Thus,
*     "corresponding axes" are not necessarily identical. For instance,
*     SkyFrame axes in two Frames will match even if they describe
*     different celestial coordinate systems
*/

/* Local Variables: */
   AstFrame *frm2;

/* Check the global error status. */
   if ( !astOK ) return;

/* Get a pointer to the current Frame in the FrameSet. */
   frm2 = astGetFrame( ((AstRegion *) frm2_frame)->frameset, AST__CURRENT );

/* Invoke the astMatchAxesX on the current Frame. */
   astMatchAxesX( frm2, frm1, axes );

/* Free resources */
   frm2 = astAnnul( frm2 );
}

static void Negate( AstRegion *this, int *status ) {
/*
*++
*  Name:
c     astNegate
f     AST_NEGATE

*  Purpose:
*     Negate the area represented by a Region.

*  Type:
*     Public virtual function.

*  Synopsis:
c     #include "region.h"
c     void astNegate( AstRegion *this )
f     CALL AST_NEGATE( THIS, STATUS )

*  Class Membership:
*     Region method.

*  Description:
*     This function negates the area represented by a Region. That is,
*     points which were previously inside the region will then be
*     outside, and points which were outside will be inside. This is
*     acomplished by toggling the state of the Negated attribute for
*     the supplied region.

*  Parameters:
c     this
f     THIS = INTEGER (Given)
*        Pointer to the Region.
f     STATUS = INTEGER (Given and Returned)
f        The global status.

*--
*/

/* Check the global error status. */
   if ( !astOK ) return;

/* Toggle the Negated attribute. */
   astSetNegated( this, astGetNegated( this ) ? 0 : 1 );

}

static void Norm( AstFrame *this_frame, double value[], int *status ) {
/*
*  Name:
*     Norm

*  Purpose:
*     Normalise a set of Region coordinates.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     void Norm( AstAxis *this, double value[], int *status )

*  Class Membership:
*     Region member function (over-rides the astNorm method
*     inherited from the Frame class).

*  Description:
*     This function converts a set of coordinate values for the
*     current Frame of a Region, which might potentially be
*     unsuitable for display to a user (for instance, may lie outside
*     the expected range of values) into a set of acceptable
*     alternative values suitable for display.
*
*     Typically, for Frames whose axes represent cyclic values (such
*     as angles or positions on the sky), this function wraps an
*     arbitrary set of coordinates, so that they lie within the first
*     cycle (say zero to 2*pi or -pi/2 to +pi/2). For Frames with
*     ordinary linear axes, without constraints, this function will
*     typically return the original coordinate values unchanged.

*  Parameters:
*     this
*        Pointer to the Region.
*     value
*        An array of double, with one element for each Region axis.
*        This should contain the initial set of coordinate values,
*        which will be modified in place.
*     status
*        Pointer to the inherited status variable.
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to the current Frame */
   AstRegion *this;              /* Pointer to the Region structure */

/* Check the global error status. */
   if ( !astOK ) return;

/* Obtain a pointer to the Region structure. */
   this = (AstRegion *) this_frame;

/* Obtain a pointer to the Region's current Frame and invoke this
   Frame's astNorm method to obtain the new values. Annul the Frame
   pointer afterwards. */
   fr = astGetFrame( this->frameset, AST__CURRENT );
   astNorm( fr, value );
   fr = astAnnul( fr );
}

static void NormBox( AstFrame *this_frame, double lbnd[], double ubnd[],
                     AstMapping *reg, int *status ) {
/*
*  Name:
*     NormBox

*  Purpose:
*     Extend a box to include effect of any singularities in the Frame.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     void astNormBox( AstFrame *this, double lbnd[], double ubnd[],
*                      AstMapping *reg, int *status )

*  Class Membership:
*     Region member function (over-rides the astNormBox method inherited
*     from the Frame class).

*  Description:
*     This function modifies a supplied box to include the effect of any
*     singularities in the co-ordinate system represented by the Frame.
*     For a normal Cartesian coordinate system, the box will be returned
*     unchanged. Other classes of Frame may do other things. For instance,
*     a SkyFrame will check to see if the box contains either the north
*     or south pole and extend the box appropriately.

*  Parameters:
*     this
*        Pointer to the Frame.
*     lbnd
*        An array of double, with one element for each Frame axis
*        (Naxes attribute). Initially, this should contain a set of
*        lower axis bounds for the box. They will be modified on exit
*        to include the effect of any singularities within the box.
*     ubnd
*        An array of double, with one element for each Frame axis
*        (Naxes attribute). Initially, this should contain a set of
*        upper axis bounds for the box. They will be modified on exit
*        to include the effect of any singularities within the box.
*     reg
*        A Mapping which should be used to test if any singular points are
*        inside or outside the box. The Mapping should leave an input
*        position unchanged if the point is inside the box, and should
*        set all bad if the point is outside the box.
*     status
*        Pointer to the inherited status variable.
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to the current Frame */
   AstRegion *this;              /* Pointer to the Region structure */

/* Check the global error status. */
   if ( !astOK ) return;

/* Obtain a pointer to the Region structure. */
   this = (AstRegion *) this_frame;

/* Obtain a pointer to the Region's current Frame and invoke this
   Frame's astNormBox method to obtain the new values. Annul the Frame
   pointer afterwards. */
   fr = astGetFrame( this->frameset, AST__CURRENT );
   astNormBox( fr, lbnd, ubnd, reg );
   fr = astAnnul( fr );
}

static void Offset( AstFrame *this_frame, const double point1[],
                    const double point2[], double offset, double point3[], int *status ) {
/*
*  Name:
*     Offset

*  Purpose:
*     Calculate an offset along a geodesic curve.

*  Type:
*     Public virtual function.

*  Synopsis:
*     #include "region.h"
*     void Offset( AstFrame *this,
*                  const double point1[], const double point2[],
*                  double offset, double point3[], int *status )

*  Class Membership:
*     Region member function (over-rides the protected astOffset
*     method inherited from the Frame class).

*  Description:
*     This function finds the Region coordinate values of a point
*     which is offset a specified distance along the geodesic curve
*     between two other points.

*  Parameters:
*     this
*        Pointer to the Region.
*     point1
*        An array of double, with one element for each Region axis.
*        This should contain the coordinates of the point marking the
*        start of the geodesic curve.
*     point2
*        An array of double, with one element for each Region axis
*        This should contain the coordinates of the point marking the
*        end of the geodesic curve.
*     offset
*        The required offset from the first point along the geodesic
*        curve. If this is positive, it will be towards the second
*        point. If it is negative, it will be in the opposite
*        direction. This offset need not imply a position lying
*        between the two points given, as the curve will be
*        extrapolated if necessary.
*     point3
*        An array of double, with one element for each Region axis
*        in which the coordinates of the required point will be
*        returned.
*     status
*        Pointer to the inherited status variable.

*  Notes:
*     - The geodesic curve used by this function is the path of
*     shortest distance between two points, as defined by the
*     astDistance function.
*     - This function will return "bad" coordinate values (AST__BAD)
*     if any of the input coordinates has this value.
*     - "Bad" coordinate values will also be returned if the two
*     points supplied are coincident (or otherwise fail to uniquely
*     specify a geodesic curve) but the requested offset is non-zero.
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to current Frame */
   AstRegion *this;              /* Pointer to the Region structure */

/* Check the global error status. */
   if ( !astOK ) return;

/* Obtain a pointer to the Region structure. */
   this = (AstRegion *) this_frame;

/* Obtain a pointer to the Region's current Frame and invoke this
   Frame's astOffset method. Annul the Frame pointer afterwards. */
   fr = astGetFrame( this->frameset, AST__CURRENT );
   astOffset( fr, point1, point2, offset, point3 );
   fr = astAnnul( fr );
}

static double Offset2( AstFrame *this_frame, const double point1[2],
                       double angle, double offset, double point2[2], int *status ){
/*
*  Name:
*     Offset2

*  Purpose:
*     Calculate an offset along a geodesic curve in a 2D Frame.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     double Offset2( AstFrame *this, const double point1[2], double angle,
*                     double offset, double point2[2], int *status );

*  Class Membership:
*     Region member function (over-rides the protected astOffset2
*     method inherited from the Frame class).

*  Description:
*     This function finds the Frame coordinate values of a point which
*     is offset a specified distance along the geodesic curve at a
*     given angle from a specified starting point. It can only be
*     used with 2-dimensional Frames.
*
*     For example, in a basic Frame, this offset will be along the
*     straight line joining two points. For a more specialised Frame
*     describing a sky coordinate system, however, it would be along
*     the great circle passing through two sky positions.

*  Parameters:
*     this
*        Pointer to the Frame.
*     point1
*        An array of double, with one element for each Frame axis
*        (Naxes attribute). This should contain the coordinates of the
*        point marking the start of the geodesic curve.
*     angle
*        The angle (in radians) from the positive direction of the second
*        axis, to the direction of the required position, as seen from
*        the starting position. Positive rotation is in the sense of
*        rotation from the positive direction of axis 2 to the positive
*        direction of axis 1.
*     offset
*        The required offset from the first point along the geodesic
*        curve. If this is positive, it will be in the direction of the
*        given angle. If it is negative, it will be in the opposite
*        direction.
*     point2
*        An array of double, with one element for each Frame axis
*        in which the coordinates of the required point will be returned.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     The direction of the geodesic curve at the end point. That is, the
*     angle (in radians) between the positive direction of the second
*     axis and the continuation of the geodesic curve at the requested
*     end point. Positive rotation is in the sense of rotation from
*     the positive direction of axis 2 to the positive direction of axis 1.

*  Notes:
*     - The geodesic curve used by this function is the path of
*     shortest distance between two points, as defined by the
*     astDistance function.
*     - An error will be reported if the Frame is not 2-dimensional.
*     - This function will return "bad" coordinate values (AST__BAD)
*     if any of the input coordinates has this value.
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to current Frame */
   AstRegion *this;              /* Pointer to the Region structure */
   double result;                /* Value to return */

/* Check the global error status. */
   if ( !astOK ) return AST__BAD;

/* Obtain a pointer to the FrameSet structure. */
   this = (AstRegion *) this_frame;

/* Obtain a pointer to the Region's encapsulated Frame and invoke the
   astOffset2 method for this Frame. Annul the Frame pointer afterwards. */
   fr = astGetFrame( this->frameset, AST__CURRENT );
   result = astOffset2( fr, point1, angle, offset, point2 );
   fr = astAnnul( fr );

/* If an error occurred, clear the result value. */
   if ( !astOK ) result = AST__BAD;

/* Return the result. */
   return result;
}

static int Overlap( AstRegion *this, AstRegion *that, int *status ){
/*
*++
*  Name:
c     astOverlap
f     AST_OVERLAP

*  Purpose:
*     Test if two regions overlap each other.

*  Type:
*     Public virtual function.

*  Synopsis:
c     #include "region.h"
c     int astOverlap( AstRegion *this, AstRegion *that )
f     RESULT = AST_OVERLAP( THIS, THAT, STATUS )

*  Class Membership:
*     Region method.

*  Description:
*     This function returns an integer value indicating if the two
*     supplied Regions overlap. The two Regions are converted to a commnon
*     coordinate system before performing the check. If this conversion is
*     not possible (for instance because the two Regions represent areas in
*     different domains), then the check cannot be performed and a zero value
*     is returned to indicate this.

*  Parameters:
c     this
f     THIS = INTEGER (Given)
*        Pointer to the first Region.
c     that
f     THAT = INTEGER (Given)
*        Pointer to the second Region.
f     STATUS = INTEGER (Given and Returned)
f        The global status.

*  Returned Value:
c     astOverlap()
f     AST_OVERLAP = INTEGER
*        A value indicating if there is any overlap between the two Regions.
*        Possible values are:
*
*        0 - The check could not be performed because the second Region
*            could not be mapped into the coordinate system of the first
*            Region.
*
*        1 - There is no overlap between the two Regions.
*
*        2 - The first Region is completely inside the second Region.
*
*        3 - The second Region is completely inside the first Region.
*
*        4 - There is partial overlap between the two Regions.
*
*        5 - The Regions are identical to within their uncertainties.
*
*        6 - The second Region is the exact negation of the first Region
*            to within their uncertainties.

*  Notes:
*     - The returned values 5 and 6 do not check the value of the Closed
*     attribute in the two Regions.
*     - A value of zero will be returned if this function is invoked with the
*     AST error status set, or if it should fail for any reason.
*--

* Implementation Notes:
*    This function is simply a wrap-up for the protected astOverlapX
*    method which performs the required processing but swaps the order
*    of the two arguments. This is a trick to allow the astOverlap method
*    to be over-ridden by derived classes on the basis of the class of either
*    of the two arguments.
*/

/* Check the global error status. */
   if ( !astOK ) return 0;

/* Invoke the "astOverlapX" method with the two arguments swapped. */
   return astOverlapX( that, this );
}

static int OverlapX( AstRegion *that, AstRegion *this, int *status ){
/*
*+
*  Name:
*     astOverlapX

*  Purpose:
*     Test if two regions overlap each other.

*  Type:
*     Protected virtual function.

*  Synopsis:
*     #include "region.h"
*     int astOverlapX( AstRegion *that, AstRegion *this )

*  Class Membership:
*     Region method.

*  Description:
*     This function performs the processing for the public astOverlap
*     method and has exactly the same interface except that the order
*     of the two arguments is swapped. This is a trick to allow
*     the astOverlap method to be over-ridden by derived classes on
*     the basis of the class of either of its two arguments.
*
*     See the astOverlap method for details of the interface.
*-
*/

/* Local Variables: */
   AstFrame *bfrm_reg1;           /* Pointer to base Frame in "reg1" Frame */
   AstFrame *frm_reg1;            /* Pointer to current Frame in "reg1" Frame */
   AstFrameSet *fs0;              /* FrameSet connecting Region Frames */
   AstFrameSet *fs;               /* FrameSet connecting Region Frames */
   AstMapping *cmap;              /* Mapping connecting Region Frames */
   AstMapping *map;               /* Mapping form "reg2" current to "reg1" base */
   AstMapping *map_reg1;          /* Pointer to current->base Mapping in "reg1" */
   AstPointSet *ps1;              /* Mesh covering second Region */
   AstPointSet *ps2;              /* Mesh covering second Region */
   AstPointSet *ps3;              /* Mesh covering first Region */
   AstPointSet *ps4;              /* Mesh covering first Region */
   AstPointSet *ps5;              /* Another PointSet */
   AstPointSet *reg1_mesh;        /* Mesh covering first Region */
   AstPointSet *reg2_mesh;        /* Mesh covering second Region */
   AstPointSet *reg2_submesh;     /* Second Region mesh minus boundary points */
   AstRegion *reg1;               /* Region to use as the first Region */
   AstRegion *reg2;               /* Region to use as the second Region */
   AstRegion *unc1;               /* "unc" mapped into Frame of first Region */
   AstRegion *unc;                /* Uncertainty in second Region */
   double **ptr1;                 /* Pointer to mesh axis values */
   double **ptr;                  /* Pointer to pointset data */
   double *p;                     /* Pointer to next axis value */
   double axsum;                  /* Sum of axis values */
   int *mask;                     /* Mask identifying common boundary points */
   int allbad;                    /* Were all axis values bad? */
   int allgood;                   /* Were all axis values good? */
   int bnd1;                      /* Does reg1 have a finite boundary */
   int bnd2;                      /* Does reg2 have a finite boundary */
   int bnd_that;                  /* Does "that" have a finite boundary */
   int bnd_this;                  /* Does "this" have a finite boundary */
   int case1;                     /* First region inside second region? */
   int first;                     /* First pass? */
   int good;                      /* Any good axis values found? */
   int i;                         /* Mesh axis index */
   int iax;                       /* Axis index */
   int inv0;                      /* Original FrameSet Invert flag */
   int inside1;                   /* The position is inside reg1? */
   int inside2;                   /* The position is inside reg2? */
   int ip;                        /* Index of point */
   int j;                         /* Mesh point index */
   int nc;                        /* Number of axis values per point */
   int np;                        /* Number of points in mesh */
   int reg1_neg;                  /* Was "reg1" negated to make it bounded? */
   int reg2_neg;                  /* Was "reg2" negated to make it bounded? */
   int result;                    /* Value to return */
   int that_neg;                  /* Was "that" negated to make it bounded? */
   int this_neg;                  /* Was "this" negated to make it bounded? */
   int touch;                     /* Do the Regions touch? */

/* Initialise. */
   result = 0;

/* Check the global error status. */
   if ( !astOK ) return result;

/* Return 5 if the two Regions are equal using the astEqual method. */
   if( astEqual( this, that ) ) {
      return 5;

/* Return 6 if the two Regions are equal using the Equal method after
   temporarily negating the first. */
   } else {
      astNegate( this );
      result = astEqual( this, that );
      astNegate( this );
      if( result ) return 6;
   }

/* Get a FrameSet which connects the Frame represented by the second Region
   to the Frame represented by the first Region. Check that the conection is
   defined. */
   fs0 = astConvert( that, this, "" );
   if( !fs0 ) return 0;
   inv0 = astGetInvert( fs0 );

/* The rest of this function tests for overlap by representing one of the
   Regions as a mesh of points along its boundary, and then checking to see
   if any of the points in this mesh fall inside or outside the other Region.
   This can only be done if the Region has a boundary of finite length (e.g.
   Circles, Boxes, etc). Other Regions (e.g. some Intervals) do not have
   finite boundaries and consequently report an error if an attempt is made
   to represent them using a boundary mesh. We now therefore check to see if
   either of the two Regions has a finite boundary length. This will be the
   case if the region is bounded, or if it can be made bounded simply by
   negating it. If a Region is unbounded regardless of the setting of its
   Negated flag, then it does not have a finite boundary. We leave the
   Negated attributes (temporaily) set to the values that cause the
   Regions to be bounded. Set flags to indicate if the Regions have been
   negated. */
   bnd_this = astGetBounded( this );
   if( !bnd_this ) {
      astNegate( this );
      bnd_this = astGetBounded( this );
      if( ! bnd_this ) {
         astNegate( this );
         this_neg = 0;
      } else {
         this_neg = 1;
      }
   } else {
      this_neg = 0;
   }

   bnd_that = astGetBounded( that );
   if( !bnd_that ) {
      astNegate( that );
      bnd_that = astGetBounded( that );
      if( ! bnd_that ) {
         astNegate( that );
         that_neg = 0;
      } else {
         that_neg = 1;
      }
   } else {
      that_neg = 0;
   }

/* If neither Regions has a finite boundary, then we cannot currently
   determine any overlap, so report an error. Given more time, it
   is probably possible to think of some way of determining overlap
   between two unbounded Regions, but it will probably not be a common
   requirement and so is currently put off to a rainy day. */
   if( !bnd_this && !bnd_that && astOK ) {
      astError( AST__INTER, "astOverlap(Region): Neither of the two "
                "supplied Regions (classes %s and %s) has a finite "
                "boundary.", status, astGetClass(this), astGetClass(that) );
      astError( AST__INTER, "The current implementation of astOverlap "
                "cannot determine the overlap between two Regions "
                "unless at least one of them has a finite boundary." , status);
   }

/* If only one of the two Regions has a finite boundary, we must use its
   mesh first. Choose the finite boundary Region as the "second" region.
   Also store a flag indicating if the first Region has a finite boundary. */
   if( bnd_that ) {
      reg1 = this;
      reg2 = that;
      bnd1 = bnd_this;
      bnd2 = bnd_that;
      reg1_neg = this_neg;
      reg2_neg = that_neg;
   } else {
      reg1 = that;
      reg2 = this;
      bnd1 = bnd_that;
      bnd2 = bnd_this;
      reg1_neg = that_neg;
      reg2_neg = this_neg;
   }

/* We may need to try again with the above selections swapped. We only do
   this once though. Set a flag to indicate that we are about to start the
   first pass. */
   first = 1;
L1:

/* Get a FrameSet which connects the Frame represented by the second Region
   to the Frame represented by the first Region. Check that the conection is
   defined. */
   fs = astClone( fs0 );
   astSetInvert( fs, (reg2 == that ) ? inv0 : 1 - inv0 );
   if( fs ) {

/* Get a pointer to the Frame represented by the first Region. */
      frm_reg1 = astGetFrame( reg1->frameset, AST__CURRENT );

/* Get a pointer to the Mapping from current to base Frame in the first
   Region. */
      map_reg1 = astGetMapping( reg1->frameset, AST__CURRENT, AST__BASE );

/* Get the Mapping from the current Frame of the second Region to the
   current Frame of the first Region. */
      cmap = astGetMapping( fs, AST__BASE, AST__CURRENT );

/* Combine these Mappings to get the Mapping from current Frame of the
   second region to the base Frame of the first Region. */
      map = (AstMapping *) astCmpMap( cmap, map_reg1, 1, "", status );

/* Get a mesh of points covering the second Region. These points are
   within the current Frame of the second Region. */
      reg2_mesh = astRegMesh( reg2 );

/* Transform this mesh into the base Frame of the first Region. */
      ps1 = astTransform( map, reg2_mesh, 1, NULL );

/* Check there are some good points in the transformed pointset. */
      good = 0;
      np = astGetNpoint( ps1 );
      nc = astGetNcoord( ps1 );
      ptr1 = astGetPoints( ps1 );
      if( ptr1 ) {
         for( i = 0; i < nc && !good; i++ ) {
            for( j = 0; j < np; j++ ) {
               if( ptr1[ i ][ j ] != AST__BAD ) {
                  good = 1;
                  break;
               }
            }
         }
      }

/* If the transformed mesh contains no good points, swap the regions and
   try again. */
      if( !good ) {
         fs = astAnnul( fs );
         frm_reg1 = astAnnul( frm_reg1 );
         map_reg1 = astAnnul( map_reg1 );
         cmap = astAnnul( cmap );
         map = astAnnul( map );
         reg2_mesh = astAnnul( reg2_mesh );
         ps1 = astAnnul( ps1 );

         if( first ) {
            first = 0;

            if( !bnd_that ) {
               reg1 = this;
               reg2 = that;
               bnd1 = bnd_this;
               bnd2 = bnd_that;
               reg1_neg = this_neg;
               reg2_neg = that_neg;
            } else {
               reg1 = that;
               reg2 = this;
               bnd1 = bnd_that;
               bnd2 = bnd_this;
               reg1_neg = that_neg;
               reg2_neg = this_neg;
            }
            goto L1;

         } else {
            return 0;
         }
      }

/* Also transform the Region describing the positional uncertainty within
   the second supplied Region into the base Frame of the first supplied
   Region. */
      unc = astGetUncFrm( reg2, AST__CURRENT );
      bfrm_reg1 = astGetFrame( reg1->frameset, AST__BASE );
      unc1 = astMapRegion( unc, map, bfrm_reg1 );

/* See if all points within this transformed mesh fall on the boundary of
   the first Region, to within the joint uncertainty of the two Regions. If
   so the two Regions have equivalent boundaries. We can only do this is
   the first region is bounded. */
      if( astRegPins( reg1, ps1, unc1, &mask ) && good ) {

/* If the boundaries are equivalent, the Regions are either identical
   or are mutually exclusive. To distinguish between these cases, we
   transform an aritrary position (the mean of the pin positions) using
   both Regions - if it's inside both or outside both, then the Regions are
   identical, otherwise they are mutually exclusive. Note, we cannot just
   check the value of the Bounded attribute since both the region and its
   negation will be bounded if the region is defined on the sky. */
         ps4 = astPointSet( 1, nc, " ", status );
         ptr = astGetPoints( ps4 );
         if( astOK ) {

/* Get the average of the pin positions. */
            for( i = 0; i < nc; i++ ) {
               good = 0;
               axsum = 0.0;
               for( j = 0; j < np; j++ ) {
                  if( ptr1[ i ][ j ] != AST__BAD ) {
                     good++;
                     axsum += ptr1[ i ][ j ];
                  }
               }
               if( good ) {
                  ptr[ i ][ 0 ] = axsum/good;
               } else {
                  ptr[ i ][ 0 ] = AST__BAD;
               }
            }
         }

/* Transform from the base frame of reg1 to the current frame of reg1,
   then transform using reg1 as a Mapping to determine if it is inside
   reg1. */
         ps3 = astTransform( map_reg1, ps4, 0, NULL );
         ps5 = astTransform( reg1, ps3, 0, NULL );
         ptr = astGetPoints( ps5 );
         inside1 = astOK ? ( ptr[ 0 ][ 0 ] != AST__BAD ) : 0;
         ps3 = astAnnul( ps3 );
         ps5 = astAnnul( ps5 );

/* Transform from the base frame of reg1 to the current frame of reg2,
   then transform using reg2 as a Mapping to determine if it is inside
   reg2. */
         ps3 = astTransform( map, ps4, 0, NULL );
         ps5 = astTransform( reg2, ps3, 0, NULL );
         ptr = astGetPoints( ps5 );
         inside2 = astOK ? ( ptr[ 0 ][ 0 ] != AST__BAD ) : 0;
         ps3 = astAnnul( ps3 );
         ps5 = astAnnul( ps5 );

/* Free the remaining PointSet. */
         ps4 = astAnnul( ps4 );

/* Swap the inside flags if the regions were negated. */
         if( reg1_neg ) inside1 = !inside1;
         if( reg2_neg ) inside2 = !inside2;

/* If both points are inside or both points are outside, reg1 and reg2
   are equivalent, otherwise they are mutually exclusive. */
         result = ( inside1 == inside2 ) ? 5 : 6;

/* If the boundaries of the two Regions are not equivalent. */
      } else {

/* Create a new PointSet containing those points from the mesh which are
   not on the boundary of the first Region. These points are identified by
   the mask array created by the astRegPins method above. */
         reg2_submesh = GetSubMesh( mask, reg2_mesh, status );

/* Transform the points in the submesh of the second Region into the
   current Frame of the first Region. */
         (void ) astAnnul( ps1 );
         ps1 = astTransform( cmap, reg2_submesh, 1, NULL );

/* Transform this submesh using the first Region as a Mapping. Any points
   outside the first region will be set bad in the output PointSet. */
         ps2 = astTransform( (AstMapping *) reg1, ps1, 1, NULL );

/* Get the number of axes and points in this PointSet. */
         nc = astGetNcoord( ps2 );
         np = astGetNpoint( ps2 );

/* Note if there were any common points (i.e. points on the boundary of
   both regions). */
         touch = ( astGetNpoint( reg2_mesh ) != np );

/* Get pointers to the axis data in this PointSet, and check they can be
   used safely. */
         ptr = astGetPoints( ps2 );
         if( astOK ) {

/* Loop round all points checking if the axis values are bad. We want a
   flag saying if there are any good axis values and another flag saying if
   there are any bad axis values. */
            allbad = 1;
            allgood = 1;
            for( iax = 0; iax < nc; iax++ ) {
               p = ptr[ iax ];
               for( ip = 0; ip < np; ip++,p++ ) {
                  if( *p == AST__BAD ) {
                     allgood = 0;
                     if( !allbad ) break;
                  } else {
                     allbad = 0;
                     if( !allgood ) break;
                  }
               }
            }

/* If the entire mesh of the (potentially negated) second Region was either
   on the boundary of, or inside, the (potentially negated) first region,
   determine the result depending on whether the regions have been
   negated and whether they are bounded. Check for impossible states (or
   maybe just errors in my logic). */
            if( allgood ) {

/* Second region has a mesh so it must be bounded. */
               if( !bnd2 && astOK ) {
                     astError( AST__INTER, "astOverlap(%s): Inconsistent "
                               "state 1 (internal AST programming error).",
                               status, astGetClass( this ) );

/* If the first region has been made bounded by negating it... */
               } else if( reg1_neg ) {
                  if( bnd1 ) {

/* If the second region has been made bounded by negating it, then the
   unnegated first region is completely inside the unnegated second region. */
                     if( reg2_neg ) {
                        result = 2;

/* If the second region was bounded without negating it, then there is
   no overlap between the unnegated first region and the second region. */
                     } else {
                        result = 1;
                     }

/* If the first region has been negated then it should not be unbounded.
   This is ensured by the nature of the code that sets the "this_neg" and
   "that_neg" flags above. */
                  } else if( astOK ) {
                     astError( AST__INTER, "astOverlap(%s): Inconsistent "
                               "state 2 (internal AST programming error).",
                               status, astGetClass( this ) );
                  }

/* If the first region was bounded without negating it, but the second
   region was made bounded by negating it, there is partial overlap. */
               } else if( reg2_neg ) {
                  result = 4;

/* If the first region was bounded without negating it, but the second
   region was also bounded without negating it, the second region is
   completely inside the first region. */
               } else {
                  result = 3;
               }

/* If part of the mesh of the second Region was inside the first region,
   and part was outside, then there is partial ocverlap. */
            } else if( !allbad ) {
               result = 4;

/* If no part of the mesh of the (possibly negated) second Region was inside
   the (possibly negated) first region ... */
            } else {

/* First deal with cases where the first region is unbounded. */
               if( !bnd1 ) {
                  if( reg1_neg && astOK ) {
                     astError( AST__INTER, "astOverlap(%s): Inconsistent "
                               "state 5 (internal AST programming error).",
                               status, astGetClass( this ) );
                  } else if( reg2_neg ){
                     result = 2;
                  } else {
                     result = 1;
                  }

/* The second region has a mesh so it must be bounded. */
               } else if( !bnd2 && astOK ) {
                     astError( AST__INTER, "astOverlap(%s): Inconsistent "
                               "state 6 (internal AST programming error).",
                               status, astGetClass( this ) );

/* So now we know both (possibly negated) regions are bounded. */
               } else {

/* We know that none of the reg2 mesh points are inside the bounded reg1.
   But this still leaves two cases: 1) reg1 could be contained completely
   within reg2, or 2) there is no overlap between reg2 and reg1. To
   distinguish between these two cases we use reg2 to transform a point
   on the boundary of reg1. First get a mesh on the boundary of reg1. */
                  reg1_mesh = astRegMesh( reg1 );

/* Transform this mesh into the coordinate system of the second Region. */
                  ps3 = astTransform( cmap, reg1_mesh, 0, NULL );

/* Transform the points in this mesh using the second Region as a Mapping.
   Any points outside the second region will be set bad in the output
   PointSet. */
                  ps4 = astTransform( (AstMapping *) reg2, ps3, 1, NULL );

/* Get pointers to the axis data in this PointSet,and check they can be
   used safely. */
                  ptr = astGetPoints( ps4 );
                  if( astOK ) {

/* Test the firts point and set a flag indicating if we are in case 1 (if
   not, we must be in case 2). */
                     case1 = ( ptr[ 0 ][ 0 ] != AST__BAD );

/* Apply logic similar to the other cases to determine the result. */
                     if( reg1_neg ) {
                        if( case1 == ( reg2_neg != 0 ) ) {
                           result = 3;
                        } else {
                           result = 4;
                        }
                     } else {
                        if( case1 == ( reg2_neg != 0 ) ) {
                           result = 1;
                        } else {
                           result = 2;
                        }
                     }
                  }

/* Free resources. */
                  reg1_mesh = astAnnul( reg1_mesh );
                  ps3 = astAnnul( ps3 );
                  ps4 = astAnnul( ps4 );
               }
	    }
        }

/* If there was no intersection or overlap, but the regions touch, then we
   consider there to be an intersection if either region is closed. */
	if( touch && result == 1 ) {
	   if( astGetClosed( this) || astGetClosed( that ) ) result = 4;
	}

/* Free resources.*/
         reg2_submesh = astAnnul( reg2_submesh );
         ps2 = astAnnul( ps2 );
      }

/* Free resources.*/
      fs = astAnnul( fs );
      bfrm_reg1 = astAnnul( bfrm_reg1 );
      frm_reg1 = astAnnul( frm_reg1 );
      map_reg1 = astAnnul( map_reg1 );
      cmap = astAnnul( cmap );
      map = astAnnul( map );
      ps1 = astAnnul( ps1 );
      reg2_mesh = astAnnul( reg2_mesh );
      unc = astAnnul( unc );
      unc1 = astAnnul( unc1 );
      if( mask) mask = astFree( mask );
   }
   fs0 = astAnnul( fs0 );

/* The returned value should take account of whether "this" or "that" is
   the first Region. If "this" was used as the first Region, then the
   result value calculated above is already correct. If "that" was used as
   the first Region, then we need to change the result to swap "this" and
   "that". */
   if( reg1 == that ) {
      if( result == 2 ) {
         result = 3;
      } else if( result == 3 ) {
         result = 2;
      }
   }

/* Re-instate the original Negated flags. */
   if( this_neg ) astNegate( this );
   if( that_neg ) astNegate( that );

/* If not OK, return zero. */
   if( !astOK ) result = 0;

/* Return the result. */
   return result;
}

static void Overlay( AstFrame *template_frame, const int *template_axes,
                     AstFrame *result, int *status ) {
/*
*  Name:
*     Overlay

*  Purpose:
*     Overlay the attributes of a template Region on to another Frame.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     void Overlay( AstFrame *template, const int *template_axes,
*                   AstFrame *result, int *status )

*  Class Membership:
*     Region member function (over-rides the protected astOverlay
*     method inherited from the Frame class).

*  Description:
*     This function overlays attributes from the current Frame of a
*     Region on to another Frame, so as to over-ride selected
*     attributes of that second Frame. Normally only those attributes
*     which have been specifically set in the template will be
*     transferred. This implements a form of defaulting, in which a
*     Frame acquires attributes from the template, but retains its
*     original attributes (as the default) if new values have not
*     previously been explicitly set in the template.

*  Parameters:
*     template
*        Pointer to the template Region, for whose current Frame
*        values should have been explicitly set for any attribute
*        which is to be transferred.
*     template_axes
*        Pointer to an array of int, with one element for each axis of
*        the "result" Frame (see below). For each axis in the result
*        frame, the corresponding element of this array should contain
*        the (zero-based) index of the axis in the current Frame of
*        the template Region to which it corresponds. This array is
*        used to establish from which template Frame axis any
*        axis-dependent attributes should be obtained.
*
*        If any axis in the result Frame is not associated with a
*        template Frame axis, the corresponding element of this array
*        should be set to -1.
*
*        If a NULL pointer is supplied, the template and result axis
*        indices are assumed to be identical.
*     result
*        Pointer to the Frame which is to receive the new attribute values.
*     status
*        Pointer to the inherited status variable.
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to current Frame */

/* Check the global error status. */
   if ( !astOK ) return;

/* Obtain a pointer to the current Frame in the Region and invoke its
   astOverlay method to overlay its attributes. Annul the Frame pointer
   afterwards. */
   fr = astGetFrame( ((AstRegion *) template_frame)->frameset, AST__CURRENT );
   astOverlay( fr, template_axes, result );
   fr = astAnnul( fr );
}

static void PermAxes( AstFrame *this_frame, const int perm[], int *status ) {
/*
*  Name:
*     PermAxes

*  Purpose:
*     Permute the order of a Region's axes.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     void PermAxes( AstFrame *this, const int perm[], int *status )

*  Class Membership:
*     Region member function (over-rides the astPermAxes method
*     inherited from the Frame class).

*  Description:
*     This function permutes the order in which the axes in the
*     current Frame of a Region occur.

*  Parameters:
*     this
*        Pointer to the Region.
*     perm
*        An array of int (with one element for each axis of the
*        Region's current Frame) which lists the axes in their new
*        order. Each element of this array should be a (zero-based)
*        axis index identifying the axes according to their old
*        (un-permuted) order.
*     status
*        Pointer to the inherited status variable.

*  Notes:
*     - Only genuine permutations of the axis order are permitted, so
*     each axis must be referenced exactly once in the "perm" array.
*     - If more than one axis permutation is applied to the same Frame
*     in a Region, the effects are cumulative.
*/

/* Local Variables: */
   AstRegion *this;              /* Pointer to the Region structure */

/* Check the global error status. */
   if ( !astOK ) return;

/* Obtain a pointer to the Region structure. */
   this = (AstRegion *) this_frame;

/* Invoke the astPermAxes method on the encapsulated FrameSet. */
   astPermAxes( this->frameset, perm );

}

static AstFrame *PickAxes( AstFrame *this_frame, int naxes, const int axes[],
                           AstMapping **map, int *status ) {
/*
*  Name:
*     PickAxes

*  Purpose:
*     Create a new Frame by picking axes from a Region.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     AstFrame *PickAxes( AstFrame *this, int naxes, const int axes[],
*                         AstMapping **map, int *status )

*  Class Membership:
*     Region member function (over-rides the astPickAxes protected
*     method inherited from the Frame class).

*  Description:
*     This function creates a new Frame whose axes are copies of axes
*     picked from the encapsulated Frame of an existing Region. Other
*     Frame attributes are also copied from this existing Frame to the
*     new Frame. Zero or more of the original axes may be picked in
*     any order, but each can be used only once. Additional axes (with
*     default characteristics) may be included in the new Frame if
*     required.
*
*     Optionally, a Mapping that converts between the original Frame's
*     axes and those of the new Frame may also be returned.

*  Parameters:
*     this
*        Pointer to the Region.
*     naxes
*        The number of axes required in the new Frame.
*     axes
*        Pointer to an array of int with naxes elements. This should
*        contain (zero based) axis indices specifying the axes which
*        are to be included in the new Frame, in the order
*        required. Each axis index may occur only once.
*
*        If additional (default) axes are also to be included, the
*        corresponding elements of this array should be set to -1.
*     map
*        Address of a location to receive a pointer to a new
*        Mapping. This will be a PermMap (or a UnitMap as a special
*        case) that describes the axis permutation that has taken
*        place between the current Frame of the Region and the new
*        Frame.  The forward transformation will convert from the
*        original Region's axes to the new one's, and vice versa.
*
*        If this Mapping is not required, a NULL value may be supplied
*        for this parameter.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     Pointer to the new Frame.

*  Notes:
*     - The class of object returned may differ from that of the
*     original current Frame, depending on which axes are
*     selected. For example, if a single axis is picked from a
*     SkyFrame (which always has two axes), the resulting Frame cannot
*     be a valid SkyFrame, so will revert to the parent class (Frame)
*     instead.
*     - The new Frame contains a deep copy of all the data selected
*     from the original current Frame. Modifying the new Frame will
*     therefore not affect the Region or the Frames it contains.
*     - A NULL pointer will be returned if this function is invoked
*     with the global error status set, or if it should fail for any
*     reason.
*/

/* Local Variables: */
   AstFrame *cfrm;            /* Current Frame from input Region */
   AstFrame *frame;           /* Pointer to Frame to be returned */
   AstMapping *cbmap;         /* Base->current Mapping from input Region */
   AstMapping *fsmap;         /* Mapping from selected current to base axes */
   AstRegion *breg;           /* Region spanning selected base Frame axes */
   AstRegion *creg;           /* Region spanning selected current Frame axes */
   AstRegion *this;           /* Pointer to Region structure */
   int *base_axes;            /* Holds selected base frame axis indices */
   int def;                   /* Were any default axes requested? */
   int i;                     /* Axis index */
   int nbase;                 /* No. of selected base Frame axes */

/* Initialise the returned pointers. */
   if ( map ) *map = NULL;
   frame = NULL;

/* Check the global error status. */
   if ( !astOK ) return frame;

/* Obtain a pointer to the Region structure. */
   this = (AstRegion *) this_frame;

/* Check that a valid set of axes is being selected . */
   astValidateAxisSelection( this, naxes, axes, "astPickAxes" );

/* Pick the required axes from the current Frame of the encapsulated
   FrameSet. */
   cfrm = astGetFrame( this->frameset, AST__CURRENT );
   frame = astPickAxes( cfrm, naxes, axes, map );

/* See if any default axes are to be included in the returned Frame. */
   def = 0;
   for( i = 0; i < naxes; i++ ) {
      if( axes[ i ] < 0 ) def = 1;
   }

/* Regions cannot yet include extra default axes in the returned Frame
   so return a basic Frame if any default axes were requested. */
   if( ! def ) {

/* We now see if the requested set of current Frame axes correspond to a
   unique set of base Frame axes. If they do, we may be able to return a
   Region spanning the selected axes rather than just a Frame. The check
   is performed by attempting to split the current->base Mapping. */
      cbmap = astGetMapping( this->frameset, AST__CURRENT, AST__BASE );
      base_axes = astMapSplit( cbmap, naxes, axes, &fsmap );

/* Check the Mapping could be split. */
      if( base_axes ) {

/* Store the number of base Frame axes that correspond to the requested
   set of current Frame axes. */
         nbase = astGetNout( fsmap );

/* Attempt to create a new Region that spans the corresponding set of
   base Frame axes. */
         breg = astRegBasePick( this, nbase, base_axes );
         if( breg ) {

/* Use the split Mapping to map the base Frame region into the requested
   Frame. We invert the "fsmap" first so that it maps the selected base
   Frame axes into the selected current Frame axes. */
            astInvert( fsmap );
            creg = astMapRegion( breg, fsmap, frame );

/* Copy properties from the old Region to the new Region. */
            astRegOverlay( creg, this, 0 );

/* Return this new Region in place of the simple Frame found above. */
            (void) astAnnul( frame );
            frame = (AstFrame *) creg;

/* Free resources */
            breg = astAnnul( breg );
         }
         fsmap = astAnnul( fsmap );
         base_axes = astFree( base_axes );
      }
      cbmap = astAnnul( cbmap );
   }
   cfrm = astAnnul( cfrm );

/* If an error occurred, annul the Mapping pointer (if requested) and
   the new Frame pointer. */
   if ( !astOK ) {
      if ( map ) *map = astAnnul( *map );
      frame = astAnnul( frame );
   }

/* Return the pointer to the new Frame. */
   return frame;
}

static void RegBaseBox( AstRegion *this, double *lbnd, double *ubnd, int *status ){
/*
*+
*  Name:
*     astRegBaseBox

*  Purpose:
*     Returns the bounding box of an un-negated Region in the base Frame of
*     the encapsulated FrameSet.

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     void astRegBaseBox( AstRegion *this, double *lbnd, double *ubnd )

*  Class Membership:
*     Region virtual function.

*  Description:
*     This function returns the upper and lower axis bounds of a Region in
*     the base Frame of the encapsulated FrameSet, assuming the Region
*     has not been negated. That is, the value of the Negated attribute
*     is ignored.

*  Parameters:
*     this
*        Pointer to the Region.
*     lbnd
*        Pointer to an array in which to return the lower axis bounds
*        covered by the Region in the base Frame of the encapsulated
*        FrameSet. It should have at least as many elements as there are
*        axes in the base Frame.
*     ubnd
*        Pointer to an array in which to return the upper axis bounds
*        covered by the Region in the base Frame of the encapsulated
*        FrameSet. It should have at least as many elements as there are
*        axes in the base Frame.

*-
*/

/* Check the inherited status. */
   if( !astOK ) return;

/* This abstract implementation simply reports an error. All sub-classes of
   Region should over-ride this to return appropriate values. */
   astError( AST__NOIMP, "astRegBaseBox(%s): The %s class does not implement "
             "the astRegBaseBox method inherited from the Region class "
             "(internal AST programming error).", status, astGetClass( this ),
             astGetClass( this ) );
}

static void RegBaseBox2( AstRegion *this, double *lbnd, double *ubnd, int *status ){
/*
*+
*  Name:
*     astRegBaseBox2

*  Purpose:
*     Returns the bounding box of an un-negated Region in the base Frame of
*     the encapsulated FrameSet.

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     void astRegBaseBox2( AstRegion *this, double *lbnd, double *ubnd )

*  Class Membership:
*     Region virtual function.

*  Description:
*     This function is similar to astRegBaseBox in that it returns the
*     upper and lower axis bounds of a Region in the base Frame of the
*     encapsulated FrameSet. But, in addition to assuming that the
*     supplied Region has not been negated, it also assumes that any
*     component Regions contained within the supplied Region have not been
*     negated.

*  Parameters:
*     this
*        Pointer to the Region.
*     lbnd
*        Pointer to an array in which to return the lower axis bounds
*        covered by the Region in the base Frame of the encapsulated
*        FrameSet. It should have at least as many elements as there are
*        axes in the base Frame.
*     ubnd
*        Pointer to an array in which to return the upper axis bounds
*        covered by the Region in the base Frame of the encapsulated
*        FrameSet. It should have at least as many elements as there are
*        axes in the base Frame.

*-
*/

/* This base class implementation simply calls astRegBaseBox. Sub-classes
   which contain component Regions should override it. */
   astRegBaseBox( this, lbnd, ubnd );

}

static AstPointSet *RegBaseGrid( AstRegion *this, int *status ){
/*
*+
*  Name:
*     astRegBaseGrid

*  Purpose:
*     Return a PointSet containing points spread through the volume of a
*     Region.

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     AstPointSet *astRegBaseGrid( AstRegion *this )

*  Class Membership:
*     Region virtual function.

*  Description:
*     This function returns a PointSet containing a set of points spread
*     through the volume of the Region. The points refer to the base Frame of
*     the encapsulated FrameSet.

*  Parameters:
*     this
*        Pointer to the Region.

*  Returned Value:
*     Pointer to the PointSet. If the Region is unbounded, a NULL pointer
*     will be returned.

*  Notes:
*    - A NULL pointer is returned if an error has already occurred, or if
*    this function should fail for any reason.
*-
*/

/* Local Variables: */
   AstBox *box;
   AstFrame *frmb;
   AstPointSet *ps1;
   AstPointSet *ps2;
   AstPointSet *result;
   double **ptr2;
   double **ptr;
   double *lbnd;
   double *ubnd;
   int good;
   int ic;
   int ip;
   int ipr;
   int meshsize;
   int naxb;
   int np;
   int npnt2;
   int ntry;

/* Initialise */
   result= NULL;

/* Check the local error status. */
   if ( !astOK ) return NULL;

/* If the Region structure contains a pointer to a PointSet holding
   positions spread over the volume of the Region in the base Frame,
   return it. */
   if( this->basegrid ) {
      result = astClone( this->basegrid );

/* Otherwise, check the Region is bounded. */
   } else if( astGetBounded( this ) ) {

/* Get the original MeshSize attribute. */
      meshsize = astGetMeshSize( this );

/* Get the base Frame bounding box. */
      naxb = astGetNin( this->frameset );
      lbnd = astMalloc( sizeof( double )*(size_t)naxb );
      ubnd = astMalloc( sizeof( double )*(size_t)naxb );
      astRegBaseBox( this, lbnd, ubnd );

/* Create a Box covering this bounding box. */
      frmb = astGetFrame( this->frameset, AST__BASE );
      box = astBox( frmb, 1, lbnd, ubnd, NULL, "", status );

/* Loop until we have a grid of nearly the right size. Make at most three
   attempts. */
      ipr = 0;
      np = meshsize;
      ntry = 0;
      while( ntry++ < 3 ) {

/* Copy the MeshSize attribute to the new Box since this will be used by
   the invocation of astRegBaseGrid below. */
         astSetMeshSize( box, np );

/* Invoke the Box astRegGrid method. Note, the Box class overrides this
   implementation of astRegBaseGrid and does not (must not) invoke this
   implementation, in order to avoid an infinite loop. */
         ps1 = astRegBaseGrid( box );

/* Some of the base Frame points in the above bounding box will fall outside
   the supplied Region. Use the Region as a Mapping to determine which they
   are. Since the points are base Frame points, use astBTransform rather
   than astTransform. */
         ps2 = astBTransform( this, ps1, 1, NULL );

/* We now create a PointSet which is a copy of "ps2" but with all the bad
   points (i.e. the points in the bounding box grid which are not inside
   the supplied Region) removed. Create a result PointSet which is the same
   size as "ps2", then copy just the good points from "ps2" to the result
   PointSet, keeping a record of the number of points copied. */
         ptr2 = astGetPoints( ps2 );
         npnt2 = astGetNpoint( ps2 );
         result = astPointSet( npnt2, naxb, "", status );
         ptr = astGetPoints( result );
         if( astOK ) {

/* Initialise the index of the next point to be stored in "result". */
            ipr = 0;

/* Loop round all points in "ps2" */
            for( ip = 0; ip < npnt2; ip++ ) {

/* Copy each axis value for this point from "ps2" to "result". If a bad
   axis value is encountered, flag that the point is bad and break out of
   the axis loop. */
               good = 1;
               for( ic = 0; ic < naxb; ic++ ) {
                  if( ptr2[ ic ][ ip ] == AST__BAD ) {
                     good = 0;
                     break;
                  } else {
                     ptr[ ic ][ ipr ] = ptr2[ ic ][ ip ];
                  }
               }

/* If the current point has no bad axis values, increment the index of
   the next point to be stored in "result". */
               if( good ) ipr++;
            }
         }

/* Free resources */
         ps1 = astAnnul( ps1 );
         ps2 = astAnnul( ps2 );

/* Leave the loop if an error has occurred. */
         if( !astOK ) break;

/* If the number of points in the grid is within 5% of the target value,
   it is good enough, so break. */
         if( fabs( (double)( ipr - meshsize ) )/meshsize < 0.05 ) break;

/* Otherwise, adjust the target size of the grid by the ratio by which it
   is in error. Don't do this if we have reached the maximum number of
   re-tries. */
         if( ntry < 3 ) {
            if( ipr == 0 ) {
               np *= 10;
            } else {
               np *= (double)meshsize/(double)ipr;
            }
            result = astAnnul( result );
         }
      }

/* Truncate the "result" PointSet to exclude any unused space at the end
   of the axis values arrays. */
      if( astOK ) astSetNpoint( result, ipr );

/* Free resources */
      lbnd = astFree( lbnd );
      ubnd = astFree( ubnd );
      frmb = astAnnul( frmb );
      box = astAnnul( box );

/* Cache the new grid for future use. */
      if( astOK ) this->basegrid = astClone( result );
   }

/* Annul the result if an error occurred. */
   if( !astOK ) result = astAnnul( result );

/* Return the result */
   return result;
}

static AstRegion **RegSplit( AstRegion *this, int *nlist, int *status ){
/*
*+
*  Name:
*     astRegSplit

*  Purpose:
*     Split a Region into a list of disjoint component Regions.

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     AstRegion **astRegSplit( AstRegion *this, int *nlist )

*  Class Membership:
*     Region virtual function.

*  Description:
*     This function splits the supplied Region into a set of disjoint
*     component Regions. If the Region cannot be split, then the returned
*     array contains only one pointer - a clone of the supplied Region
*     pointer.

*  Parameters:
*     this
*        Pointer to the Region.
*     nlist
*        Pointer to an int in which to return the number of elements in
*        the returned array.

*  Returned Value:
*     Pointer to dynamically alloctaed memory holding an array of Region
*     pointers. The length of this array is given by the value returned
*     in "*nlist". The pointers in the returned array should be annulled
*     using astAnnul when no longer needed, and the memory used to hold
*     the array should be freed using astFree.

*  Notes:
*    - A NULL pointer is returned if an error has already occurred, or if
*    this function should fail for any reason.
*-
*/

/* Local Variables; */
   AstRegion **result;

/* Initialise. */
   result = NULL;
   *nlist = 0;

/* Check the local error status. */
   if ( !astOK ) return result;

/* The base class just returns an array containing a clone of the
   supplied Region pointer. */
   result = astMalloc( sizeof( *result ) );
   if( astOK ) {
      result[ 0 ] = astClone( this );
      *nlist = 1;
   }

   if( !astOK ) {
      result = astFree( result );
      *nlist = 0;
   }

   return result;
}

static AstPointSet *RegBaseMesh( AstRegion *this, int *status ){
/*
*+
*  Name:
*     astRegBaseMesh

*  Purpose:
*     Return a PointSet containing points spread around the boundary of a
*     Region.

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     AstPointSet *astRegBaseMesh( AstRegion *this )

*  Class Membership:
*     Region virtual function.

*  Description:
*     This function returns a PointSet containing a set of points on the
*     boundary of the Region. The points refer to the base Frame of
*     the encapsulated FrameSet.

*  Parameters:
*     this
*        Pointer to the Region.

*  Returned Value:
*     Pointer to the PointSet. The axis values in this PointSet will have
*     associated accuracies derived from the uncertainties which were
*     supplied when the Region was created.
*
*    If the Region has no boundary (i.e. is equivalent to a NullRegion), the
*    returned PointSet will contain a single point with a value of AST__BAD
*    on every axis.

*  Notes:
*    - A NULL pointer is returned if an error has already occurred, or if
*    this function should fail for any reason.
*-
*/

/* Check the local error status. */
   if ( !astOK ) return NULL;

/* This abstract method must be over-ridden by each concrete sub-class.
   Report an error if this null imlementation is called.*/
   astError( AST__NOIMP, "astRegBaseMesh(%s): The %s class does not implement "
             "the astRegBaseMesh method inherited from the Region class "
             "(internal AST programming error).", status, astGetClass( this ),
             astGetClass( this ) );
   return NULL;
}

static AstRegion *RegBasePick( AstRegion *this, int naxes, const int *axes,
                               int *status ){
/*
*+
*  Name:
*     astRegBasePick

*  Purpose:
*     Return a Region formed by picking selected base Frame axes from the
*     supplied Region.

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     AstRegion *astRegBasePick( AstRegion *this, int naxes, const int *axes )

*  Class Membership:
*     Region virtual function.

*  Description:
*     This function attempts to return a Region that is spanned by selected
*     axes from the base Frame of the encapsulated FrameSet of the supplied
*     Region. This may or may not be possible, depending on the class of
*     Region. If it is not possible a NULL pointer is returned.

*  Parameters:
*     this
*        Pointer to the Region.
*     naxes
*        The number of base Frame axes to select.
*     axes
*        An array holding the zero-based indices of the base Frame axes
*        that are to be selected.

*  Returned Value:
*     Pointer to the Region, or NULL if no region can be formed.

*  Notes:
*    - This base implementation returns NULL unless all base Frame axes
*    are selected (possibly in a permuted order).
*    - A NULL pointer is returned if an error has already occurred, or if
*    this function should fail for any reason.
*-
*/
/* Local Variables: */
   AstFrame *fr;        /* Pointer to the Region's base Frame */
   AstRegion *result;   /* The returned Region pointer */
   int found;           /* Has the current axis index been found yet? */
   int i;               /* Axis index */
   int j;               /* Index into the "axes" array */
   int nax;             /* No. of base Frame axes */
   int ok;              /* Are we doing a genuine axis permutation? */
   int unit;            /* Is the axis permutation a unit map? */

/* Initialise */
   result = NULL;

/* Check the local error status. */
   if ( !astOK ) return result;

/* Get a pointer to the base Frame int he encapsulated FrameSet. */
   fr = astGetFrame( this->frameset, AST__BASE );

/* See how many axes it has. We only proceed if we are selecting all axes
   in the base Frame. */
   nax = astGetNaxes( fr );
   if( nax == naxes ) {

/* We now check that the axes array is a genuine permutation of all axes.
   This means that all axis indices must occur once, and only once, within
   the "axes" array. Look for each axis index in turn. */
      unit = 1;
      ok = 1;
      for( i = 0; i < nax && ok; i++ ) {

/* Check each element of the axes array to see if it holds the axis index
   currently being looked for. */
         found = 0;
         for( j = 0; j < nax; j++ ) {

/* If so, if this axis index has already been found, break out of the
   loop. */
            if( axes[ j ] == i ) {
               if( found ) {
                  ok = 0;
                  break;
               }
               found = 1;

/* Note if we do not have a unit map (i.e. each axis is permuted onto itself). */
               if( i != j ) unit = 0;
            }
         }

/* If the axis index was not found, we do not have a genuine axis
   permutation. */
         if( !found ) ok = 0;
      }

/* If we have a genuine axis permutation, create a Region which is a copy
   of the supplied region and set it to represent its base Frame. */
      if( ok ) {
         result = astCopy( this );
         astSetRegFS( result, fr );

/* If the axis selection is not equivalent to a unit mapping, we now
   permute the axes. */
         if( !unit ) astPermAxes( result, axes );
      }
   }

/* Free resources. */
   fr = astAnnul( fr );

/* Returned the result. */
   return result;
}

static double *RegCentre( AstRegion *this, double *cen, double **ptr,
                          int index, int ifrm, int *status ){
/*
*+
*  Name:
*     astRegCentre

*  Purpose:
*     Re-centre a Region.

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     double *astRegCentre( AstRegion *this, double *cen, double **ptr,
*                           int index, int ifrm )

*  Class Membership:
*     Region virtual function.

*  Description:
*     This function shifts the centre of the supplied Region to a
*     specified position, or returns the current centre of the Region.

*  Parameters:
*     this
*        Pointer to the Region.
*     cen
*        Pointer to an array of axis values, giving the new centre.
*        Supply a NULL value for this in order to use "ptr" and "index" to
*        specify the new centre.
*     ptr
*        Pointer to an array of pointers, one for each axis in the Region.
*        Each pointer locates an array of axis values. This is the format
*        returned by the PointSet method astGetPoints. Only used if "cen"
*        is NULL.
*     index
*        The index of the point within the arrays identified by "ptr" at
*        which is stored the coords for the new centre position. Only used
*        if "cen" is NULL.
*     ifrm
*        Should be AST__BASE or AST__CURRENT. Indicates whether the centre
*        position is supplied and returned in the base or current Frame of
*        the FrameSet encapsulated within "this".

*  Returned Value:
*     If both "cen" and "ptr" are NULL then a pointer to a newly
*     allocated dynamic array is returned which contains the centre
*     coords of the Region. This array should be freed using astFree when
*     no longer needed. If either of "ptr" or "cen" is not NULL, then a
*     NULL pointer is returned.

*  Notes:
*    - Any bad (AST__BAD) centre axis values are ignored. That is, the
*    centre value on such axes is left unchanged.
*    - Some Region sub-classes do not have a centre. Such classes will report
*    an AST__NOIMP error code if this method is called with either "ptr" or
*    "cen" not NULL. If "ptr" and "cen" are both NULL, then no error is
*    reported if this method is invoked on a Region of an unsuitable class,
*    but NULL is always returned.

*-
*/

/* Local Variables: */
   double *result;

/* Initialise */
   result = NULL;

/* Check the local error status. */
   if ( !astOK ) return result;

/* This abstract method must be over-ridden by each concrete sub-class
   which allows the centre to be shifted. Report an error if this null
   imlementation is called to set a new centre. If it is called to
   enquire the current centre, then return a NULL pointer. */
   if( ptr || cen ) astError( AST__NOIMP, "astRegCentre(%s): The %s "
                       "class does not implement the astRegCentre method "
                       "inherited from the Region class (internal AST "
                       "programming error).", status, astGetClass( this ),
                       astGetClass( this ) );

   return NULL;
}

static void RegClearAttrib( AstRegion *this, const char *aattrib,
                            char **base_attrib, int *status ) {
/*
*+
*  Name:
*     astRegClearAttrib

*  Purpose:
*     Clear an attribute value for a Region.

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     void astRegClearAttrib( AstRegion *this, const char *aattrib,
*                             char **base_attrib )

*  Class Membership:
*     Region virtual function

*  Description:
*     This function clears the value of a named attribute in both the base
*     and current Frame in the FrameSet encapsulated within a Region, without
*     remapping either Frame.
*
*     No error is reported if the attribute is not recognised by the base
*     Frame.

*  Parameters:
*     this
*        Pointer to the Region.
*     aattrib
*        Pointer to a null terminated string holding the attribute name.
*     base_attrib
*        Address of a location at which to return a pointer to the null
*        terminated string holding the attribute name which was cleared in
*        the base Frame of the encapsulated FrameSet. This may differ from
*        the supplied attribute if the supplied attribute contains an axis
*        index and the current->base Mapping in the FrameSet produces an
*        axis permutation. The returned pointer should be freed using
*        astFree when no longer needed. A NULL pointer may be supplied in
*        which case no pointer is returned.
*-
*/

/* Local Variables: */
   AstFrame *frm;
   AstMapping *junkmap;
   AstMapping *map;
   AstRegion *unc;
   char *attrib;
   char *battrib;
   char buf1[ 100 ];
   int *outs;
   int axis;
   int baxis;
   int i;
   int len;
   int nc;
   int rep;

/* Check the global error status. */
   if ( !astOK ) return;

/* Produce a lower case version of the attribute name string */
   nc = strlen( aattrib );
   attrib = astMalloc( nc + 1 );
   for( i = 0; i < nc; i++ ) attrib[ i ] = tolower( aattrib[ i ] );
   attrib[ nc ] = 0;

/* Clear the attribute in the current Frame in the encapsulated FrameSet.
   Use the protected astClearAttrib method which does not cause the Frame
   to be remapped within the FrameSet. */
   frm = astGetFrame( this->frameset, AST__CURRENT );
   astClearAttrib( frm, attrib );
   frm = astAnnul( frm );

/* Indicate that we should use the supplied attribute name  with the base Frame. */
   battrib = NULL;

/* If the attribute name contains an axis number, we need to create a new
   attribute name which refers to the corresponding base Frame axis
   (since the base<->current Mapping may permute the axes). First parse the
   supplied attribute name to locate any axis index. */
   len = strlen( attrib );
   if( nc = 0, ( 2 == astSscanf( attrib, "%[^(](%d) %n", buf1, &axis,
                                 &nc ) ) && ( nc >= len ) ) {

/* If found, convert the axis index from one-based to zero-based. */
      axis--;

/* See if the specified current Frame axis is connected to one and only
   one base Frame axis. If so, get the index of the base Frame axis. */
      map = astGetMapping( this->frameset, AST__CURRENT, AST__BASE );
      outs = astMapSplit( map, 1, &axis, &junkmap );
      if( junkmap && astGetNout( junkmap ) == 1 ) {
         baxis = outs[ 0 ];

/* If the base Frame axis index is different to the current Frame axis
   index, create a new attribute name string using the base Frame axis index. */
         if( baxis != axis ) {
            battrib = astMalloc( strlen( attrib ) + 10 );
            if( battrib ) sprintf( battrib, "%s(%d)", buf1, baxis + 1 );
         }

/* If there is no one base Frame axis which corresponds to the supplied
   current Frame axis, report an error. */
      } else if( astOK ) {
         astError( AST__INTER, "astRegClearAttrib(%s): Unable to clear "
                   "attribute \"%s\" in the base Frame of the %s", status,
                   astGetClass( this ), attrib, astGetClass( this ) );
         astError( AST__INTER, "There is no base Frame axis corresponding "
                   "to current Frame axis %d\n", status, axis + 1 );
      }

/* Free resources */
      outs = astFree( outs );
      if( junkmap ) junkmap = astAnnul( junkmap );
      map = astAnnul( map );
   }

/* Clear the appropriate attribute name in the base Frame. This time ensure
   that any error caused by the attribute name is annulled. Also clear it in
   any uncertainty Region (the current Frame of the uncertainty Region is
   assumed to be equivalent to the base Frame of the parent Region). */
   frm = astGetFrame( this->frameset, AST__BASE );
   if( frm ) {
      rep = astReporting( 0 );
      astClearAttrib( frm, battrib ? battrib : attrib );
      if( astTestUnc( this ) ) {
         unc = astGetUncFrm( this, AST__BASE );
         astRegClearAttrib( unc, battrib ? battrib : attrib, NULL );
         unc = astAnnul( unc );
      }
      if( astStatus == AST__BADAT ) astClearStatus;
      astReporting( rep );
   }
   frm = astAnnul( frm );

/* If required return the modified base Frame attribute name. Otherwise,
   free it. */
   if( base_attrib ) {
      if( battrib ) {
         *base_attrib = battrib;
      } else {
         *base_attrib = astStore( NULL, attrib, strlen( attrib ) + 1 );
      }
   } else {
      battrib = astFree( battrib );
   }

/* Since the base Frame has been changed, any cached information calculated
   on the basis of the base Frame properties may no longer be up to date. */
   astResetCache( this );

/* Free resources. */
   attrib = astFree( attrib );

}

static AstPointSet *RegGrid( AstRegion *this, int *status ){
/*
*+
*  Name:
*     astRegGrid

*  Purpose:
*     Return a PointSet containing points spread through the volume of a
*     Region.

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     AstPointSet *astRegGrid( AstRegion *this )

*  Class Membership:
*     Region virtual function.

*  Description:
*     This function returns a PointSet containing a mesh of points spread
*     throughout the volume of the Region. The points refer to the current
*     Frame of the encapsulated FrameSet.

*  Parameters:
*     this
*        Pointer to the Region.

*  Returned Value:
*     Pointer to the PointSet. The axis values in this PointSet will have
*     associated accuracies derived from the uncertainties which were
*     supplied when the Region was created. Annul the pointer using
*     astAnnul when it is no longer needed.

*  Notes:
*    - It should not be assumed that the returned points are evenly
*    spaced withint he volume.
*    - A NULL pointer is returned if an error has already occurred, or if
*    this function should fail for any reason.
*-
*/

/* Local Variables; */
   AstMapping *map;          /* Base -> current Frame Mapping */
   AstPointSet *result;      /* Pointer to returned PointSet */

/* Initialise the returned pointer */
   result = NULL;

/* Check the local error status. */
   if ( !astOK ) return result;

/* If the Region structure does not contain a pointer to a PointSet holding
   positions evenly spread over the volume of the Region in the base
   Frame, create one now. Note, we cannot cache the grid in the current
   Frame in this way since the current Frame grid depends on the proprties
   of the current Frame (e.g. System) which can be changed at any time.
   astRegBaseGrid stores a pointer for the PointSet in this->basegrid,
   and returns a clone of the pointer, which we do not need so annul it. */
   if( !this->basegrid ) astAnnul( astRegBaseGrid( this ) );

/* Get the simplified base->current Mapping */
   map = astRegMapping( this );

/* If the Mapping is a UnitMap, just return a clone of the PointSet
   pointer stored in the Region structure. */
   if( astIsAUnitMap( map ) ){
      result = astClone( this->basegrid );

/* Otherwise, create a new PointSet holding the above points transformed
   into the current Frame. */
   } else {
      result = astTransform( map, this->basegrid, 1, NULL );
   }

/* Free resources.*/
   map = astAnnul( map );

/* If an error has occurred, annul the returned PointSet. */
   if( !astOK ) result = astAnnul( result );

/* Return the result. */
   return result;
}

static AstPointSet *RegMesh( AstRegion *this, int *status ){
/*
*+
*  Name:
*     astRegMesh

*  Purpose:
*     Return a PointSet containing points spread over the boundary of a
*     Region.

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     AstPointSet *astRegMesh( AstRegion *this )

*  Class Membership:
*     Region virtual function.

*  Description:
*     This function returns a PointSet containing a mesh of points on the
*     boundary of the Region. The points refer to the current Frame of
*     the encapsulated FrameSet.

*  Parameters:
*     this
*        Pointer to the Region.

*  Returned Value:
*     Pointer to the PointSet. The axis values in this PointSet will have
*     associated accuracies derived from the uncertainties which were
*     supplied when the Region was created. Annul the pointer using
*     astAnnul when it is no longer needed.

*  Notes:
*    - It should not be assumed that the returned points are evenly
*    spaced on the boundary.
*    - A NULL pointer is returned if an error has already occurred, or if
*    this function should fail for any reason.
*-
*/

/* Local Variables; */
   AstMapping *map;          /* Base -> current Frame Mapping */
   AstPointSet *bmesh;       /* Base Frame mesh */
   AstPointSet *result;      /* Pointer to returned PointSet */

/* Initialise the returned pointer */
   result = NULL;

/* Check the local error status. */
   if ( !astOK ) return result;

/* Get a pointer to a PointSet holding positions evenly spread over the
   boundary of the Region in the base Frame. */
   bmesh = astRegBaseMesh( this );

/* Get the simplified base->current Mapping */
   map = astRegMapping( this );

/* If the Mapping is a UnitMap, just return a clone of the mesh PointSet
   pointer. */
   if( astIsAUnitMap( map ) ){
      result = astClone( bmesh );

/* Otherwise, create a new PointSet holding the above points transformed
   into the current Frame. */
   } else {
      result = astTransform( map, bmesh, 1, NULL );
   }

/* Free resources.*/
   bmesh = astAnnul( bmesh );
   map = astAnnul( map );

/* If an error has occurred, annul the returned PointSet. */
   if( !astOK ) result = astAnnul( result );

/* Return the result. */
   return result;
}

static int RegDummyFS( AstRegion *this, int *status ){
/*
*+
*  Name:
*     astRegDummyFS

*  Purpose:
*     Check if a Region has a dummy FrameSet.

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     int astRegDummyFS( AstRegion *this )

*  Class Membership:
*     Region virtual function.

*  Description:
*     This function returns a flag indicating if the supplied Region has
*     a dummy FrameSet.
*
*     The astDump method for a Region may choose not to include the
*     Region's FrameSet in the dump, depending on the value of the
*     RegionFS attribute and the nature of the FrameSet. If the FrameSet
*     is omitted from the Dump, then special action has to be taken when
*     the dump is subsequently read in and used to re-create the Region.
*     On encounterting such a dump, the astLoadRegion function will create
*     a dummy FrameSet and associate it with the reconstructed  Region.
*     The new Region should not be used however until this dummy FrameSet
*     has been replaced by the correct FrameSet. Performing this replacement
*     is the responsibility of the parent class (i.e. the class which choose
*     to omit the FrameSet from the dump). These will usually be Region
*     classes which encapsulate other Regions, such as CmpRegion, Prism,
*     Stc, etc.
*
*     This function can be used by astLoad... methods in sub-classes to
*     determine if a newly loaded component Region has a dummy FrameSet. If
*     so the astLoad function should either use the astSetRegFS method to
*     store a new FrameSet in the component Region. If the parent Region
*     itself has a dummy FrameSet (i.e. is a component Region contained
*     within a higher level Region) then it cannot do this and should
*     ignore the presence of the dummy FrameSet (it then becomes the
*     responsibility of hte parent Region to load appropriate FrameSets
*     into all its components).

*  Parameters:
*     this
*        Pointer to the Region.

*  Returned Value:
*     Non-zero if the Region has a dummy FrameSet.

*-
*/

/* Check the inherited status. */
   if( !astOK ) return 0;

/* The Ident attribute of the FrameSet will be set to DUMMY_FS if the
   FrameSet is a dummy. */
   return !strcmp( astGetIdent( this->frameset ), DUMMY_FS );
}

static int RegPins( AstRegion *this, AstPointSet *pset, AstRegion *unc,
                    int **mask, int *status ){
/*
*+
*  Name:
*     astRegPins

*  Purpose:
*     Check if a set of points fall on the boundary of a given Region.

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     int astRegPins( AstRegion *this, AstPointSet *pset, AstRegion *unc,
*                     int **mask )

*  Class Membership:
*     Region virtual function.

*  Description:
*     This function returns a flag indicating if the supplied set of
*     points all fall on the boundary of the given Region.
*
*     Some tolerance is allowed, as specified by the uncertainty Region
*     stored in the supplied Region "this", and the supplied uncertainty
*     Region "unc" which describes the uncertainty of the supplied points.

*  Parameters:
*     this
*        Pointer to the Region.
*     pset
*        Pointer to the PointSet. The points are assumed to refer to the
*        base Frame of the FrameSet encapsulated by "this".
*     unc
*        Pointer to a Region representing the uncertainties in the points
*        given by "pset". The Region is assumed to represent the base Frame
*        of the FrameSet encapsulated by "this". Zero uncertainity is assumed
*        if NULL is supplied.
*     mask
*        Pointer to location at which to return a pointer to a newly
*        allocated dynamic array of ints. The number of elements in this
*        array is equal to the value of the Npoint attribute of "pset".
*        Each element in the returned array is set to 1 if the
*        corresponding position in "pset" is on the boundary of the Region
*        and is set to zero otherwise. A NULL value may be supplied
*        in which case no array is created. If created, the array should
*        be freed using astFree when no longer needed.

*  Returned Value:
*     Non-zero if the points all fall on the boundary of the given
*     Region, to within the tolerance specified. Zero otherwise.

*-
*/

/* Check the inherited status. */
   if( !astOK ) return 0;

/* This abstract implementation simply reports an error. All sub-classes of
   Region should over-ride this to return appropriate values. */
   astError( AST__NOIMP, "astRegPins(%s): The %s class does not implement "
             "the astRegPins method inherited from the Region class "
             "(internal AST programming error).", status, astGetClass( this ),
             astGetClass( this ) );
   return 0;
}

static void GetRegionBounds( AstRegion *this, double *lbnd, double *ubnd, int *status ){
/*
*++
*  Name:
c     astGetRegionBounds
f     AST_GETREGIONBOUNDS

*  Purpose:
*     Returns the bounding box of Region.

*  Type:
*     Public virtual function.

*  Synopsis:
c     #include "region.h"
c     void astGetRegionBounds( AstRegion *this, double *lbnd, double *ubnd )
f     CALL AST_GETREGIONBOUNDS( THIS, LBND, UBND, STATUS )

*  Class Membership:
*     Region method.

*  Description:
c     This function
f     This routine
*     returns the upper and lower limits of a box which just encompasses
*     the supplied Region. The limits are returned as axis values within
*     the Frame represented by the Region. The value of the Negated
*     attribute is ignored (i.e. it is assumed that the Region has not
*     been negated).

*  Parameters:
c     this
f     THIS = INTEGER (Given)
*        Pointer to the Region.
c     lbnd
f     LBND() = DOUBLE PRECISION (Returned)
c        Pointer to an
f        An
*        array in which to return the lower axis bounds covered by the Region.
*        It should have at least as many elements as there are axes in the
*        Region. If an axis has no lower limit, the returned value will
*        be the largest possible negative value.
c     ubnd
f     UBND() = DOUBLE PRECISION (Returned)
c        Pointer to an
f        An
*        array in which to return the upper axis bounds covered by the Region.
*        It should have at least as many elements as there are axes in the
*        Region. If an axis has no upper limit, the returned value will
*        be the largest possible positive value.
f     STATUS = INTEGER (Given and Returned)
f        The global status.

*  Notes:
*    - The value of the Negated attribute is ignored (i.e. it is assumed that
*    the Region has not been negated).
*    - If an axis has no extent on an axis then the lower limit will be
*    returned larger than the upper limit. Note, this is different to an
*    axis which has a constant value (in which case both lower and upper
*    limit will be returned set to the constant value).
*    - If the bounds on an axis cannot be determined, AST__BAD is returned for
*    both upper and lower bounds

*--
*/

/* Local Variables: */
   AstFrame *frm;             /* Current Frame */
   AstMapping *smap;          /* Simplified base -> current Mapping */
   AstPointSet *bmesh;        /* PointSet holding base Frame mesh */
   AstPointSet *cmesh;        /* PointSet holding current Frame mesh */
   double **bptr;             /* Pointer to PointSet coord arrays */
   double **cptr;             /* Pointer to PointSet coord arrays */
   double *blbnd;             /* Lower bounds in base Frame */
   double *bubnd;             /* Upper bounds in base Frame */
   double *p;                 /* Array of values for current axis */
   double width;              /* Width of bounding box on i'th axis */
   int i;                     /* Axis count */
   int ip;                    /* Index of current corner */
   int j;                     /* Timer for low/high swaps */
   int jmax;                  /* Increment between low/high swaps */
   int lo;                    /* Assign low bound to next corner? */
   int nbase;                 /* Number of base Frame axes */
   int ncur;                  /* Number of current Frame axes */
   int npos;                  /* Number of box corners */

/* Check the inherited status. */
   if( !astOK ) return;

/* Get the simplified base to current Mapping. */
   smap = astRegMapping( this );

/* If the simplified Mapping is a UnitMap, just store the base box bounds
   in the returned arrays */
   if( astIsAUnitMap( smap ) ) {
      astRegBaseBox( this, lbnd, ubnd );

/* Otherwise, we get a mesh of points over the boundary of the Region within
   the base Frame, transform them into the current Frame, and find their bounds. */
   } else {

/* If the Region is bounded, we can get a genuine mesh of points on the
   boundary of the Region. */
      if( astGetBounded( this ) ) {
         bmesh = astRegBaseMesh( this );

/* If the Region is not bounded, no mesh can be created so we use the
   corners of the base frame bounding box instead. */
      } else {

/* Get workspace to hold the bounds of the region within the base Frame. */
         nbase = astGetNin( smap );
         blbnd = astMalloc( sizeof( double )*nbase );
         bubnd = astMalloc( sizeof( double )*nbase );

/* Get the base Frame bounding box. */
         astRegBaseBox( this, blbnd, bubnd );

/* Get the number of corners in the base Frame bounding box. */
         npos = pow( 2, nbase );

/* Create a PointSet to hold the positions at the corners in the base
   frame box. */
         bmesh = astPointSet( npos, nbase, " ", status );
         bptr = astGetPoints( bmesh );
         if( bptr ) {

/* Store the coordinates of the box corners in the PointSet. */
            jmax = 1;
            for( i = 0; i < nbase; i++ ) {
               p = bptr[ i ];

               lo = 1;
               j = 0;
               for( ip = 0; ip < npos; ip++,j++ ) {
                  if( j == jmax ) {
                     lo = 1 - lo;
                     j = 0;
                  }
                  p[ ip ] = lo ? blbnd[ i ] : bubnd[ i ];
               }

               jmax *= 2;
            }
         }

/* Release resources. */
         blbnd = astFree( blbnd );
         bubnd = astFree( bubnd );
      }

/* Create a new PointSet holding the above points transformed into the
   current Frame. */
      cmesh = astTransform( smap, bmesh, 1, NULL );

/* There is a possibility that these points may span a singularity in the
   coordinate system such as the RA=0 line in a SkyFrame. So ensure the
   axis values are normalised into the shortest possible range. */
      frm = astGetFrame( this->frameset, AST__CURRENT );
      ncur = astGetNaxes( frm );

      cptr = astGetPoints( cmesh );
      npos = astGetNpoint( cmesh );
      for( i = 0; i < ncur; i++ ) {
         astAxNorm( frm, i+1, 1, npos, cptr[i] );
      }

/* Get the axis bounds of this PointSet. */
      astBndPoints( cmesh, lbnd, ubnd );

/* There is again a possibility that these bounds may span a singularity in
   the coordinate system such as the RA=0 line in a SkyFrame. So for each
   axis we ensure the width (i.e. "ubnd-lbnd" ) is correct. */
      for( i = 0; i < ncur; i++ ) {
         width = astAxDistance( frm, i + 1, lbnd[ i ], ubnd[ i ] );
         if( width != AST__BAD ) {
            ubnd[ i ] = lbnd[ i ] + width;
         } else {
            ubnd[ i ] = AST__BAD;
            lbnd[ i ] = AST__BAD;
         }
      }

/* Release resources. */
      frm = astAnnul( frm );
      bmesh = astAnnul( bmesh );
      cmesh = astAnnul( cmesh );
   }
   smap = astAnnul( smap );
}

static void GetRegionBounds2( AstRegion *this, double *lbnd, double *ubnd, int *status ){
/*
*+
*  Name:
*     astGetRegionBounds

*  Purpose:
*     Returns the bounding box of Region.

*  Type:
*     Protected virtual function.

*  Synopsis:
*     #include "region.h"
*     void astGetRegionBounds2( AstRegion *this, double *lbnd, double *ubnd )

*  Class Membership:
*     Region method.

*  Description:
*     This function is like astGetRegionBounds, in that it returns the upper
*     and lower limits of a box which just encompasses the supplied Region,
*     as axis values within the Frame represented by the Region. But, in
*     addition to assuming that the supplied Region has not been negated, it
*     also assumes that any component Regions contained within the supplied
*     Region have not been negated.

*  Parameters:
*     this
*        Pointer to the Region.
*     lbnd
*        Pointer to an array in which to return the lower axis bounds
*        covered by the Region. It should have at least as many elements
*        as there are axes in the Region.
*     ubnd
*        Pointer to an array in which to return the upper axis bounds
*        covered by the Region. It should have at least as many elements
*        as there are axes in the Region.

*  Notes:
*    - The value of the Negated attribute is ignored (i.e. it is assumed that
*    the Region has not been negated). The Nagated attributes of any
*    component Regions are also ignored.

*-
*/

/* Local Variables: */
   AstMapping *smap;          /* Simplified base -> current Mapping */
   double *lbndb;             /* Pointer to lower bounds on base box */
   double *ubndb;             /* Pointer to upper bounds on base box */
   int i;                     /* Axis count */
   int nbase;                 /* Number of base Frame axes */
   int ncur;                  /* Number of current Frame axes */

/* Check the inherited status. */
   if( !astOK ) return;

/* Find the number of axes in the base and current Frames of the
   encapsulated FrameSet. */
   nbase = astGetNin( this->frameset );
   ncur = astGetNout( this->frameset );

/* Get the bounding box in the base Frame of the encapsulated FrameSet. */
   lbndb = astMalloc( sizeof( double )*(size_t) nbase );
   ubndb = astMalloc( sizeof( double )*(size_t) nbase );
   astRegBaseBox2( this, lbndb, ubndb );

/* Get the simplified base to current Mapping. */
   smap = astRegMapping( this );

/* Check pointers can be used safely. */
   if( smap ) {

/* If the simplified Mapping is a UnitMap, just copy the base box bounds
   to the returned arrays */
      if( astIsAUnitMap( smap ) ) {
         for( i = 0; i < ncur; i++ ) {
            lbnd[ i ] = lbndb[ i ];
            ubnd[ i ] = ubndb[ i ];
         }

/* Otherwise, use astMapBox to find the corresponding current Frame
   limits. */
      } else {
         for( i = 0; i < ncur; i++ ) {
            astMapBox( smap, lbndb, ubndb, 1, i, lbnd + i, ubnd + i,
                       NULL, NULL );
         }
      }
   }

/* Release resources. */
   smap = astAnnul( smap );
   lbndb = astFree( lbndb );
   ubndb = astFree( ubndb );
}

static void GetRegionMesh( AstRegion *this, int surface, int maxpoint,
                           int maxcoord, int *npoint, double *points,
                           int *status ){
/*
*++
*  Name:
c     astGetRegionMesh
f     AST_GETREGIONMESH

*  Purpose:
*     Return a mesh of points covering the surface or volume of a Region.

*  Type:
*     Public virtual function.

*  Synopsis:
c     #include "region.h"
c     void astGetRegionMesh( AstRegion *this, int surface, int maxpoint,
c                            int maxcoord, int *npoint, double *points )
f     CALL AST_GETREGIONMESH( THIS, SURFACE, MAXPOINT, MAXCOORD, NPOINT,
f                             POINTS, STATUS )

*  Class Membership:
*     Region method.

*  Description:
c     This function
f     This routine
*     returns the axis values at a mesh of points either covering the
*     surface (i.e. boundary) of the supplied Region, or filling the
*     interior (i.e. volume) of the Region. The number of points in
*     the mesh is determined by the MeshSize attribute.

*  Parameters:
c     this
f     THIS = INTEGER (Given)
*        Pointer to the Region.
c     surface
f     SURFACE = LOGICAL (Given)
c        If non-zero,
f        If .TRUE.,
*        the returned points will cover the surface or the Region.
*        Otherwise, they will fill the interior of the Region.
c     maxpoint
f     MAXPOINT = INTEGER (Given)
*        If zero, the number of points in the mesh is returned in
c        "*npoint",
f        NPOINT,
*        but no axis values are returned and all other parameters are ignored.
*        If not zero, the supplied value should be the length of the
c        second dimension of the "points"
f        first dimension of the POINTS
*        array. An error is reported if the number of points in the mesh
*        exceeds this number.
c     maxcoord
f     MAXCOORD = INTEGER (Given)
*        The length of the
c        first dimension of the "points" array.
f        second dimension of the POINTS array.
*        An error is reported if the number of axes in the supplied Region
*        exceeds this number.
c     npoint
f     NPOINT = INTEGER (Returned)
c        A pointer to an integer in which to return the
f        The
*        number of points in the returned mesh.
c     points
f     POINTS( MAXPOINT, MAXCOORD ) = DOUBLE PRECISION (Returned)
c        The address of the first element in a 2-dimensional array of
c        shape "[maxcoord][maxpoint]", in which to return the coordinate
c        values at the mesh positions. These are stored such that the
c        value of coordinate number "coord" for point number "point" is
c        found in element "points[coord][point]".
f        An array in which to return the coordinates values at the mesh
f        positions. These are stored such that the value of coordinate
f        number COORD for point number POINT is found in element
f        POINTS(POINT,COORD).
f     STATUS = INTEGER (Given and Returned)
f        The global status.

*  Notes:
*     - An error is reported if the Region is unbounded.
*     - If the coordinate system represented by the Region has been
*     changed since it was first created, the returned axis values refer
*     to the new (changed) coordinate system, rather than the original
*     coordinate system. Note however that if the transformation from
*     original to new coordinate system is non-linear, the shape within
*     the new coordinate system may be distorted, and so may not match
*     that implied by the name of the Region subclass (Circle, Box, etc).

*--
*/

/* Local Variables: */
   AstPointSet *pset;       /* PointSet holding mesh/grid axis values */
   double **ptr;            /* Pointer to mesh/grid axes values */
   double *p;               /* Pointer to next input axis value */
   double *q;               /* Pointer to next output axis value */
   int j;                   /* Axis index */
   int nc;                  /* No. of axes to copy */

/* Initialise */
   *npoint = 0;

/* Check the inherited status. */
   if( !astOK ) return;

/* Report an error if the Region is unbounded. */
   if( !astGetBounded( this ) ) {
      if( astOK ) astError( AST__MBBNF, "astGetRegionMesh(%s): The supplied %s"
                            " is unbounded so no mesh can be created to cover "
                            "it.", status, astGetClass( this ), astGetClass( this ) );
   } else {

/* Get the mesh or grid as required. If only the size of the mesh or grid
   is required, get it in the base Frame as there is no need to spend the
   extra time transforming it into the current Frame. */
      if( maxpoint == 0  ){
         if( surface ) {
            pset = astRegBaseMesh( this );
         } else {
            pset = astRegBaseGrid( this );
         }
      } else {
         if( surface ) {
            pset = astRegMesh( this );
         } else {
            pset = astRegGrid( this );
         }
      }

/* Return the number of points in the mesh or grid. */
      *npoint = astGetNpoint( pset );

/* Do nothing more unless a non-zero array size was supplied. */
      if( *npoint > 0 && maxpoint != 0 && astOK ) {

/* Check the supplied array is large enough. */
         if( *npoint > maxpoint ) {
            astError( AST__DIMIN, "astGetRegionMesh(%s): The supplied "
                      "array can hold up to %d points but the %s supplied "
                      "has %d points on its mesh (programming error).",
                      status, astGetClass( this ), maxpoint, astGetClass( this ),
                      *npoint );
         }

/* Get the dimensionality of the PointSet, and get a pointer to the axis
   values. */
         nc = astGetNcoord( pset );
         ptr = astGetPoints( pset );

/* Check pointers can be used safely. */
         if ( astOK ) {

/* Check the supplied array has room for all the axes. */
            if( nc > maxcoord ) {
               astError( AST__DIMIN, "astGetRegionMesh(%s): The supplied "
                         "array can hold up to %d axes but the %s supplied "
                         "has %d axes (programming error).", status,
                         astGetClass( this ), maxcoord, astGetClass( this ), nc );

/* If all is OK, copy the current Frame axis values into the supplied array. */
            } else {

/* Loop round the axes to be copied. */
               for( j = 0; j < nc; j++ ) {

/* Get points to the first element of the input and output arrays. */
                  p = ptr[ j ];
                  q = points + j*maxpoint;

/* Copying the axis values. */
                  (void) memcpy( q, p, sizeof( double )*( *npoint ) );
               }
            }
         }
      }

/* Free resources. */
      pset = astAnnul( pset );
   }
}

static void GetRegionPoints( AstRegion *this, int maxpoint, int maxcoord,
                             int *npoint, double *points, int *status ){
/*
*++
*  Name:
c     astGetRegionPoints
f     AST_GETREGIONPOINTS

*  Purpose:
*     Returns the positions that define the given Region.

*  Type:
*     Public virtual function.

*  Synopsis:
c     #include "region.h"
c     void astGetRegionPoints( AstRegion *this, int maxpoint, int maxcoord,
c                              int *npoint, double *points )
f     CALL AST_GETREGIONPOINTS( THIS, MAXPOINT, MAXCOORD, NPOINT, POINTS,
f                               STATUS )

*  Class Membership:
*     Region method.

*  Description:
c     This function
f     This routine
*     returns the axis values at the points that define the supplied
*     Region. The particular meaning of these points will depend on the
*     type of class supplied, as listed below under "Applicability:".

*  Parameters:
c     this
f     THIS = INTEGER (Given)
*        Pointer to the Region.
c     maxpoint
f     MAXPOINT = INTEGER (Given)
*        If zero, the number of points needed to define the Region is
*        returned in
c        "*npoint",
f        NPOINT,
*        but no axis values are returned and all other parameters are ignored.
*        If not zero, the supplied value should be the length of the
c        second dimension of the "points"
f        first dimension of the POINTS
*        array. An error is reported if the number of points needed to define
*        the Region exceeds this number.
c     maxcoord
f     MAXCOORD = INTEGER (Given)
*        The length of the
c        first dimension of the "points" array.
f        second dimension of the POINTS array.
*        An error is reported if the number of axes in the supplied Region
*        exceeds this number.
c     npoint
f     NPOINT = INTEGER (Returned)
c        A pointer to an integer in which to return the
f        The
*        number of points defining the Region.
c     points
f     POINTS( MAXPOINT, MAXCOORD ) = DOUBLE PRECISION (Returned)
c        The address of the first element in a 2-dimensional array of
c        shape "[maxcoord][maxpoint]", in which to return
c        the coordinate values at the positions that define the Region.
c        These are stored such that the value of coordinate number
c        "coord" for point number "point" is found in element
c        "points[coord][point]".
f        An array in which to return the coordinates values at the
f        positions that define the Region. These are stored such that the
f        value of coordinate number COORD for point number POINT
f        is found in element POINTS(POINT,COORD).
f     STATUS = INTEGER (Given and Returned)
f        The global status.

*  Applicability:
*     Region
*        All Regions have this attribute.
*     Box
*        The first returned position is the Box centre, and the second is
*        a Box corner.
*     Circle
*        The first returned position is the Circle centre, and the second is
*        a point on the circumference.
*     CmpRegion
*        Returns a value of zero for
c        "*npoint"
f        NPOINT
*        and leaves the supplied array contents unchanged. To find the
*        points defining a CmpRegion, use this method on the component
*        Regions, which can be accessed by invoking
c        astDecompose
f        AST_DECOMPOSE
*        on the CmpRegion.
*     Ellipse
*        The first returned position is the Ellipse centre. The second is
*        the end of one of the axes of the ellipse. The third is some
*        other point on the circumference of the ellipse, distinct from
*        the second point.
*     Interval
*        The first point corresponds to the lower bounds position, and
*        the second point corresponds to the upper bounds position. These
*        are reversed to indicate an extcluded interval rather than an
*        included interval. See the Interval constructor for more
*        information.
*     NullRegion
*        Returns a value of zero for
c        "*npoint"
f        NPOINT
*        and leaves the supplied array contents unchanged.
*     PointList
*        The positions returned are those that were supplied when the
*        PointList was constructed.
*     Polygon
*        The positions returned are the vertex positions that were supplied
*        when the Polygon was constructed.
*     Prism
*        Returns a value of zero for
c        "*npoint"
f        NPOINT
*        and leaves the supplied array contents unchanged. To find the
*        points defining a Prism, use this method on the component
*        Regions, which can be accessed by invoking
c        astDecompose
f        AST_DECOMPOSE
*        on the CmpRegion.

*  Notes:
*     - If the coordinate system represented by the Region has been
*     changed since it was first created, the returned axis values refer
*     to the new (changed) coordinate system, rather than the original
*     coordinate system. Note however that if the transformation from
*     original to new coordinate system is non-linear, the shape within
*     the new coordinate system may be distorted, and so may not match
*     that implied by the name of the Region subclass (Circle, Box, etc).

*--
*/

/* Local Variables: */
   AstPointSet *pset;       /* PointSet holding PointList axis values */
   double **ptr;            /* Pointer to axes values in the PointList */
   double *p;               /* Pointer to next input axis value */
   double *q;               /* Pointer to next output axis value */
   int j;                   /* Axis index */
   int nc;                  /* No. of axes to copy */

/* Initialise */
   *npoint = 0;

/* Check the inherited status. */
   if( !astOK ) return;

/* Return the number of points used to define the Region, if any. */
   *npoint = this->points ? astGetNpoint( this->points ) : 0;

/* Do nothing more unless a non-zero array size was supplied. */
   if( *npoint > 0 && maxpoint != 0 ) {

/* Transform the base Frame axis values into the current Frame. */
      pset = astTransform( this->frameset, this->points, 1, NULL );

/* Get the dimensionality of this PointList, and get a pointer to the axis
   values. */
      nc = astGetNcoord( pset );
      ptr = astGetPoints( pset );

/* Check pointers can be used safely. */
      if ( astOK ) {

/* Check the supplied array has room for all the axis values. */
         if( nc > maxcoord ) {
            astError( AST__DIMIN, "astGetRegionPoints(%s): The supplied "
                      "array can hold up to %d axes but the %s supplied "
                      "has %d axes (programming error).", status,
                      astGetClass( this ), maxcoord, astGetClass( this ), nc );

         } else if( *npoint > maxpoint ) {
            astError( AST__DIMIN, "astGetRegionPoints(%s): The supplied "
                      "array can hold up to %d points but the %s supplied "
                      "requires %d points to describe it (programming "
                      "error).", status, astGetClass( this ), maxpoint,
                       astGetClass( this ), *npoint );

/* If all is OK, copy the transformed axis values into the supplied array. */
         } else {

/* Loop round the axes to be copied. */
            for( j = 0; j < nc; j++ ) {

/* Get points to the first element of the input and output arrays. */
               p = ptr[ j ];
               q = points + j*maxpoint;

/* Copying the axis values. */
               (void) memcpy( q, p, sizeof( double )*( *npoint ) );
            }
         }
      }

/* Free resources. */
      pset = astAnnul( pset );

   }
}

static void GetRegionDisc( AstRegion *this, double centre[2], double *radius,
                           int *status ){
/*
*++
*  Name:
c     astGetRegionDisc
f     AST_GETREGIONDisc

*  Purpose:
*     Returns the centre and radius of a disc containing a 2D Region.

*  Type:
*     Public virtual function.

*  Synopsis:
c     #include "region.h"
c     void GetRegionDisc( AstRegion *this, double centre[3],
c                         double *radius )
f     CALL AST_GETREGIONDISC( THIS, CENTRE, RADIUS, STATUS )

*  Class Membership:
*     Region method.

*  Description:
c     This function
f     This routine
*     returns the centre and radius of a disce that just encloses the
*     supplied 2-dimensional Region. The centre is returned as a pair
*     of axis values within the Frame represented by the Region. The
*     value of the Negated attribute is ignored (i.e. it is assumed
*     that the Region has not been negated).

*  Parameters:
c     this
f     THIS = INTEGER (Given)
*        Pointer to the Region.
c     centre
f     CENTRE( 2 ) = DOUBLE PRECISION (Returned)
c        Pointer to a
f        A
*        two-element array in which to return the axis values at the centre
*        of the bounding disc.
c     radius
f     RADIUS = DOUBLE PRECISION (Returned)
c        Pointer to a variable in which to return the
f        The
*        radius of the bounding disc, as a geodesic distance within the
*        Frame represented by the Region. It will be returned holding
*        AST__BAD If the Region is unbounded.
f     STATUS = INTEGER (Given and Returned)
f        The global status.

*  Notes:
*    - An error is reported if the Region is not 2-dimensional.
*    - The value of the Negated attribute is ignored (i.e. it is assumed that
*    the Region has not been negated).
*    - If the Region is unbounded, the radius will be returned set to
*    AST__BAD and the supplied centre axis values will be returned unchanged.

*--
*/

/* Local Variables: */
   AstPointSet *mesh;
   double **ptr;
   double angle;
   double dist;
   double dx;
   double dxmax;
   double dxmin;
   double dy;
   double dymax;
   double dymin;
   double point1[ 2 ];
   double point2[ 2 ];
   double point3[ 2 ];
   double point4[ 2 ];
   int ipoint;
   int nax;
   int npoint;
   int old_neg;
   int step;

/* Initialise the radius. */
   *radius = AST__BAD;

/* Check the inherited status. */
   if( !astOK ) return;

/* Validate */
   nax = astGetNaxes( this );
   if( nax != 2 ) {
      astError( AST__INVAR, "astGetRegionDisc(%s): Supplied %s is not "
                "2-dimensional.", status, astGetClass( this ),
                astGetClass( this ));
   }

/* Temporarily set the Negated flag to zero. */
   if( astTestNegated( this ) ) {
      old_neg = astGetNegated( this );
   } else {
      old_neg = -100;
   }
   astSetNegated( this, 0 );

/* If the Region is not bounded, return AST__BAD as the radius. */
   if( astGetBounded( this ) ){

/* Get a mesh of points over the boundary of the Region within the
   current Frame. */
      mesh = astRegMesh( this );
      ptr = astGetPoints( mesh );
      if( astOK ) {

/* Since the Region may be defined on the sky, we cannot just find the
   centroid of the mesh points since the axes may not have a flat
   geometry. Instead we form a local coordinate system by choosing an
   arbitrary mesh point as the origin, and then defining a basis vector
   joining this origin with another arbitrary mesh point. The local
   coordinate system is then distance from the origin parallel and
   perpendicular to the basis vector. This is not necessarily a flat
   system, but it should allow us to find the centre of the disk by
   taking the centroid of the mesh points (in the local coordinate
   system). First choose the origin of the local system - the first mesh
   point. */
         point1[ 0 ] = ptr[ 0 ][ 0 ];
         point1[ 1 ] = ptr[ 1 ][ 0 ];

/* Next choose the other end of the basis vector - a point about half way
   round the boundary */
         npoint = astGetNpoint( mesh );
         point2[ 0 ] = ptr[ 0 ][ npoint/2 ];
         point2[ 1 ] = ptr[ 1 ][ npoint/2 ];

/* Check all these axis values are good. */
         if( point1[ 0 ] != AST__BAD && point1[ 1 ] != AST__BAD &&
             point2[ 0 ] != AST__BAD && point2[ 1 ] != AST__BAD ) {

/* No need to use all mesh points (there can be thousands). Choose a step
   length that gives us about two hundred. */
            step = ( npoint > 200 ) ? npoint/200 : 1;

/* Loop over 200ish points in the mesh, maintaining the bounding box of
   the mesh points in the local system. No need to do point 0 since we
   know it is at (0,0) in the local system. */
            dxmax = 0.0;
            dxmin = 0.0;
            dymax = 0.0;
            dymin = 0.0;
            for( ipoint = step; ipoint < npoint; ipoint += step ) {

/* Check the mesh point is good. */
               point3[ 0 ] = ptr[ 0 ][ ipoint ];
               point3[ 1 ] = ptr[ 1 ][ ipoint ];
               if( point3[ 0 ] != AST__BAD && point3[ 1 ] != AST__BAD ) {

/* Resolve the vector from point1 to the current point into two
   components - parallel and perpendicular to the vector from point1 to
   point2. */
                  astResolve( this, point1, point2, point3, point4, &dx, &dy );

/* The dy value returned by astResolve is always positive. Assign it a
   sign depending on the sign of the angle at point4. */
                  if( astAngle( this, point1, point4, point3 ) < 0.0 ) dy = -dy;

/* Record the max and min values of the two components. */
                  dxmax = astMAX( dx, dxmax );
                  dxmin = astMIN( dx, dxmin );
                  dymax = astMAX( dy, dymax );
                  dymin = astMIN( dy, dymin );
               }
            }

/* The centre of the bounding box is a good enough approximation to the
   centre of the bounding disc. Get the centre in the local system. */
            dx = 0.5*( dxmax + dxmin );
            dy = 0.5*( dymax + dymin );

/* Convert to the system of the Region. First get the Region coords of a
   point slightly "north" of point1 (go "north" by a distance equal to
   0.001 of the distance along the basis vector used above). */
            dist = astDistance( this, point1, point2 );
            point3[ 0 ] = point1[ 0 ];
            point3[ 1 ] = point1[ 1 ] + 0.001*dist;

/* Find the angle from "north" to the basis vector. */
            angle = astAngle( this, point3, point1, point2 );

/* Offset away from point1 at the above angle by the local x value of the
   centre. */
            angle = astOffset2( this, point1, angle, dx, point3 );

/* Rotate by 90 degrees and offset away from the above point (point3)
   by the local y value of the centre. This gives us the centre in Region
   coordinates. */
            (void) astOffset2( this, point3, angle - AST__DPIBY2, dy, centre );

/* Now loop round all good points on the mesh and find the maximum distance
   from this centre to any mesh point. */
            *radius = 0.0;
            for( ipoint = 0; ipoint < npoint; ipoint++ ) {
               point3[ 0 ] = ptr[ 0 ][ ipoint ];
               point3[ 1 ] = ptr[ 1 ][ ipoint ];
               dist = astDistance( this, centre, point3 );
               if( dist != AST__BAD ) *radius = astMAX( *radius, dist );
            }

/* Increase the radius by a very small amount to account for possible
   rounding errors. */
            *radius *= 1.000001;
         }
      }

/* Free resources. */
      mesh = astAnnul( mesh );
   }

/* Re-instate the orignal value of the Negated flag. */
   if( old_neg == -100 ) {
      astClearNegated( this );
   } else {
      astSetNegated( this, old_neg );
   }
}

static void RegOverlay( AstRegion *this, AstRegion *that, int unc, int *status ){
/*
*+
*  Name:
*     astRegOverlay

*  Purpose:
*     Copy properties from one Region to another.

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     void astRegOverlay( AstRegion *this, AstRegion *that, int unc )

*  Class Membership:
*     Region virtual function.

*  Description:
*     This function copies selected properties from "that" to "this".
*     It is intended to be called by sub-classes which need to create a
*     similar copy of an existing Region. For instance, subclass
*     implementations of the Simplify method will usually use this
*     function to ensure that the simplified Region loooks like the original
*     Region.

*  Parameters:
*     this
*        Pointer to the new Region.
*     that
*        Pointer to the old Region.
*     unc
*        If non-zero, any uncertainty in "this" is cleared if "that" has
*        no uncertainty. If zero, any uncertainty in "this" is left
*        unchanged.
*-
*/

/* Check the inherited status. */
   if( !astOK ) return;

/* Copy the required attribute values. */
   this->negated = that->negated;
   this->closed = that->closed;
   this->regionfs = that->regionfs;
   this->adaptive = that->adaptive;

/* Clear things that depend on the number of axes. */
   if( astGetNaxes( this ) == astGetNaxes( that ) ) {
      if( astTestMeshSize( that ) ) astSetMeshSize( this, astGetMeshSize( that ) );
      if( astTestFillFactor( that ) ) astSetFillFactor( this, astGetFillFactor( that ) );
   } else {
      astClearMeshSize( this );
      astClearFillFactor( this );
   }

/* If required, clear uncertainty in "this" if "that" has no uncertainty. */
   if( unc && !astTestUnc( that ) ) astClearUnc( this );

}

static void RegSetAttrib( AstRegion *this, const char *asetting,
                          char **base_setting, int *status ) {
/*
*+
*  Name:
*     astRegSetAttrib

*  Purpose:
*     Set an attribute value for a Region.

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     void astRegSetAttrib( AstRegion *this, const char *asetting,
*                           char **base_setting )

*  Class Membership:
*     Region virtual function

*  Description:
*     This function assigns an attribute value to both the base and
*     current Frame in the FrameSet encapsulated within a Region, without
*     remapping either Frame.
*
*     No error is reported if the attribute is not recognised by the base
*     Frame.

*  Parameters:
*     this
*        Pointer to the Region.
*     asetting
*        Pointer to a null terminated attribute setting string. The supplied
*        string will be interpreted using the public interpretation
*        implemented by astSetAttrib. This can be different to the
*        interpretation of the protected accessor functions. For instance,
*        the public interpretation of an unqualified floating point value for
*        the Epoch attribute is to interpet the value as a gregorian year,
*        but the protected interpretation is to interpret the value as an
*        MJD.
*     base_setting
*        Address of a location at which to return a pointer to the null
*        terminated attribute setting string which was applied to the
*        base Frame of the encapsulated FrameSet. This may differ from
*        the supplied setting if the supplied setting contains an axis
*        index and the current->base Mapping in the FrameSet produces an
*        axis permutation. The returned pointer should be freed using
*        astFree when no longer needed. A NULL pointer may be supplied in
*        which case no pointer is returned.
*-
*/

/* Local Variables: */
   AstFrame *frm;
   AstMapping *junkmap;
   AstMapping *map;
   AstRegion *unc;
   char *setting;
   char *bsetting;
   char buf1[ 100 ];
   int *outs;
   int axis;
   int baxis;
   int i;
   int len;
   int nc;
   int rep;
   int value;

/* Check the global error status. */
   if ( !astOK ) return;

/* Produce a lower case version of the setting string */
   nc = strlen( asetting );
   setting = astMalloc( nc + 1 );
   for( i = 0; i < nc; i++ ) setting[ i ] = tolower( asetting[ i ] );
   setting[ nc ] = 0;

/* Apply the setting to the current Frame in the encapsulated FrameSet.
   Use the protected astSetAttrib method which does not cause the Frame
   to be remapped within the FrameSet. */
   frm = astGetFrame( this->frameset, AST__CURRENT );
   astSetAttrib( frm, setting );
   frm = astAnnul( frm );

/* Indicate that we should use the supplied setting with the base Frame. */
   bsetting = NULL;

/* If the attribute name contains an axis number, we need to create a new
   attribute setting which refers to the corresponding base Frame axis
   (since the base<->current Mapping may permute the axes). First parse the
   supplied attribute setting to locate any axis index. */
   len = strlen( setting );
   if( nc = 0, ( 2 == astSscanf( setting, "%[^(](%d)= %n%*s %n", buf1, &axis,
                                 &value, &nc ) ) && ( nc >= len ) ) {

/* If found, convert the axis index from one-based to zero-based. */
      axis--;

/* See if the specified current Frame axis is connected to one and only
   one base Frame axis. If so, get the index of the base Frame axis. */
      map = astGetMapping( this->frameset, AST__CURRENT, AST__BASE );
      outs = astMapSplit( map, 1, &axis, &junkmap );
      if( junkmap && astGetNout( junkmap ) == 1 ) {
         baxis = outs[ 0 ];

/* If the base Frame axis index is different to the current Frame axis
   index, create a new setting string using the base Frame axis index. */
         if( baxis != axis ) {
            bsetting = astMalloc( strlen( setting ) + 10 );
            if( bsetting ) {
               sprintf( bsetting, "%s(%d)=%s", buf1, baxis + 1, setting + value );
            }
         }

/* If there is no one base Frame axis which corresponds to the supplied
   current Frame axis, report an error. */
      } else if( astOK ) {
         astError( AST__INTER, "astRegSetAttrib(%s): Unable to apply "
                   "attribute setting \"%s\" to the base Frame in the %s", status,
                   astGetClass( this ), setting, astGetClass( this ) );
         astError( AST__INTER, "There is no base Frame axis corresponding "
                   "to current Frame axis %d\n", status, axis + 1 );
      }

/* Free resources */
      outs = astFree( outs );
      if( junkmap ) junkmap = astAnnul( junkmap );
      map = astAnnul( map );
   }

/* Apply the appropriate attribute setting to the base Frame. This time
   ensure that any error caused by the attribute setting is annulled.
   Also apply it to any uncertainty Region (the current Frame of the
   uncertainty Region is assumed to be equivalent to the base Frame of the
   parent Region). */
   frm = astGetFrame( this->frameset, AST__BASE );
   if( frm ) {
      rep = astReporting( 0 );
      astSetAttrib( frm, bsetting ? bsetting : setting );
      if( astTestUnc( this ) ) {
         unc = astGetUncFrm( this, AST__BASE );
         astRegSetAttrib( unc, bsetting ? bsetting : setting, NULL );
         unc = astAnnul( unc );
      }
      if( astStatus == AST__BADAT ) astClearStatus;
      astReporting( rep );
   }
   frm = astAnnul( frm );

/* If required return the modified base Frame setting. Otherwise, free it. */
   if( base_setting ) {
      if( bsetting ) {
         *base_setting = bsetting;
      } else {
         *base_setting = astStore( NULL, setting, strlen( setting ) + 1 );
      }
   } else {
      bsetting = astFree( bsetting );
   }

/* Since the base Frame has been changed, any cached information calculated
   on the basis of the base Frame properties may no longer be up to date. */
   astResetCache( this );

/* Free resources. */
   setting = astFree( setting );

}

static AstMapping *RemoveRegions( AstMapping *this_mapping, int *status ) {
/*
*  Name:
*     RemoveRegions

*  Purpose:
*     Remove any Regions from a Mapping.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     AstMapping *RemoveRegions( AstMapping *this, int *status )

*  Class Membership:
*     Region method (over-rides the astRemoveRegions method inherited
*     from the Frame class).

*  Description:
*     This function searches the supplied Mapping (which may be a
*     compound Mapping such as a CmpMap) for any component Mappings
*     that are instances of the AST Region class. It then creates a new
*     Mapping from which all Regions have been removed. If a Region
*     cannot simply be removed (for instance, if it is a component of a
*     parallel CmpMap), then it is replaced with an equivalent UnitMap
*     in the returned Mapping.
*
*     The implementation provided by the Region class just returns the
*     equivalent Frame.

*  Parameters:
*     this
*        Pointer to the original Region.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     A pointer to the modified mapping.

*  Notes:
*     - A NULL pointer value will be returned if this function is
*     invoked with the AST error status set, or if it should fail for
*     any reason.
*/

/* The Region class just returns a pointer to a deep copy of the Region's
   equivalent Frame. */
   return astGetRegionFrame( (AstRegion *)this_mapping );
}

static void ReportPoints( AstMapping *this_mapping, int forward,
                          AstPointSet *in_points, AstPointSet *out_points, int *status ) {
/*
*  Name:
*     ReportPoints

*  Purpose:
*     Report the effect of transforming a set of points using a Region.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     void ReportPoints( AstMapping *this, int forward,
*                        AstPointSet *in_points, AstPointSet *out_points, int *status )

*  Class Membership:
*     Region member function (over-rides the protected astReportPoints
*     method inherited from the Frame class).

*  Description:
*     This function reports the coordinates of a set of points before
*     and after being transformed by a Region, by writing them to
*     standard output.

*  Parameters:
*     this
*        Pointer to the Region.
*     forward
*        A non-zero value indicates that the Region's forward
*        coordinate transformation has been applied, while a zero
*        value indicates the inverse transformation.
*     in_points
*        Pointer to a PointSet which is associated with the
*        coordinates of a set of points before the Region was
*        applied.
*     out_points
*        Pointer to a PointSet which is associated with the
*        coordinates of the same set of points after the Region has
*        been applied.
*     status
*        Pointer to the inherited status variable.
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to current Frame */
   AstRegion *this;              /* Pointer to the Region structure */

/* Check the global error status. */
   if ( !astOK ) return;

/* Obtain a pointer to the Region structure. */
   this = (AstRegion *) this_mapping;

/* Obtain a pointer to the Region's current Frame and invoke its
   astReportPoints method. Annul the Frame pointer afterwards. */
   fr = astGetFrame( this->frameset, AST__CURRENT );
   astReportPoints( (AstMapping *) fr, forward, in_points, out_points );
   fr = astAnnul( fr );

}

static void ResetCache( AstRegion *this, int *status ){
/*
*+
*  Name:
*     astResetCache

*  Purpose:
*     Clear cached information within the supplied Region.

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     void astResetCache( AstRegion *this )

*  Class Membership:
*     Region virtual function

*  Description:
*     This function clears cached information from the supplied Region
*     structure.

*  Parameters:
*     this
*        Pointer to the Region.
*-
*/
   if( this ) {
      if( this->basemesh ) this->basemesh = astAnnul( this->basemesh );
      if( this->basegrid ) this->basegrid = astAnnul( this->basegrid );
      if( this->negation ) this->negation = astAnnul( this->negation );
   }
}


static void Resolve( AstFrame *this_frame, const double point1[],
                     const double point2[], const double point3[],
                     double point4[], double *d1, double *d2, int *status ){
/*
*  Name:
*     Resolve

*  Purpose:
*     Resolve a vector into two orthogonal components

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     void Resolve( AstFrame *this, const double point1[],
*                   const double point2[], const double point3[],
*                   double point4[], double *d1, double *d2, int *status );

*  Class Membership:
*     Region member function (over-rides the protected astResolve
*     method inherited from the Frame class).

*  Description:
*     This function resolves a vector into two perpendicular components.
*     The vector from point 1 to point 2 is used as the basis vector.
*     The vector from point 1 to point 3 is resolved into components
*     parallel and perpendicular to this basis vector. The lengths of the
*     two components are returned, together with the position of closest
*     aproach of the basis vector to point 3.

*  Parameters:
*     this
*        Pointer to the Frame.
*     point1
*        An array of double, with one element for each Frame axis
*        (Naxes attribute). This marks the start of the basis vector,
*        and of the vector to be resolved.
*     point2
*        An array of double, with one element for each Frame axis
*        (Naxes attribute). This marks the end of the basis vector.
*     point3
*        An array of double, with one element for each Frame axis
*        (Naxes attribute). This marks the end of the vector to be
*        resolved.
*     point4
*        An array of double, with one element for each Frame axis
*        in which the coordinates of the point of closest approach of the
*        basis vector to point 3 will be returned.
*     d1
*        The address of a location at which to return the distance from
*        point 1 to point 4 (that is, the length of the component parallel
*        to the basis vector). Positive values are in the same sense as
*        movement from point 1 to point 2.
*     d2
*        The address of a location at which to return the distance from
*        point 4 to point 3 (that is, the length of the component
*        perpendicular to the basis vector). The value is always positive.
*     status
*        Pointer to the inherited status variable.

*  Notes:
*     - Each vector used in this function is the path of
*     shortest distance between two points, as defined by the
*     astDistance function.
*     - This function will return "bad" coordinate values (AST__BAD)
*     if any of the input coordinates has this value, or if the required
*     output values are undefined.
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to current Frame */
   AstRegion *this;              /* Pointer to the Region structure */

/* Check the global error status. */
   if ( !astOK ) return;

/* Obtain a pointer to the Region structure. */
   this = (AstRegion *) this_frame;

/* Obtain a pointer to the Region's encapsulated Frame and invoke this
   Frame's astResolve method. Annul the Frame pointer afterwards. */
   fr = astGetFrame( this->frameset, AST__CURRENT );
   astResolve( fr, point1, point2, point3, point4, d1, d2 );
   fr = astAnnul( fr );

}

static AstPointSet *ResolvePoints( AstFrame *this_frame, const double point1[],
                                   const double point2[], AstPointSet *in,
                                   AstPointSet *out, int *status ) {
/*
*  Name:
*     ResolvePoints

*  Purpose:
*     Resolve a set of vectors into orthogonal components

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     AstPointSet *ResolvePoints( AstFrame *this, const double point1[],
*                                 const double point2[], AstPointSet *in,
*                                 AstPointSet *out )

*  Class Membership:
*     Region member function (over-rides the astResolvePoints method
*     inherited from the Frame class).

*  Description:
*     This function takes a Frame and a set of vectors encapsulated
*     in a PointSet, and resolves each one into two orthogonal components,
*     returning these two components in another PointSet.
*
*     This is exactly the same as the public astResolve method, except
*     that this method allows many vectors to be processed in a single call,
*     thus reducing the computational cost of overheads of many
*     individual calls to astResolve.

*  Parameters:
*     this
*        Pointer to the Frame.
*     point1
*        An array of double, with one element for each Frame axis
*        (Naxes attribute). This marks the start of the basis vector,
*        and of the vectors to be resolved.
*     point2
*        An array of double, with one element for each Frame axis
*        (Naxes attribute). This marks the end of the basis vector.
*     in
*        Pointer to the PointSet holding the ends of the vectors to be
*        resolved.
*     out
*        Pointer to a PointSet which will hold the length of the two
*        resolved components. A NULL value may also be given, in which
*        case a new PointSet will be created by this function.

*  Returned Value:
*     Pointer to the output (possibly new) PointSet. The first axis will
*     hold the lengths of the vector components parallel to the basis vector.
*     These values will be signed (positive values are in the same sense as
*     movement from point 1 to point 2. The second axis will hold the lengths
*     of the vector components perpendicular to the basis vector. These
*     values will always be positive.

*  Notes:
*     - The number of coordinate values per point in the input
*     PointSet must match the number of axes in the supplied Frame.
*     - If an output PointSet is supplied, it must have space for
*     sufficient number of points and 2 coordinate values per point.
*     - A null pointer will be returned if this function is invoked
*     with the global error status set, or if it should fail for any
*     reason.
*/

/* Local Variables: */
   AstPointSet *result;          /* Pointer to output PointSet */
   AstFrame *fr;                 /* Pointer to current Frame */
   AstRegion *this;              /* Pointer to the Region structure */

/* Initialise. */
   result = NULL;

/* Check the global error status. */
   if ( !astOK ) return result;

/* Obtain a pointer to the Region structure. */
   this = (AstRegion *) this_frame;

/* Obtain a pointer to the Region's encapsulated Frame and invoke this
   Frame's astResolve method. Annul the Frame pointer afterwards. */
   fr = astGetFrame( this->frameset, AST__CURRENT );
   result = astResolvePoints( fr, point1, point2, in, out );
   fr = astAnnul( fr );

/* Return a pointer to the output PointSet. */
   return result;

}

static void SetAttrib( AstObject *this_object, const char *setting, int *status ) {
/*
*  Name:
*     SetAttrib

*  Purpose:
*     Set an attribute value for a Region.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     void SetAttrib( AstObject *this, const char *setting, int *status )

*  Class Membership:
*     Region member function (extends the astSetAttrib method
*     inherited from the Frame class).

*  Description:
*     This function assigns an attribute value for a Region, the
*     attribute and its value being specified by means of a string of
*     the form:
*
*        "attribute= value "
*
*     Here, "attribute" specifies the attribute name and should be in
*     lower case with no white space present. The value to the right
*     of the "=" should be a suitable textual representation of the
*     value to be assigned and this will be interpreted according to
*     the attribute's data type.  White space surrounding the value is
*     only significant for string attributes.

*  Parameters:
*     this
*        Pointer to the Region.
*     setting
*        Pointer to a null terminated string specifying the new
*        attribute value.
*     status
*        Pointer to the inherited status variable.

*  Notes:
*     - This protected method is intended to be invoked by the Object
*     astSet method and makes additional attributes accessible to it.
*/

/* Local Variables: */
   AstRegion *this;              /* Pointer to the Region structure */
   double dval;                  /* Floating point attribute value */
   int ival;                     /* Integer attribute value */
   int id;                       /* Offset of ID string */
   int len;                      /* Length of setting string */
   int nc;                       /* Number of characters read by astSscanf */

/* Check the global error status. */
   if ( !astOK ) return;

/* Obtain a pointer to the Region structure. */
   this = (AstRegion *) this_object;

/* Obtain the length of the setting string. */
   len = strlen( setting );

/* Test for each recognised attribute in turn, using "astSscanf" to parse the
   setting string and extract the attribute value (or an offset to it in the
   case of string values). In each case, use the value set in "nc" to check
   that the entire string was matched. Once a value has been obtained, use the
   appropriate method to set it. */

/* We first handle attributes that apply to the Region as a whole
   (rather than to the encapsulated Frame). */

/* Negated */
/* ------- */
   if ( nc = 0,
        ( 1 == astSscanf( setting, "negated= %d %n", &ival, &nc ) )
          && ( nc >= len ) ) {
      astSetNegated( this, ival );

/* Closed */
/*------- */
   } else if ( nc = 0,
        ( 1 == astSscanf( setting, "closed= %d %n", &ival, &nc ) )
          && ( nc >= len ) ) {
      astSetClosed( this, ival );

/* FillFactor */
/* ---------- */
   } else if ( nc = 0,
        ( 1 == astSscanf( setting, "fillfactor= %lg %n", &dval, &nc ) )
        && ( nc >= len ) ) {
      astSetFillFactor( this, dval );

/* MeshSize */
/* -------- */
   } else if ( nc = 0,
        ( 1 == astSscanf( setting, "meshsize= %d %n", &ival, &nc ) )
          && ( nc >= len ) ) {
      astSetMeshSize( this, ival );

/* Adaptive */
/* -------- */
   } else if ( nc = 0,
        ( 1 == astSscanf( setting, "adaptive= %d %n", &ival, &nc ) )
          && ( nc >= len ) ) {
      astSetAdaptive( this, ival );

/* Now do attributes inherited from parent classes. We do these here to
   avoid the settings being passed on to the encapsulated FrameSet below. */

/* ID. */
/* --- */
   } else if ( nc = 0, ( 0 == astSscanf( setting, "id=%n%*[^\n]%n", &id, &nc ) )
                       && ( nc >= len ) ) {
      astSetID( this, setting + id );

/* Ident. */
/* ------ */
   } else if ( nc = 0, ( 0 == astSscanf( setting, "ident=%n%*[^\n]%n", &id, &nc ) )
                       && ( nc >= len ) ) {
      astSetIdent( this, setting + id );

/* Invert. */
/* ------- */
   } else if ( nc = 0,
        ( 1 == astSscanf( setting, "invert= %d %n", &ival, &nc ) )
        && ( nc >= len ) ) {
      astSetInvert( this, ival );

/* Report. */
/* ------- */
   } else if ( nc = 0,
        ( 1 == astSscanf( setting, "report= %d %n", &ival, &nc ) )
        && ( nc >= len ) ) {
      astSetReport( this, ival );

/* Define macros to see if the setting string matches any of the
   read-only attributes of this class. */
#define MATCH(attrib) \
        ( nc = 0, ( 0 == astSscanf( setting, attrib "=%*[^\n]%n", &nc ) ) && \
                  ( nc >= len ) )

#define AXISMATCH(attrib) \
        ( nc = 0, ( 0 == astSscanf( setting, attrib "(%*d)=%*[^\n]%n", &nc ) ) && \
                  ( nc >= len ) )

/* If the attribute was not recognised, use this macro to report an error
   if a read-only attribute has been specified. */
   } else if ( MATCH( "class" ) ||
               MATCH( "nin" ) ||
               MATCH( "nobject" ) ||
               MATCH( "bounded" ) ||
               MATCH( "nout" ) ||
               MATCH( "refcount" ) ||
               MATCH( "tranforward" ) ||
               MATCH( "traninverse" ) ) {
      astError( AST__NOWRT, "astSet: The setting \"%s\" is invalid for a %s.", status,
                setting, astGetClass( this ) );
      astError( AST__NOWRT, "This is a read-only attribute." , status);

/* Pass unrecognised attributes on to the Region's encapsulated FrameSet for
   further interpretation. Do not pass on FrameSet attributes since we
   pretend to the outside world that the encapsulated FrameSet is actually a
   Frame. */
   } else if ( !MATCH( "base" ) &&
               !MATCH( "current" ) &&
               !MATCH( "nframe" ) ) {

/* If the Region is to adapt to coordinate system chanmges, use the public
   astSet method so that the current Frame in the encapsulated FrameSet will
   be re-mapped if the attribute changes require it. */
      if( astGetAdaptive( this ) ) {
         astSet( this->frameset, setting, status );

/* If the Region is not to adapt to coordinate system chanmges, use the
   astRegSetAttrib method which assigns the attribute setting to both
   current and base Frames in the FrameSet without causing any remapping to
   be performed. */
      } else {
         astRegSetAttrib( this, setting, NULL );
      }
   }

/* Undefine macros local to this function. */
#undef MATCH
}

static void SetAxis( AstFrame *this_frame, int axis, AstAxis *newaxis, int *status ) {
/*
*  Name:
*     SetAxis

*  Purpose:
*     Set a new Axis for a Region.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     void SetAxis( AstFrame *this, int axis, AstAxis *newaxis, int *status )

*  Class Membership:
*     Region member function (over-rides the astSetAxis method
*     inherited from the Frame class).

*  Description:
*     This function allows a new Axis object to be associated with one
*     of the axes of the current Frame in a Region, replacing the
*     previous one. Each Axis object contains a description of the
*     quantity represented along one of the Frame's axes, so this
*     function allows this description to be exchanged for another
*     one.

*  Parameters:
*     this
*        Pointer to the Region.
*     axis
*        The index (zero-based) of the axis whose associated Axis
*        object is to be replaced.
*     newaxis
*        Pointer to the new Axis object.
*     status
*        Pointer to the inherited status variable.
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to current Frame */
   AstRegion *this;              /* Pointer to the Region structure */

/* Check the global error status. */
   if ( !astOK ) return;

/* Obtain a pointer to the Region structure. */
   this = (AstRegion *) this_frame;

/* Validate the axis index supplied. */
   (void) astValidateAxis( this, axis, 1, "astSetAxis" );

/* Obtain a pointer to the Region's current Frame and invoke this
   Frame's astSetAxis method to assign the new Axis object. Annul the
   Frame pointer afterwards. */
   fr = astGetFrame( this->frameset, AST__CURRENT );
   astSetAxis( fr, axis, newaxis );
   fr = astAnnul( fr );
}

static void SetRegFS( AstRegion *this, AstFrame *frm, int *status ) {
/*
*+
*  Name:
*     astSetRegFS

*  Purpose:
*     Stores a new FrameSet in a Region

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     void astSetRegFS( AstRegion *this, AstFrame *frm )

*  Class Membership:
*     Region virtual function.

*  Description:
*     This function creates a new FrameSet and stores it in the supplied
*     Region. The new FrameSet contains two copies of the supplied
*     Frame, connected by a UnitMap.

*  Parameters:
*     this
*        Pointer to the Region.
*     frm
*        The Frame to use.
*-
*/

/* Local Variables: */
   AstFrame *f1;         /* Copy of supplied Frame */
   AstFrame *f2;         /* Copy of supplied Frame */
   AstFrameSet *fs;      /* New FrameSet */
   AstRegion *unc;       /* Uncertainty Region */
   AstUnitMap *um;       /* UnitMap connecting base anc current Frames */

/* Check the global error status. */
   if ( !astOK ) return;

/* Take a copy of the supplied Frame. */
   f1 = astCopy( frm );

/* Create the new FrameSet. First take another copy of the supplied Frame
   so that modifications using the supplied pointer will not affect the new
   FrameSet. We create two copies (rather than 1) because the base and
   current Frames must be independant objects - otherwise attribute changes
   done to one will also appear in the other. Then construct the FrameSet
   containing the two Frame copies connected by a UnitMap. */
   f2 = astCopy( f1 );
   fs = astFrameSet( f1, "", status );
   um = astUnitMap( astGetNaxes( f1 ), "", status );
   astAddFrame( fs, AST__BASE, um, f2 );
   um = astAnnul( um );
   f2 = astAnnul( f2 );

/* Annul any existing FrameSet */
   if( this->frameset ) (void) astAnnul( this->frameset );

/* Use the new FrameSet */
   this->frameset = fs;

/* If any uncertainty Region has a zero value for its RegionFS attribute,
   it will currently contain a dummy FrameSet rather than the correct
   FrameSet. The correct FrameSet has copies of the base Frame of the new
   Region as both its current and base Frames, and these are connected by
   a UnitMap (this is equivalent to a FrameSet containing a single Frame). */
   if( astTestUnc( this ) ) {
      unc = astGetUncFrm( this, AST__BASE );
      if( unc && !astGetRegionFS( unc ) ) astSetRegFS( unc, f1 );
      unc = astAnnul( unc );
   }

/* Free remaining resourvces */
   f1 = astAnnul( f1 );

}

static void SetUnc( AstRegion *this, AstRegion *unc, int *status ){
/*
*++
*  Name:
c     astSetUnc
f     AST_SETUNC

*  Purpose:
*     Store uncertainty information in a Region.

*  Type:
*     Public virtual function.

*  Synopsis:
c     #include "region.h"
c     void astSetUnc( AstRegion *this, AstRegion *unc )
f     CALL AST_SETUNC( THIS, UNC, STATUS )

*  Class Membership:
*     Region method.

*  Description:
*     Each Region (of any class) can have an "uncertainty" which specifies
*     the uncertainties associated with the boundary of the Region. This
*     information is supplied in the form of a second Region. The uncertainty
*     in any point on the boundary of a Region is found by shifting the
*     associated "uncertainty" Region so that it is centred at the boundary
*     point being considered. The area covered by the shifted uncertainty
*     Region then represents the uncertainty in the boundary position.
*     The uncertainty is assumed to be the same for all points.
*
*     The uncertainty is usually specified when the Region is created, but
*     this
c     function
f     routine
*     allows it to be changed at any time.

*  Parameters:
c     this
f     THIS = INTEGER (Given)
*        Pointer to the Region which is to be assigned a new uncertainty.
c     unc
f     UNC = INTEGER (Given)
*        Pointer to the new uncertainty Region. This must be of a class for
*        which all instances are centro-symetric (e.g. Box, Circle, Ellipse,
*        etc.) or be a Prism containing centro-symetric component Regions.
*        A deep copy of the supplied Region will be taken, so subsequent
*        changes to the uncertainty Region using the supplied pointer will
*        have no effect on the Region
c        "this".
f        THIS.
f     STATUS = INTEGER (Given and Returned)
f        The global status.

*--
*/

/* Local Variables: */
   AstFrame *frm;           /* Current Frame from FrameSet */
   AstFrameSet *fs2;        /* FrameSet from "unc" current Frame to "this" base Frame */
   AstFrameSet *fs;         /* FrameSet in "this" supplied Region */
   AstMapping *map2;        /* Base->current Mapping from FrameSet */
   AstMapping *map;         /* Base->current Mapping from FrameSet */
   AstMapping *smap;        /* Simplified base->current Mapping */
   double *cen0;            /* Pointer to array holding original centre */
   double **ptr_reg;        /* Pointer to axis values for Region's Pointset */
   int changed;             /* Has the uncertainty been changed? */

/* Check the inherited status. */
   if( !astOK ) return;

/* Annul any existing uncertainty Region. */
   if( this->unc ) {
      this->unc = astIsAObject( this->unc ) ?
                                astAnnul( this->unc ) : NULL;
      changed = 1;
   } else {
      changed = 0;
   }

/* Check an uncertainty Region was supplied, and is of a usable class
   (i.e. a class which can be re-centred). */
   cen0 = unc ? astRegCentre( unc, NULL, NULL, 0, AST__CURRENT ) : NULL;
   if( cen0 ) {
      cen0 = astFree( cen0 );

/* Map it into the same Frame as that represented by the base Frame in
   the supplied Region. */
      fs = this->frameset;
      astInvert( fs );
      fs2 = Conv( unc->frameset, fs, status );
      astInvert( fs );

      if( fs2 ) {
         map = astGetMapping( fs2, AST__BASE, AST__CURRENT );
         frm = astGetFrame( fs2, AST__CURRENT );
         this->unc = astMapRegion( unc, map, frm );
         if( this->unc ) {

/* Ensure the Region is bounded. We know that negating an unbounded
   Region will make it bounded because we know that the Region consists of
   Circles, Boxes and/or Ellipses, all of which have this property. */
            if( !astGetBounded( this->unc ) ) astNegate( this->unc );

/* If the base Frame in the uncertainty Region is the same as the base
   Frame in the Region being dumped, then we do no need to include the
   FrameSet in the dump of the uncertainty Region. Since the current
   Frame in the uncertainty Region always corresponds to the base Frame of
   its parent Region, we only need to check if the base->current Mapping
   in the uncertainty Region's FrameSet is a UnitMap or not (after
   simplification). If it is, set the RegionFS attribute of the uncertainty
   Region to zero (i.e. false). This will cause the FrameSet to be omitted
   from the Dump. */
            map2 = astGetMapping( this->unc->frameset, AST__BASE, AST__CURRENT );
            smap = astSimplify( map2 );
            if( astIsAUnitMap( smap ) ) astSetRegionFS( this->unc, 0 );

/* Re-centre the uncertainty Region at the first position in the PointSet
   associated with the Region structure (if any). */
            if( this->points ) {
               ptr_reg = astGetPoints( this->points );
               astRegCentre( this->unc, NULL, ptr_reg, 0, AST__CURRENT );
            }

/* Set a flag indicating that the uncertainty in the Region has changed. */
            changed = 1;

/* Free resources */
            map2 = astAnnul( map2 );
            smap = astAnnul( smap );
         }
         frm = astAnnul( frm );
         fs2 = astAnnul( fs2 );
         map = astAnnul( map );

/* Report error if conversion between Frames is not possible. */
      } else if( astOK ) {
         astError( AST__BADIN, "astSetUnc(%s): Bad %d dimensional "
                   "uncertainty Frame (%s %s) supplied.", status, astGetClass(this),
                   astGetNaxes(unc), astGetDomain(unc), astGetTitle(unc) );
         astError( AST__NCPIN, "Cannot convert it to the Frame of the "
                   "new %s.", status, astGetClass( this ) );
      }

/* Report an error if it is not of a usable class. */
   } else if( unc && astOK ){
      astError( AST__BADIN, "astSetUnc(%s): Bad uncertainty shape "
                "(%s) supplied.", status, astGetClass( this ), astGetClass(unc) );
      astError( AST__NCPIN, "The uncertainty Region must be an instance of "
                "a centro-symetric subclass of Region (e.g. Box, Circle, "
                "Ellipse, etc)." , status);
   }

/* If the uncertainty in the Region has changed, indicate that any cached
   information in the Region is now out of date. */
   if( changed ) astResetCache( this );

}

static void ShowMesh( AstRegion *this, int format, const char *ttl, int *status ){
/*
*++
*  Name:
c     astShowMesh
f     AST_SHOWMESH

*  Purpose:
*     Display a mesh of points covering the surface of a Region.

*  Type:
*     Public virtual function.

*  Synopsis:
c     #include "region.h"
c     void astShowMesh( AstRegion *this, int format, const char *ttl )
f     CALL AST_SHOWMESH( THIS, FORMAT, TTL, STATUS )

*  Class Membership:
*     Region method.

*  Description:
c     This function
f     This routine
*     writes a table to standard output containing the axis values at a
*     mesh of points covering the surface of the supplied Region. Each row
*     of output contains a tab-separated list of axis values, one for
*     each axis in the Frame encapsulated by the Region. The number of
*     points in the mesh is determined by the MeshSize attribute.
*
*     The table is preceded by a given title string, and followed by a
*     single line containing the word "ENDMESH".

*  Parameters:
c     this
f     THIS = INTEGER (Given)
*        Pointer to the Region.
c     format
f     FORMAT = LOGICAL (Given)
*        A boolean value indicating if the displayed axis values should
*        be formatted according to the Format attribute associated with
*        the Frame's axis. Otherwise, they are displayed as simple
*        floating point values.
c     ttl
f     TTL = CHARACTER * ( * ) (Given)
*        A title to display before displaying the first position.
f     STATUS = INTEGER (Given and Returned)
f        The global status.

*--
*/

/* Local Variables: */
   AstPointSet *ps;           /* PointSet holding mesh */
   char *buffer = NULL;       /* Buffer for line output text */
   char buf[ 40 ];            /* Buffer for floating poitn value */
   double **ptr;              /* Pointers to the mesh data */
   int i;                     /* Axis index */
   int j;                     /* Position index */
   int nax;                   /* Number of axes */
   int nc;                    /* Number of characters in buffer */
   int np;                    /* Number of axis values per position */

/* Check the inherited status. */
   if( !astOK ) return;

/* Get a PointSet holding the mesh */
   ps = astRegMesh( this );
   if( ps ) {

/* Get the number of axis values per position, and the number of positions. */
      nax = astGetNcoord( ps );
      np = astGetNpoint( ps );

/* Get a pointer to the mesh data, and check it can be used. */
      ptr = astGetPoints( ps );
      if( ptr ) {

/* Display the title. */
         if( ttl ) printf( "\n%s\n\n", ttl );

/* Loop round all positions. */
         for( j = 0; j < np; j++ ) {

/* Reset the current buffer length to zero. */
            nc = 0;

/* Loop round all axes */
            for( i = 0; i < nax; i++ ){

/* If the axis value is bad, append "<bad> in the end of the output buffer. */
               if( ptr[ i ][ j ] == AST__BAD ){
                  buffer = astAppendString( buffer, &nc, "<bad>" );

/* Otherwise, if required, append the formatted value to the end of the
   buffer. */
               } else if( format ){
                  buffer = astAppendString( buffer, &nc,
                                         astFormat( this, i, ptr[ i ][ j ] ) );

/* Otherwise, append the floating point value to the end of the buffer. */
               } else {
                  sprintf( buf, "%g", ptr[ i ][ j ] );
                  buffer = astAppendString( buffer, &nc, buf );
               }
/* Add a separating tab to the end of the buffer. */
               buffer = astAppendString( buffer, &nc, "\t" );
            }

/* Display the line buffer. */
            printf( "%s\n", buffer );
         }
      }

/* Print out a marker for th eend of the list. */
      printf( "ENDMESH\n\n" );

/* Release resources. */
      ps = astAnnul( ps );
      buffer = astFree( buffer );
   }
}

static AstMapping *Simplify( AstMapping *this_mapping, int *status ) {
/*
*  Name:
*     Simplify

*  Purpose:
*     Simplify the Mapping represented by a Region.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     AstMapping *Simplify( AstMapping *this, int *status )

*  Class Membership:
*     Region method (over-rides the astSimplify method inherited
*     from the Frame class).

*  Description:
*     This function simplifies the encapsulated FrameSet and any
*     uncertainty Region in the supplied Region. This is different to
*     the Simplify method in the parent Frame class which always returns
*     a UnitMap.

*  Parameters:
*     this
*        Pointer to the original Region.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     A pointer to the simplified Region. A cloned pointer to the
*     supplied Region will be returned if no simplication could be
*     performed.

*  Notes:
*     - This implementation just simplifies the encapsulated FrameSet
*     and uncertainty Region. Sub-classes should usually provide their own
*     implementation which invokes this implemetation, and then continues to
*     check for further simplifications (such as fitting a new region to the
*     current Frame).
*     - A NULL pointer value will be returned if this function is
*     invoked with the AST error status set, or if it should fail for
*     any reason.
*/

/* Local Variables: */
   AstFrame *bfrm;               /* Pointer to "this" baseFrame */
   AstFrameSet *fs;              /* Pointer to encapsulated FrameSet */
   AstMapping *map;              /* Base->current Mapping for "this" */
   AstMapping *result;           /* Result pointer to return */
   AstPointSet *pset1;           /* Base Frame centre position */
   AstPointSet *pset2;           /* Current Frame centre position */
   AstRegion *new;               /* Pointer to simplified Region */
   AstRegion *sunc;              /* Simplified uncertainty Region */
   AstRegion *this;              /* Pointer to original Region structure */
   AstRegion *unc;               /* Original uncertainty Region */
   double **ptr1;                /* Pointer to axis values in "pset1" */
   double *cen;                  /* Original centre of uncertainty Region */
   double *lbnd;                 /* Lower bounds of "this" bounding box */
   double *orig_cen;             /* Original centre for uncertainty Region */
   double *s1_lbnd;              /* Lower bounds of "unc" when centred at lbnd */
   double *s1_ubnd;              /* Upper bounds of "unc" when centred at lbnd */
   double *s2_lbnd;              /* Lower bounds of "unc" when centred at ubnd */
   double *s2_ubnd;              /* Upper bounds of "unc" when centred at ubnd */
   double *ubnd;                 /* Upper bounds of "this" bounding box */
   double delta;                 /* Half width of test box */
   double w1;                    /* Width of "s1" bounding box */
   double w2;                    /* Width of "s2" bounding box */
   int ic;                       /* Axis index */
   int naxb;                     /* No. of base Frame axes in "this" */
   int nin;                      /* Number of base Frame axes in "this" */
   int nout;                     /* Number of current Frame axes in "this" */
   int ok;                       /* Can we use the simplified uncertainty? */
   int simpler;                  /* Has some simplication taken place? */

/* Initialise. */
   result = NULL;

/* Check the global error status. */
   if ( !astOK ) return result;

/* Obtain a pointer to the Region structure. */
   this = (AstRegion *) this_mapping;

/* Take a deep copy of the supplied Region. This is so that the returned
   pointer will have a diferent value to the supplied pointer if any
   simplication takes place. */
   new = astCopy( this );

/* Simplify the encapsulated FrameSet, and note if any simplification took
   place. */
   fs = astSimplify( new->frameset );
   simpler = ( fs != new->frameset );

/* If so, annull the existing FrameSet and use the simpler FrameSet. */
   if( simpler ) {
      (void) astAnnul( new->frameset );
      new->frameset = astClone( fs );
   }
   fs = astAnnul( fs );

/* If the Region has default uncertainty, we simplify the uncertainty
   Region simply by deleting it. It will be regenerated when needed,
   using the simplified Region. */
   if( new->defunc ) new->defunc = astAnnul( new->defunc );

/* If the Region's uncertainty was supplied explicitly, try simplifying
   the unncertainty Region. */
   if( astTestUnc( new ) ){

/* Obtain the Region's uncertainty. */
      unc = astGetUncFrm( new, AST__BASE );

/* Get the base->current Mapping from "this". */
      map = astGetMapping( this->frameset, AST__BASE, AST__CURRENT );

/* If it has different numbers of inputs and outputs (e.g. a PermMap used
   to take a slice through a Region), we need to ensure that the
   uncertainty Region is centred on the slice. */
      nin = astGetNin( map );
      nout = astGetNout( map );
      if( nin != nout ) {

/* Get the current centre of the uncertainty Region in its current Frame
   (the same as the base Frame of "this"). */
         cen = astRegCentre( unc, NULL, NULL, 0, AST__CURRENT );

/* Store it in a PointSet so it can be transformed. */
         pset1 = astPointSet( 1, nin, "", status );
         ptr1 = astGetPoints( pset1 );
         if( astOK ) for( ic = 0; ic < nin; ic++ ) ptr1[ ic ][ 0 ] = cen[ ic ];

/* Transform into the curent Frame of "this", and then back into the base
   Frame. */
         pset2 = astTransform( map, pset1, 1, NULL );
         (void) astTransform( map, pset2, 0, pset1 );

/* Re-centre the uncertainty Region at this position. */
         astRegCentre( unc, NULL, ptr1, 0, AST__CURRENT );

/* Free resources. */
         cen = astFree( cen );
         pset1 = astAnnul( pset1 );
         pset2 = astAnnul( pset2 );
      }

/* Free resources. */
      map = astAnnul( map );

/* Try simplifying the uncertainty. Only proceed if the uncertainty can
   be simplified. */
      sunc = astSimplify( unc );
      if( sunc != unc ) {

/* If the uncertainty can be simplified it means that the base->current
   Mapping in the uncertainty Region is sufficiently linear to allow the
   uncertainty shape to retain its form when transformed from the base to
   the current Frane. But this has only been tested at the current centre
   position in the uncertainty Region. The uncertainty Region should
   describe the whole of "this" Region, and so we need to check that the
   simplified uncertainty does not change as we move it around within "this"
   Region. To do this, we re-centre the uncertainty region at opposite
   corners of a large test box, and then we find the bounding box of the
   re-centred uncertainty Region. If this uncertainty bounding box changes
   from corner to corner of the test box, then we do not simplify the
   uncertainty Region. If "this" is bounded, we use the bounding box of
   "this" as the test box. Otherwise we use a box 100 times the size of the
   uncertainty Region. */

/* Note the original base Frame centre of the simplified uncertainty Region. */
         orig_cen = astRegCentre( sunc, NULL, NULL, 0, AST__BASE );

/* Allocate memory to hold the bounds of the test box. */
         naxb = astGetNin( this->frameset );
         lbnd = astMalloc( sizeof( double )*(size_t)naxb );
         ubnd = astMalloc( sizeof( double )*(size_t)naxb );

/* If possible, get the base Frame bounding box of "this" and use it as
   the test box. */
         if( astGetBounded( this ) ) {
            astRegBaseBox( this, lbnd, ubnd );

/* Otherwise, store the bounds of a box which is 100 times the size of
   the uncertainty region, centred on the current centre of the uncertainty
   region (we know all uncertainty regions are bounded). */
         } else {
            astGetRegionBounds( sunc, lbnd, ubnd );
            for( ic = 0; ic < naxb; ic++ ) {
               delta = 0.5*fabs( ubnd[ ic ] - lbnd[ ic ] );
               lbnd[ ic ] = orig_cen[ ic ] - delta;
               ubnd[ ic ] = orig_cen[ ic ] + delta;
            }
         }

/* Re-centre it at the lower bounds of the test box. This is in the base Frame
   of "this" which is the same as the current Frame of "sunc". */
         astRegCentre( sunc, lbnd, NULL, 0, AST__CURRENT );

/* Get the bounding box of the re-centred uncertainty Region, within its
   current Frame, which is the same as the base Frame of "this". */
         s1_lbnd = astMalloc( sizeof( double )*(size_t)naxb );
         s1_ubnd = astMalloc( sizeof( double )*(size_t)naxb );
         astGetRegionBounds( sunc, s1_lbnd, s1_ubnd );

/* Now re-centre the uncertainty Region at the upper bounds of the test
   box. */
         astRegCentre( sunc, ubnd, NULL, 0, AST__CURRENT );

/* Get the bounding box of the re-centred uncertainty Region. */
         s2_lbnd = astMalloc( sizeof( double )*(size_t)naxb );
         s2_ubnd = astMalloc( sizeof( double )*(size_t)naxb );
         astGetRegionBounds( sunc, s2_lbnd, s2_ubnd );

/* Get a pointer to the base Frame of "this". */
         bfrm = astGetFrame( this->frameset, AST__BASE );

/* The "ok" flag is initialised to indicate that the simplified uncertainty
   Region should not be used. */
         ok = 0;

/* Check pointers can be referenced safely */
         if( astOK ) {

/* Now indicate that the simplified uncertainty Region should be used. */
            ok = 1;

/* Loop round all axes of the base Frame of "this". */
            for( ic = 0; ic < naxb; ic++ ) {

/* Get the width of the two bounding boxes on this axis. */
               w1 = s1_ubnd[ ic ] - s1_lbnd[ ic ];
               w2 = s2_ubnd[ ic ] - s2_lbnd[ ic ];

/* If these differ by more than 0.1% then we determine that the simplified
   uncertainty Region varies in size across the bounding box of "this", and
   so we do not use the simplified uncertainty Region. The figure of 0.1%
   is arbitrary. */
               if( fabs( w1 - w2 ) > 0.005*( fabs( w1 ) + fabs( w2 ) ) ) {
                  ok = 0;
                  break;
               }
            }
         }

/* Reinstate the original base Frame centre of the simplified uncertainty Region. */
         astRegCentre( sunc, orig_cen, NULL, 0, AST__BASE );

/* Free resources. */
         orig_cen = astFree( orig_cen );
         lbnd = astFree( lbnd );
         ubnd = astFree( ubnd );
         s1_lbnd = astFree( s1_lbnd );
         s1_ubnd = astFree( s1_ubnd );
         s2_lbnd = astFree( s2_lbnd );
         s2_ubnd = astFree( s2_ubnd );
         bfrm = astAnnul( bfrm );

/* If we can use the simplified uncertainty Region, indicate that we have
   performed some simplification, and store the new uncertainty Region. */
         if( ok ) {
            simpler = 1;
            astSetUnc( new, sunc );
         }
      }

/* Free resources */
      unc = astAnnul( unc );
      sunc = astAnnul( sunc );
   }

/* If any simplification could be performed, return the new Region.
   Otherwise, return a clone of the supplied pointer. */
   if( simpler ){
      result = (AstMapping *) new;
   } else {
      new = astAnnul( new );
      result = astClone( this );
   }

/* If an error occurred, annul the returned pointer. */
   if ( !astOK ) result = astAnnul( result );

/* Return the result. */
   return result;
}

static int SubFrame( AstFrame *this_frame, AstFrame *template,
                     int result_naxes,
                     const int *target_axes, const int *template_axes,
                     AstMapping **map, AstFrame **result, int *status ) {
/*
*  Name:
*     SubFrame

*  Purpose:
*     Select axes from a Region and convert to the new coordinate system.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     int SubFrame( AstFrame *target, AstFrame *template, int result_naxes,
*                   const int *target_axes, const int *template_axes,
*                   AstMapping **map, AstFrame **result, int *status )

*  Class Membership:
*     Region member function (over-rides the protected astSubFrame
*     method inherited from the Frame class).

*  Description:
*     This function selects a requested sub-set (or super-set) of the
*     axes from the current Frame of a "target" Region and creates a
*     new Frame with copies of the selected axes assembled in the
*     requested order. It then optionally overlays the attributes of a
*     "template" Frame on to the result. It returns both the resulting
*     Frame and a Mapping that describes how to convert between the
*     coordinate systems described by the current Frame of the target
*     Region and the result Frame. If necessary, this Mapping takes
*     account of any differences in the Frames' attributes due to the
*     influence of the template.

*  Parameters:
*     target
*        Pointer to the target Region, from whose current Frame the
*        axes are to be selected.
*     template
*        Pointer to the template Frame, from which new attributes for
*        the result Frame are to be obtained. Optionally, this may be
*        NULL, in which case no overlaying of template attributes will
*        be performed.
*     result_naxes
*        Number of axes to be selected from the target Region. This
*        number may be greater than or less than the number of axes in
*        the Region's current Frame (or equal).
*     target_axes
*        Pointer to an array of int with result_naxes elements, giving
*        a list of the (zero-based) axis indices of the axes to be
*        selected from the current Frame of the target Region. The
*        order in which these are given determines the order in which
*        the axes appear in the result Frame. If any of the values in
*        this array is set to -1, the corresponding result axis will
*        not be derived from the target Region, but will be assigned
*        default attributes instead.
*     template_axes
*        Pointer to an array of int with result_naxes elements. This
*        should contain a list of the template axes (given as
*        zero-based axis indices) with which the axes of the result
*        Frame are to be associated. This array determines which axes
*        are used when overlaying axis-dependent attributes of the
*        template on to the result. If any element of this array is
*        set to -1, the corresponding result axis will not receive any
*        template attributes.
*
*        If the template argument is given as NULL, this array is not
*        used and a NULL pointer may also be supplied here.
*     map
*        Address of a location to receive a pointer to the returned
*        Mapping.  The forward transformation of this Mapping will
*        describe how to convert coordinates from the coordinate
*        system described by the current Frame of the target Region
*        to that described by the result Frame. The inverse
*        transformation will convert in the opposite direction.
*     result
*        Address of a location to receive a pointer to the result Frame.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     A non-zero value is returned if coordinate conversion is
*     possible between the current Frame of the target Region and
*     the result Frame. Otherwise zero is returned and *map and
*     *result are returned as NULL (but this will not in itself result
*     in an error condition). In general, coordinate conversion should
*     always be possible if no template Frame is supplied but may not
*     always be possible otherwise.

*  Notes:
*     - A value of zero will be returned if this function is invoked
*     with the global error status set, or if it should fail for any
*     reason.
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to Region's current Frame */
   int match;                    /* Result to be returned */

/* Initialise. */
   *map = NULL;
   *result = NULL;
   match = 0;

/* Check the global error status. */
   if ( !astOK ) return match;

/* Invoke the parent astSubFrame method on the Frame represented by the
   region. */
   fr = astGetFrame( ((AstRegion *) this_frame)->frameset, AST__CURRENT );
   match = astSubFrame( fr, template, result_naxes, target_axes, template_axes,
                        map, result );
   fr = astAnnul( fr );

/* Return the result. */
   return match;
}

static AstSystemType SystemCode( AstFrame *this_frame, const char *system, int *status ) {
/*
*  Name:
*     SystemCode

*  Purpose:
*     Convert a string into a coordinate system type code.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     AstSystemType SystemCode( AstFrame *this, const char *system, int *status )

*  Class Membership:
*     Region member function (over-rides the protected astSystemCode
*     method inherited from the Frame class).

*  Description:
*     This function converts a string used for the external description of
*     a coordinate system into a Frame coordinate system type code (System
*     attribute value). It is the inverse of the astSystemString function.

*  Parameters:
*     this
*        Pointer to the Frame.
*     system
*        Pointer to a constant null-terminated string containing the
*        external description of the coordinate system.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     The System type code.

*  Notes:
*     - A value of AST__BADSYSTEM is returned if the coordinate system
*     description was not recognised. This does not produce an error.
*     - A value of AST__BADSYSTEM is also returned if this function
*     is invoked with the global error status set or if it should fail
*     for any reason.
*/

/* Local Variables: */
   AstSystemType result;      /* Result value to return */
   AstFrame *fr;              /* Pointer to FrameSet's current Frame */
   AstRegion *this;           /* Pointer to the Region structure */

/* Initialise. */
   result = AST__BADSYSTEM;

/* Check the global error status. */
   if ( !astOK ) return result;

/* Obtain a pointer to the FrameSet structure. */
   this = (AstRegion *) this_frame;

/* Obtain a pointer to the Region's encapsulated Frame and invoke the
   astSystemCode method for this Frame. Annul the Frame pointer afterwards. */
   fr = astGetFrame( this->frameset, AST__CURRENT );
   result = astSystemCode( fr, system );
   fr = astAnnul( fr );

/* If an error occurred, clear the result value. */
   if ( !astOK ) result = AST__BADSYSTEM;

/* Return the result. */
   return result;
}

static const char *SystemString( AstFrame *this_frame, AstSystemType system, int *status ) {
/*
*  Name:
*     SystemString

*  Purpose:
*     Convert a coordinate system type code into a string.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     const char *SystemString( AstFrame *this, AstSystemType system, int *status )

*  Class Membership:
*     Region member function (over-rides the protected astSystemString
*     method inherited from the Frame class).

*  Description:
*     This function converts a Frame coordinate system type code
*     (System attribute value) into a string suitable for use as an
*     external representation of the coordinate system type.

*  Parameters:
*     this
*        Pointer to the Frame.
*     system
*        The coordinate system type code.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     Pointer to a constant null-terminated string containing the
*     textual equivalent of the type code supplied.

*  Notes:
*     - A NULL pointer value is returned if the coordinate system
*     code was not recognised. This does not produce an error.
*     - A NULL pointer value is also returned if this function is
*     invoked with the global error status set or if it should fail
*     for any reason.
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to FrameSet's current Frame */
   AstRegion *this;              /* Pointer to the Region structure */
   const char *result;           /* Pointer value to return */

/* Initialise. */
   result = NULL;

/* Check the global error status. */
   if ( !astOK ) return result;

/* Obtain a pointer to the FrameSet structure. */
   this = (AstRegion *) this_frame;

/* Obtain a pointer to the Region's encapsulated Frame and invoke the
   astSystemString method for this Frame. Annul the Frame pointer
   afterwards. */
   fr = astGetFrame( this->frameset, AST__CURRENT );
   result = astSystemString( fr, system );
   fr = astAnnul( fr );

/* If an error occurred, clear the result value. */
   if ( !astOK ) result = NULL;

/* Return the result pointer. */
   return result;

}

static int RegTrace( AstRegion *this, int n, double *dist, double **ptr, int *status ){
/*
*+
*  Name:
*     astRegTrace

*  Purpose:
*     Return requested positions on the boundary of a 2D Region.

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     int astRegTrace( AstRegion *this, int n, double *dist, double **ptr );

*  Class Membership:
*     Region virtual function

*  Description:
*     This function returns positions on the boundary of the supplied
*     Region, if possible. The required positions are indicated by a
*     supplied list of scalar parameter values in the range zero to one.
*     Zero corresponds to some arbitrary starting point on the boundary,
*     and one corresponds to the end (which for a closed region will be
*     the same place as the start).

*  Parameters:
*     this
*        Pointer to the Region.
*     n
*        The number of positions to return. If this is zero, the function
*        returns without action (but the returned function value still
*        indicates if the method is supported or not).
*     dist
*        Pointer to an array of "n" scalar parameter values in the range
*        0 to 1.0.
*     ptr
*        A pointer to an array of pointers. The number of elements in
*        this array should equal tthe number of axes in the Frame spanned
*        by the Region. Each element of the array should be a pointer to
*        an array of "n" doubles, in which to return the "n" values for
*        the corresponding axis. The contents of the arrays are unchanged
*        if the supplied Region belongs to a class that does not
*        implement this method.

*  Returned Value:
*     Non-zero if the astRegTrace method is implemented by the class
*     of Region supplied, and zero if not.

*-
*/

/* Concrete sub-classes of Region must over-ride this method. */
   return 0;
}

static int TestAttrib( AstObject *this_object, const char *attrib, int *status ) {
/*
*  Name:
*     TestAttrib

*  Purpose:
*     Test if a specified attribute value is set for a Region.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     int TestAttrib( AstObject *this, const char *attrib, int *status )

*  Class Membership:
*     Region member function (over-rides the astTestAttrib protected
*     method inherited from the Frame class).

*  Description:
*     This function returns a boolean result (0 or 1) to indicate whether
*     a value has been set for one of a Region's attributes.

*  Parameters:
*     this
*        Pointer to the Region.
*     attrib
*        Pointer to a null terminated string specifying the attribute
*        name.  This should be in lower case with no surrounding white
*        space.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     One if a value has been set, otherwise zero.

*  Notes:
*     - A value of zero will be returned if this function is invoked
*     with the global status set, or if it should fail for any reason.
*/

/* Local Variables: */
   AstRegion *this;              /* Pointer to the Region structure */
   int result;                   /* Result value to return */

/* Initialise. */
   result = 0;

/* Check the global error status. */
   if ( !astOK ) return result;

/* Obtain a pointer to the Region structure. */
   this = (AstRegion *) this_object;

/* Check the attribute name and test the appropriate attribute. */

/* We first handle attributes that apply to the Region as a whole
   (rather than to the encapsulated FrameSet). */

/* Negated. */
/* -------- */
   if ( !strcmp( attrib, "negated" ) ) {
      result = astTestNegated( this );

/* Closed. */
/* ------- */
   } else if ( !strcmp( attrib, "closed" ) ) {
      result = astTestClosed( this );

/* FillFactor */
/* ---------- */
   } else if ( !strcmp( attrib, "fillfactor" ) ) {
      result = astTestFillFactor( this );

/* MeshSize */
/* -------- */
   } else if ( !strcmp( attrib, "meshsize" ) ) {
      result = astTestMeshSize( this );

/* Adaptive */
/* -------- */
   } else if ( !strcmp( attrib, "adaptive" ) ) {
      result = astTestAdaptive( this );

/* Now do attributes inherited from parent classes. This is so that the
   attribute test will not be passed on to the encpasulated FrameSet below. */

/* ID. */
/* --- */
   } else if ( !strcmp( attrib, "id" ) ) {
      result = astTestID( this );

/* Ident. */
/* ------ */
   } else if ( !strcmp( attrib, "ident" ) ) {
      result = astTestIdent( this );

/* Invert. */
/* ------- */
   } else if ( !strcmp( attrib, "invert" ) ) {
      result = astTestInvert( this );

/* Report. */
/* ------- */
   } else if ( !strcmp( attrib, "report" ) ) {
      result = astTestReport( this );

/* If the name is not recognised, test if it matches any of the
   read-only attributes of this class. If it does, then return
   zero. */
   } else if ( !strcmp( attrib, "class" ) ||
               !strcmp( attrib, "nin" ) ||
               !strcmp( attrib, "nobject" ) ||
               !strcmp( attrib, "bounded" ) ||
               !strcmp( attrib, "nout" ) ||
               !strcmp( attrib, "refcount" ) ||
               !strcmp( attrib, "tranforward" ) ||
               !strcmp( attrib, "traninverse" ) ) {
      result = 0;

/* Pass unrecognised attributes on to the Region's encapsulated FrameSet for
   further interpretation. Do not pass on FrameSet attributes since we
   pretend to the outside world that the encapsulated FrameSet is actually a
   Frame. */
   } else if ( strcmp( attrib, "base" ) &&
               strcmp( attrib, "current" ) &&
               strcmp( attrib, "nframe" ) ) {
      result = astTestAttrib( this->frameset, attrib );
   }

/* If an error occurred, clear the result value. */
   if ( !astOK ) result = 0;

/* Return the result, */
   return result;
}

double *astRegTranPoint_( AstRegion *this, double *in, int np, int forward, int *status ){
/*
*+
*  Name:
*     astRegTranPoint

*  Purpose:
*     Transform points between the base and current Frames in a Region.

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     double *astRegTranPoint( AstRegion *this, double *in, int np, int forward )

*  Class Membership:
*     Region member function

*  Description:
*     This function transforms one or more points between the base and
*     current Frames of the FrameSet encapsulated by the supplied Region.

*  Parameters:
*     this
*        The Region pointer.
*     in
*        Pointer to a 1-d array holding the axis values to be transformed.
*        If "forward" is non-zero, the number of axis values supplied for
*        each position should equal the number of axes in the base Frame
*        of the FrameSet encapsulated by "this". If "forward" is zero, the
*        number of axis values supplied for each position should equal the
*        number of axes in the current Frame of the FrameSet encapsulated by
*        "this". All the axis values for a position should be in adjacent
*        elements of the array.
*     np
*        The number of points supplied in "in".
*     forward
*        If non-zero, the supplied points are assumed to refer to the base
*        Frame of the encapsulated FrameSet, and they are transformed to the
*        current Frame. If zero, the supplied points are assumed to refer to
*        the current Frame of the encapsulated FrameSet, and they are
*        transformed to the base Frame.

*  Returned Value:
*     Pointer to a new dynamically allocated array holding the
*     transformed axis values. If "forward" is non-zero, the number of axis
*     values for each position will be equal the number of axes in the
*     current Frame of the FrameSet encapsulated by "this". If "forward" is
*     zero, the number of axis values for each position will be equal to the
*     number of axes in the base Frame of the FrameSet encapsulated by "this".
*     All the axis values for a position will be in adjacent elements of the
*     array. The array should be freed using astFree when no longer needed.

*  Notes:
*    - A NULL pointer is returned if an error has already occurred, or if
*    this function should fail for any reason.

*-
*/

/* Local Variables: */
   AstMapping *map;
   AstPointSet *pset_in;
   AstPointSet *pset_out;
   double **ptr_in;
   double **ptr_out;
   double *p;
   double *result;
   int ic;
   int ip;
   int naxin;
   int naxout;

/* Initialise */
   result = NULL;

/* Check the global error status. */
   if ( !astOK ) return result;

/* Get a pointer to the required Mapping. */
   if( forward ) {
      map = astGetMapping( this->frameset, AST__BASE, AST__CURRENT );
   } else {
      map = astGetMapping( this->frameset, AST__CURRENT, AST__BASE );
   }

/* Get the number of axis values per input and per output point. */
   naxin = astGetNin( map );
   naxout = astGetNout( map );

/* Create a pointSet holding the supplied axis values. */
   pset_in = astPointSet( np, naxin, "", status );

/* Get pointers to the memory used to store axis values within this
   PointSet. */
   ptr_in = astGetPoints( pset_in );

/* Allocate the output array. */
   result = astMalloc( sizeof( double )*(size_t)( naxout*np ) );

/* Check the pointers can be used. */
   if( astOK ) {

/* Store the supplied axis values in the PointSet memory. */
      p = in;
      for( ip = 0; ip < np; ip++ ) {
         for( ic = 0; ic < naxin; ic++ ) ptr_in[ ic ][ ip ] = *(p++);
      }

/* Transform the PointSet. */
      pset_out = astTransform( map, pset_in, 1, NULL );

/* Get a pointer to the memory in the transformed PointSet. */
      ptr_out = astGetPoints( pset_out );

      if( pset_out && astStatus == AST__INTER ) {
         p = in;
         for( ip = 0; ip < np; ip++ ) {
            for( ic = 0; ic < naxin; ic++ ) printf("%.*g\n", AST__DBL_DIG, *(p++) );
         }
      }

      if( astOK ) {

/* Store the resulting axis values in the output array. */
         p = result;
         for( ip = 0; ip < np; ip++ ) {
            for( ic = 0; ic < naxout; ic++ ) *(p++) = ptr_out[ ic ][ ip ];
         }
      }

/* Free resources. */
      pset_out = astAnnul( pset_out );
   }
   pset_in = astAnnul( pset_in );
   map = astAnnul( map );

/* Return NULL if anything went wrong. */
   if( !astOK ) result = astAnnul( result );

/* Return the result.*/
   return result;
}

static AstPointSet *RegTransform( AstRegion *this, AstPointSet *in,
                                  int forward, AstPointSet *out, AstFrame **frm, int *status ) {
/*
*+
*  Name:
*     astRegTransform

*  Purpose:
*     Transform a set of points using the encapsulated FrameSet.

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     AstPointSet *astRegTransform( AstRegion *this, AstPointSet *in,
*                                   int forward, AstPointSet *out,
*                                   AstFrameSet **frm )

*  Class Membership:
*     Region virtual function

*  Description:
*     This function takes a Region and a set of points encapsulated
*     in a PointSet, and applies either the forward or inverse
*     coordinate transformation represented by the encapsulated FrameSet.
*     It also returned a pointer to either the current or base Frame in
*     the FrameSet.

*  Parameters:
*     this
*        Pointer to the Region.
*     in
*        Pointer to the PointSet holding the input coordinate data. If
*        NULL then the "points" PointSet within the supplied Region
*        ("this") is used.
*     forward
*        A non-zero value indicates that the forward coordinate transformation
*        (from base to current) should be applied, while a zero value requests
*        the inverse transformation (from current to base).
*     out
*        Pointer to a PointSet which will hold the transformed (output)
*        coordinate values. A NULL value may also be given, in which case a
*        new PointSet will be created by this function.
*     frm
*        Location at which to return a pointer to a Frame. If "forward"
*        is non-zero, the current Frame in the encapsulated FrameSet will
*        be returned. Otherwise, the base Frame is returned. The returned
*        pointer should be annulled when no longer needed. May be NULL if
*        no pointer is needed.

*  Returned Value:
*     Pointer to the output (possibly new) PointSet. If "out" is NULL,
*     the returned pointer will be a clone of "in" if the Mapping is a
*     UnitMap. If "out" is not NULL, then the supplied "out" PointSet will
*     be used and returned.

*  Notes:
*     - An error will result if the Region supplied does not define
*     the requested coordinate transformation (either forward or
*     inverse).
*     - The number of coordinate values per point in the input
*     PointSet must match the number of input coordinates for the
*     Region being applied (or number of output coordinates if the
*     inverse transformation is requested).  This will be equal to the
*     number of axes in the Region's base Frame (or the current
*     Frame for the inverse transformation).
*     - If an output PointSet is supplied, it must have space for
*     sufficient number of points and coordinate values per point to
*     accommodate the result (e.g. the number of Region output
*     coordinates, or number of input coordinates if the inverse
*     transformation is requested). Any excess space will be ignored.
*     - A null pointer will be returned if this function is invoked
*     with the global error status set, or if it should fail for any
*     reason.
*-
*/

/* Local Variables: */
   AstMapping *smap;           /* Pointer to simplified Mapping */
   AstPointSet *result;        /* Pointer value to return */

/* Initialise */
   if( frm ) *frm = NULL;

/* Check the global error status. */
   if ( !astOK ) return NULL;

/* If no input PointSet was provided, use the PointSet in the Region. */
   if( !in ) {
      if( this->points ) {
         in = this->points;
      } else {
         astError( AST__INTER, "astRegTransform(%s): No PointSet supplied "
                   "and the supplied %s has no PointSet (internal AST "
                   "programming error)", status, astGetClass( this ),astGetClass( this ) );
      }
   }

/* Get the simplified Mapping from base to current Frame. */
   smap = astRegMapping( this );

/* If it is a UnitMap, return a clone of the input PointSet unless an
   explicit output PointSet has been supplied. */
   if( astIsAUnitMap( smap ) && !out ) {
      result = astClone( in );

/* Otherwise use the Mapping to transform the supplied positions. */
   } else {
      result = astTransform( smap, in, forward, out );
   }

/* Return a pointer to the appropriate Frame. */
   if( frm ) *frm = astGetFrame( this->frameset, forward ? AST__CURRENT : AST__BASE );

/* Release resources. */
   smap = astAnnul( smap );

/* Return a pointer to the output PointSet. */
   return result;
}

static int Unformat( AstFrame *this_frame, int axis, const char *string,
                     double *value, int *status ) {
/*
*  Name:
*     Unformat

*  Purpose:
*     Read a formatted coordinate value for a Region axis.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     int Unformat( AstFrame *this, int axis, const char *string,
*                   double *value, int *status )

*  Class Membership:
*     Region member function (over-rides the public astUnformat
*     method inherited from the Frame class).

*  Description:
*     This function reads a formatted coordinate value for a Region
*     axis (supplied as a string) and returns the equivalent numerical
*     value as a double. It also returns the number of characters read
*     from the string.

*  Parameters:
*     this
*        Pointer to the Region.
*     axis
*        The number of the Region axis for which the coordinate
*        value is to be read (axis numbering starts at zero for the
*        first axis).
*     string
*        Pointer to a constant null-terminated string containing the
*        formatted coordinate value.
*     value
*        Pointer to a double in which the coordinate value read will be
*        returned.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     The number of characters read from the string to obtain the
*     coordinate value.

*  Notes:
*     - Any white space at the beginning of the string will be
*     skipped, as also will any trailing white space following the
*     coordinate value read. The function's return value will reflect
*     this.
*     - A function value of zero (and no coordinate value) will be
*     returned, without error, if the string supplied does not contain
*     a suitably formatted value.
*     - The string "<bad>" is recognised as a special case and will
*     generate the value AST__BAD, without error. The test for this
*     string is case-insensitive and permits embedded white space.
*     - A function result of zero will be returned and no coordinate
*     value will be returned via the "value" pointer if this function
*     is invoked with the global error status set, or if it should
*     fail for any reason.
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to current Frame */
   AstRegion *this;              /* Pointer to the Region structure */
   double coord;                 /* Coordinate value read */
   int nc;                       /* Number of characters read */

/* Initialise. */
   nc = 0;

/* Check the global error status. */
   if ( !astOK ) return nc;

/* Obtain a pointer to the Region structure. */
   this = (AstRegion *) this_frame;

/* Validate the axis index. */
   (void) astValidateAxis( this, axis, 1, "astUnformat" );

/* Obtain a pointer to the Region's current Frame and invoke the
   astUnformat method for this Frame. Annul the Frame pointer
   afterwards. */
   fr = astGetFrame( this->frameset, AST__CURRENT );
   nc = astUnformat( fr, axis, string, &coord );
   fr = astAnnul( fr );

/* If an error occurred, clear the number of characters read. */
   if ( !astOK ) {
      nc = 0;

/* Otherwise, if characters were read, return the coordinate value. */
   } else if ( nc ) {
      *value = coord;
   }

/* Return the number of characters read. */
   return nc;
}

static int ValidateAxis( AstFrame *this_frame, int axis, int fwd,
                         const char *method, int *status ) {
/*
*  Name:
*     ValidateAxis

*  Purpose:
*     Validate and permute a Region's axis index.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     int ValidateAxis( AstFrame *this, int axis, int fwd, const char *method,
*                       int *status )

*  Class Membership:
*     Region member function (over-rides the protected
*     astValidateAxis method inherited from the Frame class).

*  Description:
*     This function checks the validity of an index (zero-based) which
*     is to be used to address one of the coordinate axes of the
*     current Frame in a Region. If the index is valid, it is
*     permuted using the axis permutation array associated with the
*     Region's current Frame and the (zero-based) permuted axis
*     index is returned.  This gives the index the axis had when the
*     Frame was first created. If the axis index supplied is not
*     valid, an error is reported and the global error status is set.

*  Parameters:
*     this
*        Pointer to the Region.
*     axis
*        The axis index (zero-based) to be checked. To be valid, it
*        must lie between zero and (naxes-1) inclusive, where "naxes"
*        is the number of coordinate axes associated with the
*        Region's current Frame.
*     fwd
*        If non-zero, the suppplied axis index is assumed to be an
*        "external" axis index, and the corresponding "internal" axis index
*        is returned as the function value. Otherwise, the suppplied axis
*        index is assumed to be an "internal" axis index, and the
*        corresponding "external" axis index is returned as the function
*        value.
*     method
*        Pointer to a constant null-terminated character string
*        containing the name of the method that invoked this function
*        to validate an axis index. This method name is used solely
*        for constructing error messages.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     The permuted axis index - either "internal" or "external" as
*     specified by "fwd".

*  Notes:
*     - A value of zero will be returned if this function is invoked
*     with the global error status set, or if it should fail for any
*     reason.
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to current Frame */
   AstRegion *this;              /* Pointer to the Region structure */
   int naxes;                    /* Number of Region axes */
   int result;                   /* Permuted axis index */

/* Initialise. */
   result = 0;

/* Check the global error status. */
   if ( !astOK ) return result;

/* Obtain a pointer to the Region structure. */
   this = (AstRegion *) this_frame;

/* Determine the number of Region axes. */
   naxes = astGetNaxes( this );
   if ( astOK ) {

/* If the Region has no axes, report an error (convert to 1-based
   axis numbering for the benefit of the public interface). */
      if ( naxes == 0 ) {
         astError( AST__AXIIN, "%s(%s): Invalid attempt to use an axis index "
                   "(%d) for a %s which has no axes.", status, method,
                   astGetClass( this ), axis + 1, astGetClass( this ) );

/* Otherwise, check the axis index for validity and report an error if
   it is not valid (again, convert to 1-based axis numbering). */
      } else if ( ( axis < 0 ) || ( axis >= naxes ) ) {
         astError( AST__AXIIN, "%s(%s): Axis index (%d) invalid - it should "
                   "be in the range 1 to %d.", status, method, astGetClass( this ),
                   axis + 1, naxes );

/* If the axis index was valid, obtain a pointer to the Region's
   current Frame and invoke this Frame's astValidateAxis method to
   obtain the permuted axis index. Annul the Frame pointer
   afterwards. */
      } else {
         fr = astGetFrame( this->frameset, AST__CURRENT );
         result = astValidateAxis( fr, axis, fwd, "astValidateAxis" );
         fr = astAnnul( fr );
      }
   }

/* If an error occurred, clear the result value. */
   if ( !astOK ) result = 0;

/* Return the result. */
   return result;
}

static void ValidateAxisSelection( AstFrame *this_frame, int naxes,
                                   const int *axes, const char *method, int *status ) {
/*
*  Name:
*     ValidateAxisSelection

*  Purpose:
*     Check that a set of axes selected from a Frame is valid.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     void ValidateAxisSelection( AstFrame *this, int naxes,
*                                 const int *axes, const char *method, int *status )

*  Class Membership:
*     Region member function (over-rides the protected astValidateAxisSelection
*     method inherited from the Frame class).

*  Description:
*     This function checks the validity of an array of (zero-based)
*     axis indices that specify a set of axes to be selected from a
*     Frame. To be valid, no axis should be selected more than
*     once. In assessing this, any axis indices that do not refer to
*     valid Frame axes (e.g. are set to -1) are ignored.
*
*     If the axis selection is valid, this function returns without further
*     action. Otherwise, an error is reported and the global error status is
*     set.

*  Parameters:
*     this
*        Pointer to the Frame.
*     naxes
*        The number of axes to be selected (may be zero).
*     axes
*        Pointer to an array of int with naxes elements that contains the
*        (zero based) axis indices to be checked.
*     method
*        Pointer to a constant null-terminated character string
*        containing the name of the method that invoked this function
*        to validate an axis selection. This method name is used
*        solely for constructing error messages.
*     status
*        Pointer to the inherited status variable.
*/

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to current Frame */
   AstRegion *this;              /* Pointer to the Region structure */

/* Check the global error status. */
   if ( !astOK ) return;

/* Obtain a pointer to the FrameSet structure. */
   this = (AstRegion *) this_frame;

/* Obtain a pointer to the Region's encapsulated Frame and invoke this
   Frame's astValidateAxisSelection method. Annul the Frame pointer
   afterwards. */
   fr = astGetFrame( this->frameset, AST__CURRENT );
   astValidateAxisSelection( fr, naxes, axes, method );
   fr = astAnnul( fr );

}

static int ValidateSystem( AstFrame *this_frame, AstSystemType system, const char *method, int *status ) {
/*
*  Name:
*     ValidateSystem

*  Purpose:
*     Validate a value for a Frame's System attribute.

*  Type:
*     Private function.

*  Synopsis:
*     #include "region.h"
*     int ValidateSystem( AstFrame *this, AstSystemType system,
*                         const char *method, int *status )

*  Class Membership:
*     Region member function (over-rides the protected astValidateSystem
*     method inherited from the Frame class).

*  Description:
*     This function checks the validity of the supplied system value.
*     If the value is valid, it is returned unchanged. Otherwise, an
*     error is reported and a value of AST__BADSYSTEM is returned.

*  Parameters:
*     this
*        Pointer to the Frame.
*     system
*        The system value to be checked.
*     method
*        Pointer to a constant null-terminated character string
*        containing the name of the method that invoked this function
*        to validate an axis index. This method name is used solely
*        for constructing error messages.
*     status
*        Pointer to the inherited status variable.

*  Returned Value:
*     The validated system value.

*  Notes:
*     - A value of AST_BADSYSTEM will be returned if this function is invoked
*     with the global error status set, or if it should fail for any
*     reason.
*-
*/

/* Local Variables: */
   AstSystemType result;      /* Validated system value */
   AstFrame *fr;              /* Pointer to FrameSet's current Frame */
   AstRegion *this;           /* Pointer to the Region structure */

/* Initialise. */
   result = AST__BADSYSTEM;

/* Check the global error status. */
   if ( !astOK ) return result;

/* Obtain a pointer to the FrameSet structure. */
   this = (AstRegion *) this_frame;

/* Obtain a pointer to the Region's encapsulated Frame and invoke the
   astValidateSystem method for this Frame. Annul the Frame pointer
   afterwards. */
   fr = astGetFrame( this->frameset, AST__CURRENT );
   result = astValidateSystem( this, system, method );
   fr = astAnnul( fr );

/* If an error occurred, clear the result value. */
   if ( !astOK ) result = AST__BADSYSTEM;

/* Return the result. */
   return result;
}

/* Region Attributes. */
/* -------------------- */

/*
*att++
*  Name:
*     Adaptive

*  Purpose:
*     Should the area adapt to changes in the coordinate system?

*  Type:
*     Public attribute.

*  Synopsis:
*     Integer (boolean).

*  Description:
*     The coordinate system represented by a Region may be changed by
*     assigning new values to attributes such as System, Unit, etc.
*     For instance, a Region representing an area on the sky in ICRS
*     coordinates may have its System attribute changed so that it
*     represents (say) Galactic coordinates instead of ICRS. This
*     attribute controls what happens when the coordinate system
*     represented by a Region is changed in this way.
*
*     If Adaptive is non-zero (the default), then the area represented by
*     the Region adapts to the new coordinate system. That is, the numerical
*     values which define the area represented by the Region are changed
*     by mapping them from the old coordinate system into the new coordinate
*     system. Thus the Region continues to represent the same physical
*     area.
*
*     If Adaptive is zero, then area represented by the Region does not adapt
*     to the new coordinate system. That is, the numerical values which
*     define the area represented by the Region are left unchanged. Thus
*     the physical area represented by the Region will usually change.
*
*     As an example, consider a Region describe a range of wavelength from
*     2000 Angstrom to 4000 Angstrom. If the Unit attribute for the Region
*     is changed from Angstrom to "nm" (nanometre), what happens depends
*     on the setting of Adaptive. If Adaptive is non-zero, the Mapping
*     from the old to the new coordinate system is found. In this case it
*     is a simple scaling by a factor of 0.1 (since 1 Angstrom is 0.1 nm).
*     This Mapping is then used to modify the numerical values within the
*     Region, changing 2000 to 200 and 4000 to 400. Thus the modified
*     region represents 200 nm to 400 nm, the same physical space as
*     the original 2000 Angstrom to 4000 Angstrom. However, if Adaptive
*     had been zero, then the numerical values would not have been changed,
*     resulting in the final Region representing 2000 nm to 4000 nm.
*
*     Setting Adaptive to zero can be necessary if you need to correct
*     inaccurate attribute settings in an existing Region. For instance,
*     when creating a Region you may not know what Epoch value to use, so
*     you would leave Epoch unset resulting in some default value being used.
*     If at some later point in the application, the correct Epoch value
*     is determined, you could assign the correct value to the Epoch
*     attribute. However, you would first need to set Adaptive temporarily
*     to zero, because otherwise the area represented by the Region would
*     be Mapped from the spurious default Epoch to the new correct Epoch,
*     which is not what is required.

*  Applicability:
*     Region
*        All Regions have this attribute.
*att--
*/

/* This is a boolean value (0 or 1) with a value of -INT_MAX when
   undefined but yielding a default of 1. */
astMAKE_CLEAR(Region,Adaptive,adaptive,-INT_MAX)
astMAKE_GET(Region,Adaptive,int,1,( ( this->adaptive == -INT_MAX ) ?
                                   1 : this->adaptive ))
astMAKE_SET(Region,Adaptive,int,adaptive,( value != 0 ))
astMAKE_TEST(Region,Adaptive,( this->adaptive != -INT_MAX ))

/*
*att++
*  Name:
*     Negated

*  Purpose:
*     Region negation flag.

*  Type:
*     Public attribute.

*  Synopsis:
*     Integer (boolean).

*  Description:
*     This attribute controls whether a Region represents the "inside" or
*     the "outside" of the area which was supplied when the Region was
*     created. If the attribute value is zero (the default), the Region
*     represents the inside of the original area. However, if it is non-zero,
*     it represents the outside of the original area. The value of this
*     attribute may be toggled using the
c     astNegate function.
f     AST_NEGATE routine.

*     Note, whether the boundary is considered to be inside the Region or
*     not is controlled by the Closed attribute. Changing the value of
*     the Negated attribute does not change the value of the Closed attribute.
*     Thus, if Region is closed, then the boundary of the Region will be
*     inside the Region, whatever the setting of the Negated attribute.

*  Applicability:
*     Region
*        All Regions have this attribute.
*att--
*/

/* This is a boolean value (0 or 1) with a value of -INT_MAX when
   undefined but yielding a default of zero. */
astMAKE_CLEAR(Region,Negated,negated,(astResetCache(this),-INT_MAX))
astMAKE_GET(Region,Negated,int,0,( ( this->negated == -INT_MAX ) ?
                                   0 : this->negated ))
astMAKE_SET(Region,Negated,int,negated,(astResetCache(this),( value != 0 )))
astMAKE_TEST(Region,Negated,( this->negated != -INT_MAX ))

/*
*att++
*  Name:
*     Bounded

*  Purpose:
*     Is the Region bounded?

*  Type:
*     Public attribute.

*  Synopsis:
*     Integer (boolean), read-only.

*  Description:
*     This is a read-only attribute indicating if the Region is bounded.
*     A Region is bounded if it is contained entirely within some
*     finite-size bounding box.

*  Applicability:
*     Region
*        All Regions have this attribute.
*att--
*/

/*
*att+
*  Name:
*     RegionFS

*  Purpose:
*     Should Region FrameSet be dumped?

*  Type:
*     Protected attribute.

*  Synopsis:
*     Integer (boolean).

*  Description:
*     This attribute indicates whether the FrameSet encapsulated by the
*     Region should be included in the dump produced by the Dump function.
*
*     If set to a non-zero value (the default), the FrameSet in the Region
*     will always be included in the dump as usual. If set to zero, the
*     FrameSet will only be included in the dump if the Mapping from base
*     to current Frame is not a UnitMap. If the base->current Mapping is
*     a UnitMap, the FrameSet is omitted from the dump. If the dump is
*     subsequently used to re-create the Region, the new Region will have a
*     default FrameSet containing a single default Frame with the appropriate
*     number of axes.
*
*     This facility is indended to reduce the size of textual dumps of
*     Regions in situations where the Frame to which the Region refers can
*     be implied by the context in which the Region is used. This is
*     often the case when a Region is encapsulated within another Region.
*     In such cases the current Frame of the encapsulated Region will
*     usually be equivalent to the base Frame of the parent Region
*     structure, and so can be re-instated (by calling the astSetRegFS
*     method) even if the FrameSet is omitted from the dump of the
*     encapsulated Region. Note if the base->current Mapping in the FrameSet
*     in the encapsulated Region is not a UnitMap, then we should always
*     dump the FrameSet regardless of the setting of RegionFS. This is because
*     the parent Region structure will not know how to convert the PointSet
*     stored in the encapsulated Region into its own base Frame if the
*     FrameSet is not available.

*  Applicability:
*     Region
*        All Regions have this attribute.
*att-
*/

/* This is a boolean value (0 or 1) with a value of -INT_MAX when
   undefined but yielding a default of one. */
astMAKE_CLEAR(Region,RegionFS,regionfs,-INT_MAX)
astMAKE_TEST(Region,RegionFS,( this->regionfs != -INT_MAX ))
astMAKE_SET(Region,RegionFS,int,regionfs,( value != 0 ))
astMAKE_GET(Region,RegionFS,int,1,( ( this->regionfs == -INT_MAX ) ?
                                   1 : this->regionfs ))

/*
*att++
*  Name:
*     FillFactor

*  Purpose:
*     Fraction of the Region which is of interest.

*  Type:
*     Public attribute.

*  Synopsis:
*     Floating point.

*  Description:
*     This attribute indicates the fraction of the Region which is of
*     interest. AST does not use this attribute internally for any purpose.
*     Typically, it could be used to indicate the fraction of the Region for
*     which data is available.
*
*     The supplied value must be in the range 0.0 to 1.0, and the default
*     value is 1.0 (except as noted below).

*  Applicability:
*     Region
*        All Regions have this attribute.
*     CmpRegion
*        The default FillFactor for a CmpRegion is the FillFactor of its
*        first component Region.
*     Prism
*        The default FillFactor for a Prism is the product of the
*        FillFactors of its two component Regions.
*     Stc
*        The default FillFactor for an Stc is the FillFactor of its
*        encapsulated Region.
*att--
*/

astMAKE_CLEAR(Region,FillFactor,fillfactor,AST__BAD)
astMAKE_GET(Region,FillFactor,double,1.0,( ( this->fillfactor == AST__BAD ) ?
                                        1.0 : this->fillfactor ))
astMAKE_TEST(Region,FillFactor,( this->fillfactor != AST__BAD ))
astMAKE_SET(Region,FillFactor,double,fillfactor,((value<0.0||value>1.0)?(
       astError(AST__ATSER,"astSetFillFactor(%s): Invalid value (%g) supplied "
                "for attribute FillFactor.", status,astGetClass(this),value),
       astError(AST__ATSER,"FillFactor values should be in the range 0.0 to 1.0", status),
       this->fillfactor):value))

/*
*att++
*  Name:
*     MeshSize

*  Purpose:
*     Number of points used to represent the boundary of a Region.

*  Type:
*     Public attribute.

*  Synopsis:
*     Integer.

*  Description:
*     This attribute controls how many points are used when creating a
*     mesh of points covering the boundary or volume of a Region. Such a
*     mesh is returned by the
c     astGetRegionMesh
f     AST_GETREGIONMESH
*     method. The boundary mesh is also used when testing for overlap
*     between two Regions: each point in the bomdary mesh of the first
*     Region is checked to see if it is inside or outside the second Region.
*     Thus, the reliability of the overlap check depends on the value assigned
*     to this attribute. If the value used is very low, it is possible for
*     overlaps to go unnoticed. High values produce more reliable results, but
*     can result in the overlap test being very slow. The default value is 200
*     for two dimensional Regions and 2000 for three or more dimensional
*     Regions (this attribute is not used for 1-dimensional regions since the
*     boundary of a simple 1-d Region can only ever have two points). A
*     value of five is used if the supplied value is less than five.

*  Applicability:
*     Region
*        All Regions have this attribute.
*     CmpRegion
*        The default MeshSize for a CmpRegion is the MeshSize of its
*        first component Region.
*     Moc
*        The MeshSize attribute is ignored when forming a mesh covering
*        the boundary of a Moc. Instead, the mesh will include a point
*        for the exterior corners of every HEALPix cell (at the order
*        specified by attribute MaxOrder) that touches the boundary. Note,
*        this applies only to meshes covering the boundary of the Moc -
*        the MeshSize attribute is used as normal when forming a mesh
*        covering the area of the Moc.
*     Stc
*        The default MeshSize for an Stc is the MeshSize of its
*        encapsulated Region.
*att--
*/
/* If the value of MeshSize is set or cleared, annul the PointSet used to
   cache a mesh of base Frame boundary points. This will force a new
   PointSet to be created next time it is needed. See function RegMesh. */
astMAKE_CLEAR(Region,MeshSize,meshsize,(astResetCache(this),-INT_MAX))
astMAKE_SET(Region,MeshSize,int,meshsize,(astResetCache(this),( value > 5 ? value : 5 )))
astMAKE_TEST(Region,MeshSize,( this->meshsize != -INT_MAX ))
astMAKE_GET(Region,MeshSize,int,0,( ( this->meshsize == -INT_MAX)?((astGetNaxes(this)==1)?2:((astGetNaxes(this)==2)?200:2000)): this->meshsize ))

/*
*att++
*  Name:
*     Closed

*  Purpose:
*     Should the boundary be considered to be inside the region?

*  Type:
*     Public attribute.

*  Synopsis:
*     Integer (boolean).

*  Description:
*     This attribute controls whether points on the boundary of a Region
*     are considered to be inside or outside the region. If the attribute
*     value is non-zero (the default), points on the boundary are considered
*     to be inside the region (that is, the Region is "closed"). However,
*     if the attribute value is zero, points on the bounary are considered
*     to be outside the region.

*  Applicability:
*     Region
*        All Regions have this attribute.
*     PointList
*        The value of the Closed attribute is ignored by PointList regions.
*        If the PointList region has not been negated, then it is always
*        assumed to be closed. If the PointList region has been negated, then
*        it is always assumed to be open. This is required since points
*        have zero volume and therefore consist entirely of boundary.
*     CmpRegion
*        The default Closed value for a CmpRegion is the Closed value of its
*        first component Region.
*     Stc
*        The default Closed value for an Stc is the Closed value of its
*        encapsulated Region.
*     Moc
*        The Moc class ignored this attribute, and the behaviour for
*        boundary points is undefined (i.e. they may be inside or
*        outside the Region, depending on the position being tested and
*        the nature of the Moc).
*att--
*/
/* This is a boolean value (0 or 1) with a value of -INT_MAX when
   undefined but yielding a default of 1. */
astMAKE_CLEAR(Region,Closed,closed,(astResetCache(this),-INT_MAX))
astMAKE_GET(Region,Closed,int,1,( ( this->closed == -INT_MAX ) ?
                                   1 : this->closed ))
astMAKE_SET(Region,Closed,int,closed,(astResetCache(this),( value != 0 )))
astMAKE_TEST(Region,Closed,( this->closed != -INT_MAX ))

/* Access to attributes of the encapsulated Frame. */
/* ----------------------------------------------- */
/* Use the macros defined at the start of this file to implement
   private member functions that give access to the attributes of the
   encapsulated Frame of a Region and its axes. These functions over-ride
   the attribute access methods inherited from the Frame class. */

/* Clear, Get, Set and Test axis-independent Frame attributes. */
MAKE_CLEAR(Digits)
MAKE_CLEAR(Domain)
MAKE_CLEAR(MatchEnd)
MAKE_CLEAR(MaxAxes)
MAKE_CLEAR(MinAxes)
MAKE_CLEAR(Permute)
MAKE_CLEAR(PreserveAxes)
MAKE_CLEAR(Title)

MAKE_GET(Digits,int)
MAKE_GET(Domain,const char *)
MAKE_GET(MatchEnd,int)
MAKE_GET(MaxAxes,int)
MAKE_GET(MinAxes,int)
MAKE_GET(Permute,int)
MAKE_GET(PreserveAxes,int)
MAKE_GET(Title,const char *)
MAKE_SET(Digits,int,I)
MAKE_SET(Domain,const char *,C)
MAKE_SET(MatchEnd,int,I)
MAKE_SET(MaxAxes,int,I)
MAKE_SET(MinAxes,int,I)
MAKE_SET(Permute,int,I)
MAKE_SET(PreserveAxes,int,I)
MAKE_SET(Title,const char *,C)
MAKE_TEST(Digits)
MAKE_TEST(Domain)
MAKE_TEST(MatchEnd)
MAKE_TEST(MaxAxes)
MAKE_TEST(MinAxes)
MAKE_TEST(Permute)
MAKE_TEST(PreserveAxes)
MAKE_TEST(Title)

MAKE_GET(ActiveUnit,int)
MAKE_SET(ActiveUnit,int,I)
MAKE_TEST(ActiveUnit)

MAKE_GET(System,AstSystemType)
MAKE_SET_SYSTEM(System)
MAKE_TEST(System)
MAKE_CLEAR(System)

MAKE_GET(AlignSystem,AstSystemType)
MAKE_SET_SYSTEM(AlignSystem)
MAKE_TEST(AlignSystem)
MAKE_CLEAR(AlignSystem)

MAKE_GET(Epoch,double)
MAKE_SET(Epoch,double,D)
MAKE_TEST(Epoch)
MAKE_CLEAR(Epoch)

MAKE_GET(ObsLon,double)
MAKE_SET(ObsLon,double,D)
MAKE_TEST(ObsLon)
MAKE_CLEAR(ObsLon)

MAKE_GET(ObsLat,double)
MAKE_SET(ObsLat,double,D)
MAKE_TEST(ObsLat)
MAKE_CLEAR(ObsLat)

MAKE_GET(ObsAlt,double)
MAKE_SET(ObsAlt,double,D)
MAKE_TEST(ObsAlt)
MAKE_CLEAR(ObsAlt)

/* Clear, Get, Set and Test axis-dependent Frame attributes. */
MAKE_CLEAR_AXIS(Direction)
MAKE_CLEAR_AXIS(Format)
MAKE_CLEAR_AXIS(Label)
MAKE_CLEAR_AXIS(Symbol)
MAKE_CLEAR_AXIS(Unit)
MAKE_GET_AXIS(Direction,int)
MAKE_GET_AXIS(Format,const char *)
MAKE_GET_AXIS(Label,const char *)
MAKE_GET_AXIS(Symbol,const char *)
MAKE_GET_AXIS(Unit,const char *)
MAKE_SET_AXIS(Direction,int,I)
MAKE_SET_AXIS(Format,const char *,C)
MAKE_SET_AXIS(Label,const char *,C)
MAKE_SET_AXIS(Symbol,const char *,C)
MAKE_SET_AXIS(Unit,const char *,C)
MAKE_TEST_AXIS(Direction)
MAKE_TEST_AXIS(Format)
MAKE_TEST_AXIS(Label)
MAKE_TEST_AXIS(Symbol)
MAKE_TEST_AXIS(Unit)

MAKE_GET_AXIS(Bottom,double)
MAKE_SET_AXIS(Bottom,double,D)
MAKE_TEST_AXIS(Bottom)
MAKE_CLEAR_AXIS(Bottom)

MAKE_GET_AXIS(Top,double)
MAKE_SET_AXIS(Top,double,D)
MAKE_TEST_AXIS(Top)
MAKE_CLEAR_AXIS(Top)

/* Copy constructor. */
/* ----------------- */
static void Copy( const AstObject *objin, AstObject *objout, int *status ) {
/*
*  Name:
*     Copy

*  Purpose:
*     Copy constructor for Region objects.

*  Type:
*     Private function.

*  Synopsis:
*     void Copy( const AstObject *objin, AstObject *objout, int *status )

*  Description:
*     This function implements the copy constructor for Region objects.

*  Parameters:
*     objin
*        Pointer to the object to be copied.
*     objout
*        Pointer to the object being constructed.
*     status
*        Pointer to the inherited status variable.

*  Notes:
*     -  This constructor makes a deep copy.
*/

/* Local Variables: */
   AstRegion *in;                /* Pointer to input Region */
   AstRegion *out;               /* Pointer to output Region */

/* Check the global error status. */
   if ( !astOK ) return;

/* Obtain pointers to the input and output Regions. */
   in = (AstRegion *) objin;
   out = (AstRegion *) objout;

/* For safety, first clear any references to the input memory from
   the output Region. */
   out->basemesh = NULL;
   out->basegrid = NULL;
   out->frameset = NULL;
   out->points = NULL;
   out->unc = NULL;
   out->negation = NULL;
   out->defunc = NULL;

/* Now copy each of the above structures. */
   out->frameset = astCopy( in->frameset );
   if( in->points ) out->points = astCopy( in->points );
   if( in->basemesh ) out->basemesh = astCopy( in->basemesh );
   if( in->basegrid ) out->basegrid = astCopy( in->basegrid );
   if( in->unc ) out->unc = astCopy( in->unc );
   if( in->negation ) out->negation = astCopy( in->negation );
   if( in->defunc ) out->defunc = astCopy( in->defunc );
}


/* Destructor. */
/* ----------- */
static void Delete( AstObject *obj, int *status ) {
/*
*  Name:
*     Delete

*  Purpose:
*     Destructor for Region objects.

*  Type:
*     Private function.

*  Synopsis:
*     void Delete( AstObject *obj, int *status )

*  Description:
*     This function implements the destructor for Region objects.

*  Parameters:
*     obj
*        Pointer to the object to be deleted.
*     status
*        Pointer to the inherited status variable.

*  Notes:
*     This function attempts to execute even if the global error status is
*     set.
*/

/* Local Variables: */
   AstRegion *this;                 /* Pointer to Region */

/* Obtain a pointer to the Region structure. */
   this = (AstRegion *) obj;

/* Annul all resources. */
   this->frameset = astAnnul( this->frameset );
   if( this->points ) this->points = astAnnul( this->points );
   if( this->basemesh ) this->basemesh = astAnnul( this->basemesh );
   if( this->basegrid ) this->basegrid = astAnnul( this->basegrid );
   if( this->unc ) this->unc = astAnnul( this->unc );
   if( this->negation ) this->negation = astAnnul( this->negation );
   if( this->defunc ) this->defunc = astAnnul( this->defunc );
}

/* Dump function. */
/* -------------- */
static void Dump( AstObject *this_object, AstChannel *channel, int *status ) {
/*
*  Name:
*     Dump

*  Purpose:
*     Dump function for Region objects.

*  Type:
*     Private function.

*  Synopsis:
*     void Dump( AstObject *this, AstChannel *channel, int *status )

*  Description:
*     This function implements the Dump function which writes out data
*     for the Region class to an output Channel.

*  Parameters:
*     this
*        Pointer to the Region whose data are being written.
*     channel
*        Pointer to the Channel to which the data are being written.
*     status
*        Pointer to the inherited status variable.
*/

/* Local Constants: */
#define KEY_LEN 50               /* Maximum length of a keyword */
#define COM_LEN 50               /* Maximum length of a comment */

/* Local Variables: */
   AstFrame *fr;                 /* Pointer to the current Frame */
   AstMapping *smap;             /* Base->current Mapping */
   AstRegion *this;              /* Pointer to the Region structure */
   AstRegion *unc;               /* Pointer to the uncertainty Region */
   double dval;                  /* Floating point attribute value */
   int ival;                     /* Integer attribute value */
   int set;                      /* Attribute value set? */
   int unit;                     /* Base->current is unitmap? */

/* Check the global error status. */
   if ( !astOK ) return;

/* Obtain a pointer to the Region structure. */
   this = (AstRegion *) this_object;

/* Write out values representing the instance variables for the
   Region class.  Accompany these with appropriate comment strings,
   possibly depending on the values being written.*/

/* In the case of attributes, we first use the appropriate (private)
   Test...  member function to see if they are set. If so, we then use
   the (private) Get... function to obtain the value to be written
   out.

   For attributes which are not set, we use the astGet... method to
   obtain the value instead. This will supply a default value
   (possibly provided by a derived class which over-rides this method)
   which is more useful to a human reader as it corresponds to the
   actual default attribute value.  Since "set" will be zero, these
   values are for information only and will not be read back. */

/* Negated. */
/* -------- */
   set = TestNegated( this, status );
   ival = set ? GetNegated( this, status ) : astGetNegated( this );
   astWriteInt( channel, "Negate", (ival != 0), 0, ival,
                ival ? "Region negated" : "Region not negated" );

/* FillFactor */
/* ---------- */
   set = TestFillFactor( this, status );
   dval = set ? GetFillFactor( this, status ) : astGetFillFactor( this );
   astWriteDouble( channel, "Fill", set, 0, dval,"Region fill factor" );

/* MeshSize. */
/* --------- */
   set = TestMeshSize( this, status );
   ival = set ? GetMeshSize( this, status ) : astGetMeshSize( this );
   astWriteInt( channel, "MeshSz", set, 0, ival,
                "No. of points used to represent boundary" );

/* Closed. */
/* ------- */
   set = TestClosed( this, status );
   ival = set ? GetClosed( this, status ) : astGetClosed( this );
   astWriteInt( channel, "Closed", set, 0, ival,
                ival ? "Boundary is inside" : "Boundary is outside" );

/* Adaptive */
/* -------- */
   set = TestAdaptive( this, status );
   ival = set ? GetAdaptive( this, status ) : astGetAdaptive( this );
   astWriteInt( channel, "Adapt", (ival != 0), 0, ival,
                ival ? "Region adapts to coord sys changes" : "Region does not adapt to coord sys changes" );

/* FrameSet */
/* -------- */

/* If the vertices are the same in both base and current Frames (i.e.
   if the Frames are connected by a UnitMap), then just dump the current
   Frame (unless the RegionFS attribute is zero, in which case the
   current Frame can be determined from the higher level context of the
   Region and so does not need to be dumped- e.g. if the Region is contained
   within another Region the parent Region will define the current Frame).
   Otherwise, dump the whole FrameSet. */
   ival = astGetRegionFS( this );
   smap = astRegMapping( this );
   if( ( unit = astIsAUnitMap( smap ) ) ){
      set = 0;
      if( ival ) {
         fr = astGetFrame( this->frameset, AST__CURRENT );
         astWriteObject( channel, "Frm", 1, 1, fr, "Coordinate system" );
         fr = astAnnul( fr );
      }
   } else {
      set = ( ival == 0 );
      astWriteObject( channel, "FrmSet", 1, 1, this->frameset,
                      "Original & current coordinate systems" );
   }

/* Annul the Mapping pointers */
   smap = astAnnul( smap );

/* RegionFS */
/* -------- */
   astWriteInt( channel, "RegFS", set, 0, ival,
                ival ? "Include Frame in dump" : "Do not include Frame in dump" );

/* Points */
/* ------ */
   if( this->points ) {
      astWriteObject( channel, "Points", 1, 1, this->points,
                      "Points defining the shape" );

/* If the FrameSet was not included in the dump, then the loader will use
   the PointSet to determine the number of axes in the frame spanned by
   the Region. If there is no PointSet, then we must explicitly include
   an item giving the number of axes.*/
   } else {
      astWriteInt( channel, "RegAxes", 1, 1, astGetNaxes( this ),
                   "Number of axes spanned by the Region" );
   }

/* Uncertainty */
/* ----------- */
/* Only dump the uncertinaty Region if required. */
   if( astTestUnc( this ) ) {
      unc = astGetUncFrm( this, AST__BASE );
      astWriteObject( channel, "Unc", 1, 1, unc,
                      "Region defining positional uncertainties." );
      unc = astAnnul( unc );
   }

/* Undefine macros local to this function. */
#undef KEY_LEN
}


/* Standard class functions. */
/* ========================= */
/* Implement the astIsARegion and astCheckRegion functions using
   the macros defined for this purpose in the "object.h" header
   file. */
astMAKE_ISA(Region,Frame)
astMAKE_CHECK(Region)

AstRegion *astInitRegion_( void *mem, size_t size, int init,
                           AstRegionVtab *vtab, const char *name,
                           AstFrame *frame, AstPointSet *pset,
                           AstRegion *unc, int *status ){
/*
*+
*  Name:
*     astInitRegion

*  Purpose:
*     Initialise a Region.

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     AstRegion *astInitRegion( void *mem, size_t size, int init,
*                               AstRegionVtab *vtab, const char *name,
*                               AstFrame *frame, AstpointSet *pset,
*                               AstRegion *unc )

*  Class Membership:
*     Region initialiser.

*  Description:
*     This function is provided for use by class implementations to
*     initialise a new Region object. It allocates memory (if
*     necessary) to accommodate the Region plus any additional data
*     associated with the derived class.  It then initialises a
*     Region structure at the start of this memory. If the "init"
*     flag is set, it also initialises the contents of a virtual
*     function table for a Region at the start of the memory passed
*     via the "vtab" parameter.

*  Parameters:
*     mem
*        A pointer to the memory in which the Region is to be
*        created. This must be of sufficient size to accommodate the
*        Region data (sizeof(Region)) plus any data used by the
*        derived class. If a value of NULL is given, this function
*        will allocate the memory itself using the "size" parameter to
*        determine its size.
*     size
*        The amount of memory used by the Region (plus derived class
*        data).  This will be used to allocate memory if a value of
*        NULL is given for the "mem" parameter. This value is also
*        stored in the Region structure, so a valid value must be
*        supplied even if not required for allocating memory.
*     init
*        A logical flag indicating if the Region's virtual function
*        table is to be initialised. If this value is non-zero, the
*        virtual function table will be initialised by this function.
*     vtab
*        Pointer to the start of the virtual function table to be
*        associated with the new Region.
*     name
*        Pointer to a constant null-terminated character string which
*        contains the name of the class to which the new object
*        belongs (it is this pointer value that will subsequently be
*        returned by the astGetClass method).
*     frame
*        Pointer to the encapsulated Frame. A deep copy of this Frame is
*        taken. This means that subsequent changes to the supplied Frame
*        will have no effect on the new Region.
*     pset
*        A PointSet holding the points which define the Region. These
*        positions should refer to the given Frame. May be NULL.
*     unc
*        A pointer to a Region which specifies the uncertainty in the
*        supplied positions (all points on the boundary of the new Region
*        being initialised are assumed to have the same uncertainty). A NULL
*        pointer can be supplied, in which case default uncertainties equal to
*        1.0E-6 of the dimensions of the new Region's bounding box are used.
*        If an uncertainty Region is supplied, it must be of a class for
*        which all instances are centro-symetric (e.g. Box, Circle, Ellipse,
*        etc.) or be a Prism containing centro-symetric component Regions.
*        Its encapsulated Frame must be related to the Frame supplied for
*        parameter "frame" (i.e. astConvert should be able to find a Mapping
*        between them). Two positions in the "frame" Frame are considered to be
*        co-incident if their uncertainty Regions overlap. The centre of the
*        supplied uncertainty Region is immaterial since it will be re-centred
*        on the point being tested before use. A deep copy is taken of the
*        supplied Region.

*  Returned Value:
*     A pointer to the new Region.

*  Notes:
*     - A null pointer will be returned if this function is invoked
*     with the global error status set, or if it should fail for any
*     reason.
*-
*/

/* Local Variables: */
   AstFrame *f0;                  /* Frame to use */
   AstRegion *new;                /* Pointer to new Region */
   int nax;                       /* No. of axes in supplied Frame */
   int ncoord;                    /* Coords per point */

/* Check the global status. */
   if ( !astOK ) return NULL;

/* If necessary, initialise the virtual function table. */
   if( init ) astInitRegionVtab( vtab, name );

/* Note the number of axes in the supplied Frame. */
   nax = astGetNaxes( frame );

/* Check the pointset if supplied. */
   if( pset ) {

/* Note the number of axes per point in the supplied PointSet */
      ncoord = astGetNcoord( pset );

/* If OK, check that the number of coordinates per point matches the number
   of axes in the Frame. Report an error if these numbers do not match. */
      if ( astOK && ( ncoord != nax ) ) {
         astError( AST__NCPIN, "astInitRegion(%s): Bad number of coordinate "
                   "values per point (%d).", status, name, ncoord );
         astError( AST__NCPIN, "The %s given requires %d coordinate value(s) "
                   "for each point.", status, astGetClass( frame ), nax );
      }
   }

/* Initialise a Frame structure (the parent class) as the first
   component within the Region structure, allocating memory if
   necessary. Give this Frame zero axes as the Frame information will be
   specified by the encapsulated FrameSet. */
   new = (AstRegion *) astInitFrame( mem, size, 0, (AstFrameVtab *) vtab,
                                     name, 0 );
   if ( astOK ) {

/* Initialise the Region data. */
/* ----------------------------- */
      new->frameset = NULL;
      new->points = NULL;
      new->unc = NULL;
      new->meshsize = -INT_MAX;
      new->adaptive = -INT_MAX;
      new->basemesh = NULL;
      new->basegrid = NULL;
      new->negated = -INT_MAX;
      new->closed = -INT_MAX;
      new->regionfs = -INT_MAX;
      new->fillfactor = AST__BAD;
      new->defunc = NULL;
      new->nomap = 0;
      new->negation = NULL;

/* If the supplied Frame is a Region, gets its encapsulated Frame. If a
   FrameSet was supplied, use its current Frame, otherwise use the
   supplied Frame. */
      if( astIsARegion( frame ) ) {
         f0 = astGetFrame( ((AstRegion *) frame)->frameset, AST__CURRENT );

      } else if( astIsAFrameSet( frame ) ) {
         f0 = astGetFrame( (AstFrameSet *) frame, AST__CURRENT );

      } else {
         f0 = astClone( frame );
      }

/* Store a clone of the supplied PointSet pointer. */
      new->points = pset ? astClone( pset ) : NULL;


#ifdef DEBUG
      if( pset ) {
         double **ptr;
         double lim;
         int ii,jj, np;
         ptr = astGetPoints( pset );
         np = astGetNpoint( pset );
         lim = sqrt( DBL_MAX );
         for( ii = 0; astOK && ii < ncoord; ii++ ) {
            for( jj = 0; jj < np; jj++ ) {
               if( fabs( ptr[ ii ][ jj ] ) > lim ) {
                  if( !strcmp( name, "Interval" ) ) {
                     if( ptr[ ii ][ jj ] != AST__BAD &&
                         ptr[ ii ][ jj ] != DBL_MAX &&
                         ptr[ ii ][ jj ] != -DBL_MAX ) {
                        astError( AST__INTER, "astInitRegion(%s): suspicious "
                          "axis value (%g) supplied.", status, name, ptr[ ii ][ jj ] );
                        break;
                     }
                  } else {
                     astError( AST__INTER, "astInitRegion(%s): suspicious "
                            "axis value (%g) supplied.", status, name,
                            ptr[ ii ][ jj ] );
                     break;
                  }
               }
            }
         }
      }
#endif

/* Form a FrameSet consisting of two copies of the supplied Frame connected
   together by a UnitMap, and store in the Region structure. We use the
   private SetRegFS rather than the protected astSetRegFS because this
   initialiser may be being called from a subclass which over-rides
   astSetRegFS. If this were the case, then the implementation of
   astSetRegFS provided by the subclass may access information within the
   subclass structure which has not yet been initialised. */
      SetRegFS( new, f0, status );
      f0 = astAnnul( f0 );

/* Store any uncertainty Region. Use the private SetUnc rather than
   astSetUnc to avoid subclass implementations using subclass data which
   has not yet been initialised. */
      SetUnc( new, unc, status );

/* If an error occurred, clean up by deleting the new object. */
      if ( !astOK ) new = astDelete( new );
   }

/* Return a pointer to the new object. */
   return new;
}

AstRegion *astLoadRegion_( void *mem, size_t size,
                           AstRegionVtab *vtab, const char *name,
                           AstChannel *channel, int *status ) {
/*
*+
*  Name:
*     astLoadRegion

*  Purpose:
*     Load a Region.

*  Type:
*     Protected function.

*  Synopsis:
*     #include "region.h"
*     AstRegion *astLoadRegion( void *mem, size_t size,
*                               AstRegionVtab *vtab, const char *name,
*                               AstChannel *channel )

*  Class Membership:
*     Region loader.

*  Description:
*     This function is provided to load a new Region using data read
*     from a Channel. It first loads the data used by the parent class
*     (which allocates memory if necessary) and then initialises a
*     Region structure in this memory, using data read from the
*     input Channel.

*  Parameters:
*     mem
*        A pointer to the memory into which the Region is to be
*        loaded.  This must be of sufficient size to accommodate the
*        Region data (sizeof(Region)) plus any data used by
*        derived classes. If a value of NULL is given, this function
*        will allocate the memory itself using the "size" parameter to
*        determine its size.
*     size
*        The amount of memory used by the Region (plus derived class
*        data).  This will be used to allocate memory if a value of
*        NULL is given for the "mem" parameter. This value is also
*        stored in the Region structure, so a valid value must be
*        supplied even if not required for allocating memory.
*
*        If the "vtab" parameter is NULL, the "size" value is ignored
*        and sizeof(AstRegion) is used instead.
*     vtab
*        Pointer to the start of the virtual function table to be
*        associated with the new Region. If this is NULL, a pointer
*        to the (static) virtual function table for the Region class
*        is used instead.
*     name
*        Pointer to a constant null-terminated character string which
*        contains the name of the class to which the new object
*        belongs (it is this pointer value that will subsequently be
*        returned by the astGetClass method).
*
*        If the "vtab" parameter is NULL, the "name" value is ignored
*        and a pointer to the string "Region" is used instead.

*  Returned Value:
*     A pointer to the new Region.

*  Notes:
*     - A null pointer will be returned if this function is invoked
*     with the global error status set, or if it should fail for any
*     reason.
*-
*/

/* Local Constants: */
   astDECLARE_GLOBALS            /* Pointer to thread-specific global data */
#define KEY_LEN 50               /* Maximum length of a keyword */

/* Local Variables: */
   AstFrame *f1;                  /* Base Frame for encapsulated FrameSet */
   AstRegion *new;                /* Pointer to the new Region */
   int nax;                       /* No. of axes in Frame, or FrameSet base Frame */
   int naxpt;                     /* No. of axes in per point */

/* Get a pointer to the thread specific global data structure. */
   astGET_GLOBALS(channel);

/* Initialise. */
   new = NULL;

/* Check the global error status. */
   if ( !astOK ) return new;

/* If a NULL virtual function table has been supplied, then this is
   the first loader to be invoked for this Region. In this case the
   Region belongs to this class, so supply appropriate values to be
   passed to the parent class loader (and its parent, etc.). */
   if ( !vtab ) {
      size = sizeof( AstRegion );
      vtab = &class_vtab;
      name = "Region";

/* If required, initialise the virtual function table for this class. */
      if ( !class_init ) {
         astInitRegionVtab( vtab, name );
         class_init = 1;
      }
   }

/* Invoke the parent class loader to load data for all the ancestral
   classes of the current one, returning a pointer to the resulting
   partly-built Region. */
   new = astLoadFrame( mem, size, (AstFrameVtab *) vtab, name,
                       channel );

   if ( astOK ) {

/* Read input data. */
/* ================ */
/* Request the input Channel to read all the input data appropriate to
   this class into the internal "values list". */
      astReadClassData( channel, "Region" );

/* Now read each individual data item from this list and use it to
   initialise the appropriate instance variable(s) for this class. */

/* In the case of attributes, we first read the "raw" input value,
   supplying the "unset" value as the default. If a "set" value is
   obtained, we then use the appropriate (private) Set... member
   function to validate and set the value properly. */

/* Negated */
/* ------- */
      new->negated = astReadInt( channel, "negate", -INT_MAX );
      if ( TestNegated( new, status ) ) SetNegated( new, new->negated, status );

/* FillFactor */
/* ---------- */
      new->fillfactor = astReadDouble( channel, "fill", AST__BAD );
      if ( TestFillFactor( new, status ) ) SetFillFactor( new, new->fillfactor, status );

/* MeshSize */
/* -------- */
      new->meshsize = astReadInt( channel, "meshsz", -INT_MAX );
      if ( TestMeshSize( new, status ) ) SetMeshSize( new, new->meshsize, status );

/* Closed */
/* ------ */
      new->closed = astReadInt( channel, "closed", -INT_MAX );
      if ( TestClosed( new, status ) ) SetClosed( new, new->closed, status );

/* Adaptive */
/* -------- */
      new->adaptive = astReadInt( channel, "adapt", -INT_MAX );
      if ( TestAdaptive( new, status ) ) SetAdaptive( new, new->adaptive, status );

/* Points */
/* ------ */
      new->points = astReadObject( channel, "points", NULL );

/* If some points were found, ensure that they are in a PointSet and get
   the number of axis values per point. */
      if( new->points ){
         if( astIsAPointSet( new->points) ) {
            naxpt = astGetNcoord( new->points );
         } else {
            naxpt = 0;
            astError( AST__REGIN, "astLoadRegion(%s): Corrupt %s specifies points "
                      "using a %s (should be a PointSet).", status, astGetClass( new ),
                      astGetClass( new ), astGetClass( new->points ) );
         }

/* If no PointSet was loaded, attempt to determine the number of axes
   spanned by the Region by reading the RegAxes value. */
      } else {
         naxpt = astReadInt( channel, "regaxes", 0 );
      }

/* Uncertainty */
/* ----------- */
      new->unc = astReadObject( channel, "unc", NULL );
      new->defunc = NULL;

/* FrameSet */
/* -------- */
/* First see if the dump contains a single Frame. If so, create a
   FrameSet from it and a copy of itself, using a UnitMap to connect the
   two. */
      new->nomap = 0;
      new->frameset = NULL;
      f1 = astReadObject( channel, "frm", NULL );
      if( f1 ) {
         new->regionfs = 1;
         nax = astGetNaxes( f1 );
         astSetRegFS( new, f1 );
         f1 = astAnnul( f1 );

/* If no Frame was found in the dump, look for a FrameSet. Get the number
   of axes spanning its base Frame ("Nin"). */
      } else {
         new->frameset = astReadObject( channel, "frmset", NULL );
         if( new->frameset ) {
            nax = astGetNin( new->frameset );

/* If a FrameSet was found, the value of the RegionFS attribute is still
   unknown and so we must read it from an attribute as normal. */
            new->regionfs = astReadInt( channel, "regfs", 1 );
            if ( TestRegionFS( new, status ) ) SetRegionFS( new, new->regionfs, status );

         } else {
            nax = 0;
         }
      }

/* If neither a Frame nor a FrameSet was found, create a default FrameSet
   and set the RegionFS attribute false, to indicate that the FrameSet
   should not be used. */
      if( !new->frameset ){
         nax = naxpt ? naxpt : 1;
         f1 = astFrame( nax, "", status );
         new->frameset = astFrameSet( f1, "", status );
         astSetIdent( new->frameset, DUMMY_FS );
         f1 = astAnnul( f1 );
         new->regionfs = 0;
      }

/* Report an error if the number of axis values per point in the pointset is
   incorrect. */
      if ( astOK && new->points && ( naxpt != nax ) ) {
         astError( AST__REGIN, "astLoadRegion(%s): Corrupt %s contains "
                   " incorrect number of coordinate values per point (%d).", status,
                   astGetClass( new ), astGetClass( new ), naxpt );
         astError( AST__REGIN, "The %s requires %d coordinate value(s) "
                   "for each point.", status, astGetClass( new ), nax );
      }

/* Initialise other fields which are used as caches for values derived
   from the attributes set above. */
      new->basemesh = NULL;
      new->basegrid = NULL;

/* If an error occurred, clean up by deleting the new Region. */
      if ( !astOK ) new = astDelete( new );
   }

/* Return the new Region pointer. */
   return new;

/* Undefine macros local to this function. */
#undef KEY_LEN
}

/* Virtual function interfaces. */
/* ============================ */
/* These provide the external interface to the virtual functions defined by
   this class. Each simply checks the global error status and then locates and
   executes the appropriate member function, using the function pointer stored
   in the object's virtual function table (this pointer is located using the
   astMEMBER macro defined in "object.h").

   Note that the member function may not be the one defined here, as it may
   have been over-ridden by a derived class. However, it should still have the
   same interface. */

void astRegClearAttrib_( AstRegion *this, const char *attrib, char **base_attrib, int *status ) {
   if ( !astOK ) return;
   (**astMEMBER(this,Region,RegClearAttrib))( this, attrib, base_attrib, status );
}
void astRegSetAttrib_( AstRegion *this, const char *setting, char **base_setting, int *status ) {
   if ( !astOK ) return;
   (**astMEMBER(this,Region,RegSetAttrib))( this, setting, base_setting, status );
}
void astNegate_( AstRegion *this, int *status ){
   if ( !astOK ) return;
   (**astMEMBER(this,Region,Negate))( this, status );
}
AstFrame *astGetRegionFrame_( AstRegion *this, int *status ){
   if ( !astOK ) return NULL;
   return (**astMEMBER(this,Region,GetRegionFrame))( this, status );
}
AstFrameSet *astGetRegionFrameSet_( AstRegion *this, int *status ){
   if ( !astOK ) return NULL;
   return (**astMEMBER(this,Region,GetRegionFrameSet))( this, status );
}
AstRegion *astMapRegion_( AstRegion *this, AstMapping *map, AstFrame *frame, int *status ){
   if ( !astOK ) return NULL;
   return (**astMEMBER(this,Region,MapRegion))( this, map, frame, status );
}
int astOverlap_( AstRegion *this, AstRegion *that, int *status ){
   if ( !astOK ) return 0;
   return (**astMEMBER(this,Region,Overlap))( this, that, status );
}
int astOverlapX_( AstRegion *that, AstRegion *this, int *status ){
   if ( !astOK ) return 0;
   return (**astMEMBER(that,Region,OverlapX))( that, this, status );
}
AstFrame *astRegFrame_( AstRegion *this, int *status ){
   if ( !astOK ) return NULL;
   return (**astMEMBER(this,Region,RegFrame))( this, status );
}
AstRegion *astRegBasePick_( AstRegion *this, int naxes, const int *axes, int *status ){
   if ( !astOK ) return NULL;
   return (**astMEMBER(this,Region,RegBasePick))( this, naxes, axes, status );
}
AstPointSet *astBTransform_( AstRegion *this, AstPointSet *in,
                             int forward, AstPointSet *out, int *status ) {
   if ( !astOK ) return NULL;
   return (**astMEMBER(this,Region,BTransform))( this, in, forward, out, status );
}
AstPointSet *astRegTransform_( AstRegion *this, AstPointSet *in,
                               int forward, AstPointSet *out,
                               AstFrame **frm, int *status ) {
   if( frm ) *frm = NULL;
   if ( !astOK ) return NULL;
   return (**astMEMBER(this,Region,RegTransform))( this, in, forward, out, frm, status );
}
int astRegPins_( AstRegion *this, AstPointSet *pset, AstRegion *unc, int **mask, int *status ){
   if( mask ) *mask = NULL;
   if ( !astOK ) return 0;
   return (**astMEMBER(this,Region,RegPins))( this, pset, unc, mask, status );
}
AstMapping *astRegMapping_( AstRegion *this, int *status ){
   if ( !astOK ) return NULL;
   return (**astMEMBER(this,Region,RegMapping))( this, status );
}
int astRegDummyFS_( AstRegion *this, int *status ){
   if ( !astOK ) return 0;
   return (**astMEMBER(this,Region,RegDummyFS))( this, status );
}
int astGetBounded_( AstRegion *this, int *status ){
   if ( !astOK ) return 0;
   return (**astMEMBER(this,Region,GetBounded))( this, status );
}
int astTestUnc_( AstRegion *this, int *status ){
   if ( !astOK ) return 0;
   return (**astMEMBER(this,Region,TestUnc))( this, status );
}
void astClearUnc_( AstRegion *this, int *status ){
   if ( !astOK ) return;
   (**astMEMBER(this,Region,ClearUnc))( this, status );
}
void astRegBaseBox_( AstRegion *this, double *lbnd, double *ubnd, int *status ){
   if ( !astOK ) return;
   (**astMEMBER(this,Region,RegBaseBox))( this, lbnd, ubnd, status );
}
void astRegBaseBox2_( AstRegion *this, double *lbnd, double *ubnd, int *status ){
   if ( !astOK ) return;
   (**astMEMBER(this,Region,RegBaseBox2))( this, lbnd, ubnd, status );
}
void astResetCache_( AstRegion *this, int *status ){
   if ( !astOK ) return;
   (**astMEMBER(this,Region,ResetCache))( this, status );
}
int astRegTrace_( AstRegion *this, int n, double *dist, double **ptr, int *status ){
   if ( !astOK ) return 0;
   return (**astMEMBER(this,Region,RegTrace))( this, n, dist, ptr, status );
}
void astGetRegionBounds_( AstRegion *this, double *lbnd, double *ubnd, int *status ){
   if ( !astOK ) return;
   (**astMEMBER(this,Region,GetRegionBounds))( this, lbnd, ubnd, status );
}
void astGetRegionMesh_( AstRegion *this, int surface, int maxpoint,
                        int maxcoord, int *npoint, double *points,
                        int *status ){
   if ( !astOK ) return;
   (**astMEMBER(this,Region,GetRegionMesh))( this, surface, maxpoint, maxcoord,
                                             npoint, points, status );
}
void astGetRegionPoints_( AstRegion *this, int maxpoint, int maxcoord,
                          int *npoint, double *points, int *status ){
   if ( !astOK ) return;
   (**astMEMBER(this,Region,GetRegionPoints))( this, maxpoint, maxcoord,
                                               npoint, points, status );
}
void astGetRegionDisc_( AstRegion *this, double centre[2], double *radius, int *status ){
   if ( !astOK ) return;
   (**astMEMBER(this,Region,GetRegionDisc))( this, centre, radius, status );
}
void astShowMesh_( AstRegion *this, int format, const char *ttl, int *status ){
   if ( !astOK ) return;
   (**astMEMBER(this,Region,ShowMesh))( this, format,ttl, status );
}
void astGetRegionBounds2_( AstRegion *this, double *lbnd, double *ubnd, int *status ){
   if ( !astOK ) return;
   (**astMEMBER(this,Region,GetRegionBounds2))( this, lbnd, ubnd, status );
}
void astRegOverlay_( AstRegion *this, AstRegion *that, int unc, int *status ){
   if ( !astOK ) return;
   (**astMEMBER(this,Region,RegOverlay))( this, that, unc, status );
}
AstPointSet *astRegGrid_( AstRegion *this, int *status ){
   if ( !astOK ) return NULL;
   return (**astMEMBER(this,Region,RegGrid))( this, status );
}
AstPointSet *astRegMesh_( AstRegion *this, int *status ){
   if ( !astOK ) return NULL;
   return (**astMEMBER(this,Region,RegMesh))( this, status );
}
double *astRegCentre_( AstRegion *this, double *cen, double **ptr, int index,
                       int ifrm, int *status ){
   if ( !astOK ) return NULL;
   return (**astMEMBER(this,Region,RegCentre))( this, cen, ptr, index, ifrm, status );
}
AstRegion *astGetNegation_( AstRegion *this, int *status ){
   if ( !astOK ) return NULL;
   return (**astMEMBER(this,Region,GetNegation))( this, status );
}
AstRegion *astGetUncFrm_( AstRegion *this, int ifrm, int *status ){
   if ( !astOK ) return NULL;
   return (**astMEMBER(this,Region,GetUncFrm))( this, ifrm, status );
}
AstRegion *astGetDefUnc_( AstRegion *this, int *status ){
   if ( !astOK ) return NULL;
   return (**astMEMBER(this,Region,GetDefUnc))( this, status );
}
AstRegion *astGetUnc_( AstRegion *this, int def, int *status ){
   if ( !astOK ) return NULL;
   return (**astMEMBER(this,Region,GetUnc))( this, def, status );
}
void astSetUnc_( AstRegion *this, AstRegion *unc, int *status ){
   if ( !astOK ) return;
   (**astMEMBER(this,Region,SetUnc))( this, unc, status );
}
AstFrameSet *astGetRegFS_( AstRegion *this, int *status ){
   if ( !astOK ) return NULL;
   return (**astMEMBER(this,Region,GetRegFS))( this, status );
}
void astSetRegFS_( AstRegion *this, AstFrame *frm, int *status ){
   if ( !astOK ) return;
   (**astMEMBER(this,Region,SetRegFS))( this, frm, status );
}
AstPointSet *astRegBaseMesh_( AstRegion *this, int *status ){
   if ( !astOK ) return NULL;
   return (**astMEMBER(this,Region,RegBaseMesh))( this, status );
}
AstRegion **astRegSplit_( AstRegion *this, int *nlist, int *status ){
   if ( !astOK ) return NULL;
   return (**astMEMBER(this,Region,RegSplit))( this, nlist, status );
}
AstPointSet *astRegBaseGrid_( AstRegion *this, int *status ){
   if ( !astOK ) return NULL;
   return (**astMEMBER(this,Region,RegBaseGrid))( this, status );
}
AstPointSet *astBndBaseMesh_( AstRegion *this, double *lbnd, double *ubnd, int *status ){
   if ( !astOK ) return NULL;
   return (**astMEMBER(this,Region,BndBaseMesh))( this, lbnd, ubnd, status );
}
AstPointSet *astBndMesh_( AstRegion *this, double *lbnd, double *ubnd, int *status ){
   if ( !astOK ) return NULL;
   return (**astMEMBER(this,Region,BndMesh))( this, lbnd, ubnd, status );
}

#define MAKE_MASK_(X,Xtype) \
int astMask##X##_( AstRegion *this, AstMapping *map, int inside, int ndim, \
                   const int lbnd[], const int ubnd[], Xtype in[], \
                   Xtype val, int *status ) { \
   if ( !astOK ) return 0; \
   return (**astMEMBER(this,Region,Mask##X))( this, map, inside, ndim, lbnd, \
                                              ubnd, in, val, status ); \
}
#if HAVE_LONG_DOUBLE     /* Not normally implemented */
MAKE_MASK_(LD,long double)
#endif
MAKE_MASK_(D,double)
MAKE_MASK_(F,float)
MAKE_MASK_(L,long int)
MAKE_MASK_(UL,unsigned long int)
MAKE_MASK_(I,int)
MAKE_MASK_(UI,unsigned int)
MAKE_MASK_(S,short int)
MAKE_MASK_(US,unsigned short int)
MAKE_MASK_(B,signed char)
MAKE_MASK_(UB,unsigned char)
#undef MAKE_MASK_

/* Special public interface functions. */
/* =================================== */
/* These provide the public interface to certain special functions
   whose public interface cannot be handled using macros (such as
   astINVOKE) alone. In general, they are named after the
   corresponding protected version of the function, but with "Id"
   appended to the name. */

/* Public Interface Function Prototypes. */
/* ------------------------------------- */
/* The following functions have public prototypes only (i.e. no
   protected prototypes), so we must provide local prototypes for use
   within this module. */

/* Special interface function implementations. */
/* ------------------------------------------- */


AstRegion *astMapRegionId_( AstRegion *this, AstMapping *map, AstFrame *frame, int *status ) {
/*
*++
*  Name:
c     astMapRegion
f     AST_MAPREGION

*  Purpose:
*     Transform a Region into a new Frame using a given Mapping.

*  Type:
*     Public virtual function.

*  Synopsis:
c     #include "region.h"
c     AstRegion *astMapRegion( AstRegion *this, AstMapping *map,
c                              AstFrame *frame )
f     RESULT = AST_MAPREGION( THIS, MAP, FRAME, STATUS )

*  Class Membership:
*     Region method.

*  Description:
*     This function returns a pointer to a new Region which corresponds to
*     supplied Region described by some other specified coordinate system. A
*     Mapping is supplied which transforms positions between the old and new
*     coordinate systems. The new Region may not be of the same class as
*     the original region.

*  Parameters:
c     this
f     THIS = INTEGER (Given)
*        Pointer to the Region.
c     map
f     MAP = INTEGER (Given)
*        Pointer to a Mapping which transforms positions from the
*        coordinate system represented by the supplied Region to the
*        coordinate system specified by
c        "frame".
f        FRAME.
*        The supplied Mapping should define both forward and inverse
*        transformations, and these transformations should form a genuine
*        inverse pair. That is, transforming a position using the forward
*        transformation and then using the inverse transformation should
*        produce the original input position. Some Mapping classes (such
*        as PermMap, MathMap, SphMap) can result in Mappings for which this
*        is not true.
c     frame
f     FRAME = INTEGER (Given)
*        Pointer to a Frame describing the coordinate system in which
*        the new Region is required.
f     STATUS = INTEGER (Given and Returned)
f        The global status.

*  Returned Value:
c     astMapRegion()
f     AST_MAPREGION = INTEGER
*        A pointer to a new Region. This Region will represent the area
*        within the coordinate system specified by
c        "frame"
f        FRAME
*        which corresponds to the supplied Region.

*  Notes:
*     - The uncertainty associated with the supplied Region is modified
*     using the supplied Mapping.
*     - A null Object pointer (AST__NULL) will be returned if this
c     function is invoked with the AST error status set, or if it
f     function is invoked with STATUS set to an error value, or if it
*     should fail for any reason.
*--

*  Implementation Notes:
*     - The only difference between this public interface and the protected
*     astMapRegion interface is that this implementation additionally
*     simplifies the returned Region. The protected implementation does
*     not do this since doing so can lead to infinite recursion because
*     it is sometimes necessary for Simplify to call astMapRegion.

*/

/* Local Variables: */
   AstRegion *new;                /* Pointer to new Region */
   AstRegion *result;             /* Pointer value to return */

/* Initialise. */
   result = NULL;

/* Check the global error status. */
   if ( !astOK ) return result;

/* Invoke the protected astMapRegion function. */
   new = astMapRegion( this, map, frame );

/* Simplify the resulting Region. */
   result = astSimplify( new );

/* Free resources. */
   new = astAnnul( new );

/* If not OK, annul the returned pointer. */
   if( !astOK ) result = astAnnul( result );

/* Return the result. */
   return result;
}