File: read.py

package info (click to toggle)
cf-python 1.3.2%2Bdfsg1-4
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 7,996 kB
  • sloc: python: 51,733; ansic: 2,736; makefile: 78; sh: 2
file content (2939 lines) | stat: -rw-r--r-- 102,666 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
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
import os
import netCDF4
import csv
import re
import textwrap
from datetime import datetime

from numpy import any          as numpy_any
from numpy import arange       as numpy_arange
from numpy import arccos       as numpy_arccos
from numpy import arcsin       as numpy_arcsin
from numpy import array        as numpy_array
from numpy import clip         as numpy_clip
from numpy import column_stack as numpy_column_stack
from numpy import cos          as numpy_cos
from numpy import deg2rad      as numpy_deg2rad
from numpy import dtype        as numpy_dtype
from numpy import empty        as numpy_empty
from numpy import mean         as numpy_mean
from numpy import pi           as numpy_pi
from numpy import rad2deg      as numpy_rad2deg
from numpy import resize       as numpy_resize
from numpy import result_type  as numpy_result_type
from numpy import sin          as numpy_sin
from numpy import transpose    as numpy_transpose
from numpy import where        as numpy_where

from netCDF4 import date2num as netCDF4_date2num

from ..            import __version__, __Conventions__, __file__
from ..domain      import Domain
from ..coordinatereference import CoordinateReference
from ..field       import Field, FieldList
from ..cellmethods import CellMethods
from ..cfdatetime  import Datetime
from ..coordinate  import DimensionCoordinate, AuxiliaryCoordinate
from ..functions   import RTOL, ATOL, equals
from ..units       import Units
from ..functions   import (open_files_threshold_exceeded, close_one_file,
                           abspath)
from ..data.data import Data, Partition, PartitionMatrix

from .filearray     import UMFileArray
from .functions     import _open_um_file
from .umread.umfile import UMFileException

# --------------------------------------------------------------------
# Constants
# --------------------------------------------------------------------
_pi_over_180 = numpy_pi/180.0

# PP missing data indicator
_pp_rmdi = -1.0e+30 

# Reference surface pressure in Pascals
_pstar     = 1.0e5

# --------------------------------------------------------------------
# Characters used in decoding LBEXP into a runid
# --------------------------------------------------------------------
_characters = ('a','b','c','d','e','f','g','h','i','j','k','l','m',
               'n','o','p','q','r','s','t','u','v','w','x','y','z', 
               '0','1','2','3','4','5','6','7','8','9')
_n_characters = len(_characters)

# --------------------------------------------------------------------
# Number matching regular expression
# --------------------------------------------------------------------
_number_regex = '([-+]?\d*\.?\d+(e[-+]?\d+)?)'

# --------------------------------------------------------------------
# Date-time object that copes with non-standard calendars
# --------------------------------------------------------------------
netCDF4_netcdftime_datetime = netCDF4.netcdftime.datetime

# --------------------------------------------------------------------
# Caches for derived values
# --------------------------------------------------------------------
_cache_latlon      = {}
_cached_runid      = {}
_cached_latlon     = {}
_cached_time       = {}
_cached_ctime      = {}
_cached_size_1_height_coordinate = {}
_cached_z_coordinate = {}
_cached_date2num = {}
_cached_model_level_number_coordinate = {}

_Units = {
    None                 : Units(),
    ''                   : Units(''),
    '1'                  : Units('1'),
    'Pa'                 : Units('Pa'),
    'm'                  : Units('m'),
    'hPa'                : Units('hPa'),
    'K'                  : Units('K'),
    'degrees'            : Units('degrees'),
    'degrees_east'       : Units('degrees_east'),
    'degrees_north'      : Units('degrees_north'),
    'days'               : Units('days'),
    'gregorian 1752-9-13': Units('days since 1752-9-13', 'gregorian'),
    '365_day 1752-9-13'  : Units('days since 1752-9-13', '365_day'),
    '360_day 0-1-1'      : Units('days since 0-1-1', '360_day'),
}

# --------------------------------------------------------------------
# Names of PP integer and real header items
# --------------------------------------------------------------------
_header_names = ('LBYR', 'LBMON', 'LBDAT', 'LBHR', 'LBMIN', 'LBDAY',
                 'LBYRD', 'LBMOND', 'LBDATD', 'LBHRD', 'LBMIND',
                 'LBDAYD', 'LBTIM', 'LBFT', 'LBLREC', 'LBCODE', 'LBHEM',
                 'LBROW', 'LBNPT', 'LBEXT', 'LBPACK', 'LBREL', 'LBFC',
                 'LBCFC', 'LBPROC', 'LBVC', 'LBRVC', 'LBEXP', 'LBEGIN', 
                 'LBNREC', 'LBPROJ', 'LBTYP', 'LBLEV', 'LBRSVD1',
                 'LBRSVD2', 'LBRSVD3', 'LBRSVD4', 'LBSRCE', 'LBUSER1',
                 'LBUSER2', 'LBUSER3', 'LBUSER4', 'LBUSER5', 'LBUSER6',
                 'LBUSER7',
                 'BRSVD1', 'BRSVD2', 'BRSVD3', 'BRSVD4', 
                 'BDATUM', 'BACC', 'BLEV', 'BRLEV', 'BHLEV', 'BHRLEV',
                 'BPLAT', 'BPLON', 'BGOR',
                 'BZY', 'BDY', 'BZX', 'BDX', 'BMDI', 'BMKS')

# --------------------------------------------------------------------
# Positions of PP header items in their arrays
# --------------------------------------------------------------------
(lbyr, lbmon, lbdat, lbhr, lbmin, lbday,
 lbyrd, lbmond, lbdatd, lbhrd, lbmind,
 lbdayd, lbtim, lbft, lblrec, lbcode, lbhem,
 lbrow, lbnpt, lbext, lbpack, lbrel, lbfc,
 lbcfc, lbproc, lbvc, lbrvc, lbexp, lbegin, 
 lbnrec, lbproj, lbtyp, lblev, lbrsvd1,
 lbrsvd2, lbrsvd3, lbrsvd4, lbsrce, lbuser1,
 lbuser2, lbuser3, lbuser4, lbuser5, lbuser6,
 lbuser7,
 ) = range(45)

(brsvd1, brsvd2, brsvd3, brsvd4, 
 bdatum, bacc, blev, brlev, bhlev, bhrlev,
 bplat, bplon, bgor,
 bzy, bdy, bzx, bdx, bmdi, bmks,
 ) = range(19)

# --------------------------------------------------------------------
# Assign CF standard name attributes to PP axis codes. (The full list
# of field code keys may be found at
# http://cms.ncas.ac.uk/html_umdocs/wave/@header.)
# --------------------------------------------------------------------
_coord_standard_name = {
    0   : None, # Sigma (or eta, for hybrid coordinate data).
    1   : 'air_pressure', # Pressure (mb).
    2   : 'altitude', # Height above sea level (km).
    3   : 'atmosphere_hybrid_sigma_pressure_coordinate', # Eta (U.M. hybrid coordinates) only.
    4   : 'depth', # Depth below sea level (m)
    5   : 'model_level_number', # Model level.        
    6   : 'air_potential_temperature', # Theta
    7   : 'atmosphere_sigma_coordinate', # Sigma only.
    8   : None, # Sigma-theta
    10  : 'latitude',  # Latitude (degrees N). 
    11  : 'longitude', # Longitude (degrees E).
    13  : 'region', # Site number (set of parallel rows or columns e.g.Time series)
    14  : 'atmosphere_hybrid_height_coordinate',
    15  : 'height',
    20  : 'time', # Time (days) (Gregorian calendar (not 360 day year))
    21  : 'time', # Time (months)
    22  : 'time', # Time (years)
    23  : 'time', # Time (model days with 360 day model calendar)
    40  : None,   # pseudolevel
    99  : None,   # Other
    -10 : 'grid_latitude',  # Rotated latitude (degrees). 
    -11 : 'grid_longitude', # Rotated longitude (degrees).
    -20 : 'radiation_wavelength',  
    }

# --------------------------------------------------------------------
# Assign CF long names to PP axis codes.
# --------------------------------------------------------------------
_coord_long_name = {}

# --------------------------------------------------------------------
# Assign CF units strings to PP axis codes.
# --------------------------------------------------------------------
#_coord_units = {
_axiscode_to_units = {
    0   : '1',             # Sigma (or eta, for hybrid coordinate data)
    1   : 'hPa',           # air_pressure                      
    2   : 'm',             # altitude         
    3   : '1',             # atmosphere_hybrid_sigma_pressure_coordinate
    4   : 'm',             # depth                                  
    5   : '1',             # model_level_number                         
    6   : 'K',             # air_potential_temperature
    7   : '1',             # atmosphere_sigma_coordinate               
    10  : 'degrees_north', # latitude                               
    11  : 'degrees_east',  # longitude                                
    13  : '',              # region                                     
    14  : '1',             # atmosphere_hybrid_height_coordinate          
    15  : 'm',             # height                                      
    20  : 'days',          # time (gregorian)                    
    23  : 'days',          # time (360_day)
    40  : '1',             # pseudolevel
    -10 : 'degrees', # rotated latitude  (not an official axis code)
    -11 : 'degrees', # rotated longitude (not an official axis code)
}

_axiscode_to_Units = {
    0   : _Units['1'],             # Sigma (or eta, for hybrid coordinate data)
    1   : _Units['hPa'],           # air_pressure                      
    2   : _Units['m'],             # altitude         
    3   : _Units['1'],             # atmosphere_hybrid_sigma_pressure_coordinate
    4   : _Units['m'],             # depth                                  
    5   : _Units['1'],             # model_level_number    
    6   : _Units['K'],             # air_potential_temperature
    7   : _Units['1'],             # atmosphere_sigma_coordinate  
    10  : _Units['degrees_north'], # latitude             
    11  : _Units['degrees_east'],  # longitude            
    13  : _Units[''],              # region               
    14  : _Units['1'],             # atmosphere_hybrid_height_coordinate
    15  : _Units['m'],             # height             
    20  : _Units['days'],          # time (gregorian)                    
    23  : _Units['days'],          # time (360_day)
    40  : _Units['1'],             # pseudolevel
    -10 : _Units['degrees'], # rotated latitude  (not an official axis code)
    -11 : _Units['degrees'], # rotated longitude (not an official axis code)
    }

# --------------------------------------------------------------------
# Assign CF axis attributes to PP axis codes.
# --------------------------------------------------------------------
_coord_axis = {
    1   : 'Z',   # air_pressure                       
    2   : 'Z',   # altitude                                     
    3   : 'Z',   # atmosphere_hybrid_sigma_pressure_coordinate  
    4   : 'Z',   # depth                                        
    5   : 'Z',   # model_level_number                          
    6   : 'Z',   # air_potential_temperature
    7   : 'Z',   # atmosphere_sigma_coordinate                
    10  : 'Y',   # latitude                                     
    11  : 'X',   # longitude                                    
    13  : None,  # region                                       
    14  : 'Z',   # atmosphere_hybrid_height_coordinate          
    15  : 'Z',   # height                                       
    20  : 'T',   # time (gregorian)                                         
    23  : 'T',   # time (360_day)                                         
    40  : None,  # pseudolevel                                    
    -10 : 'Y', # rotated latitude  (not an official axis code)
    -11 : 'X', # rotated longitude (not an official axis code)         
    }

# --------------------------------------------------------------------
# Assign CF positive attributes to PP axis codes.
# --------------------------------------------------------------------
_coord_positive = {
    1   : 'down',  # air_pressure                     
    2   : 'up',    # altitude                                  
    3   : 'down',  # atmosphere_hybrid_sigma_pressure_coordinate 
    4   : 'down',  # depth                                     
    5   : None,    # model_level_number                         
    6   : 'up',    # air_potential_temperature
    7   : 'down',  # atmosphere_sigma_coordinate               
    10  : None,    # latitude                                   
    11  : None,    # longitude                                   
    13  : None,    # region                                     
    14  : 'up',    # atmosphere_hybrid_height_coordinate         
    15  : 'up',    # height                                      
    20  : None,    # time (gregorian)                                          
    23  : None,    # time (360_day)                                        
    40  : None,    # pseudolevel                                    
    -10 : None, # rotated latitude  (not an official axis code)
    -11 : None, # rotated longitude (not an official axis code)
    }

# --------------------------------------------------------------------
# Translate LBVC codes to PP axis codes. (The full list of field code
# keys may be found at
# http://cms.ncas.ac.uk/html_umdocs/wave/@fcodes.)
# --------------------------------------------------------------------
_lbvc_to_axiscode = {
    1   :  2,   # altitude (Height) 
    2   :  4,   # depth (Depth)
    3   : None, # (Geopotential (= g*height))
    4   : None, # (ICAO height)
    6   :  5,   # model_level_number  
    7   : None, # (Exner pressure)
    8   :  1,   # air_pressure  (Pressure)
    9   :  3,   # atmosphere_hybrid_sigma_pressure_coordinate (Hybrid pressure)
    10  :  7,   # atmosphere_sigma_coordinate (Sigma (= p/surface p))   ## dch check
    16  : None, # (Temperature T)
    19  :  6,   # air_potential_temperature (Potential temperature)
    27  : None, # (Atmospheric) density
    28  : None, # (d(p*)/dt .  p* = surface pressure)
    44  : None, # (Time in seconds)
    65  : 14,   # atmosphere_hybrid_height_coordinate (Hybrid height)
    129 : None, # Surface
    176 : 10,   # latitude    (Latitude)
    177 : 11,   # longitude   (Longitude)
    }

# --------------------------------------------------------------------
# Names of PP extra data codes
# --------------------------------------------------------------------
_extra_data_name = {
    1  : 'x',
    2  : 'y',
    3  : 'y_domain_lower_bound',
    4  : 'x_domain_lower_bound',
    5  : 'y_domain_upper_bound',
    6  : 'x_domain_upper_bound',
    7  : 'z_domain_lower_bound',
    8  : 'x_domain_upper_bound',
    9  : 'title',
    10 : 'domain_title',
    11 : 'x_lower_bound',
    12 : 'x_upper_bound',
    13 : 'y_lower_bound',
    14 : 'y_upper_bound',
    }

# --------------------------------------------------------------------
# Model identifier codes. These are the the last four digits of
# LBSRCE.
# --------------------------------------------------------------------
_lbsrce_model_codes = {1111 : 'UM'}

# --------------------------------------------------------------------
# LBCODE values for unrotated latitude longitude grids
# --------------------------------------------------------------------
_true_latitude_longitude_lbcodes = set((1, 2))

# --------------------------------------------------------------------
# LBCODE values for rotated latitude longitude grids
# --------------------------------------------------------------------
_rotated_latitude_longitude_lbcodes = set((101, 102, 111))

_axis = {'t'   : 'dim0',
         'z'   : 'dim1',
         'y'   : 'dim2',
         'x'   : 'dim3',
         'r'   : 'dim4', 
         'p'   : 'dim5',
         'area': None,
     }

class UMField(object):
    '''

'''
    _debug = False

    def __init__(self, var, fmt, byte_ordering, word_size, um_version,
                 set_standard_name, height_at_top_of_model, **kwargs):
        '''

**Initialization**

:Parameters:

    var : cf.um.umread.umfile.Var

    byte_ordering : str
        'little_endian' or 'big_endian'

    word_size : int
        Word size in bytes (4 or 8).

    fmt : str
        'PP' or 'FF'

    um_version : number
    
    set_standard_name : bool
        If True then set the standard_name CF property.

    height_at_top_of_model : float, optional

    **kwargs : *optional*
        Keyword arguments specifying CF properties for the UM field.

'''       
        self._nonzero = False
       
        self.fmt                    = fmt
        self.height_at_top_of_model = height_at_top_of_model
        self.byte_ordering          = byte_ordering
        self.word_size              = word_size

        self.atol = ATOL()

        self.domain = Domain()

        cf_properties = {}
        attributes    = {}

        self.fields = []

        filename = abspath(var.file.path)
        self.filename = filename
    
        groups = var.group_records_by_extra_data()

        n_groups = len(groups)

        if n_groups == 1:
            # There is one group of records
            groups_nz = [var.nz]
            groups_nt = [var.nt]
        elif n_groups > 1:
            # There are multiple groups of records, distinguished by
            # different extra data.
            groups_nz = []
            groups_nt = []
            groups2 = []
            for group in groups:
                group_size = len(group)
                if group_size == 1:
                    # There is only one record in this group
                    split_group= False
                    nz = 1
                elif group_size > 1:
                    # There are multiple records in this group
                    # Find the lengths of runs of identical times
                    times   = [(self.header_vtime(rec), self.header_dtime(rec))
                               for rec in group]
                    lengths = [len(tuple(g)) for k, g in itertools.groupby(times)]
                    if len(set(lengths)) == 1: 
                        # Each run of identical times has the same
                        # length, so it is possible that this group
                        # forms a variable of nz x nt records. 
                        split_group = False
                        nz = lengths.pop()
                        z0 = [self.z for rec in group[:nz]]
                        for i in range(nz, group_size, nz):
                            z1 = [self.header_z(rec) for rec in group[i:i+nz]]
                            if z1 != z0:
                                split_group = True
                                break
                    else:  
                        # Different runs of identical times have
                        # different lengths, so it is not possible for
                        # this group to form a variable of nz x nt
                        # records.
                        split_group = True
                        nz = 1
                #--- End: if
                    
                if split_group:
                    # This group doesn't form a complete nz x nt
                    # matrix, so split it up into 1 x 1 groups.
                    groups2.extend([[rec] for rec in group])
                    groups_nz.extend([1] * group_size)
                    groups_nt.extend([1] * group_size)
                else:
                    # This group forms a complete nz x nt matrix, so
                    # it may be considered as a variable in its own
                    # right and doesn't need to be split up.
                    groups2.append(group)
                    groups_nz.append(nz)
                    groups_nt.append(group_size/nz)
            #--- End: for
            groups = groups2
        #--- End: if

        rec0 = groups[0][0]

        int_hdr = rec0.int_hdr
        self.int_hdr_dtype = int_hdr.dtype

        int_hdr  = int_hdr.tolist()
        real_hdr = rec0.real_hdr.tolist()
        self.int_hdr  = int_hdr
        self.real_hdr = real_hdr

        # ------------------------------------------------------------
        # Set some metadata quantities which are guaranteed to be the
        # same for all records in a variable
        # ------------------------------------------------------------
        LBNPT   = int_hdr[lbnpt]
        LBROW   = int_hdr[lbrow]
        LBTIM   = int_hdr[lbtim]
        LBCODE  = int_hdr[lbcode]
        LBPROC  = int_hdr[lbproc]
        LBVC    = int_hdr[lbvc]
        LBUSER5 = int_hdr[lbuser5]
        BPLAT = real_hdr[bplat]
        BPLON = real_hdr[bplon]
        BDX   = real_hdr[bdx]
        BDY   = real_hdr[bdy]
        
        self.lbnpt   = LBNPT
        self.lbrow   = LBROW
        self.lbtim   = LBTIM
        self.lbproc  = LBPROC
        self.lbvc    = LBVC
        self.bplat = BPLAT
        self.bplon = BPLON
        self.bdx   = BDX
        self.bdy   = BDY

        # ------------------------------------------------------------
        # Set some derived metadata quantities which are (as good as)
        # guaranteed to be the same for all records in a variable
        # ------------------------------------------------------------
        self.lbtim_ia, ib = divmod(LBTIM, 100)
        self.lbtim_ib, ic = divmod(ib, 10)
        
        if ic == 1:
            calendar = 'gregorian'
        elif ic == 4:
            calendar = '365_day'
        else:
            calendar = '360_day'
    
        self.calendar = calendar
        self.reference_time_Units()
    
        header_um_version, source = divmod(int_hdr[lbsrce], 10000)
       
        if header_um_version > 0 and int(um_version) == um_version: #len(um_version) <= 3:
#            header_um_version = str(header_um_version)
            model_um_version = header_um_version
            self.um_version  = header_um_version
        else:
            model_um_version = None
            self.um_version  = um_version
            
        # Set source
        source = _lbsrce_model_codes.setdefault(source, None)
        if source is not None and model_um_version is not None:
            source += ' vn%s' % model_um_version
        if source:
            cf_properties['source'] = source
            
        # ------------------------------------------------------------
        # Set the T, Z, Y and X axis codes. These are guaranteed to be
        # the same for all records in a variable.
        # ------------------------------------------------------------
        if LBCODE == 1 or LBCODE == 2:
            # 1 = Unrotated regular lat/long grid
            # 2 = Regular lat/lon grid boxes (grid points are box
            #     centres)
            ix = 11
            iy = 10
        elif LBCODE == 101 or LBCODE == 102:
            # 101 = Rotated regular lat/long grid
            # 102 = Rotated regular lat/lon grid boxes (grid points
            #       are box centres)
            ix = -11  # rotated longitude (not an official axis code)
            iy = -10  # rotated latitude  (not an official axis code)
        elif LBCODE >= 10000:
            # Cross section
            ix, iy = divmod(divmod(LBCODE, 10000)[1], 100)
        else:
            ix = None
            iy = None
        
        iz = _lbvc_to_axiscode.setdefault(LBVC, None)
        
        # Set it from the calendar type
        if iy in (20, 23) or ix in (20, 23):
            # Time is dealt with by x or y
            it = None
        elif calendar == 'gregorian':
            it = 20
        else:
            it = 23
        
        self.ix = ix
        self.iy = iy
        self.iz = iz
        self.it = it
    
        self.cf_info = {}
    
        # Set a identifying name based on the submodel and STASHcode
        # (or field code).
        stash    = int_hdr[lbuser4]
        submodel = int_hdr[lbuser7]
        self.stash = stash
    
        # The STASH code has been set in the PP header, so try to find
        # its standard_name from the conversion table
        stash_records = _stash2standard_name.get((submodel, stash), None)
    
        um_Units     = None
        long_name    = None
        um_condition = None
    
        if stash_records:
            um_version = self.um_version
            for (long_name, 
                 units,
                 valid_from,
                 valid_to, 
                 standard_name,
                 cf_info,
                 um_condition) in stash_records:
    
                # Check that conditions are met
                if not self.test_um_version(valid_from, valid_to, um_version):
                    continue
    
                if um_condition:
                    if not self.test_um_condition(um_condition,
                                                  LBCODE, BPLAT, BPLON):
                        continue
    
                # Still here? Then we have our standard_name, etc.
                if standard_name:
                    if set_standard_name:
                        cf_properties['standard_name'] = standard_name
                    else:
                        attributes['_standard_name'] = standard_name
                    
                cf_properties['long_name'] = long_name.rstrip()
    
                um_Units = _Units.get(units, None)
                if um_Units is None:
                    um_Units = Units(units)
                    _Units[units] = um_Units
    
                self.um_Units = um_Units
                self.cf_info  = cf_info
                
                break
            #--- End: for
        #--- End: if
    
        if stash:
            section, item = divmod(stash, 1000)
            um_stash_source = 'm%02ds%02di%03d' % (submodel, section, item)
            cf_properties['um_stash_source'] = um_stash_source 
            identity = 'UM_%s_vn%s' % (um_stash_source, self.um_version)
        else:
            identity = 'UM_%d_fc%d_vn%s' % (submodel, int_hdr[lbfc],
                                            self.um_version)
            
        if um_Units is None:
            self.um_Units = _Units[None]
    
        if um_condition:
            identity += '_%s' % um_condition
            
        if long_name is None:
            cf_properties['long_name'] = identity
                
        for recs, nz, nt in zip(groups, groups_nz, groups_nt):
            self.recs = recs
            self.nz = nz
            self.nt = nt
            self.z_recs = recs[:nz]
            self.t_recs = recs[::nz]
               
            LBUSER5 = recs[0].int_hdr.item(lbuser5,)

            self.cell_method_axis_name = {'area': 'area'}
    
            self.down_axes = set()
            self.z_axis    = 'z'
    
            # ------------------------------------------------------------
            # Get the extra data for this group
            # ------------------------------------------------------------
            extra = recs[0].get_extra_data()
            self.extra = extra

            # ------------------------------------------------------------
            # Set some derived metadata quantities
            # ------------------------------------------------------------
            if self._debug:
                print self.__dict__
                self.printfdr()
            
            # ------------------------------------------------------------
            # Create the 'T' dimension coordinate
            # ------------------------------------------------------------
            axiscode = it
            if axiscode is not None:         
                c = self.time_coordinate(axiscode)
    

            # ------------------------------------------------------------
            # Create the 'Z' dimension coordinate
            # ------------------------------------------------------------
            axiscode = iz
            if axiscode is not None:             
                # Get 'Z' coordinate from LBVC
                if axiscode == 3:
                    c = self.atmosphere_hybrid_sigma_pressure_coordinate(axiscode)
                elif axiscode == 2 and 'height' in self.cf_info:                
                    # Create the height coordinate from the information
                    # given in the STASH to standard_name conversion table
                    height, units = self.cf_info['height']
                    c = self.size_1_height_coordinate(axiscode, height, units)
                elif axiscode == 14:
                    c = self.atmosphere_hybrid_height_coordinate(axiscode)
                else:
                    c = self.z_coordinate(axiscode)
                             
   
                # Create a model_level_number auxiliary coordinate
                LBLEV = int_hdr[lblev]
                if LBVC in (2, 9, 65) or LBLEV in (7777, 8888): # CHECK!
                    self.LBLEV = LBLEV
                    c = self.model_level_number_coordinate(aux=bool(c)) 
            #--- End: if
     
            # ------------------------------------------------------------
            # Create the 'Y' dimension coordinate
            # ------------------------------------------------------------
            axiscode = iy
            yc = None
            if axiscode is not None:
                if axiscode in (20, 23):
                    # 'Y' axis is time-since-reference-date
                    if extra.get('y', None) is not None:                        
                        c = self.time_coordinate_from_extra_data(axiscode, 'y')
                    else:
                        LBUSER3 = int_hdr[lbuser3]
                        if LBUSER3 == LBROW:
                            self.lbuser3 = LBUSER3
                            c = self.time_coordinate_from_um_timeseries(axiscode,
                                                                       'y')
                else:
                    yc = self.xy_coordinate(axiscode, 'y')
            #--- End: if
    
            # ------------------------------------------------------------
            # Create the 'X' dimension coordinate
            # ------------------------------------------------------------
            axiscode = ix
            xc = None
            if axiscode is not None:
                if axiscode in (20, 23):
                    # X axis is time since reference date
                    if extra.get('x', None) is not None:                       
                        c = self.time_coordinate_from_extra_data(axiscode, 'x')
                    else:
                        LBUSER3 = int_hdr[lbuser3]
                        if LBUSER3 == LBNPT:
                            self.lbuser3 = LBUSER3
                            c = self.time_coordinate_from_um_timeseries(axiscode, 'x')
                else:
                    xc = self.xy_coordinate(axiscode, 'x')
            #--- End: if

            # -10: rotated latitude  (not an official axis code)
            # -11: rotated longitude (not an official axis code)


            if (iy, ix) == (-10, -11) or (iy, ix) == (-11, -10):
                # ----------------------------------------------------
                # Create a ROTATED_LATITUDE_LONGITUDE coordinate
                # reference
                # ----------------------------------------------------
                transform = CoordinateReference(
                    name='rotated_latitude_longitude',
                    grid_north_pole_latitude=BPLAT,
                    grid_north_pole_longitude=BPLON,
                    coords=(_axis['y'], _axis['x']))
    
                # --------------------------------------------------------
                # Create UNROTATED, 2-D LATITUDE and LONGITUDE auxiliary
                # coordinates
                # --------------------------------------------------------
                self.latitude_longitude_2d_aux_coordinates(yc, xc, transform)
    
                # Insert the coordinate reference into the domain
                self.domain.insert_ref(transform, copy=False)
            #--- End: if
    
            # ------------------------------------------------------------
            # Create a RADIATION WAVELENGTH dimension coordinate
            # ------------------------------------------------------------
            try:
                rwl, rwl_units = self.cf_info['below']
            except (KeyError, TypeError):
                pass
            else:
                c = self.radiation_wavelength_coordinate(rwl, rwl_units)
    
                # Set LBUSER5 to zero so that it is not confused for a
                # pseudolevel
                LBUSER5 = 0
            #--- End: try
    
            # ------------------------------------------------------------
            # Create a PSEUDOLEVEL dimension coordinate. This must be
            # done *after* the possible creation of a radiation
            # wavelength dimension coordinate.
            # ------------------------------------------------------------
            if LBUSER5 != 0:
                self.pseudolevel_coordinate(LBUSER5)
    
            attributes['int_hdr']  = int_hdr[:]
            attributes['real_hdr'] = real_hdr[:]
            attributes['file']     = filename        
            attributes['id']       = identity
            
            cf_properties['Conventions'] = __Conventions__
            cf_properties['runid']       = self.decode_lbexp()
            cf_properties['lbproc']      = str(LBPROC)
            cf_properties['lbtim']       = str(LBTIM)
            cf_properties['stash_code']  = str(stash)
    
            # ------------------------------------------------------------
            # Create cell methods
            # ------------------------------------------------------------
            cell_methods = self.create_cell_methods()
            if cell_methods is not None:
                cf_properties['cell_methods'] = cell_methods
    
            # ------------------------------------------------------------
            # Set the data and extra data
            # ------------------------------------------------------------
            data = self.create_data()

            cf_properties['_FillValue'] = data.fill_value

            # ------------------------------------------------------------
            # Create the field
            # ------------------------------------------------------------
            # Add kwargs to the CF properties
            cf_properties.update(kwargs)
            
            field = Field(domain=self.domain,
                          data=self.data,
                          axes=self.data_axes,
                          properties=cf_properties, 
                          attributes=attributes,
                          copy=False)
    
            # Check for decreasing axes that aren't decreasing
            down_axes = self.down_axes
            if down_axes:
                field.flip(down_axes, i=True)
                
            # Force cyclic X axis for paritcular values of LBHEM
            if int_hdr[lbhem] in (0, 1, 2, 4):
                field.cyclic('X', period=360)
                
            self.fields.append(field)
        #--- End: for

        self._nonzero = True
    #--- End: def

    def __nonzero__(self):
        '''

x.__nonzero__() <==> bool(x)

'''
        return self._nonzero
    #--- End: if

    def __repr__(self):
        '''

x.__repr__() <==> repr(x)

'''
        return self.fdr()
    #--- End: def

    def __str__(self):
        '''

x.__str__() <==> str(x)

'''
        out = [self.fdr()]        
        
        attrs = ('endian',
                 'reftime', 'vtime', 'dtime',
                 'um_version', 'source',
                 'it', 'iz', 'ix', 'iy', 
                 'site_time_cross_section', 'timeseries',
                 'file')

        for attr in attrs:
            out.append('%s=%s' % (attr, getattr(self, attr, None)))
            
        out.append('')

        return '\n'.join(out)   
    #--- End: def

    def atmosphere_hybrid_height_coordinate(self, axiscode):
        '''

**From appendix A of UMDP F3**

From UM Version 5.2, the method of defining the model levels in PP
headers was revised. At vn5.0 and 5.1, eta values were used in the PP
headers to specify the levels of model data, which was of limited use
when plotting data on model levels. From 5.2, the PP headers were
redefined to give information on the height of the level. Given a 2D
orography field, the height field for a given level can then be
derived. The height coordinates for PP-output are defined as:

  Z(i,j,k)=Zsea(k)+C(k)*orography(i,j)

where Zsea(k) and C(k) are height based hybrid coefficients.

  Zsea(k) = eta_value(k)*Height_at_top_of_model

  C(k)=[1-eta_value(k)/eta_value(first_constant_rho_level)]**2 forlevels less than or equal to first_constant_rho_level

  C(k)=0.0 for levels greater than first_constant_rho_level

where eta_value(k) is the eta_value for theta or rho level k. The
eta_value is a terrain-following height coordinate; full details are
given in UMDP15, Appendix B.

The PP headers store Zsea and C as follows :-

  * 46 = bulev = brsvd1  = Zsea of upper layer boundary
  * 52 = blev            = Zsea of level
  * 53 = brlev           = Zsea of lower layer boundary
  * 47 = bhulev = brsvd2 = C of upper layer boundary
  * 54 = bhlev           = C of level
  * 55 = bhrlev          = C of lower layer boundary

:Parameters:

    axiscode : int

:Returns:

    out : cf.DimensionCoordinate or None

        '''
        domain = self.domain
        zdim = _axis['z']

        # Insert new Z axis
        domain.insert_axis(self.nz, key=zdim)

        # "a" auxiliary coordinate
        array = numpy_array([rec.real_hdr[blev] for rec in self.z_recs],  # Zsea
                            dtype=float)
        bounds0 = numpy_array([rec.real_hdr[brlev] for rec in self.z_recs], #Zsea lower
                              dtype=float)
        bounds1 = numpy_array([rec.real_hdr[brsvd1] for rec in self.z_recs], #Zsea upper
                              dtype=float)
        bounds = numpy_column_stack((bounds0, bounds1))

        ac = AuxiliaryCoordinate()
        ac = self.coord_data(ac, array, bounds, units=_Units['m'])
        ac.id        = 'UM_atmosphere_hybrid_height_coordinate_a'
        ac.long_name = 'height based hybrid coeffient a'
        key_a = domain.insert_aux(ac, axes=[zdim], copy=False)

        # atmosphere_hybrid_height_coordinate dimension coordinate
        TOA_height = bounds1.max()
        if TOA_height <= 0:
            TOA_height = self.height_at_top_of_model
        if not TOA_height:
            dc = None
        else:            
            array  = array  / TOA_height
            bounds = bounds / TOA_height
                
            dc = DimensionCoordinate()
            dc = self.coord_data(dc, array, bounds, units=_Units[''])
            dc.standard_name = 'atmosphere_hybrid_height_coordinate'
            dc = self.coord_axis(dc, axiscode)
            dc = self.coord_positive(dc, axiscode, zdim)
            domain.insert_dim(dc, key=zdim, copy=False)
        #--- End: if

        # "b" auxiliary coordinate
        array = numpy_array([rec.real_hdr[bhlev] for rec in self.z_recs],
                            dtype=float)
        bounds0 = numpy_array([rec.real_hdr[bhrlev] for rec in self.z_recs],
                              dtype=float)
        bounds1 = numpy_array([rec.real_hdr[brsvd2] for rec in self.z_recs],
                              dtype=float)
        bounds = numpy_column_stack((bounds0, bounds1))

        ac = AuxiliaryCoordinate()
        ac = self.coord_data(ac, array, bounds, units=_Units['1'])
        ac.id        = 'UM_atmosphere_hybrid_height_coordinate_b'
        ac.long_name = 'height based hybrid coeffient b'
        key_b = domain.insert_aux(ac, axes=[zdim], copy=False)
        
        if bool(dc):
            self.cell_method_axis_name['z'] = dc.identity()
            
            # atmosphere_hybrid_height_coordinate coordinate reference
            ref = CoordinateReference(
                name='atmosphere_hybrid_height_coordinate',
                a=key_a, b=key_b,
                coords=(key_a, key_b), coord_terms=('a', 'b'))
            
            self.domain.insert_ref(ref, copy=False)
        #--- End: if

        return dc
    #--- End: def

    def depth_coordinate(self, axiscode):
        '''

:Parameters:

    axiscode : int

:Returns:

    out : cf.DimensionCoordinate or None

        '''
        dc = self.model_level_number_coordinate(aux=False)

        domain = self.domain
        zdim = _axis['z']

        array = numpy_array([rec.real_hdr[blev] for rec in self.z_recs],
                            dtype=float)
        bounds0 = numpy_array([rec.real_hdr[brlev] for rec in self.z_recs],
                              dtype=float)
        bounds1 = numpy_array([rec.real_hdr[brsvd1] for rec in self.z_recs],
                              dtype=float)
        bounds = numpy_column_stack((bounds0, bounds1))

        ac = AuxiliaryCoordinate()
        ac = self.coord_data(ac, array, bounds, units=_Units['m'])
        ac.id        = 'UM_atmosphere_hybrid_height_coordinate_ak'
        ac.long_name = 'atmosphere_hybrid_height_coordinate_ak'
        domain.insert_aux(ac, axes=[zdim], copy=False)

        array = numpy_array([rec.real_hdr[bhlev] for rec in self.z_recs],
                            dtype=float)
        bounds0 = numpy_array([rec.real_hdr[bhrlev] for rec in self.z_recs],
                              dtype=float)
        bounds1 = numpy_array([rec.real_hdr[brsvd2] for rec in self.z_recs],
                              dtype=float)
        bounds = numpy_column_stack((bounds0, bounds1))

        ac = AuxiliaryCoordinate()
        ac = self.coord_data(ac, array, bounds, units=_Units['1'])
        ac.id        = 'UM_atmosphere_hybrid_height_coordinate_bk'
        ac.long_name = 'atmosphere_hybrid_height_coordinate_bk'
        domain.insert_aux(ac, axes=[zdim], copy=False)
        
        if dc:
            self.cell_method_axis_name['z'] = dc.identity()

        return dc
    #--- End: def

    def atmosphere_hybrid_sigma_pressure_coordinate(self, axiscode):
        '''

atmosphere_hybrid_sigma_pressure_coordinate when not an array axis

:Parameters:

    axiscode : int

:Returns:

    out : cf.DimensionCoordinate

'''

# 46 BULEV Upper layer boundary or BRSVD(1)
# 
# 47 BHULEV Upper layer boundary or BRSVD(2)
# 
#         For hybrid levels:
#         - BULEV is B-value at half-level above.
#         - BHULEV is A-value at half-level above.
# 
#         For hybrid height levels (vn5.2-, Smooth heights)
#         - BULEV is Zsea of upper layer boundary
#             * If rho level: Zsea for theta level above
#         * If theta level: Zsea for rho level above
#         - BHLEV is C of upper layer boundary
#             * If rho level: C for theta level above
#             * If theta level: C for rho level above

        array     = []
        bounds    = []
        ak_array  = []
        ak_bounds = []
        bk_array  = []
        bk_bounds = []

        for rec in self.z_recs:
            BLEV, BRLEV, BHLEV, BHRLEV, BULEV, BHULEV = self.header_bz(rec)

            array.append(BLEV + BHLEV/_pstar)
            bounds.append([BRLEV + BHRLEV/_pstar, BULEV + BHULEV/_pstar])
            
            ak_array.append(BHLEV)
            ak_bounds.append((BHRLEV, BHULEV))
            
            bk_array.append(BLEV)
            bk_bounds.append((BRLEV , BULEV))
        #--- End: for    
   
        array     = numpy_array(array    , dtype=float)
        bounds    = numpy_array(bounds   , dtype=float)
        ak_array  = numpy_array(ak_array , dtype=float)
        ak_bounds = numpy_array(ak_bounds, dtype=float)
        bk_array  = numpy_array(bk_array , dtype=float)
        bk_bounds = numpy_array(bk_bounds, dtype=float)
        
        domain = self.domain

        zdim  = _axis['z']

        dc = DimensionCoordinate()
        dc = self.coord_data(
            dc, array, bounds,
            units=_axiscode_to_Units.setdefault(axiscode, None))
        dc = self.coord_positive(dc, axiscode, zdim)
        dc = self.coord_axis(dc, axiscode)
        dc = self.coord_names(dc, axiscode)
        domain.insert_dim(dc, key=zdim, copy=False)

        ac = AuxiliaryCoordinate()
        ac = self.coord_data(ac, ak_array, ak_bounds, units=_Units['Pa'])
        ac.id        = 'UM_atmosphere_hybrid_sigma_pressure_coordinate_ak'
        ac.long_name = 'atmosphere_hybrid_sigma_pressure_coordinate_ak'
        domain.insert_aux(ac, axes=[zdim], copy=False)

        ac = AuxiliaryCoordinate()
        ac = self.coord_data(ac, bk_array, bk_bounds, units=_Units['1'])
        domain.insert_aux(ac, axes=[zdim], copy=False)
        ac.id        = 'UM_atmosphere_hybrid_sigma_pressure_coordinate_bk'
        ac.long_name = 'atmosphere_hybrid_sigma_pressure_coordinate_bk'

        self.cell_method_axis_name['z'] = dc.identity()

        return dc
    #--- End: def
           
    def create_cell_methods(self):
        '''Create the cell methods

        '''
        cell_methods = []
        
        LBPROC = self.lbproc
        LBTIM_IB = self.lbtim_ib
        tmean_proc = 0
        if LBTIM_IB in (2, 3) and LBPROC in (128, 192, 2176, 4224, 8320):
            tmean_proc = 128
            LBPROC -= 128
                    
        # ------------------------------------------------------------
        # Area cell methods
        # ------------------------------------------------------------
        # -10: rotated latitude  (not an official axis code)
        # -11: rotated longitude (not an official axis code)
        if self.ix in (10, 11, 12, -10, -11) and self.iy in (10, 11, 12, -10, -11):
            cf_info = self.cf_info

            if 'where' in cf_info:
                cell_methods.append('area: mean')
                
                cell_methods.append(cf_info['where'])
                if 'over' in cf_info:
                    cell_methods.append(cf_info['over'])
             #--- End: if
   
            if LBPROC == 64:
               cell_methods.append('x: mean')

            # dch : do special zonal mean as as in pp_cfwrite
            
        # ------------------------------------------------------------
        # Vertical cell methods
        # ------------------------------------------------------------
        if LBPROC == 2048:
            cell_methods.append('z: mean')
    
        # ------------------------------------------------------------
        # Time cell methods
        # ------------------------------------------------------------
        if LBTIM_IB == 0 or LBTIM_IB == 1:
            cell_methods.append('t: point')
        elif LBPROC == 4096:
            cell_methods.append('t: minimum')
        elif LBPROC == 8192:
            cell_methods.append('t: maximum')
        if tmean_proc == 128:
            if LBTIM_IB == 2:
                cell_methods.append('t: mean')
            elif LBTIM_IB == 3:
                cell_methods.append('t: mean within years')
                cell_methods.append('t: mean over years')
        #--- End: if
    
        if not cell_methods:
            return None

        cell_methods = CellMethods(' '.join(cell_methods))
            
        cell_method_axis_name = self.cell_method_axis_name
        for c in cell_methods:
            names0 =  c.names[0]
            c.axes  = [_axis[name]                 for name in names0]
            c.names = [cell_method_axis_name[name] for name in names0]
        #--- End: for

        return cell_methods
    #--- End: def
  
    def coord_axis(self, c, axiscode):
        axis = _coord_axis.setdefault(axiscode, None)
        if axis is not None:
            c.axis = axis

        return c
    #--- End: def

    def coord_data(self, c, array=None, bounds=None,
                   units=None, fill_value=None, climatology=False):
        '''
   
Set the data array of a coordinate construct.

 :Parameters:
   
       c : cf.DimensionCoordinate or cf.AuxiliaryCoordinate
   
       data : array-like, optional
           The data array.
             
       bounds : array-like, optional
           The Cell bounds for the data array.
              
       units : cf.Units, optional
           The units of the data array.

       fill_value : optional

       climatology : bool, optional
           Whether or not the coordinate construct is a time
           climatology. By default it is not.

 :Returns:
   
       out : cf.Coordinate
        
        '''
        if array is not None:
            array = Data(array, units=units, fill_value=fill_value)
            
        if bounds is not None:
            bounds = Data(bounds, units=units, fill_value=fill_value)
            if climatology:
                c.climatology = True
        #--- End: if

        c.insert_data(array, bounds=bounds, copy=False)
   
        return c
    #--- End: def

    def coord_names(self, c, axiscode):
        '''
        '''
        standard_name = _coord_standard_name.setdefault(axiscode, None)
        if standard_name is not None:
            c.setprop('standard_name', standard_name)
            c.ncvar = standard_name
        else:
            long_name = _coord_long_name.setdefault(axiscode, None)
            if long_name is not None:
                c.long_name = long_name

        return c
    #--- End: def

    def coord_positive(self, c, axiscode, dim):
        positive = _coord_positive.setdefault(axiscode, None)
        if positive is not None:
            c.positive = positive
            if positive == 'down' and axiscode != 4:
                self.down_axes.add(dim)
        #--- End: def

        return c
    #--- End: def

    def ctime(self, rec):
        '''
        '''
        reftime = self.refUnits
        LBVTIME = tuple(self.header_vtime(rec))
        LBDTIME = tuple(self.header_dtime(rec))

        key = (LBVTIME, LBDTIME, self.refunits, self.calendar)
        ctime = _cached_ctime.get(key, None)
        if ctime is None:
#            LTIME = list(LBDTIME)
#            LTIME[0] =  LBVTIME[0]
            ctime = Datetime(*LBDTIME)
            ctime.year = LBVTIME[0]
            if ctime < Datetime(*LBVTIME):
                ctime.year += 1
            ctime = Data(ctime, reftime).array.item()
            _cached_ctime[key] = ctime
        #--- End: if

        return ctime
    #--- End: def

    def header_vtime(self, rec):
        '''

Return the list [LBYR, LBMON, LBDAT, LBHR, LBMIN] for the given
record.

:Parameters:

    rec : 

:Returns:

    out : list 

:Examples:

>>> u.header_vtime(rec)
[1991, 1, 1, 0, 0]

        '''
        return rec.int_hdr[lbyr:lbmin+1]
    #--- End: def

    def header_dtime(self, rec):
        '''

Return the list [LBYRD, LBMOND, LBDATD, LBHRD, LBMIND] for the
given record.

:Parameters:

    rec : 

:Returns:

    out : list 

:Examples:

>>> u.header_dtime(rec)
[1991, 2, 1, 0, 0]

        '''
        return rec.int_hdr[lbyrd:lbmind+1]
    #--- End: def

    def header_bz(self, rec):
        '''

Return the list [BLEV, BRLEV, BHLEV, BHRLEV, BULEV, BHULEV] for the
given record.

:Parameters:

    rec : 

:Returns:

    out : list 

:Examples:

>>> u.header_bz(rec)


'''
        real_hdr = rec.real_hdr
        return (real_hdr[blev:bhrlev+1].tolist()    +  # BLEV, BRLEV, BHLEV, BHRLEV
                real_hdr[brsvd1:brsvd2+1].tolist())    # BULEV, BHULEV
    #--- End: def
    
    def header_lz(self, rec):
        '''

Return the list [LBLEV, LBUSER5] for the given record.

:Parameters:

    rec : 

:Returns:

    out : list 

:Examples:

>>> u.header_lz(rec)


'''
        int_hdr = rec.int_hdr
        return [int_hdr.item(lblev,), int_hdr.item(lbuser5,)]
    #--- End: def

    def header_z(self, rec):
        '''

Return the list [LBLEV, LBUSER5, BLEV, BRLEV, BHLEV, BHRLEV, BULEV,
BHULEV] for the given record.

:Parameters:

    rec : 

:Returns:

    out : list 

:Examples:

>>> u.header_z(rec)


'''
        # ------------------------------------------------------------
        # These header items are used by the compare_levels function
        # in compare.c
        # ------------------------------------------------------------
        return self.header_lz + self.header_bz
    #--- End: def

    def create_data(self):
        '''

Sets the `!data` and `!data_axes` attributes.
    
:Returns:

    None
    
'''
        LBROW = self.lbrow
        LBNPT = self.lbnpt

        yx_shape = (LBROW, LBNPT)
        yx_size  = LBROW * LBNPT

        nz   = self.nz
        nt   = self.nt
        recs = self.recs

        units = self.um_Units

        data_type_in_file = self.data_type_in_file

        filename = self.filename

        data_axes = [_axis['y'], _axis['x']]

        if len(recs) == 1:
            # --------------------------------------------------------
            # 0-d partition matrix
            # --------------------------------------------------------            
            rec = recs[0]            
            data = Data(UMFileArray(file=filename, 
                                    ndim=2,
                                    shape=yx_shape,
                                    size=yx_size,
                                    dtype=data_type_in_file(rec),
                                    header_offset=rec.hdr_offset,
                                    data_offset=rec.data_offset,
                                    disk_length=rec.disk_length),
                        units=units,
                        fill_value=rec.real_hdr.item(bmdi,))
        else:
            # --------------------------------------------------------
            # 1-d or 2-d partition matrix
            # --------------------------------------------------------
            file_data_types = set()
            word_sizes = set()

            # Find the partition matrix shape
            pmshape = [n for n in (nt, nz) if n > 1]
            pmndim  = len(pmshape)
                      
            partitions = []
            empty_list = []
            partitions_append = partitions.append

            zero_to_LBROW = (0, LBROW)
            zero_to_LBNPT = (0, LBNPT)

            if pmndim == 1:
                # ----------------------------------------------------
                # 1-d partition matrix
                # ----------------------------------------------------
                data_ndim = 3
                if nz > 1:
                    pmaxes = [_axis[self.z_axis]]
                    data_shape = (nz, LBROW, LBNPT)
                    data_size  = nz * yx_size
                else:
                    pmaxes = [_axis['t']]
                    data_shape = (nt, LBROW, LBNPT)
                    data_size  = nt * yx_size

                partition_shape = [1, LBROW, LBNPT]

                for i, rec  in enumerate(recs):
                    # Find the data type of the array in the file
                    file_data_type = data_type_in_file(rec)
                    file_data_types.add(file_data_type)

                    subarray = UMFileArray(file=filename, 
                                           ndim=2,
                                           shape=yx_shape,
                                           size=yx_size,
                                           dtype=file_data_type,
                                           header_offset=rec.hdr_offset,
                                           data_offset=rec.data_offset,
                                           disk_length=rec.disk_length)

                    partitions_append(Partition(
                        subarray = subarray,
                        location = [(i, i+1), zero_to_LBROW, zero_to_LBNPT],
                        shape    = partition_shape,
                        axes     = data_axes,
                        flip     = empty_list,
                        part     = empty_list,
                        Units    = units))
                #--- End: for

                # Populate the 1-d partition matrix
                matrix = numpy_array(partitions, dtype=object)
            else:
                # ----------------------------------------------------
                # 2-d partition matrix
                # ----------------------------------------------------
                pmaxes = [_axis['t'], _axis[self.z_axis]]
                data_shape = (nt, nz, LBROW, LBNPT)
                data_size  = nt * nz * yx_size
                data_ndim  = 4

                partition_shape = [1, 1, LBROW, LBNPT]

                for i, rec  in enumerate(recs):
                    # Find T and Z axis indices
                    t, z = divmod(i, nz)
                 
                    # Find the data type of the array in the file
                    file_data_type = data_type_in_file(rec)
                    file_data_types.add(file_data_type)

                    subarray = UMFileArray(file=filename,  
                                           ndim=2,
                                           shape=yx_shape,
                                           size=yx_size,
                                           dtype=file_data_type,
                                           header_offset=rec.hdr_offset,
                                           data_offset=rec.data_offset,
                                           disk_length=rec.disk_length)

                    partitions_append(Partition(
                        subarray=subarray,
                        location=[(t, t+1), (z, z+1), zero_to_LBROW, zero_to_LBNPT],
                        shape=partition_shape,
                        axes=data_axes,
                        flip=empty_list,
                        part=empty_list,
                        Units=units))
                #--- End: for

                # Populate the 2-d partition matrix
                matrix = numpy_array(partitions, dtype=object)
                matrix.resize(pmshape)                
            #--- End: if
                       
            data_axes = pmaxes + data_axes

            # Set the data array
            data = Data(units=units, fill_value=recs[0].real_hdr.item(bmdi,))

            data._axes      = data_axes
            data._shape     = data_shape 
            data._ndim      = data_ndim
            data._size      = data_size
            data.partitions = PartitionMatrix(matrix, pmaxes)
            data.dtype      = numpy_result_type(*file_data_types)
        #--- End: if

        self.data      = data
        self.data_axes = data_axes

        return data
    #---End: def

    def decode_lbexp(self):
        '''Decode the integer value of LBEXP in the PP header into a runid.
    
If this value has already been decoded, then it will be returned from
the cache, otherwise the value will be decoded and then added to the
cache.

:Returns:

    out : str
       A string derived from LBEXP. If LBEXP is a negative integer
       then that number is returned as a string.

:Examples:

>>> self.decode_lbexp()
'aaa5u'
>>> self.decode_lbexp()
'-34'

        '''
        LBEXP = self.int_hdr[lbexp]

        runid = _cached_runid.get(LBEXP, None)
        if runid is not None:
            # Return a cached decoding of this LBEXP
            return runid
    
        if LBEXP < 0:
            runid = str(LBEXP)
        else:
            # Convert LBEXP to a binary string, filled out to 30 bits with
            # zeros
            bits = bin(LBEXP)
            bits = bits.lstrip('0b').zfill(30)
        
            # Step through 6 bits at a time, converting each 6 bit chunk into
            # a decimal integer, which is used as an index to the characters
            # lookup list.
            runid = []
            for i in xrange(0,30,6):
                index = int(bits[i:i+6], 2) 
                if index < _n_characters:
                    runid.append(_characters[index])
            #--- End: for
            runid = ''.join(runid)
        #--- End: def

        # Enter this runid into the cache
        _cached_runid[LBEXP] = runid
    
        # Return the runid
        return runid
    #--- End: def 

    def dtime(self, rec):
        '''
        '''
        reftime = self.refUnits
        units    = self.refunits
        calendar = self.calendar

        LBDTIME = tuple(self.header_dtime(rec))

        key = (LBDTIME, units, calendar)
        time = _cached_date2num.get(key, None)
        if time is None:
            # It is important to use the same time_units as vtime
            if self.calendar == 'gregorian':
                time = netCDF4_date2num(
                    datetime(*LBDTIME), units, calendar)
            else:
                time = netCDF4_date2num(
                    netCDF4_netcdftime_datetime(*LBDTIME), units, calendar)
            _cached_date2num[key] = time
        #--- End: if

        return time
    #--- End: def

    def fdr(self):
        '''Return a the contents of PP field headers as strings.

This is a bit like printfdr in the UKMO IDL PP library.

:Returns:

    out : list

'''
        out2 = []
        for i, rec in enumerate(self.recs):
            out = ['Field %d:' % i]

            x = ['%s::%s' % (name, value)
                 for name, value in zip(_header_names,
                                        self.int_hdr + self.real_hdr)]
            
            x = textwrap.fill(' '.join(x), width=79)
            out.append(x.replace('::', ': '))
            
            if self.extra:
                out.append('EXTRA DATA:')
                for key in sorted(self.extra):
                    out.append('%s: %s' % (key, str(self.extra[key])))
            #--- End: if

            out.append('file: '+self.filename)
            out.append('format, byte order, word size: %s, %s, %d' % 
                       (self.fmt, self.byte_ordering, self.word_size))

            out.append('')

            out2.append('\n'.join(out))
        #--- End: for

        return out2
    #--- End: def

    def latitude_longitude_2d_aux_coordinates(self, yc, xc, transform):
        '''
'''
        BDX   = self.bdx
        BDY   = self.bdy
        LBNPT = self.lbnpt
        LBROW = self.lbrow
        BPLAT = self.bplat
        BPLON = self.bplon
        
        # Create the unrotated latitude and longitude arrays if we
        # couldn't find them in the cache
        cache_key = (LBNPT, LBROW, BDX, BDY, BPLAT, BPLON)
        lat, lon = _cache_latlon.get(cache_key, (None, None))

        if lat is None:
            lat, lon = self.unrotated_latlon(yc.varray, xc.varray,
                                             BPLAT, BPLON) 

            atol = self.atol
            if abs(BDX) >= atol and abs(BDY) >= atol:
                _cache_latlon[cache_key] = (lat, lon)
        #--- End: if

#        if xc.hasbounds and yc.hasbounds:
#            cache_key = ('bounds',) + cache_key
#            lat_bounds, lon_bounds = _cache_latlon.get(cache_key, (None, None))
#            print lat_bounds
#            if lat_bounds is None:
#                print  'CALC BOUNDS'
#                xb = numpy_empty(xc.size+1)
#                yb = numpy_empty(yc.size+1)
#                xb[:-1] = xc.bounds.subspace[ :, 0].squeeze(1, i=True).array
#                xb[-1 ] = xc.bounds.subspace[-1, 1].squeeze(1, i=True).array
#                yb[:-1] = yc.bounds.subspace[ :, 0].squeeze(1, i=True).array
#                yb[-1 ] = yc.bounds.subspace[-1, 1].squeeze(1, i=True).array
#                
#                lat_bounds, lon_bounds = self.unrotated_latlon(yb, xb, BPLAT, BPLON) 
#
#                print lat_bounds
#                print lat_bounds.shape
#                yyy = numpy_empty(lat.shape + (4,))
#
#                
#
#                print lat.shape, yyy.shape
#
#            atol = self.atol
#            if abs(BDX) >= atol and abs(BDY) >= atol:
#                _cache_latlon[cache_key] = (lat, lon)
        #--- End: if

        axes = [_axis['y'], _axis['x']]
        
        for axiscode, array in zip((10,  11),
                                   (lat, lon)):
            ac = AuxiliaryCoordinate()
            ac = self.coord_data(ac, array,
                                 units=_axiscode_to_Units.setdefault(axiscode, None))
            ac = self.coord_names(ac, axiscode)
            
            key = self.domain.insert_aux(ac, axes=axes, copy=False)
            
            transform.coords.add(key)
        #--- End: for
    #--- End: def

    def model_level_number_coordinate(self, aux=False):
        '''model_level_number dimension or auxiliary coordinate

:Parameters:

    aux : bool

:Returns:

    out : cf.AuxiliaryCoordinate or cf.DimensionCoordinate or None

''' 
        array = tuple([rec.int_hdr.item(lblev,) for rec in self.z_recs])

        key = array
        c = _cached_model_level_number_coordinate.get(key, None)

        if c is not None:
            if aux:
                self.domain.insert_aux(c, axes=[_axis['z']], copy=True)
            else:
                self.domain.insert_dim(c, key=_axis['z'], copy=True)
                self.cell_method_axis_name['z'] = c.identity()
        else:
            array = numpy_array(array, dtype=self.int_hdr_dtype)
            
            if array.min() < 0:
                return

            array = numpy_where(array==9999, 0, array)
        
            axiscode = 5
    
            if aux:
                c = AuxiliaryCoordinate()
                c = self.coord_data(c, array, units=Units('1'))
                c = self.coord_names(c, axiscode)
                self.domain.insert_aux(c, axes=[_axis['z']], copy=False)
            else:
                c = DimensionCoordinate()
                c = self.coord_data(c, array, units=Units('1'))
                c = self.coord_names(c, axiscode)
                c = self.coord_axis(c, axiscode)
                self.domain.insert_dim(c, key=_axis['z'], copy=False)
    
                self.cell_method_axis_name['z'] = c.identity()
            #--- End: if
            _cached_model_level_number_coordinate[key] = c
        #--- End: if

        return c
    #--- End: def

    def data_type_in_file(self, rec):
        '''Return the data type of the data array.

:Parameters:

    rec : umfile.Rec

:Returns:

    out : numpy.dtype

:Examples:

'''
        # Find the data type
        if rec.int_hdr.item(lbuser2,) == 3:
            # Boolean
            return numpy_dtype(bool)
        else:
            # Int or float
            return rec.get_type_and_num_words()[0]
#            rec_file = rec.file
##            data_type = rec_file.c_interface.get_type_and_length(
#            data_type = rec_file.c_interface.get_type_and_num_words(rec.int_hdr)[0]
#            if data_type == 'int':
#                # Integer
#                data_type = 'int%d' % (rec_file.word_size * 8)
#            else:
#                # Float
#                data_type = 'float%d' % (rec_file.word_size * 8)
#        #--- End: if
#
#        return numpy_dtype(data_type)
    #--- End: def

    def printfdr(self):
        '''Print out the contents of PP field headers.

This is a bit like printfdr in the UKMO IDL PP library.

:Examples:

>>> u.printfdr()

'''
        for header in self.fdr():
            print header
    #--- End: def

    def pseudolevel_coordinate(self, LBUSER5):
        '''
'''
        if self.nz == 1:            
            array = numpy_array((LBUSER5,), dtype=self.int_hdr_dtype)
        else:
            # 'Z' aggregation has been done along the pseudolevel axis
            array = numpy_array([rec.int_hdr.item(lbuser5,)
                                 for rec in self.z_recs],
                                dtype=self.int_hdr_dtype)
            self.z_axis = 'p'
        #--- End: if
        
        axiscode = 40

        dc = DimensionCoordinate()
        dc = self.coord_data(
            dc, array,
            units=_axiscode_to_Units.setdefault(axiscode, None))
        dc.long_name = 'pseudolevel' # for PP stash_code %d' % self.stash
        dc.id = 'UM_pseudolevel'

        self.domain.insert_dim(dc, key=_axis['p'], copy=False)        

        self.cell_method_axis_name['p'] = dc.identity()

        return dc
    #--- End: def

    def radiation_wavelength_coordinate(self, rwl, rwl_units):
        '''
'''
        array  = numpy_array((rwl,), dtype=float)
        bounds = numpy_array(((0.0, rwl)), dtype=float)

        units = _Units.get(rwl_units, None)
        if units is None:
            units = Units(rwl_units)
            _Units[rwl_units] = units
 
        axiscode = -20
        dc = DimensionCoordinate()
        dc = self.coord_data(dc, array, bounds, units=units)
        dc = self.coords_names(dc, axiscode)
        
        self.domain.insert_dim(dc, key=_axis['r'], copy=False)

        self.cell_method_axis_name['r'] = dc.identity()

        return dc
    #--- End: def

    def reference_time_Units(self):
        '''
        '''
        time_units = 'days since %d-1-1' % self.int_hdr[lbyr]
        calendar = self.calendar

        key = time_units+' calendar='+calendar
        units = _Units.get(key, None)
        if units is None:
            units = Units(time_units, calendar)
            _Units[key] = units
        #--- End: if

        self.refUnits = units
        self.refunits = time_units

        return units
    #--- End: def
    
    def size_1_height_coordinate(self, axiscode, height, units):
        # Create the height coordinate from the information given in the
        # STASH to standard_name conversion table

        key = (axiscode, height, units)
        dc = _cached_size_1_height_coordinate.get(key, None)

        zdim = _axis['z']

        if dc is not None:            
            copy = True
        else:
            height_units = _Units.get(units, None)
            if height_units is None:
                height_units = Units(units)
                _Units[units] = height_units
    
            array = numpy_array((height,), dtype=float)

            dc = DimensionCoordinate()
            dc = self.coord_data(dc, array, units=height_units)
            dc = self.coord_positive(dc, axiscode, zdim)
            dc = self.coord_axis(dc, axiscode)
            dc = self.coord_names(dc, axiscode)

            _cached_size_1_height_coordinate[key] = dc            
            copy = False
        #--- End: def 

        self.domain.insert_dim(dc, key=zdim, copy=copy)

        self.cell_method_axis_name['z'] = dc.identity()

        return dc
    #--- End: def
        
    def test_um_condition(self, um_condition, LBCODE, BPLAT, BPLON):
        '''Return True if a field satisfies the condition specified for a
STASH code to standard name conversion.
    
:Parameters:
    
    um_condition : str

    LBCODE : int        

    BPLAT : float

    BPLON : float

:Returns:
    
    out : bool
        True if a field satisfies the condition specified, False
        otherwise.
   
:Examples:
    
>>> ok = u.test_um_condition('true_latitude_longitude', ...)

        '''
        if um_condition == 'true_latitude_longitude':
            if LBCODE in _true_latitude_longitude_lbcodes:
                return True
    
            # Check pole location in case of incorrect LBCODE
            atol = self.atol
            if (abs(BPLAT-90.0) <= atol + RTOL()*90.0 and 
                abs(BPLON) <= atol):
                return True
    
        elif um_condition == 'rotated_latitude_longitude':
            if LBCODE in _rotated_latitude_longitude_lbcodes:
                return True
    
            # Check pole location in case of incorrect LBCODE
            atol = self.atol
            if not (abs(BPLAT-90.0) <= atol + RTOL()*90.0 and 
                    abs(BPLON) <= atol):
                return True
            
        else:
            raise ValueError(
                "Unknown UM condition in STASH code conversion table: '%s'" %
                um_condition)
    
        # Still here? Then the condition has not been satisfied.
        return
    #--- End: def

    def test_um_version(self, valid_from, valid_to, um_version):
        '''Return True if the UM version applicable to tghis field is
        within the given range.
    
If possible, the UM version is derived from the PP header and stored
in the metadata object. Otherwise it is taken from the *um_version*
parameter.
    
:Parameters:

    valid_from : int, float or None

    valid_to : int, float or None

    um_version : int or float

:Returns:

    out : bool
        True if the UM version applicable to this field is within the
        range, False otherwise.

:Examples:

>>> ok = u.test_um_version(401, 505, 1001)
>>> ok = u.test_um_version(401, None, 606.3)
>>> ok = u.test_um_version(None, 405, 401)

''' 
        if valid_to is None:
            if valid_from <= um_version:
                return True 
        elif valid_from is None:
            if um_version <= valid_to:
                return True 
        elif valid_from <= um_version <= valid_to:
            return True 

        return False    

#        if valid_from is '':
#        valid_from = None
#    
#        if valid_to is '':
#            if valid_from <= um_version:
#                return True 
#        elif valid_from <= um_version <= valid_to:
#            return True 
#    
#        return False
    #--- End: def

    def time_coordinate(self, axiscode):
        '''

Return the T dimension coordinate

'''

        recs = self.t_recs
        vtimes = numpy_array([self.vtime(rec) for rec in recs], dtype=float)
        dtimes = numpy_array([self.dtime(rec) for rec in recs], dtype=float)
        
        IB = self.lbtim_ib

        if IB <= 1 or vtimes.item(0,) >= dtimes.item(0,): 
            array  = vtimes
            bounds = None
            climatology = False                
        elif IB == 3:
            # The field is a time mean from T1 to T2 for each year
            # from LBYR to LBYRD
            ctimes = numpy_array([self.ctime(rec) for rec in recs])
            array  = 0.5*(vtimes + ctimes)
            bounds = numpy_column_stack((vtimes, dtimes))
            climatology = True                    
        else:
            array  = 0.5*(vtimes + dtimes)
            bounds = numpy_column_stack((vtimes, dtimes))
            climatology = False                
        #--- End: if            

        dc = DimensionCoordinate()
        dc = self.coord_data(dc, array, bounds,
                             units=self.refUnits,
                             climatology=climatology)
        dc = self.coord_axis(dc, axiscode)
        dc = self.coord_names(dc, axiscode)

        self.domain.insert_dim(dc, key=_axis['t'], copy=False)

        self.cell_method_axis_name['t'] = dc.identity()

        return dc
    #--- End: def

    def time_coordinate_from_extra_data(self, axiscode, axis):
        '''
'''     
        extra = self.extra
        array = extra[axis]
        bounds = extra.get(axis+'_bounds', None)

        calendar = self.calendar
        if calendar == '360_day':
            units = _Units['360_day 0-1-1']
        elif calendar == 'gregorian':
            units = _Units['gregorian 1752-9-13']
        elif calendar == '365_day':
            units = _Units['365_day 1752-9-13']
        else:
            units = None
                
        dc = DimensionCoordinate()
        dc = self.coord_data(dc, array, bounds, units=units)
        dc = self.coord_axis(dc, axiscode)
        dc = self.coord_names(dc, axiscode)

        self.domain.insert_dim(dc, key=_axis[axis], copy=False)

        self.cell_method_axis_name[axis] = dc.identity()
        self.cell_method_axis_name['t'] = self.cell_method_axis_name[axis]

        return dc
    #--- End: def        

    def time_coordinate_from_um_timeseries(self, axiscode, axis):
        # This PP/FF field is a timeseries. The validity time is
        # taken to be the time for the first sample, the data time
        # for the last sample, with the others evenly between.
        rec = self.recs[0]
        vtime = self.vtime(rec)
        dtime = self.dtime(rec)
        
        size  = self.lbuser3 - 1.0
        delta = (dtime - vtime)/size
        
        array = numpy_arange(vtime, vtime+delta*size, size, dtype=float)
                
        dc = DimensionCoordinate()
        dc = self.coord_data(dc, array, units=units)
        dc = self.coord_axis(dc, axiscode)
        dc = self.coord_names(dc, axiscode)

        self.domain.insert_dim(dc, key=_axis[axis], copy=False)

        self.cell_method_axis_name['t'] = dc.identity()

        return dc
    #--- End: def        

    def vtime(self, rec):
        '''
        '''
        reftime  = self.refUnits
        units    = self.refunits
        calendar = self.calendar

#        LBVTIME = tuple(rec.int_hdr[lbyr: lbmin+1])
        LBVTIME = tuple(self.header_vtime(rec))

        key = (LBVTIME, units, calendar)
        time = _cached_date2num.get(key, None)
        if time is None:
            # It is important to use the same time_units as dtime
            if self.calendar == 'gregorian':
                time = netCDF4_date2num(
                    datetime(*LBVTIME), units, calendar)
            else:                
                time = netCDF4_date2num(
                    netCDF4_netcdftime_datetime(*LBVTIME), units, calendar)
            _cached_date2num[key] = time
        #--- End: if

        return time
    #--- End: def

    def dddd(self):
        for axis_code, extra_type in zip((11 , 10 ),
                                         ('x', 'y')):
            coord_type = extra_type + '_domain_bounds'
            
            if coord_type in p.extra:
                p.extra[coord_type]
                # Create, from extra data, an auxiliary coordinate should   
                # with 1) data and bounds, if the upper and lower  be       
                # bounds have no missing values; or 2) data but no the      
                # bounds, if the upper bound has missing values  axis     
                # but the lower bound does not.                  # which    
                file_position = ppfile.tell()                                             # has      
                bounds = p.extra[coord_type][...]                                         # axis_code
                # Reset the file pointer after reading the extra                          # 13       
                # data into a numpy array
                ppfile.seek(file_position, os.SEEK_SET)
                data = None
                if numpy_any(bounds[..., 1] == _pp_rmdi): # dch also test in bmdi?
                    if not numpy_any(bounds[...,0] == _pp_rmdi): # dch also test in bmdi?
                        data = bounds[...,0]
                    bounds = None
                else:
                    data = numpy_mean(bounds, axis=1)

                if (data, bounds) != (None, None):
                    aux   = 'aux%(auxN)d' % locals()           
                    auxN += 1                        # Increment auxiliary number
                    
                    coord = _create_Coordinate(domain, aux, axis_code, p=p,
                                               array        = data,
                                               aux=True,
                                               bounds_array = bounds, 
                                               pubattr      = {'axis': None},
                                               dimensions   = [xdim]) # DCH      
                                                                    # xdim?    
                                                                    # should   
                                                                    # be       
                                                                    # the      
                                                                    # axis     
                                                                    # which    
                                                                    # has      
                                                                    # axis_code
                                                                    # 13       
                #--- End: if
            else:
                coord_type = '%s_domain_lower_bound' % extra_type
                if coord_type in p.extra:
                    # Create, from extra data, an auxiliary
                    # coordinate with data but no bounds, if the
                    # data noes not contain any missing values
                    file_position = ppfile.tell()
                    data = p.extra[coord_type][...]
                    # Reset the file pointer after reading the
                    # extra data into a numpy array
                    ppfile.seek(file_position, os.SEEK_SET)
                    if not numpy_any(data == _pp_rmdi): # dch also test in bmdi?   
                        aux   = 'aux%(auxN)d' % locals()           
                        auxN += 1                        # Increment auxiliary number
                        coord = _create_Coordinate(domain, aux, axis_code, p=p,
                                                   aux=True,
                                                   array=numpy_array(data),
                                                   pubattr={'axis': None}, 
                                                   dimensions=[xdim])# DCH xdim?    
           #--- End: if
       #--- End: for
    #--- End: if
        
        # --------------------

    def unrotated_latlon(self, rotated_lat, rotated_lon, pole_lat, pole_lon):
        '''
    
    Create 2-d arrays of unrotated latitudes and longitudes.
        
:Parameters:

rotated_lat, rotated_lon, pole_lat, pole_lon

    '''
        # Make sure rotated_lon and pole_lon is in [0, 360)
        pole_lon = pole_lon % 360.0
    
        # Convert everything to radians
        pole_lon *= _pi_over_180
        pole_lat *= _pi_over_180
    
        cos_pole_lat = numpy_cos(pole_lat)
        sin_pole_lat = numpy_sin(pole_lat)
    
        # Create appropriate copies of the input rotated arrays
        rot_lon = rotated_lon.copy()
        rot_lat = rotated_lat.view()
    
        # Make sure rotated longitudes are between -180 and 180
        rot_lon %= 360.0
        rot_lon = numpy_where(rot_lon < 180.0, rot_lon, rot_lon-360)
    
        # Create 2-d arrays of rotated latitudes and longitudes in radians
        nlat = rot_lat.size
        nlon = rot_lon.size
        rot_lon = numpy_resize(numpy_deg2rad(rot_lon), (nlat, nlon))    
        rot_lat = numpy_resize(numpy_deg2rad(rot_lat), (nlon, nlat))
        rot_lat = numpy_transpose(rot_lat, axes=(1,0))
    
        # Find unrotated latitudes
        CPART = numpy_cos(rot_lon) * numpy_cos(rot_lat)
        sin_rot_lat = numpy_sin(rot_lat)
        x = cos_pole_lat * CPART + sin_pole_lat * sin_rot_lat
        x = numpy_clip(x, -1.0, 1.0)
        unrotated_lat = numpy_arcsin(x)
        
        # Find unrotated longitudes
        x = -cos_pole_lat*sin_rot_lat + sin_pole_lat*CPART
        x /= numpy_cos(unrotated_lat)   # dch /0 or overflow here? surely
                                        # lat could be ~+-pi/2? if so,
                                        # does x ~ cos(lat)?
        x = numpy_clip(x, -1.0, 1.0)
        unrotated_lon = -numpy_arccos(x)
        
        unrotated_lon = numpy_where(rot_lon > 0.0, 
                                    -unrotated_lon, unrotated_lon)
        if pole_lon >= self.atol:
            SOCK = pole_lon - numpy_pi
        else:
            SOCK = 0
        unrotated_lon += SOCK
    
        # Convert unrotated latitudes and longitudes to degrees
        unrotated_lat = numpy_rad2deg(unrotated_lat)
        unrotated_lon = numpy_rad2deg(unrotated_lon)
    
        # Return unrotated latitudes and longitudes
        return unrotated_lat, unrotated_lon
    #--- End: def

    def xy_coordinate(self, axiscode, axis):
        '''

Create an X or Y dimension coordinate from header entries or extra
data.

:Parameters:

    axiscode : int

    axis : str
        'x' or 'y'

:Returns:

    out : cf.DimensionCoordinate

        '''
        if axis == 'y':
            delta  = self.bdy
            origin = self.real_hdr[bzy]
            size   = self.lbrow    
        else:
            delta  = self.bdx
            origin = self.real_hdr[bzx]
            size   = self.lbnpt

        if abs(delta) > self.atol:
            # Create regular coordinates from header items
            if axiscode == 11 or axiscode == -11:
                origin -= divmod(origin + delta*size, 360.0)[0] * 360
                while origin + delta*size > 360.0:
                    origin -= 360.0
                while origin + delta*size < -360.0:
                    origin += 360.0
            #--- End: if

            array = numpy_arange(origin+delta, origin+delta*(size+0.5), delta,
                                 dtype=float)

            # Create the coordinate bounds
            if axiscode in (13, 31, 40, 99):
                # The following axiscodes do not have bounds:
                # 13 = Site number (set of parallel rows or columns
                #      e.g.Time series)
                # 31 = Logarithm to base 10 of pressure in mb
                # 40 = Pseudolevel
                # 99 = Other
                bounds = None
            else:
                delta_by_2 = 0.5 * delta
                bounds = numpy_empty((size, 2), dtype=float)
                bounds[:, 0] = array - delta_by_2
                bounds[:, 1] = array + delta_by_2                
        else:
            # Create coordinate from extra data
            array  = self.extra.get(axis, None)
            bounds = self.extra.get(axis+'_bounds', None)
        #--- End: if

        dc = DimensionCoordinate()
        dc = self.coord_data(
            dc, array, bounds,
            units=_axiscode_to_Units.setdefault(axiscode, None))
        dc = self.coord_positive(dc, axiscode, _axis[axis])
        dc = self.coord_axis(dc, axiscode)
        dc = self.coord_names(dc, axiscode)

        self.domain.insert_dim(dc, key=_axis[axis], copy=False)       

        self.cell_method_axis_name[axis] = dc.identity()

        return dc
    #--- End: def

    def z_coordinate(self, axiscode):
        '''Create a Z dimension coordinate from BLEV

:Parameters:

    axiscode : int

:Returns:

    out : cf.DimensionCoordinate

        '''
        z_recs = self.z_recs
        array   = tuple([rec.real_hdr.item(blev,) for rec in z_recs])        
        bounds0 = tuple([rec.real_hdr[brlev]      for rec in z_recs]) # lower level boundary
        bounds1 = tuple([rec.real_hdr[brsvd1]     for rec in z_recs]) # bulev

        if _coord_positive.get(axiscode, None) == 'down':
            bounds0, bounds1 = bounds1, bounds0        

#        key = (axiscode, array, bounds0, bounds1)
#        dc = _cached_z_coordinate.get(key, None)

#        if dc is not None:
#            copy = True
#        else:
        copy = False
        array   = numpy_array(array, dtype=float)
        bounds0 = numpy_array(bounds0, dtype=float)
        bounds1 = numpy_array(bounds1, dtype=float)
        bounds  = numpy_column_stack((bounds0, bounds1))

        if (bounds0 == bounds1).all():
            bounds = None
        else:
            bounds = numpy_column_stack((bounds0, bounds1))

        dc = DimensionCoordinate()
        dc = self.coord_data(
            dc, array, 
            bounds=bounds,
            units=_axiscode_to_Units.setdefault(axiscode, None))
        dc = self.coord_positive(dc, axiscode, _axis['z'])
        dc = self.coord_axis(dc, axiscode)
        dc = self.coord_names(dc, axiscode)
        
#        _cached_z_coordinate[key] = dc
#        #--- End: if

        self.domain.insert_dim(dc, key=_axis['z'], copy=copy)

        self.cell_method_axis_name['z'] = dc.identity()
        
        return dc
    #--- End: def
    
    def z_reference_coordinate(self, axiscode):        
        '''
'''
        array = numpy_array([rec.real_hdr.item(brlev,) for rec in self.z_recs],
                            dtype=float)

        LBVC = self.lbvc

        key = (axiscode, LBVC, array)
        dc = _cached_z_reference_coordinate.get(key, None)

        if dc is not None:
            copy = True
        else:
            if not 128 <= LBVC <= 139:
                bounds = []
                for rec in self.z_recs: 
                    BRLEV  = rec.real_hdr.item(brlev,)
                    BRSVD1 = rec.real_hdr.item(brsvd1,)
                    
                    if abs(BRSVD1-BRLEV) >= ATOL:
                        bounds = None
                        break
                        
                    bounds.append((BRLEV, BRSVD1))
                #--- End: for    
            else:
                bounds = None
    
            if bounds:
                bounds = numpy_array((bounds,), dtype=float)                
    
            dc = DimensionCoordinate()
            dc = self.coord_data(
                dc, array, bounds,
                units=_axiscode_to_Units.setdefault(axiscode, None))
            dc = self.coord_axis(dc, axiscode)
            dc = self.coord_names(dc, axiscode)

            if not dc.get('positive', True): # ppp
                dc.flip(i=True)

            _cached_z_reference_coordinate[key] = dc
            copy = False
        #--- End: def

        self.domain.insert_dim(dc, key=_axis['z'], copy=copy)

        return dc
    #--- End: def

#--- End: class

_stash2standard_name = {}

def load_stash2standard_name(table=None, delimiter='!'):
    '''Load a STASH to standard name conversion table.

:Parameters:

    table : str, optional
        Use the conversion table at this file location. By default the
        table will be looked for at
        ``os.path.join(os.path.dirname(cf.__file__),'etc/STASH_to_CF.txt')``

    delimiter : str, optional
        The delimiter of the table columns. By default, ``!`` is taken
        as the delimiter.

:Returns:

    None

*Examples:*

>>> load_stash2standard_name()
>>> load_stash2standard_name('my_table.txt')
>>> load_stash2standard_name('my_table2.txt', ',')

    '''
    # 0  Model           
    # 1  STASH code      
    # 2  STASH name      
    # 3  units           
    # 4  valid from UM vn
    # 5  valid to   UM vn
    # 6  standard_name   
    # 7  CF extra info   
    # 8  PP extra info

    if table is None:
        # Use default conversion table
        package_path = os.path.dirname(__file__)
        table = os.path.join(package_path, 'etc/STASH_to_CF.txt')
    #--- End: if

    lines = csv.reader(open(table, 'r'), 
                       delimiter=delimiter, skipinitialspace=True)

    raw_list = []
    [raw_list.append(line) for line in lines]

    # Get rid of comments
    for line in raw_list[:]:
        if line[0].startswith('#'):
            raw_list.pop(0)
            continue
        break
    #--- End: for

    # Convert to a dictionary which is keyed by (submodel, STASHcode)
    # tuples

    (model, stash, name,
     units, 
     valid_from, valid_to,
     standard_name, cf, pp) = range(9)
        
    stash2sn = {}
    for x in raw_list:
        key = (int(x[model]), int(x[stash]))

        if not x[units]:
            x[units] = None

        try:            
            cf_info = {}
            if x[cf]:
                for d in x[7].split():
                    if d.startswith('height='): 
                        cf_info['height'] = re.split(_number_regex, d,
                                                     re.IGNORECASE)[1:4:2]
                        if cf_info['height'] == '':
                            cf_info['height'][1] = '1'

                    if d.startswith('below_'):
                        cf_info['below'] = re.split(_number_regex, d,
                                                     re.IGNORECASE)[1:4:2]
                        if cf_info['below'] == '':
                            cf_info['below'][1] = '1'

                    if d.startswith('where_'):         
                        cf_info['where'] = d.replace('where_', 'where ', 1)
                    if d.startswith('over_'):         
                        cf_info['over'] = d.replace('over_', 'over ', 1)

            x[cf] = cf_info                    
        except IndexError:
            pass

        try:
            x[valid_from] = float(x[valid_from])
        except ValueError:
            x[valid_from] = None

        try:
            x[valid_to] = float(x[valid_to])
        except ValueError:
            x[valid_to] = None

        x[pp] = x[pp].rstrip()

        line = (x[name:],)

        if key in stash2sn:
            stash2sn[key] += line
        else:
            stash2sn[key] = line

    #--- End: for

    _stash2standard_name.clear()
    _stash2standard_name.update(stash2sn)

#    return stash2sn
#--- End: def

# ---------------------------------------------------------------------
# Create the STASH code to standard_name conversion dictionary
# ---------------------------------------------------------------------
#_stash2standard_name = load_stash2standard_name()
load_stash2standard_name()

def read(filename, um_version=405, verbose=False, aggregate=True,
         byte_ordering=None, word_size=None, set_standard_name=True,
         height_at_top_of_model=None):
    '''Read fields from a PP file or UM fields file.

The file may be big or little endian, 32 or 64 bit

:Parameters:

    filename : file or str
        A string giving the file name, or an open file object, from
        which to read fields.

    um_version : number, optional
        The Unified Model (UM) version to be used when decoding the PP
        header. Valid versions are, for example, ``402`` (v4.2),
        ``606.3`` (v6.6.3) and ``1001`` (v10.1). The default version
        is ``405`` (v4.5). The version is ignored if it can be
        inferred from the PP headers, which will generally be the case
        for files created at versions 5.3 and later. Note that the PP
        header can not encode tertiary version elements (such as the
        ``3`` in ``606.3``), so it may be necessary to provide a UM
        version in such cases.
    
    verbose : bool, optional

    set_standard_name : bool, optional

:Returns:

    out : FieldList
        The fields in the file.

:Examples:

>>> f = read('file.pp')
>>> f = read('*/file[0-9].pp', um_version=708)

    '''    
    history = 'Converted from UM by cf-python v%s' % __version__

    f = _open_um_file(filename)

#    print 'um.read.read.py um_version=', repr(um_version)

    um = [UMField(var, f.format, f.byte_ordering, f.word_size,
                  um_version, set_standard_name, history=history,
                  height_at_top_of_model=height_at_top_of_model)
          for var in f.vars]

#    # Clear the cache of unrotated latitude and longitude arrays
#    _cache_latlon.clear()

    return FieldList([field
                      for x in um
                      for field in x.fields
                      if field])
#--- End: def

def _atmosphere_hybrid_sigma_pressure_coordinate(f):
    # atmosphere_hybrid_sigma_pressure_coordinate
    real_hdr = f.real_hdr
    
    BLEV, BRLEV, BHLEV, BHRLEV = real_hdr[blev:bhrlev+1]
    BRSVD1, BRSVD2             = real_hdr[brsvd1:brsvd2+1]
    
    if 'z' not in pmaxes:
        indices = [0] * pmndim
        indices[pmaxes.index('z')] = slice(1, None, None)
        
        for rec in var.recs[tuple(indices)]:
            BLEV, BRLEV, BHLEV, BHRLEV = rec.real_hdr[blev:bhrlev+1]
            BRSVD1, BRSVD2             = rec.real_hdr[brsvd1:brsvd2+1]
            
            array.append(BLEV + BHLEV/_pstar)
            bounds.append([BRLEV + BHRLEV/_pstar, BRSVD1 + BRSVD2/_pstar])
            
            ak_array.append(BHLEV)
            ak_bounds.append([BHRLEV, BRSVD2])
            
            bk_array.append(BLEV)
            bk_bounds.append([BRLEV , BRSVD1])

            array     = numpy_array(array    , dtype=float)
            bounds    = numpy_array(bounds   , dtype=float)
            ak_array  = numpy_array(ak_array , dtype=float)
            ak_bounds = numpy_array(ak_bounds, dtype=float)
            bk_array  = numpy_array(bk_array , dtype=float)
            bk_bounds = numpy_array(bk_bounds, dtype=float)
            
            domain = f.field.domain
            
            coord = _create_Coordinate(domain, vdim, axis_code=axis_code,
                                       p=p,
                                       array=array,
                                       bounds_array=bounds,
                                       dimensions=[vdim])
            
            coord = _create_Coordinate(
                domain, aux, axis_code=None,
                p=p,
                pubattr={'standard_name':
                         'atmosphere_hybrid_sigma_pressure_coordinate_ak'},
                units=_units['Pa'],
                array=ak_array,
                bounds_array=ak_array,
                dimensions=[vdim],
                aux=True)
            
            coord = _create_Coordinate(
                domain, aux, axis_code=None,
                p=p,
                pubattr={'standard_name':
                         'atmosphere_hybrid_sigma_pressure_coordinate_bk'},
                units=_units['1'],
                array=bk_array,
                bounds_array=bk_array,
                dimensions=[vdim],
                aux=True)
            
        else:
            cache_key = ('atmosphere_hybrid_sigma_pressure_coordinate',
                         BLEV, BHLEV, BRLEV, BHRLEV, BRSVD1, BRSVD2)
            cache_key_ak = ('atmosphere_hybrid_sigma_pressure_coordinate_ak',
                            BLEV, BHLEV, BRLEV, BHRLEV, BRSVD1, BRSVD2)
            cache_key_bk = ('atmosphere_hybrid_sigma_pressure_coordinate_bk',
                            BLEV, BHLEV, BRLEV, BHRLEV, BRSVD1, BRSVD2)
            if cache_key in _cached_coordinate:
                c = _cached_coordinate[cache_key]
                domain.insert_dim(c, key=vdim, copy=True)
                c = _cached_coordinate[cache_key_ak]
                domain.insert_aux(c, axes=[vdim], copy=True)
                c = _cached_coordinate[cache_key_bk]
                domain.insert_aux(c, axes=[vdim], copy=True)
            else:                                                        
                array  = numpy_array((BLEV + BHLEV/_pstar,), dtype=float)
                bounds = numpy_array(((BRLEV  + BHRLEV/_pstar,
                                       BRSVD1 + BRSVD2/_pstar)), dtype=float)
                
                ak_array  = numpy_array((BHLEV,)          , dtype=float)
                ak_bounds = numpy_array(((BHRLEV, BRSVD2)), dtype=float)
                
                bk_array  = numpy_array((BLEV,)          , dtype=float)
                bk_bounds = numpy_array(((BRLEV, BRSVD1)), dtype=float)
                
                coord = _create_Coordinate(domain, vdim, axis_code=axis_code,
                                           p=p,
                                           array=array,
                                           bounds_array=bounds,
                                           dimensions=[vdim],
                                           cache_key=cache_key)
                
                coord = _create_Coordinate(
                    domain, aux, axis_code=None,
                    p=p,
                    pubattr={'standard_name':
                             'atmosphere_hybrid_sigma_pressure_coordinate_ak'},
                    units=_units['Pa'],
                    array=ak_array,
                    bounds_array=ak_array,
                    dimensions=[vdim],
                    aux=True,
                    cache_key=cache_key_ak)
                
                coord = _create_Coordinate(
                    domain, aux, axis_code=None,
                    p=p,
                    pubattr={'standard_name':
                             'atmosphere_hybrid_sigma_pressure_coordinate_bk'},
                    units=_units['1'],
                    array=bk_array,
                    bounds_array=bk_array,
                    dimensions=[vdim],
                    aux=True,
                    cache_key=cache_key_bk)
#--- End: def
          
def is_um_file(filename):
    '''Return True if a file is a PP file or UM fields file.

Note that the file type is determined by inspecting the file's
contents and any file suffix is not not considered.

:Parameters:

    filename : str

:Returns:

    out : bool

:Examples:

>>> is_um_file('myfile.pp')
True
>>> is_um_file('myfile.nc')
False
>>> is_um_file('myfile.pdf')
False
>>> is_um_file('myfile.txt')
False

    ''' 
    try:
        f = _open_um_file(filename)
    except:
        return False

    try:
        f.close_fd()
    except:
        pass

    return True
#--- End: def
      
'''
Problems:

Z and P coordinates
/home/david/data/pp/aaaao/aaaaoa.pmh8dec.03328.pp

/net/jasmin/chestnut/data-24/david/testpp/026000000000c.fc0607.000128.0000.00.04.0260.0020.1491.12.01.00.00.pp
skipping variable stash code=0, 0, 0 because: grid code not supported
umfile: error condition detected in routine list_copy_to_ptr_array
umfile: error condition detected in routine process_vars
umfile: error condition detected in routine file_parse
OK 2015-04-01

/net/jasmin/chestnut/data-24/david/testpp/026000000000c.fc0619.000128.0000.00.04.0260.0020.1491.12.01.00.00.pp
skipping variable stash code=0, 0, 0 because: grid code not supported
umfile: error condition detected in routine list_copy_to_ptr_array
umfile: error condition detected in routine process_vars
umfile: error condition detected in routine file_parse
OK 2015-04-01

/net/jasmin/chestnut/data-24/david/testpp/lbcode_10423.pp
skipping variable stash code=0, 0, 0 because: grid code not supported
umfile: error condition detected in routine list_copy_to_ptr_array
umfile: error condition detected in routine process_vars
umfile: error condition detected in routine file_parse
OK 2015-04-01

/net/jasmin/chestnut/data-24/david/testpp/lbcode_11323.pp
skipping variable stash code=0, 0, 0 because: grid code not supported
umfile: error condition detected in routine list_copy_to_ptr_array
umfile: error condition detected in routine process_vars
umfile: error condition detected in routine file_parse
OK 2015-04-01

EXTRA_DATA:
/net/jasmin/chestnut/data-24/david/testpp/ajnjgo.pmm1feb.pp

SLOW: (Not any more! 2015-04-01)
/net/jasmin/chestnut/data-24/david/testpp/xgdria.pdk949a.pp
/net/jasmin/chestnut/data-24/david/testpp/xhbmaa.pm27sep.pp

RUN LENGTH ENCODED dump (not fields file)
/home/david/data/um/xhlska.dak69h0
Field 115 (stash code 9)

dch@eslogin008:/nerc/n02/n02/dch> ff2pp xgvwko.piw96b0 xgvwko.piw96b0.pp

file xgvwko.piw96b0 is a byte swapped 64 bit ieee um file 

'''