File: METAR.pm

package info (click to toggle)
libgeo-metar-perl 1.15-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 416 kB
  • sloc: perl: 836; makefile: 2
file content (1761 lines) | stat: -rw-r--r-- 47,534 bytes parent folder | download | duplicates (3)
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
# $Id: METAR.pm,v 1.11 2008/01/02 13:47:00 koos Exp $

# KH: fix the parser
# should be a finite state machine
# - metar has rules what comes after what. but codes can be missing.
# (measurement not done) or //// (measurement broken at the moment)
# so given a state counter, it can stay the same or go up one or more states,
# but it can never go down
#
# info on the last bit which is actually a forecast: (German)
# http://www.wetterklima.de/flug/metar/Metarvorhersage.htm
#
# more info here (dutch, and txt 707 is not standard metar)
# http://www.vwkweb.nl/index.html?http://www.vwkweb.nl/weerinfo/weerinfo_teletekst707.html
# and also (dutch)
# http://www.gids.nl/weather/eheh/metari.html
#
# 'METAR decoding in Europe'
# http://users.hol.gr/~chatos/VATSIM/TM/metar.html
#
# english explanation
# http://booty.org.uk/booty.weather/metinfo/codes/METAR_decode.htm
#
# canadian explanation
# http://meteocentre.com/doc/metar.html
#
# 'METAR decoding, TAF decoding'
# http://stoivane.kapsi.fi/metar/
#

# This module is used for decoding NWS METAR code.

# Example METARs
#
# Findlay, Ohio
# KFDY 251450Z 21012G21KT 8SM OVC065 04/M01 A3010 RMK SLP201 57014
#
# Toledo, Ohio
# KTOL 251451Z 23016G22KT 8SM CLR 04/00 A3006 RMK AO2 SLP185 T00440000 56016 
#
# Cleveland, Ohio
# KCLE 251554Z 20015KT 10SM FEW055 OVC070 03/M02 A3011 RMK AO2 SLP205 T00331017
#
# Houston, Texas
# KHST 251455Z 06017G22KT 7SM FEW040 BKN330 25/18 A3016 RMK SLP213 8/508
# 9/205 51007
#
# LA
#
# KLAX 251450Z 07004KT 7SM SCT100 BKN200 14/11 A3005 RMK AO2 SLP173
# T01390111 56005
#
# Soesterberg
#
# EHSB 181325Z 24009KT 8000 -RA BR FEW011 SCT022 OVC030 07/06 Q1011 WHT WHT TEMPO GRN

# For METAR info, please see
# http://tgsv5.nws.noaa.gov/oso/oso1/oso12/metar.htm
# moved
# http://metar.noaa.gov/
#
# in scary detail (metar coding)
#
# http://metar.noaa.gov/table_master.jsp?sub_menu=yes&show=fmh1ch12.htm&dir=./handbook/&title=title_handbook
#


# The METAR specification is dictated in the Federal Meteorological Handbook
# which is available on-line at:
# http://tgsv5.nws.noaa.gov/oso/oso1/oso12/fmh1.htm

# General Structure is:
# TYPE, SITE, DATE/TIME, WIND, VISIBILITY, CLOUDS, TEMPERATURE, PRESSURE, REMARKS

# Specifically:

# TYPE (optional)
# METAR or SPECI
# METAR: regular report
# SPECI: special report

# SITE (required, only once)
#
# 4-Char site identifier (KLAX for LA, KHST for Houston)

# DATE/TIME (required, only once)
#
# 6-digit time followed by "Z", indicating UTC

# REPORT MODIFIER (optional)
# AUTO or COR
# AUTO = Automatic report (no human intervention)
# COR = Corrected METAR or SPECI

# WIND (group)
#
# Wind direction (\d\d\d) and speed (\d?\d\d) and optionaling gusting
# information denoted by "G" and speed (\d?\d\d) followed by "KT", for knots.
#
# Wind direction MAY be "VRB" (variable) instead of a compass direction.
#
# Variable Wind Direction (Speeds greater than 6 knots).  Variable wind
# direction with wind speed greater than 6 knots shall be coded in the
# format, dndndnVdxdxdx
#
# Calm wind is recorded as 00000KT.

# VISIBILITY (group)
#
# Visibility (\d+) followed by "SM" for statute miles or no 'SM' for meters
# (european)
#
# May be 1/(\d)SM for a fraction.
#
# May be M1/\d)SM for less than a given fraction. (M="-")
#
# \d\d\d\d according to KNMI
# lowest horizontal visibility (looking around)
# round down
# 0000 - 0500m in steps of 0050m
# 0500 - 5000m in steps of 0100m
# 5000 - 9999m in steps of 1000m
# 10km or more is 9999

# RUNWAY Visual Range (Group)
#
# R(\d\d\d)(L|C|R)?/((M|P)?\d\d\d\d){1,2}FT
#
# Where:
#  $1 is the runway number.
#  $2 is the runway (Left/Center/Right) for parallel runways.
#  $3 is the reported visibility in feet.
#  $4 is the MAXIMUM reported visibility, making $3 the MINIMUM.
#
#  "M" beginning a value means less than the reportable value of \d\d\d\d.
#  "P" beginning a value means more than the reportable value of \d\d\d\d.
#
#  new
#
#  R(\d\d\d[LCR]?)/([MP]?\d\d\d\d)(V[MP]?\d\d\d\d)?FT
#
# $1 runway number + Left/Center/Right
# $2 visibility feet
# $3 Varying feet
# M = less than
# P = more than

# WEATHER (Present Weather Group)
#
# See table in Chapter 12 of FMH-1.

# CLOUDS (Sky Condition Group)
#
# A space-separated grouping of cloud conditions which will contain at least
# one cloud report. Examples: "CLR", "BKN330", "SCT100", "FEW055", "OVC070"
# The three-letter codes represent the condition (Clear, Broken, Scattered,
# Few, Overcast) and the numbers (\d\d\d) represent altitlude/100.
#
# The report may have a trailing CB (cumulonimbus) or TCU (towering
# cumulus) appended. ([A-Z]{2,3})?(\d\d\d)(CB|TCU)?

# Vertical visibility (VV)
#
# VV
# This group is reported when the sky is obscured. VV is the group indicator,
# and hshshs is the vertical visibility in units of 30 metres
# (hundreds of feet).
#  
#  hshshs - Examples of Encoding
#  HEIGHT 		METAR CODE
#  100 ft 	(30 metres) 	001
#  450 ft 	(135 metres) 	004
#  2,700 ft 	(810 metres) 	027
#  12,600 ft 	(3,780 metres) 	1300
#
# source http://meteocentre.com/doc/metar.html
# 
# TEMPERATURE and DEW POINT
#
# (M?\d\d)/(M?\d\d) where $1 is the current temperature in degrees celcius,
# and $2 is the current dewpoint in degrees celcius.
#
# The "M" signifies a negative temperature, so converting the "M" to a
# "-" ought to suffice.

# PRESSURE
#
# The pressure, or altimeter setting, at the reporting site recorded in whole
# hectopascals (starts with a Q) or inches of mercury (Hg) minus the decimal
# point (starts with an A). It should always look like ([AQ]\d\d\d\d).
#
# KNMI: Q\d\d\d\d pressure in hPa calculated for sea level

# REMARKS
#
# Remarks contain additional information. They are optional but often
# informative of special conditions.
#
# Remarks begin with the "RMK" keyword and continue to the end of the line.
#
# trend group
#
# color codes BLU WHT GRN YLO AMB RED
# BLACK: vliegveld dicht
# future trend 
# NOSIG no significant change
# TEMPO temporary change
# WHT WHT TEMPO GRN = current white, prediction white temporary green
# NSW no significant weather
# AT at a given time
# PROB30 probability 30%
# BECMG becoming
# BECMG (weather) FM \d\d\d\d TL \d\d\d\d = from until utc times
# BECMG (weather) AT \d\d\d\d = at utc time
# BECMG (weather) TL \d\d\d\d = change until utc time
# BECMG 2000 visibility
# BECMG NSW weather type
# etc etc
# FCST CANCEL (2 tokens!) Forecast cancel: no further forecasts for a while

### Package Definition

package Geo::METAR;

## Required Modules

use 5.005;
use strict;
use vars qw($AUTOLOAD $VERSION);
use Carp 'cluck';

$VERSION = '1.15';

##
## Lookup tables
##

my %_weather_types = (
    MI => 'shallow',
    PI => 'partial',
    BC => 'patches',
    DR => 'drizzle',
    BL => 'blowing',
    SH => 'shower(s)',
    TS => 'thunderstorm',
    FZ => 'freezing',

    DZ => 'drizzle',
    RA => 'rain',
    SN => 'snow',
    SG => 'snow grains',
    IC => 'ice crystals',
    PE => 'ice pellets',
    GR => 'hail',
    GS => 'small hail/snow pellets',
    UP => 'unknown precip',

    BR => 'mist',
    FG => 'fog',
    PRFG => 'fog banks',  # officially PR is a modifier of FG
    FU => 'smoke',
    VA => 'volcanic ash',
    DU => 'dust',
    SA => 'sand',
    HZ => 'haze',
    PY => 'spray',

    PO => 'dust/sand whirls',
    SQ => 'squalls',
    FC => 'funnel cloud(tornado/waterspout)',
    SS => 'sand storm',
    DS => 'dust storm',
);

my $_weather_types_pat = join("|", keys(%_weather_types));

my %_sky_types = (
    SKC => "Sky Clear",
    CLR => "Sky Clear",
    SCT => "Scattered",
    BKN => "Broken",
    FEW => "Few",
    OVC => "Solid Overcast",
    NSC => "No significant clouds",
    NCD => "No cloud detected",
);

my %_trend_types = (
    BLU => "8 km view",
    WHT => "5 km view",
    GRN => "3.7 km view",
    YLO => "1.6 km view",
    AMB => "0.8 km view",
    RED => "< 0.8 km view",
    BLACK => "airport closed",
    NOSIG => "No significant change",
    TEMPO => "Temporary change",
    NSW => "No significant weather",
    PROB => "Probability",
    BECMG => "Becoming",
    LAST => "Last",
);

my $_trend_types_pat = join("|", keys(%_trend_types));

##
## Constructor.
##

sub new
{
    my $this = shift;
    my $class = ref($this) || $this;
    my $self = {};

    ##
    ## UPPERCASE items have documented accssor functions (methods) or
    ## use AUTOLOAD, while lowercase items are reserved for internal
    ## use.
    ##

    $self->{VERSION}       = $VERSION;          # version number
    $self->{METAR}         = undef;             # the actual, raw METAR
    $self->{TYPE}          = undef;             # the type of report
    $self->{SITE}          = undef;             # site code
    $self->{DATE}          = undef;             # when it was issued
    $self->{TIME}          = undef;             # time it was issued
    $self->{MOD}           = undef;             # modifier (AUTO/COR)
    $self->{WIND_DIR_DEG}  = undef;             # wind dir in degrees
    $self->{WIND_DIR_ENG}  = undef;             # wind dir in english (Northwest/Southeast)
    $self->{WIND_DIR_ABB}  = undef;             # wind dir in abbreviated english (NW/SE)
    $self->{WIND_KTS}      = undef;             # wind speed (knots)
    $self->{WIND_GUST_KTS} = undef;             # wind gusts (knots)
    $self->{WIND_MPH}      = undef;             # wind speed (MPH)
    $self->{WIND_GUST_MPH} = undef;             # wind gusts (MPH)
    $self->{WIND_MS}       = undef;             # wind speed (m/s)
    $self->{WIND_GUST_MS}  = undef;             # wind gusts (m/s)
    $self->{WIND_VAR}      = undef;             # wind variation (text)
    $self->{WIND_VAR_1}    = undef;             # wind variation (direction 1)
    $self->{WIND_VAR_2}    = undef;             # wind variation (direction 2)
    $self->{WIND_VAR_ENG_1}= undef;         # wind variation (text, direction 1)
    $self->{WIND_VAR_ENG_2}= undef;         # wind variation (text, direction 2)
    $self->{VISIBILITY}    = undef;             # visibility info
    $self->{RUNWAY}        = [ ];               # runway vis.
    $self->{WEATHER}       = [ ];               # current weather
    $self->{WEATHER_LOG}   = [ ];               # weather log
    $self->{SKY}           = [ ];               # current sky (cloudcover)
    $self->{TEMP_F}        = undef;             # current temp, celcius
    $self->{TEMP_C}        = undef;             # converted to fahrenheit
    $self->{DEW_F}         = undef;             # dew point, celcius
    $self->{DEW_C}         = undef;             # dew point, fahrenheit
    $self->{HOURLY_TEMP_F} = undef;             # hourly current temp, celcius
    $self->{HOURLY_TEMP_C} = undef;             # hourly converted to fahrenheit
    $self->{HOURLY_DEW_F}  = undef;             # hourly dew point, celcius
    $self->{HOURLY_DEW_C}  = undef;             # hourly dew point, fahrenheit
    $self->{HOURLY_PRECIP} = undef;             # hourly precipitation
    $self->{ALT}           = undef;             # altimeter setting (Hg)
    $self->{ALT_HP}        = undef;             # altimeter setting (hPa)
    $self->{SLP}           = undef;             # sea level pressure
    $self->{REMARKS}       = undef;             # remarks

    $self->{tokens}        = [ ];               # the "token" list
    $self->{type}          = "METAR";           # the report type (METAR/SPECI)
                                                # default=METAR
    $self->{site}          = undef;             # the site code (4 chars)
    $self->{date_time}     = undef;             # date/time
    $self->{modifier}      = undef;             # the AUTO/COR modifier
    $self->{wind}          = undef;             # the wind information
    $self->{windtype}      = undef;             # the wind speed type (knots/meterpersecond/kilometersperhour)
    $self->{windvar}       = undef;             # the wind variation
    $self->{visibility}    = undef;             # visibility information
    $self->{runway}        = undef;             # runway visibility
    $self->{weather}       = [ ];               # current weather conditions
    $self->{sky}           = [ ];               # sky conditions (cloud cover)
    $self->{temp_dew}      = undef;             # temp and dew pt.
    $self->{alt}           = undef;             # altimeter setting
    $self->{pressure}      = undef;             # pressure (HPa)
    $self->{slp}           = undef;             # sea level pressure
    $self->{remarks}       = [ ];               # remarks

    $self->{debug}         = undef;             # enable debug trace

    bless $self, $class;
    return $self;
}

##
## Autoload for access methods to stuff in %fields hash. We should
## probably disallow access to the lower-case items as stated above,
## but I don't feel like being a Nazi about it. Besides, I haven't
## checked to see what that might break.
##

sub AUTOLOAD
{
    my $self = shift;

    if (not ref $self)
    {
	cluck "bad AUTOLOAD for obj [$self]";
    }

    if ($AUTOLOAD =~ /.*::(.*)/)
    {
        my $key = $1;


        ## Backward compatible temps...

        my %compat = (
                      F_TEMP    =>  'TEMP_F',
                      C_TEMP    =>  'TEMP_C',
                      F_DEW     =>  'DEW_F',
                      C_DEW     =>  'DEW_C',
                     );

        if ($compat{$key})
        {
            $key = $compat{$key};
        }

        ## Check for the items...

        if (exists $self->{$key})
        {
            return $self->{$key};
        }
        else
        {
            return undef;
        }
    }
    else
    {
        warn "strange AUTOLOAD problem!";
        return undef;
    }
}

##
## Get current version number.
##

sub version
{
    my $self = shift;
    print "version() called.\n" if $self->{debug};
    return $self->{VERSION};
}

##
## Take a METAR, tokenize, and process it.
##

sub metar
{
    my $self = shift;

    if (@_)
    {
        $self->{METAR} = shift;
        $self->{METAR} =~ s/\n//g;    ## nuke any newlines
        _tokenize($self);
        _process($self);
    }
    return $self->{METAR};
}

##
## Break {METAR} into parts. Stuff into @tokens.
##

sub _tokenize
{
    my $self = shift;
    my $tok;
    my @toks;

    # Split tokens on whitespace.
    @toks = split(/\s+/, $self->{METAR});
    $self->{tokens} = \@toks;
}

## Process @tokens to populate METAR values.
##
## This is a long and involved subroutine. It basically copies the
## @tokens array and treats it as a stack, popping off items,
## examining them, and see what they look like.  Based on their
## "apppearance" it takes care populating the proper fields
## internally.

sub _process
{
    my $self = shift;

    my @toks = @{$self->{tokens}};      # copy tokens array...

    my $tok;

    ## This is a semi-brute-force way of doing things, but the amount
    ## of data is relatively small, so it shouldn't be a big deal.
    ##
    ## Ideally, I'd have it skip checks for items which have been
    ## found, but that would make this more "linear" and I'd remove
    ## the pretty while loop.
	#
	# KH: modified to maintain state to not get lost in remarks and stuff
	# and be a lot better at parsing
	
	# states

	my $expect_type = 0;
	my $expect_site = 1;
	my $expect_datetime = 2;
	my $expect_modifier = 3;
	my $expect_wind = 4;
	my $expect_visibility = 5;
	my $expect_runwayvisual = 6;
	my $expect_presentweather = 7;
	my $expect_clouds = 8;
	my $expect_temperature = 9;
	my $expect_pressure = 10;
	my $expect_recentweather = 11;
	my $expect_remarks = 12;
	my $expect_usremarks = 13;

	my $parsestate = $expect_type;

	# windtypes
	
	my $wt_knots = 1;
	my $wt_mps = 2;
	my $wt_kph = 3;

    ## Assume standard report by default

    $self->{type} = "METAR";
    $self->{TYPE} = "Routine Weather Report";

    while (defined($tok = shift(@toks))) ## as long as there are tokens
    {
        print "trying to match [$tok] state is $parsestate\n" if $self->{debug};

        ##
        ## is it a report type?
        ##

        if (($parsestate == $expect_type) and ($tok =~ /(METAR|SPECI)/i))
        {
            $self->{type} = $tok;

            if ($self->{type} eq "METAR")
            {
                $self->{TYPE} = "Routine Weather Report";
            }
            elsif ($self->{type} eq "SPECI")
            {
                $self->{TYPE} = "Special Weather Report";
            }
            print "[$tok] is a report type.\n" if $self->{debug};
			$parsestate = $expect_site;
            next;
        }

        ##
        ## is is a site ID?
        ##

        elsif (($parsestate <= $expect_site) and ($tok =~ /([A-Z]{4}|K[A-Z0-9]{3})/))
        {
            $self->{site} = $tok;
            print "[$tok] is a site ID.\n" if $self->{debug};
			$parsestate = $expect_datetime;
            next;
        }

        ##
        ## is it a date/time?
        ##

        elsif (($parsestate == $expect_datetime) and ($tok =~ /\d{6,6}Z/i))
        {
            $self->{date_time} = $tok;
            print "[$tok] is a date/time.\n" if $self->{debug};
			$parsestate = $expect_modifier;
            next;


        }

        ##
        ## is it a report modifier?
        ##

        elsif (($parsestate == $expect_modifier) and ($tok =~ /AUTO|COR|CC[A-Z]/i))
        {
            $self->{modifier} = $tok;
            print "[$tok] is a report modifier.\n" if $self->{debug};
			$parsestate = $expect_wind;
            next;
        }

        ##
        ## is it wind information in knots?
        #
		# eew: KT seems to be optional
		# but making it optional fails on other stuff
		# sortafix: wind needs to be \d\d\d\d\d or VRB\d\d
		#      optional \d\d\d\d\dG\d\d\d (gust direction)

        elsif (($parsestate >= $expect_modifier) and ($parsestate < $expect_visibility) and ($tok =~ /(\d{3}|VRB)\d{2}(G\d{1,3})?(KT)?$/i))
        {
            $self->{wind} = $tok;
			$self->{windtype} = $wt_knots;
            print "[$tok] is wind information in knots.\n" if $self->{debug};
			$parsestate = $expect_wind; # stay in wind, it can have variation
            next;
        }

		##
		## is it wind information in meters per second?
		##
		## can be variable too

        elsif (($parsestate >= $expect_modifier) and ($parsestate < $expect_visibility) and ($tok =~ /^(\d{3}|VRB)\d{2}(G\d{2,3})?MPS$/))
        {
            $self->{wind} = $tok;
            print "[$tok] is wind information.\n" if $self->{debug};
			$self->{windtype} = $wt_mps;
			$parsestate = $expect_wind; # stay in wind, it can have variation
            next;
        }

		##
		## is it wind variation information?
		##

		elsif (($parsestate >= $expect_wind) and ($parsestate < $expect_visibility) and ($tok =~ /^\d{3}V\d{3}$/))
		{
			$self->{windvar} = $tok;
			print "[$tok] is wind variation information.\n" if $self->{debug};
			$parsestate = $expect_visibility;
			next;
		}

		##
		## wind information missing at the moment?
		##

		elsif (($parsestate >= $expect_wind) and ($parsestate < $expect_visibility) and ($tok =~ /^\/\/\/\/\/(KT|MPS)$/)){
			print "[$tok] is missing wind information.\n" if $self->{debug};
			$parsestate = $expect_visibility;
			next;
		}

		##
		## is it visibility information in meters?
		##
	
		elsif (($parsestate >= $expect_modifier) and ($parsestate < $expect_runwayvisual) and ($tok =~ /^\d{4}$/))
		{
			$self->{visibility} = $tok;
            print "[$tok] is numerical visibility information.\n" if $self->{debug};
			$parsestate = $expect_visibility;
            next;
        }

		## auto visibility information in meters?

		elsif (($parsestate >= $expect_modifier) and ($parsestate < $expect_runwayvisual) and ($tok =~ /^\d{4}NDV$/))
		{
			$self->{visibility} = $tok;
            print "[$tok] is automatic numerical visibility information.\n" if $self->{debug};
			$parsestate = $expect_visibility;
            next;
        }

        ##
        ## is it visibility information in statute miles?
        ##

        elsif (($parsestate >= $expect_modifier) and ($parsestate < $expect_runwayvisual) and ($tok =~ /.*?SM$/i))
        {
            $self->{visibility} = $tok;
            print "[$tok] is statute miles visibility information.\n" if $self->{debug};
			$parsestate = $expect_visibility;
            next;
        }

        ##
        ## is it visibility information with a leading digit?
		##
		## sample:
		## KERV 132345Z AUTO 07008KT 1 1/4SM HZ 34/11 A3000 RMK AO2
		##                           ^^^^^^^
        ##

        elsif (($parsestate >= $expect_modifier) and ($parsestate < $expect_runwayvisual) and  ($tok =~ /^\d$/))
        {
            $tok .= " " . shift(@toks);
            $self->{visibility} = $tok;
            print "[$tok] is multi-part visibility information.\n" if $self->{debug};
			$parsestate = $expect_visibility;
            next;
        }

		## visibility modifier

		elsif (($parsestate == $expect_visibility) and ($tok =~ /^\d{4}(N|S|E|W|NE|NW|SE|SW)$/))
		{
            print "[$tok] is a visibility modifier.\n" if $self->{debug};
            next;
		}

        ##
        ## is it runway visibility info?
        ##
		# KH: I've seen runway visibility with 'U' units
		# EHSB 121425Z 22010KT 1200 R27/1600U -DZ BKN003 OVC007 07/07 Q1016 AMB FCST CANCEL
		# U= going up, D= going down, N= no change
		# tendency of visual range, http://stoivane.kapsi.fi/metar/

        elsif (($parsestate >= $expect_modifier) and ($parsestate < $expect_presentweather) and ($tok =~ /R\d+(L|R|C)?\/P?\d+(VP?\d+)?(FT|D|U|N|\/)?$/i))
        {
            push (@{$self->{RUNWAY}},$tok);
            print "[$tok] is runway visual information.\n" if $self->{debug};
			$parsestate = $expect_runwayvisual;
			# there can be multiple runways, so stay at this state
            next;
        }

        ##
        ## is it current weather info?
        ##

        elsif (($parsestate >= $expect_modifier) and ($parsestate < $expect_clouds) and ($tok =~ /^(-|\+)?(VC)?($_weather_types_pat)+/i))
        {
            my $engl = "";
            my $qual = $1;
            my $addlqual = $2;

            ## qualifier

            if (defined $qual)
            {
                if ( $qual eq "-" ) {
                    $engl = "light";
                } elsif ( $qual eq "+" ) {
                    $engl = "heavy";
                } else {
                    $engl = ""; ## moderate
                }
            }
            else
            {
                $engl = ""; ## moderate
            }

            while ( $tok =~ /($_weather_types_pat)/gi )
            {
                $engl .= " " . $_weather_types{$1}; ## figure out weather
            }

            ## addl qualifier

            if (defined $addlqual)
            {
                if ( $addlqual eq "VC" )
                {
                    $engl .= " in vicinity";
                }
            }

            $engl =~ s/^\s//gio;
            $engl =~ s/\s\s/ /gio;

            push(@{$self->{WEATHER}},$engl);
            push(@{$self->{weather}},$tok);
            print "[$tok] is current weather.\n" if $self->{debug};
			$parsestate = $expect_presentweather;
			# there can be multiple current weather types, so stay at this state
            next;
        }

		##
		## special case: CAVOK
		##
		
		elsif (($parsestate >= $expect_modifier) and ($parsestate < $expect_temperature) and ( $tok eq 'CAVOK' ))
		{
            push(@{$self->{sky}},$tok);
            push(@{$self->{SKY}}, "Sky Clear");
            push(@{$self->{weather}},$tok);
            push(@{$self->{WEATHER}},"No significant weather");
			$self->{visibility} = '9999';
			$parsestate = $expect_temperature;
			next;
		}

        ##
        ## is it sky conditions (clear)?
        ##

        elsif (($parsestate >= $expect_modifier) and ($parsestate < $expect_temperature) and ( $tok =~ /SKC|CLR/ ))
        {
            push(@{$self->{sky}},$tok);
            push(@{$self->{SKY}}, "Sky Clear");
            print "[$tok] is a sky condition.\n" if $self->{debug};
			$parsestate = $expect_clouds;
			next;
        }

        ##
        ## is it sky conditions (clouds)?
        ##
		## sky conditions can end with ///

        elsif (($parsestate >= $expect_modifier) and ($parsestate < $expect_temperature) and ( $tok =~ /^(FEW|SCT|BKN|OVC)(\d\d\d)?(CB|TCU)?\/*$/i))
        {
            push(@{$self->{sky}},$tok);
            my $engl = "";

            $engl = $_sky_types{$1};

            if (defined $3)
            {
                if ($3 eq "TCU")
                {
                    $engl .= " Towering Cumulus";
                }
                elsif ($3 eq "CB")
                {
                    $engl .= " Cumulonimbus";
                }
            }

            if ($2 ne "")
            {
                my $agl = int($2)*100;
                $engl .= " at $agl" . "ft";
            }

            push(@{$self->{SKY}}, $engl);
            print "[$tok] is a sky condition.\n" if $self->{debug};
			$parsestate = $expect_clouds;
			# clouds DO repeat. a lot ;)
            next;
        }

		##
		## auto detected cloud conditions
		##

        elsif (($parsestate >= $expect_modifier) and ($parsestate < $expect_temperature) and ( $tok =~ /^(NSC|NCD)$/ )){
            my $engl = "";

            $engl = $_sky_types{$tok};
            push(@{$self->{SKY}}, $engl);
			print "[$tok] is an automatic sky condition.\n" if $self->{debug};
			$parsestate = $expect_temperature;
			next;
		}

		##
		## Vertical visibility
		##

        elsif (($parsestate >= $expect_modifier) and ($parsestate < $expect_temperature) and ( $tok =~ /^VV\d+$/ )){
			print "[$tok] is vertical visibility.\n" if $self->{debug};
			$parsestate = $expect_temperature;
			next;
		}

        ##
        ## is it temperature and dew point info?
        ##

        elsif (($parsestate >= $expect_modifier) and ($parsestate < $expect_pressure) and ($tok =~ /^(M?\d\d)\/(M?\d{0,2})/i))
        {
            next if $self->{temp_dew};
            $self->{temp_dew} = $tok;

            $self->{TEMP_C} = $1;
            $self->{DEW_C} = $2;
            $self->{TEMP_C} =~ s/^M/-/;
            $self->{DEW_C} =~ s/^M/-/;

            print "[$tok] is temperature/dew point information.\n" if $self->{debug};
			$parsestate = $expect_pressure;
            next;
        }

        ##
        ## is it an altimeter setting? (in.Hg)
        ##

        elsif (($parsestate >= $expect_modifier) and ($parsestate < $expect_remarks) and ($tok =~ /^A(\d\d)(\d\d)$/i))
        {
            $self->{alt} = $tok;
            $self->{ALT} = "$1.$2"+0;
            $self->{ALT_HP} = "$1.$2" * 33.863886;

            print "[$tok] is an altimeter setting.\n" if $self->{debug};
			$parsestate = $expect_recentweather;
            next;
        }

		##
		## is it a pressure? (hPa)
		##

		elsif (($parsestate >= $expect_modifier) and ($parsestate < $expect_remarks) and ($tok =~ /^Q(\d\d\d\d)$/i))
		{
			$self->{pressure} = $1;
            $self->{ALT_HP} = $1;
			$self->{ALT} = 0.029529983 * $self->{pressure};
			print "[$tok] is an air pressure.\n" if $self->{debug};
			$parsestate = $expect_recentweather;
			next;
		}

		##
		## recent weather?
		##

		elsif (($parsestate >= $expect_modifier) and ($parsestate < $expect_remarks) and ($tok =~ /^RE($_weather_types_pat)$/)){
			print "[$tok] is recent significant weather.\n" if $self->{debug};
			$parsestate = $expect_remarks;
			next;
		}

		##
		## euro type trend?
		##

		elsif (($parsestate >= $expect_modifier) and ($tok =~ /^$_trend_types_pat/)){
			print "[$tok] is a trend.\n" if $self->{debug};
			$parsestate = $expect_remarks;
			next;
		}

        ##
        ## us type remarks? .. can happen quite early in the process already
        ##

        elsif (($parsestate >= $expect_modifier) and ($tok =~ /^RMK$/i))
        {
            push(@{$self->{remarks}},$tok);
            print "[$tok] is a (US type) remark.\n" if $self->{debug};
			$parsestate  = $expect_usremarks;
            next;
        }

        ##
        ## automatic station type?
        ##

        elsif (($parsestate == $expect_usremarks) and ($tok =~ /^A(O\d)$/i))
        {
            $self->{autostationtype} = $tok;
            $self->{AUTO_STATIONTYPE} = $1;
            print "[$tok] is an automatic station type remark.\n" if $self->{debug};
            next;
        }

        ##
        ## sea level pressure
        ##

        elsif (($parsestate == $expect_usremarks) and ($tok =~ /^SLP(\d+)/i))
        {
            $self->{slp} = $tok;
            $self->{SLP} = "$1 mb";
            print "[$tok] is a sea level pressure.\n" if $self->{debug};
            next;
        }

        ##
        ## sea level pressure not available
        ##

        elsif (($parsestate == $expect_usremarks) and ($tok eq "SLPNO"))
        {
            $self->{slp} = "SLPNO";
            $self->{SLP} = "not available";
            print "[$tok] is a sea level pressure.\n" if $self->{debug};
            next;
        }

        ##
        ## hourly precipitation
        ##

        elsif (($parsestate == $expect_usremarks) and ($tok =~ /^P(\d\d\d\d)$/i))
        {
            $self->{hourlyprecip} = $tok;

            if ( $1 eq "0000" ) {
                $self->{HOURLY_PRECIP} = "Trace";
            } else {
                $self->{HOURLY_PRECIP} = $1;
            }
        }

        ##
        ## weather begin/end times
        ##

        elsif (($parsestate == $expect_usremarks) and ($tok =~ /^($_weather_types_pat)([BE\d]+)$/i))
        {
            my $engl = "";
            my $times = $2;

            $self->{weatherlog} = $tok;

            $engl = $_weather_types{$1};

            while ( $times =~ /(B|E)(\d\d)/g )
            {
                if ( $1 eq "B" ) {
                    $engl .= " began :$2";
                } else {
                    $engl .= " ended :$2";
                }
            }

            push(@{$self->{WEATHER_LOG}}, $engl);
            print "[$tok] is a weather log.\n" if $self->{debug};
            next;
        }

        ##
        ## remarks for significant cloud types
        ##

        elsif (($parsestate >= $expect_recentweather) and ($tok eq "CB" || $tok eq "TCU"))
        {
            push(@{$self->{sigclouds}}, $tok);

            if ( $tok eq "CB" ) {
                push(@{$self->{SIGCLOUDS}}, "Cumulonimbus");
            } elsif ( $tok eq "TCU" ) {
                push(@{$self->{SIGCLOUDS}}, "Towering Cumulus");
            }
			$parsestate = $expect_usremarks;
        }

        ##
        ## hourly temp/dewpoint
        ##

        elsif (($parsestate == $expect_usremarks) and ($tok =~ /^T(\d)(\d\d)(\d)(\d)(\d\d)(\d)$/i))
        {
            $self->{hourlytempdew} = $tok;
            if ( $1 == 1 ) {
                $self->{HOURLY_TEMP_C} = "-";
            }
            $self->{HOURLY_TEMP_C} .= "$2.$3";

            $self->{HOURLY_DEW_C} = "";
            if ( $4 == 1 ) {
                $self->{HOURLY_DEW_C} = "-";
            }
            $self->{HOURLY_DEW_C} .= "$5.$6";

            print "[$tok] is a hourly temp and dewpoint.\n" if $self->{debug};
            next;
        }

        ##
        ## unknown, not in remarks yet
        ##

        elsif ($parsestate < $expect_remarks)
        {
            push(@{$self->{unknown}},$tok);
            push(@{$self->{UNKNOWN}},$tok);
            print "[$tok] is unexpected at this state.\n" if $self->{debug};
            next;
        }

        ##
        ## unknown. assume remarks
        ##

        else
        {
            push(@{$self->{remarks}},$tok);
            push(@{$self->{REMARKS}},$tok);
            print "[$tok] is unknown remark.\n" if $self->{debug};
            next;
        }

    }

    ##
    ## Now that the internal stuff is set, let's do the external
    ## stuff.
    ##

    $self->{SITE} = $self->{site};
    $self->{DATE} = substr($self->{date_time},0,2);
    $self->{TIME} = substr($self->{date_time},2,4) . " UTC";
    $self->{TIME} =~ s/(\d\d)(\d\d)/$1:$2/o;
    $self->{MOD}  = $self->{modifier};

    ##
    ## Okay, wind finally gets interesting.
    ##

    if ( defined $self->{wind} )
	{
        my $wind = $self->{wind};
        my $dir_deg  = substr($wind,0,3);
        my $wind_speed;
        my $dir_eng = "";
		my $dir_abb = "";

        $wind_speed = $1 if($wind =~ /...(\d{2,3})/o);
        # Check for wind direction
        if ($dir_deg =~ /VRB/i) {
            $dir_deg = $dir_eng = "Variable";
        } else {
            if ($wind_speed == 0 and $dir_deg == 0) {
                # Calm wind (00000KT in METAR)
                $dir_eng = "Calm";
                print "wind is calm\n" if $self->{debug};
            } elsif ($dir_deg < 15) {
                $dir_eng = "North";
				$dir_abb = "N";
            } elsif ($dir_deg < 30) {
                $dir_eng = "North/Northeast";
				$dir_abb = "NNE";
            } elsif ($dir_deg < 60) {
                $dir_eng = "Northeast";
				$dir_abb = "NE";
            } elsif ($dir_deg < 75) {
                $dir_eng = "East/Northeast";
				$dir_abb = "ENE";
            } elsif ($dir_deg < 105) {
                $dir_eng = "East";
				$dir_abb = "E";
            } elsif ($dir_deg < 120) {
                $dir_eng = "East/Southeast";
				$dir_abb = "ESE";
            } elsif ($dir_deg < 150) {
                $dir_eng = "Southeast";
				$dir_abb = "SE";
            } elsif ($dir_deg < 165) {
                $dir_eng = "South/Southeast";
				$dir_abb = "SSE";
            } elsif ($dir_deg < 195) {
                $dir_eng = "South";
				$dir_abb = "S";
            } elsif ($dir_deg < 210) {
                $dir_eng = "South/Southwest";
				$dir_abb = "SSW";
            } elsif ($dir_deg < 240) {
                $dir_eng = "Southwest";
				$dir_abb = "SW";
            } elsif ($dir_deg < 265) {
                $dir_eng = "West/Southwest";
				$dir_abb = "WSW";
            } elsif ($dir_deg < 285) {
                $dir_eng = "West";
				$dir_abb = "W";
            } elsif ($dir_deg < 300) {
                $dir_eng = "West/Northwest";
				$dir_abb = "WNW";
            } elsif ($dir_deg < 330) {
                $dir_eng = "Northwest";
				$dir_abb = "NW";
            } elsif ($dir_deg < 345) {
                $dir_eng = "North/Northwest";
				$dir_abb = "NNW";
            } elsif ($dir_deg < 360) {
                $dir_eng = "North";
				$dir_abb = "N";
            } else {
                # Shouldn't happen, but if for some reason the METAR
                # information doesn't contain a reasonable direction...
                $dir_eng = "undeterminable";
            }
        }

		my $kts_speed = undef;
		my $mph_speed = undef;
		my $mps_speed = undef;

		my $kts_gust = "";
		my $mph_gust = "";
		my $mps_gust = "";

		# parse knots

		if ($self->{windtype} == $wt_knots){
			$wind =~ /...(\d\d\d?)/o;
			$kts_speed = $1;
			$mph_speed = $kts_speed * 1.15077945;
			$mps_speed = $kts_speed * 0.514444444;

			if ($wind =~ /.{5,6}G(\d\d\d?)/o) {
				$kts_gust = $1;
				$mph_gust = $kts_gust * 1.15077945;
				$mps_gust = $kts_gust * 0.514444444;
			}
		# else: parse meters/second
		} elsif ($self->{windtype} == $wt_mps){
			$wind=~ /...(\d\d\d?)/o;
			$mps_speed = $1;
			$kts_speed = $mps_speed * 1.9438445; # units
			$mph_speed = $mps_speed * 2.2369363;
			if ($wind =~ /\d{5,6}G(\d\d\d?)/o) {
				$mps_gust = $1;
				$kts_gust = $mps_gust * 1.9438445;
				$mph_gust = $mps_gust * 2.2369363;
			}
		} else {
			warn "Geo::METAR Parser error: unknown windtype\n";
		}

        $self->{WIND_KTS} = $kts_speed;
        $self->{WIND_MPH} = $mph_speed;
        $self->{WIND_MS}  = $mps_speed;

        $self->{WIND_GUST_KTS} = $kts_gust;
        $self->{WIND_GUST_MPH} = $mph_gust;
        $self->{WIND_GUST_MS}  = $mps_gust;

        $self->{WIND_DIR_DEG} = $dir_deg;
        $self->{WIND_DIR_ENG} = $dir_eng;
        $self->{WIND_DIR_ABB} = $dir_abb;

    }

	##
	## wind variation
	##

	if (defined $self->{windvar})
	{
		if ($self->{windvar} =~ /^(\d\d\d)V(\d\d\d)$/){
			$self->{WIND_VAR} = "Varying between $1 and $2";
            $self->{WIND_VAR_1} = $1;
            $self->{WIND_VAR_2} = $2;
            my @direction = (
                15 => "North",
                30 => "North/Northeast",
                60 => "Northeast",
                75 => "East/Northeast",
                105 => "East",
                120 => "East/Southeast",
                150 => "Southeast",
                165 => "South/Southeast",
                195 => "South",
                210 => "South/Southwest",
                240 => "Southwest",
                265 => "West/Southwest",
                285 => "West",
                300 => "West/Northwest",
                330 => "Northwest",
                345 => "North/Northwest",
                360 => "North",
                1000 => "undeterminable");
            for(my $x = 0; $x < $#direction; $x += 2) {
                if($self->{WIND_VAR_1} < $direction[$x]) {
                    $self->{WIND_VAR_ENG_1} = $direction[$x+1];
                    last;
                }
            }
            for(my $x = 0; $x < $#direction; $x += 2) {
                if($self->{WIND_VAR_2} < $direction[$x]) {
                    $self->{WIND_VAR_ENG_2} = $direction[$x+1];
                    last;
                }
            }
		}
	}

    ##
    ## Visibility.
    ##

    if($self->{visibility}) {
        my $vis = $self->{visibility};
		# test for statute miles
		if ($vis =~ /SM$/){
			$vis =~ s/SM$//oi;                              # nuke the "SM"
			if ($vis =~ /M(\d\/\d)/o) {
				$self->{VISIBILITY} = "Less than $1 statute miles";
			} else {
				$self->{VISIBILITY} = $vis . " statute miles";
			} # end if
		# auto metars can have non-directional visibility reports
		} elsif ($self->{MOD} and ($self->{MOD} eq 'AUTO')
                and ($vis =~ /(\d+)NDV$/)){
			$self->{VISIBILITY} = "$1 meters non-directional visibility";
		} else {
			$self->{VISIBILITY} = $vis . " meters";
		}
    }

    ##
    ## Calculate F temps for all C temps
    ##

    foreach my $key ( keys(%$self) )
    {
        if ( uc($key) eq $key && $key =~ /^(.*)_C$/ )
        {
            my $fkey = $1 . "_F";

            next unless defined $self->{$key} && $self->{$key};

            $self->{$fkey} = sprintf("%.1f", (($self->{$key} * (9/5)) + 32));
        }
    }

	# join the runway group
	
	$self->{runway} = join(', ' , @{$self->{RUNWAY}});
	
}

##
## Print the tokens--usually when debugging.
##

sub print_tokens
{
    my $self = shift;
    my $tok;
    foreach $tok (@{$self->{tokens}}) {
        print "> $tok\n";
    }
}

##
## Turn debugging on/off.
##

sub debug
{
    my $self = shift;
    my $flag = shift;
    return $self->{debug} unless defined $flag;

    if (($flag eq "Y") or ($flag eq "y") or ($flag == 1)) {
        $self->{debug} = 1;
    } elsif (($flag eq "N") or ($flag eq "n") or ($flag == 0)) {
        $self->{debug} = 0;
    }

    return $self->{debug};
}

##
## Dump internal data structure. Useful for debugging and such.
##

sub dump
{
    my $self = shift;

    print "Modified METAR dump follows.\n\n";

    print "type: $self->{type}\n";
    print "site: $self->{site}\n";
    print "date_time: $self->{date_time}\n";
    print "modifier: $self->{modifier}\n";
    print "wind: $self->{wind}\n";
    print "variable wind: $self->{vrbwind}\n";
    print "visibility: $self->{visibility}\n";
    print "runway: $self->{runway}\n";
    print "weather: " . join(', ', @{$self->{weather}}) . "\n";
    print "sky: " . join(', ', @{$self->{sky}}) . "\n";
    print "temp_dew: $self->{temp_dew}\n";
    print "alt: $self->{alt}\n";
    print "pressure: $self->{pressure}\n";
    print "slp: $self->{slp}\n";
    print "remarks: " . join (', ', @{$self->{remarks}}) . "\n";
    print "\n";

    foreach my $var ( sort(keys(%$self)) )
    {
        next if ( uc($var) ne $var );

        if ( ref($self->{$var}) eq "ARRAY" )
        {
            print "$var: ", join(", ", @{$self->{$var}}), "\n";
        }
        else
        {
            print "$var: ", $self->{$var}, "\n";
        }
    }
}

1;

__END__

=head1 NAME

Geo::METAR - Process aviation weather reports in the METAR format.

=head1 SYNOPSIS

  use Geo::METAR;
  use strict;

  my $m = new Geo::METAR;
  $m->metar("KFDY 251450Z 21012G21KT 8SM OVC065 04/M01 A3010 RMK 57014");
  print $m->dump;

  exit;

=head1 DESCRIPTION

METAR reports are available on-line, thanks to the National Weather Service.
Since reading the METAR format isn't easy for non-pilots, these reports are
relatively useles to the common man who just wants a quick glace at the
weather. This module tries to parse the METAR reports so the data can be
used to create readable weather reports and/or process the data in
applications.

=head1 USAGE

=head2 How you might use this

Here is how you I<might> use the Geo::METAR module.

One use that I have had for this module is to query the NWS METAR page
(using the LWP modules) at:

I<http://weather.noaa.gov/cgi-bin/mgetmetar.pl?cccc=EHSB>

to get an
up-to-date METAR. Then, I scan thru the output, looking for what looks
like a METAR string (that's not hard in Perl). Oh, EHSB can be any site
location code where there is a reporting station.

I then pass the METAR into this module and get the info I want. I can
then update my webcam page with the current temperature, sky conditions, or
whatnot. See for yourself at http://webcam.idefix.net/

See the BUGS section for a remark about multiple passes with the same
Geo::METAR object.

=head2 Functions

The following functions are defined in the METAR module. Most of
them are I<public>, meaning that you're supposed to use
them. Some are I<private>, meaning that you're not supposed to use
them -- but I won't stop you. Assume that functions are I<public>
unless otherwise documented.

=over

=item metar()

metar() is the function to whwich you should pass a METAR string.  It
will take care of decomposing it into its component parts converting
the units and so on.

Example: C<$m-E<gt>metar("KFDY 251450Z 21012G21KT 8SM OVC065 04/M01 A3010 RMK 57014");>

=item debug()

debug() toggles debugging messages. By default, debugging is turned
B<off>. Turn it on if you are developing METAR or having trouble with
it.

debug() understands all of the following:

        Enable       Disable
        ------       -------
          1             0
        'yes'         'no'
        'on'          'off'

If you contact me for help, I'll likely ask you for some debugging
output.

Example: C<$m-E<gt>debug(1);>

=item dump()

dump() will dump the internal data structure for the METAR in a
semi-human readable format.

Example: C<$m-E<gt>dump;>

=item version()

version() will print out the current version.

Example: C<print $m-E<gt>version;>

=item _tokenize()

B<PRIVATE>

Called internally to break the METAR into its component tokens.

=item _process()

B<PRIVATE>

Used to make sense of the tokens found in B<_tokenize()>.

=back

=head2 Variables

After you've called B<metar()>, you'd probably like to get at
the individual values for things like temperature, dew point,
and so on. You do that by accessing individual variables via
the METAR object.

This section lists those variables and what they represent.

If you call B<dump()>, you'll find that it spits all of these
out.

=over

=item VERSION

The version of METAR.pm that you're using.

=item METAR

The actual, raw METAR.

=item TYPE

Report type in English ("Routine Weather Report" or "Special Weather Report")

=item SITE

4-letter site code.

=item DATE

The date (just the day of the month) on which the report was issued.

=item TIME

The time at which the report was issued.

=item MOD

Modifier (AUTO/COR) if any.

=item WIND_DIR_ENG

The current wind direction in English (Southwest, East, North, etc.)

=item WIND_DIR_ABB

The current wind direction in abbreviated English (S, E, N, etc.)

=item WIND_DIR_DEG

The current wind direction in degrees.

=item WIND_KTS

The current wind speed in Knots.

=item WIND_MPH

The current wind speed in Miles Per Hour.

=item WIND_MS

The current wind speed in Metres Per Second.

=item WIND_GUST_KTS

The current wind gusting speed in Knots.

=item WIND_GUST_MPH

The current wind gusting speed in Miles Per Hour.

=item WIND_GUST_MS

The current wind gusting speed in Metres Per Second.

=item WIND_VAR

The wind variation in English

=item WIND_VAR_1

The first wind variation direction

=item WIND_VAR_ENG_1

The first wind variation direction in English

=item WIND_VAR_2

The second wind variation direction

=item WIND_VAR_ENG_2

The second wind variation direction in English

=item VISIBILITY

Visibility information.

=item WIND

Wind information.

=item RUNWAY

Runway information.

=item WEATHER

Current weather (array)

=item WEATHER_LOG

Current weather log (array)

=item SKY

Current cloud cover (array)

=item TEMP_C

Temperature in Celsius.

=item TEMP_F

Temperature in Fahrenheit.

=item DEW_C

Dew point in Celsius.

=item DEW_F

Dew point in Fahrenheit.

=item HOURLY_TEMP_F

Hourly current temperature, fahrenheit

=item HOURLY_TEMP_C

Hourly current temperature, celcius

=item HOURLY_DEW_F

Hourly dewpoint, fahrenheit

=item HOURLY_DEW_C

Hourly dewpoint, celcius

=item ALT

Altimeter setting (barometric pressure).

=item ALT_HP

Altimeter setting in hectopascals.

=item REMARKS

Any remarks in the report.

=back

=head1 NOTES

Test suite is small and incomplete. Needs work yet.

Older versions of this module were installed as "METAR" instaed of
"Geo::METAR"

=head1 BUGS

The Geo::METAR is only initialized once, which means you'll get left-over
crud in variables when you call the metar() function twice.

What is an invalid METAR in one country is a standard one in the next.
The standard is interpreted and used by meteorologists all over the world,
with local variations. This means there will always be METARs that will
trip the parser.

=head1 TODO

There is a TODO file included in the Geo::METAR distribution listing
the outstanding tasks that I or others have devised. Please check that
list before you submit a bug report or request a new feture. It might
already be on the TODO list.

=head1 AUTHORS AND COPYRIGHT

Copyright 1997-2000, Jeremy D. Zawodny <Jeremy [at] Zawodny.com>

Copyright 2007, Koos van den Hout <koos@kzdoos.xs4all.nl>

Geo::METAR is covered under the GNU Public License (GPL) version 2 or
later.

The Geo::METAR Web site is located at:

  http://idefix.net/~koos/perl/Geo-METAR/

=head1 CREDITS

In addition to our work on Geo::METAR, We've received ideas, help, and
patches from the following folks:

  * Ethan Dicks <ethan.dicks [at] gmail.com>

    Testing of Geo::METAR at the South Pole. Corrections and pointers
	to interesting cases to test.

  * Otterboy <jong [at] watchguard.com>

    Random script fixes and initial debugging help

  * Remi Lefebvre <remi [at] solaria.dhis.org>

    Debian packaging as libgeo-metar-perl.deb.

  * Mike Engelhart <mengelhart [at] earthtrip.com>

    Wind direction naming corrections.

  * Michael Starling <mstarling [at] logic.bm>

    Wind direction naming corrections.

  * Hans Einar Nielssen <hans.einar [at] nielssen.com>

    Wind direction naming corrections.

  * Nathan Neulinger <nneul [at] umr.edu>

    Lots of enhancements and corrections. Too many to list here.

=head1 RELATED PROJECTS

B<lcdproc> at http://www.lcdproc.org/ uses Geo::METAR in lcdmetar.pl to
display weather data on an lcd.

=cut


# vim:expandtab:sw=4 ts=4