~conky-companions/+junk/conkyforecast

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
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
###############################################################################
# conkyForecast.py is a (not so) simple (anymore) python script to gather 
# details of the current weather for use in conky.
#
#  Author: Kaivalagi
# Created: 13/04/2008

from datetime import datetime, timedelta, tzinfo
from optparse import OptionParser
import sys
import os
import socket
import urllib2
import gettext
import locale
import re
import codecs
import traceback
import time
import json

# not sure on these, might create more trouble, but here goes...
reload(sys)
sys.setdefaultencoding('utf-8')

# cPickle is a pickle class implemented in C - so its faster
# in case its not available, use regular pickle
try:
    import cPickle as pickle
except ImportError:
    import pickle

app_name = "conkyForecast"
app_path = os.path.dirname(os.path.abspath(__file__))
module_name = __file__.replace(os.path.dirname (__file__) + "/", "").replace(".pyc","").replace(".py", "")

# default to standard locale translation
domain = __file__.replace(os.path.dirname (__file__) + "/", "").replace(".py", "")
localedirectory = os.path.dirname(os.path.abspath(__file__)) + "/locale"
gettext.bindtextdomain(domain, localedirectory)
gettext.textdomain(domain)
gettext.install(domain)

class CommandLineParser:

    parser = None

    def __init__(self):

        self.parser = OptionParser()
        self.parser.add_option("-C", "--config", dest="config", default="~/.conkyForecastWU.config", type="string", metavar="FILE", help=u"[default: %default] The path to the configuration file, allowing multiple config files to be used.")
        self.parser.add_option("-l", "--location", dest="location", type="string", metavar="CODE", help=u"location code for weather data [default set in config]. Normally in the form \"COUNTRY/CITY\"")
        self.parser.add_option("-d", "--datatype", dest="datatype", default="HT", type="string", metavar="DATATYPE", help=u"[default: %default] The data type options are: DW (Day of Week), WI (Weather Icon Path), LT (Forecast:Low Temp,Current:Feels Like Temp), HT (Forecast:High Temp,Current:Current Temp), CT (Conditions Text), PC (Precipitation Chance), HM (Humidity), VI (Visibility), WD (Wind Direction), WA (Wind Angle - in degrees), WS (Wind Speed), WG (Wind Gusts), BF (Bearing Font), BI (Bearing Icon Path), BS (Bearing font with Speed), CN (City Name), CO (Country), OB (Observatory), BR (Barometer Reading), BD (Barometer Description), UI (UV Index), UT (UV Text), DP (Dew Point), LU (Last Update at weather.com), LF (Last Fetch from weather.com). Not applicable at command line when using templates.")
        self.parser.add_option("-s", "--startday", dest="startday", type="int", metavar="NUMBER", help=u"define the starting day number, if omitted current conditions are output. Not applicable at command line when using templates.")
        self.parser.add_option("-e", "--endday", dest="endday", type="int", metavar="NUMBER", help=u"define the ending day number, if omitted only starting day data is output. Not applicable at command line when using templates.")
        self.parser.add_option("-S", "--spaces", dest="spaces", type="int", default=1, metavar="NUMBER", help=u"[default: %default] Define the number of spaces between ranged output. Not applicable at command line when using templates.")
        self.parser.add_option("-t", "--template", dest="template", type="string", metavar="FILE", help=u"define a template file to generate output in one call. A displayable item in the file is in the form [--datatype=HT --startday=1]. The following are possible options within each item: --location,--datatype,--startday,--endday,--night,--shortweekday,--imperial,--beaufort,--metrespersecond,--hideunits,--hidedegreesymbol,--spaces,--minuteshide. Note that the short forms of the options are not supported! If any of these options is set from the commandline, it sets the default value of the option for all template items.")
        self.parser.add_option("-L", "--locale", dest="locale", type="string", help=u"override the system locale for language output (bg=bulgarian, cs=czech, de=german, es=spanish, en=english, es=spanish, fj=fijian, fr=french, it=italian, nl=dutch, pl=polish, ro=romanian, sk=slovak, more to come)")
        self.parser.add_option("-i", "--imperial", dest="imperial", default=False, action="store_true", help=u"request imperial units, if omitted output is in metric.")
        self.parser.add_option("-b", "--beaufort", dest="beaufort", default=False, action="store_true", help=u"request beaufort scale for wind speeds, if omitted output is either metric/imperial.")
        self.parser.add_option("-M", "--metrespersecond", dest="metrespersecond", default=False, action="store_true", help=u"request metres per second for wind speeds, if omitted output is either metric/imperial.")
        self.parser.add_option("-n", "--night", dest="night", default=False, action="store_true", help=u"switch output to night data, if omitted day output will be output.")
        self.parser.add_option("-w", "--shortweekday", dest="shortweekday", default=False, action="store_true", help=u"Shorten the day of week data type to 3 characters.")
        self.parser.add_option("-u", "--hideunits", dest="hideunits", default=False, action="store_true", help=u"Hide units such as mph or C, degree symbols (°) are still shown.")
        self.parser.add_option("-x", "--hidedegreesymbol", dest="hidedegreesymbol", default=False, action="store_true", help=u"Hide the degree symbol used with temperature output, this is only valid if used in conjunction with --hideunits.")
        self.parser.add_option("-m", "--minuteshide", dest="minuteshide", type="int", metavar="NUMBER", help=u"Works only with LU and LF. If present, hides the date part of the LU or LF timestamp if the day of the timestamp is today. The time part is also hidden, if the timestamp is older than minutes specified in this argument. If set to 0, the time part is always shown. If set to -1, the value EXPIRY_MINUTES from the config file is used.")
        self.parser.add_option("-c", "--centeredwidth", dest="centeredwidth", type="int", metavar="WIDTH", help=u"If used the output will be centered in a string of the set width, padded out with spaces, if the output width is greater than the setting it will be truncated")
        self.parser.add_option("-r", "--refetch", dest="refetch", default=False, action="store_true", help=u"Fetch data regardless of data expiry.")
        self.parser.add_option("-v", "--verbose", dest="verbose", default=False, action="store_true", help=u"Request verbose output, not a good idea when running through conky!")
        self.parser.add_option("-V", "--version", dest="version", default=False, action="store_true", help=u"Displays the version of the script.")
        self.parser.add_option("--errorlogfile", dest="errorlogfile", type="string", metavar="FILE", help=u"If a filepath is set, the script appends errors to the filepath.")
        self.parser.add_option("--infologfile", dest="infologfile", type="string", metavar="FILE", help=u"If a filepath is set, the script appends info to the filepath.")                

    def parse_args(self):
        (options, args) = self.parser.parse_args()
        return (options, args)

    def print_help(self):
        return self.parser.print_help()
    
# N.B: The below class member values are defaults and should be left alone, they
#      are there to provide a working script if the script is called without all
#      the expected input. Any issues raised where these values have been
#      changed will get the simple "put the .py file back to it's original
#      state" reply
class ForecastConfig:
    CACHE_FOLDERPATH = "/tmp/"
    CONNECTION_TIMEOUT = 5
    EXPIRY_MINUTES = 30
    TIME_FORMAT = "%H:%M"
    DATE_FORMAT = "%Y-%m-%d"
    LOCALE = "" # with no setting the default locale of the system is used
    XOAP_PARTNER_ID = "" # need config with correct partner id
    XOAP_LICENCE_KEY = "" # need config"N/A" with correct licence key
    DEFAULT_LOCATION = "UK/Norwich"
    MAXIMUM_DAYS_FORECAST = 7
    AUTO_NIGHT = False
    BASE_WU_JSON_URL = "http://api.wunderground.com/api/<WU_LICENCE_KEY>/geolookup/conditions/forecast/q/<LOCATION>.json"
    PROXY_HOST = None
    PROXY_PORT = 8080
    PROXY_USERNAME = None
    PROXY_PASSWORD = None


class ForecastDataset:
    def __init__(self, last_update, day_of_week, low, high, condition_url, condition_text, precip, humidity, wind_dir, wind_dir_numeric, wind_speed, wind_gusts, timezone, bar_read, bar_desc, uv_index, uv_text, dew_point, observatory, visibility, city, country):
        self.last_update = last_update
        self.day_of_week = day_of_week
        self.low = low
        self.high = high
        self.condition_url = condition_url
        self.condition_text = condition_text
        self.precip = precip
        self.humidity = humidity
        self.wind_dir = wind_dir
        self.wind_dir_numeric = wind_dir_numeric
        self.wind_speed = wind_speed
        self.wind_gusts = wind_gusts
        self.timezone = timezone
        self.bar_read = bar_read
        self.bar_desc = bar_desc
        self.uv_index = uv_index
        self.uv_text = uv_text
        self.dew_point = dew_point
        self.observatory = observatory
        self.visibility = visibility
        self.city = city
        self.country = country
        
class ForecastLocation:
    timestamp = None
    
    def __init__(self, current, day, night):
        self.current = current
        self.day = day
        self.night = night
        self.timestamp = datetime.today()
        
    def outdated(self, mins):
        if datetime.today() > self.timestamp + timedelta(minutes=mins):
            return True
        else:
            return False

# start ignoring translations required at runtime
def _(text): return text

class ForecastText:

    # translatable dictionaries
    conditions_text = {
        "0": _(u"Tornado"),
        "1": _(u"Tropical Storm"),
        "2": _(u"Hurricane"),
        "3": _(u"Severe Thunderstorms"),
        "4": _(u"Thunderstorms"),
        "5": _(u"Mixed Rain and Snow"),
        "6": _(u"Mixed Rain and Sleet"),
        "7": _(u"Mixed Precipitation"),
        "8": _(u"Freezing Drizzle"),
        "9": _(u"Drizzle"),
        "10": _(u"Freezing Rain"),"N/A"
        "11": _(u"Light Rain"),
        "12": _(u"Rain"),
        "13": _(u"Snow Flurries"),
        "14": _(u"Light Snow Showers"),
        "15": _(u"Drifting Snow"),
        "16": _(u"Snow"),
        "17": _(u"Hail"),
        "18": _(u"Sleet"),
        "19": _(u"Dust"),
        "20": _(u"Fog"),
        "21": _(u"Haze"),
        "22": _(u"Smoke"),
        "23": _(u"Blustery"),
        "24": _(u"Windy"),
        "25": _(u"N/A"),
        "26": _(u"Cloudy"),
        "27": _(u"Mostly Cloudy"),
        "28": _(u"Mostly Cloudy"),
        "29": _(u"Partly Cloudy"),
        "30": _(u"Partly Cloudy"),
        "31": _(u"Clear"),
        "32": _(u"Clear"),
        "33": _(u"Fair"),
        "34": _(u"Fair"),
        "35": _(u"Mixed Rain and Hail"),
        "36": _(u"Hot"),
        "37": _(u"Isolated Thunderstorms"),
        "38": _(u"Scattered Thunderstorms"),
        "39": _(u"Scattered Showers"),
        "40": _(u"Heavy Rain"),
        "41": _(u"Scattered Snow Showers"),
        "42": _(u"Heavy Snow"),
        "43": _(u"Heavy Snow"),
        "44": _(u"N/A"),
        "45": _(u"Scattered Showers"),
        "46": _(u"Snow Showers"),
        "47": _(u"Isolated Thunderstorms"),
        "na": _(u"N/A"),
        "-": _(u"N/A")
    }

    day_of_week_short = {
        "Today": _(u"Now"),
        "Monday": _(u"Mon"),
        "Tuesday": _(u"Tue"),
        "Wednesday": _(u"Wed"),
        "Thursday": _(u"Thu"),
        "Friday": _(u"Fri"),
        "Saturday": _(u"Sat"),
        "Sunday": _(u"Sun")
    }
    
    # this now returns ascii code
    bearing_arrow_font = {
        "S": 0x31,"N/A"
        "SSW": 0x32,
        "SW": 0x33,
        "WSW": 0x34,
        "W": 0x35,
        "WNW": 0x36,
        "NW": 0x37,
        "NNW": 0x38,
        "N": 0x39,
        "NNE": 0x3a,
        "NE": 0x3b,
        "ENE": 0x3c,
        "E": 0x3d,
        "ESE": 0x3e,
        "SE": 0x3f,
        "SSE": 0x40,
    }

    bearing_icon = {
        "calm": "00",
        "VAR": "01",
        "S": "05",
        "SSW": "06",
        "SW": "07",
        "WSW": "08",
        "W": "09",
        "WNW": "10",
        "NW": "11",
        "NNW": "12",
        "N": "13",
        "NNE": "14",
        "NE": "15",
        "ENE": "16",
        "E": "17",
        "ESE": "18",
        "SE": "19",
        "SSE": "20"
    }        
    
    # some general things...
    general = {
 	"n/a": _(u"n/a"),
	'N/A': _(u"N/A"),
	'Not Available': _(u"Not Available"),
	'unknown': _(u"unknown"),
	'NONE': _(u"NONE"),
	'day': _(u"day"),
	'night': _(u"night")
    }
    
    # UV index ...
    UV_index = {
	"Extreme": _(u"Extreme"),
	"Very high": _(u"Very High"),
	"High": _(u"High"),
	"Moderate": (u"Moderate"),
	"Low": _(u"Low")
    }
    
    # tendencies used for barometric pressure
    bar_pressure = {
	"Very Low": _(u"Very Low"),
	"Moderate": _(u"Moderate"),
	"rising": _(u"rising"),
	"falling": _(u"falling"),
	"steady": _(u"steady"),
	"calm": _(u"calm")
    }


    # wind directions long
    wind_directions_long = {
	"East": _(u"East"),
	"East Northeast": _(u"East Northeast"),
	"East Southeast": _(u"East Southeast"),
	"North": _(u"North"),
	"Northeast": _(u"Northeast"),
	"North Northeast": _(u"North Northeast"),
	"North Northwest": _(u"North Northwest"),
	"Northwest": _(u"Northwest"),
	"South": _(u"South"),
	"Souteast": _(u"Southeast"),
	"South Southeast": _(u"South Southeast"),"N/A"
	"South Southwest": _(u"South Southwest"),
	"Southwest": _(u"Southwest"),
	"variable": _(u"variable"),
	"West": _(u"West"),
	"West Northwest": _(u"West Northwest"),
	"West Southwest": _(u"West Southwest")
    }
    
    wind_directions_short = {
	"E": _(u"E"),
	"ENE": _(u"ENE"),
	"ESE": _(u"ESE"),
	"N": _(u"N"),
	"NE": _(u"NE"),
	"NNE": _(u"NNE"),
	"NNW": _(u"NNW"),
	"NW": _(u"NW"),
	"S": _(u"S"),
	"SE": _(u"SE"),
	"SSE": _(u"SSE"),
	"SSW": _(u"SSW"),
	"SW": _(u"SW"),
	"W": _(u"W"),
	"WNW": _(u"WNW"),
	"WSW": _(u"WSW")
    }

    days_of_week = {
	"Today": _(u"Today"),
	"Monday": _(u"Monday"),
	"Tuesday":_(u"Tuesday"),
	"Wednesday":_(u"Wednesday"),
	"Thursday": _(u"Thursday"),
	"Friday": _(u"Friday"),"N/A"
	"Saturday": _(u"Saturday"),
	"Sunday": _(u"Sunday")
    }
    
# end ignoring translations
del _

class ForecastInfo:
    
    # design time variables
    options = None
    config = None
    forecast_data = {}
    # a list of locations for which an attempt was made to load them
    # locations in this list are not loaded again (if there was an error,
    # this makes sure it doesn't reapeat over and over)
    loaded_locations = []
    error = ""
    errorfound = False
    
    # design time settings
    CACHE_FILENAME = ".conkyForecast-<LOCATION>.cache"
    CONDITION_IMAGE_FILENAME = ".conkyForecast-WI-<CONDITION>.gif"

    def __init__(self, options):

        self.options = options
                                         
        self.loadConfigData()
        
        # setup timeout for connections
        # TODO: seems like this doesn't work in all cases..
        socket.setdefaulttimeout(self.config.CONNECTION_TIMEOUT)
        
        # set the locale
        if self.options.locale == None:
            if self.config.LOCALE == "":
                self.options.locale = locale.getdefaultlocale()[0][0:2]
            else:
                self.options.locale = self.config.LOCALE

        self.logInfo("Locale set to " + self.options.locale)
        
        # if not the default "en" locale, configure the i18n language translation    
        if self.options.locale != "en":

            self.logInfo("Looking for translation file for '%s' under %s" % (self.options.locale, localedirectory))
            
            if gettext.find(domain, localedirectory, languages=[self.options.locale]) != None:
                self.logInfo("Translation file found for '%s'" % self.options.locale)
                
                try:
                    trans = gettext.translation(domain, localedirectory, languages=[self.options.locale])
                    trans.install(unicode=True)
                    self.logInfo("Translation installed for '%s'" % self.options.locale)
                    
                except Exception, e:
                    self.logError("Unable to load translation for '%s' %s" % (self.options.locale, e.__str__()))
            else:
                self.logInfo("Translation file not found for '%s', defaulting to 'en'" % self.options.locale)
                self.options.locale = "en"

        # setup location code if not set
        if self.options.location == None:
            self.options.location = self.config.DEFAULT_LOCATION           
        
        # setup a proxy if defined
        if self.config.PROXY_HOST != None:
            if self.config.PROXY_USERNAME != None and self.config.PROXY_PASSWORD != None:
                self.logInfo("Setting up proxy '%s:%d', with username and password"%(self.config.PROXY_HOST,self.config.PROXY_PORT))
                proxyurl = "http://%s:%s@%s:%d"%(self.config.PROXY_USERNAME,self.config.PROXY_PASSWORD,self.config.PROXY_HOST,self.config.PROXY_PORT)
            else:
                self.logInfo("Setting up proxy '%s:%d', without username and password"%(self.config.PROXY_HOST,self.config.PROXY_PORT))
                proxyurl = "http://%s:%d"%(self.config.PROXY_HOST,self.config.PROXY_PORT)

            try:
                proxy_support = urllib2.ProxyHandler({"http" : proxyurl})
                opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler)
                urllib2.install_opener(opener)
            except Exception, e:
                self.logError("Unable to setup proxy: %s"%e.__str__())
        else:
            self.logInfo("Not using a proxy as none is defined")

        # Check if the location is loaded, if not, load it. If it can't be loaded, there was an error
        if not self.checkAndLoad(self.options.location):
            self.logError("Failed to load the location cache")
                    
    def loadConfigData(self):
        try:         
            # load .conkyForecast.config from the options setting
            configfilepath = os.path.expanduser(self.options.config)
                                          
            if os.path.exists(configfilepath):
                
                self.config = ForecastConfig()
                
                #load the file
                fileinput = open(configfilepath)
                lines = fileinput.read().split("\n")
                fileinput.close() 

                for line in lines:
                    line = line.strip()
                    if len(line) > 0 and line[0:1] != "#": # ignore commented lines or empty ones

                        splitpos = line.find("=")
                        name = line[:splitpos-1].strip().upper() # config setting name on the left of =
                        value = line[splitpos+1:].split("#")[0].strip()
                        
                        if len(value) > 0:
                            if name == "CACHE_FOLDERPATH":
                                self.config.CACHE_FOLDERPATH = value
                            elif name == "CONNECTION_TIMEOUT":
                                try: # NITE: removed the isNumeric() check in favor of this..its more effective and lets the user know something is wrong
                                    self.config.CONNECTION_TIMEOUT = int(value)
                                except:
                                    self.logError("Invalid value of config option CONNECTION_TIMEOUT: " + value)
                            elif name == "EXPIRY_MINUTES":
                                try:
                                    self.config.EXPIRY_MINUTES = int(value)
                                except:
                                    self.logError("Invalid value of config option EXPIRY_MINUTES: " + value)
                            elif name == "TIME_FORMAT":
                                self.config.TIME_FORMAT = value
                            elif name == "DATE_FORMAT":
                                self.config.DATE_FORMAT = value                                    
                            elif name == "LOCALE":
                                self.config.LOCALE = value
                            elif name == "WU_LICENCE_KEY":
                                self.config.WU_LICENCE_KEY = value
                            elif name == "DEFAULT_LOCATION":
                                self.config.DEFAULT_LOCATION = value
                            elif name == "MAXIMUM_DAYS_FORECAST":
                                self.config.MAXIMUM_DAYS_FORECAST = int(value)
                            elif name == "AUTO_NIGHT":
                                self.config.AUTO_NIGHT = self.parseBoolString(value)
                            elif name == "BASE_WU_JSON_URL":
                                self.config.BASE_WU_JSON_URL = value
                            elif name == "PROXY_HOST":
                                self.config.PROXY_HOST = value
                            elif name == "PROXY_PORT":
                                self.config.PROXY_PORT = int(value)
                            elif name == "PROXY_USERNAME":
                                self.config.PROXY_USERNAME = value
                            elif name == "PROXY_PASSWORD":
                                self.config.PROXY_PASSWORD = value
                            else:
                                self.logError("Unknown option in config file: " + name)

                if self.options.verbose == True:
                    print >> sys.stdout,"*** CONFIG OPTIONS:"
                    print >> sys.stdout,"    CACHE_FOLDERPATH:", self.config.CACHE_FOLDERPATH
                    print >> sys.stdout,"    CONNECTION_TIMEOUT:", self.config.CONNECTION_TIMEOUT
                    print >> sys.stdout,"    EXPIRY_MINUTES:", self.config.EXPIRY_MINUTES
                    print >> sys.stdout,"    TIME_FORMAT:", self.config.TIME_FORMAT
                    print >> sys.stdout,"    DATE_FORMAT:", self.config.DATE_FORMAT                
                    print >> sys.stdout,"    LOCALE:", self.config.LOCALE
                    print >> sys.stdout,"    WU_LICENCE_KEY:", self.config.WU_LICENCE_KEY
                    print >> sys.stdout,"    DEFAULT_LOCATION:", self.config.DEFAULT_LOCATION
                    print >> sys.stdout,"    MAXIMUM_DAYS_FORECAST:", self.config.MAXIMUM_DAYS_FORECAST
                    print >> sys.stdout,"    BASE_WU_JSON_URL:", self.config.BASE_WU_JSON_URL
                    
            else:
                self.logError("Config data file %s not found, using defaults (Registration info is needed though)" % configfilepath)

        except Exception, e:
            self.logError("Error while loading config data, using defaults (Registration info is needed though): " + e.__str__())


    def checkAndLoad(self, location):

        # if the location was not loaded before (or attempted to load)
        if not location in self.loaded_locations:
            # add it to the list so it doesn't get loaded again (or attempted to load)
            self.loaded_locations.append(location)

            # define CACHE_FILEPATH based on cache folder and location code
            CACHE_FILEPATH = os.path.join(self.config.CACHE_FOLDERPATH, self.CACHE_FILENAME.replace("<LOCATION>", location.replace("/","-")))

            if not self.forecast_data.has_key(location):
                if os.path.exists(CACHE_FILEPATH):
                    try:
                        self.logInfo("Loading cache file " + CACHE_FILEPATH)
                        file = open(CACHE_FILEPATH, 'rb')
                        self.forecast_data[location] = pickle.load(file)
                        file.close()
                    except Exception, e:
                        self.logError("Unable to read the cache file %s: %s" % (CACHE_FILEPATH, e.__str__()))
                        #TODO: get to the bottom of failure to load pickled cache file, is this a 2.7.1 issue?
                        self.logInfo("Deleting cache file due to loading issues, it will be prepared again")
                        os.remove(CACHE_FILEPATH)
                        #return False
        
            # check the data in the dictionary and update if outdated
            # if there was an update, store the new data in the cache file
            if self.checkAndUpdate(location) == True:
                try:
                    self.logInfo("Saving updated cache file " + CACHE_FILEPATH)
                    file = open(CACHE_FILEPATH, 'wb')
                    pickle.dump(self.forecast_data[location], file)
                    file.close()
                except Exception, e:
                    self.logError("Unable to save cache file %s: %s" % (CACHE_FILEPATH, e.__str__()))
                    return False

        # if the location is still not in cache, print an error and return false to writeOutput()
        if self.forecast_data.has_key(location):
            return True
        else:
            self.logError("Location %s is not in cache." % self.options.location) 
            return False
        

    def checkAndUpdate(self, location):
        # if the location is outdated or the refetch is forced..
        if not self.forecast_data.has_key(location) or \
           self.forecast_data[location].outdated(self.config.EXPIRY_MINUTES) or \
           self.options.refetch == True:

            # obtain current conditions data from xoap service
            try:
                url = self.config.BASE_WU_JSON_URL.replace("<LOCATION>",location).replace("<WU_LICENCE_KEY>",self.config.WU_LICENCE_KEY)
                       
                self.logInfo("Fetching weather data from " + url)

                usock = urllib2.urlopen(url)
                jsondata = usock.read()
                usock.close()

            except Exception, e:
                self.logError("Server connection error: " + e.__str__())
                return False
            
            else:
                # interrogate weather data
                try:
                    # parse the XML
                    self.weatherdic = json.loads(jsondata)

                    current = self.weatherdic["current_observation"]                    
                    
                    city = current["display_location"]["city"]
                    country = current["display_location"]["country"]
                    latitude = current["display_location"]["latitude"]
                    longitude = current["display_location"]["longitude"]

                    observatory = current["observation_location"]["city"]
                    timezone = current["local_tz_short"]
                    
                    condition_url = current["icon_url"]
                    condition_text = current["weather"]

                    current_temp = str(current["temp_c"])
                    
        
                    last_update = current["observation_time_rfc822"]
                    
                    day_of_week = "Today"
                    current_temp_feels = str(current["windchill_c"])
                    
                    precip = _(u"N/A")  
                    wind_direction = current["wind_dir"]
                    wind_direction_numeric = str(current["wind_degrees"])
                    wind_speed = str(current["wind_mph"])
                    wind_gusts = str(current["wind_gust_mph"])
                    humidity = current["relative_humidity"]                    
                    
                    bar_read = str(current["pressure_mb"])
                    bar_desc = current["pressure_trend"]
                    uv_index = str(current["heat_index_c"])
                    uv_text = current["heat_index_string"]
                    dew_point = str(current["dewpoint_c"])
                    visibility = str(current["visibility_km"])

                    current_forecast_data = ForecastDataset(last_update, day_of_week, current_temp_feels, current_temp, condition_url, condition_text, precip, humidity, wind_direction, wind_direction_numeric, wind_speed, wind_gusts, timezone, bar_read, bar_desc, uv_index, uv_text, dew_point, observatory, visibility, city, country)
                    
                    bar_read = _(u"N/A")
                    bar_desc = _(u"N/A")
                    visibility = _(u"N/A")
                    uv_index = _(u"N/A")
                    uv_text = _(u"N/A")
                    dew_point = _(u"N/A")
                    
                    day_forecast_data_list = []
                    night_forecast_data_list = []

                    forecastlist = self.weatherdic["forecast"]["simpleforecast"]["forecastday"]
                    for forecastday in forecastlist:
                        last_update = time.strftime('%Y-%m-%d %I:%M:%S %p %Z',time.localtime(float(forecastday['date']['epoch'])))
                        daynumber = forecastday["period"]
                        day_of_week = forecastday["date"]["weekday"]
                        high_temp = str(forecastday["high"]["celsius"])
                        low_temp = str(forecastday["low"]["celsius"])                        

                        condition_url = forecastday["icon_url"]
                        condition_text = forecastday["conditions"]                        
                        
                        precip = str(forecastday["pop"])
                        wind_speed = _(u"N/A")
                        wind_gusts = _(u"N/A")
                        wind_direction_numeric = _(u"N/A")
                        wind_direction = _(u"N/A")
                        humidity = _(u"N/A")
        
                        
                        day_forecast_data = ForecastDataset(last_update, day_of_week, low_temp, high_temp, condition_url, condition_text, precip, humidity, wind_direction, wind_direction_numeric, wind_speed, wind_gusts, timezone, bar_read, bar_desc, uv_index, uv_text, dew_point, observatory, visibility, city, country)
                        day_forecast_data_list.append(day_forecast_data)
    
                        # no night data available at the mo....so just populating with day data
                        night_forecast_data = ForecastDataset(last_update, day_of_week, low_temp, high_temp, condition_url, condition_text, precip, humidity, wind_direction, wind_direction_numeric, wind_speed, wind_gusts, timezone, bar_read, bar_desc, uv_index, uv_text, dew_point, observatory, visibility, city, country)
                        night_forecast_data_list.append(night_forecast_data)
                        
                    self.forecast_data[location] = ForecastLocation(current_forecast_data, day_forecast_data_list, night_forecast_data_list)
    
                    return True
            
                except Exception, e:
                    self.logError("Error reading weather data: " + e.__str__())
                    return False

    def getTimestampOutput(self, timestamp, minuteshide):            
        # minuteshide:
        # None = disabled
        # -1 = hide days and use config.EXPIRY_MINUTES
        # 0 = hide days and always show hours
        
        output = u""
        
        today = datetime.today()
        days = today.day - timestamp.day
        if days or minuteshide == None:
            output += timestamp.strftime(self.config.DATE_FORMAT)
        
        if minuteshide == -1:
            minuteshide = self.config.EXPIRY_MINUTES
            
        delta = today - timestamp
        if days or minuteshide == None or minuteshide == 0 or delta.seconds > minuteshide * 60:
            if (len(output) > 0):
                output += " "
            output += timestamp.strftime(self.config.TIME_FORMAT)
        
        return output


    def getDatatypeFromSet(self, location, datatype, set, shortweekday, imperial, beaufort, metrespersecond, tempunit, speedunit, distanceunit, pressureunit, minuteshide, centeredwidth):
        output = u""

        try:
            if datatype == "LU":
                output = set.last_update.strip()                    
            elif datatype == "LF":
                output = self.getTimestampOutput(self.forecast_data[location].timestamp, minuteshide)
            elif datatype == "DW":
                if shortweekday == True:
                    output = _(ForecastText.day_of_week_short[set.day_of_week])
                else:
                    output = _(set.day_of_week)
            elif datatype == "WI":
                output = self.getImageSrcForCondition(set.condition_url, set.condition_text)
            elif datatype == "LT":
                if self.isNumeric(set.low) == True:
                    if imperial == True:
                        string = self.convertCelsiusToFahrenheit(set.low)
                    else:
                        string = set.low
                    string = string + tempunit
                else:
                    string = _(set.low)
                output = string
            elif datatype == "HT":
                if self.isNumeric(set.high) == True:
                    if imperial == True:
                        string = self.convertCelsiusToFahrenheit(set.high)
                    else:
                        string = set.high
                    string = string + tempunit
                else:
                    string = _(set.high)
                output = string                      
            elif datatype == "CT":
                output = _(set.condition_text)
            elif datatype == "PC":
                if self.isNumeric(set.precip) == True:
                    string = set.precip + u"%"
                else:
                    string = _(set.precip)
                output = string
            elif datatype == "HM":
                if self.isNumeric(set.humidity) == True:
                    string = set.humidity + u"%"
                else:
                    string = _(set.humidity)
                output = string
            elif datatype == "WD":
                output = _(set.wind_dir)
            elif datatype == "BF":
                if set.wind_speed.lower() == "calm":
                    output = chr(0x25)
                else:
                    if (set.wind_dir == "VAR"):
                        output = chr(0x22) # 2nd level var arrow
                    else:
                        try:
                            # for the old datatype, add 0x10, that makes the output in the A-P range,
                            # which is the 2nd level arrow
                            output = chr(ForecastText.bearing_arrow_font[set.wind_dir] + 0x10)
                        except KeyError:
                            # if the value wasn't found in ForecastText.bearing_arrow_font, use space
                            output = "-"
            elif datatype == "BS":
                if set.wind_speed.lower() == "calm":
                    output = chr(0x25)
                elif self.isNumeric(set.wind_speed) == True:
                    if (set.wind_dir == "VAR"):
                        output = chr(0x21 + self.getWindLevel(set.wind_speed))
                    else:
                        try:
                            output = chr(ForecastText.bearing_arrow_font[set.wind_dir] + self.getWindLevel(set.wind_speed) * 0x10)
                        except KeyError:
                            # if the value wasn't found in ForecastText.bearing_arrow_font, use N/A
                            output = "-"
                else:
                    try:
                        # if the speed is not "calm" but also not a number, add 0x10
                        # that makes the output in the A-P range, the 2nd level arrow
                        output = chr(ForecastText.bearing_arrow_font[set.wind_dir] + 0x10)
                    except KeyError:
                        # if the value wasn't found in ForecastText.bearing_arrow_font, use N/A
                        output = "-"
            elif datatype == "BI":
                if set.wind_speed.lower() == "calm":
                    output = self.getImagePathForBearing(ForecastText.bearing_icon["calm"])
                elif self.isNumeric(set.wind_speed) == True:
                    if (set.wind_dir == "VAR"):
                        output = self.getImagePathForBearing(int(ForecastText.bearing_icon[set.wind_dir]) + self.getWindLevel(set.wind_speed))
                    else:
                        try:
                            output = self.getImagePathForBearing(int(ForecastText.bearing_icon[set.wind_dir]) + self.getWindLevel(set.wind_speed)*16)
                        except KeyError:
                            # if the value wasn't found in ForecastText.bearing_icon, use calm code
                            output = self.getImagePathForBearing(ForecastText.bearing_icon["calm"])
                                        
            elif datatype == "WA":
                output = _(set.wind_dir_numeric)
            elif datatype == "WS":
                if self.isNumeric(set.wind_speed) == True:
                    if beaufort == True:
                        string = self.convertMPHtoBeaufort(set.wind_speed)
                    elif metrespersecond == True:
                        string = self.convertMPHtoMS(set.wind_speed)
                    elif imperial == True:
                        string = set.wind_speed
                    else:
                        string = self.convertMilesToKilometres(set.wind_speed)
                        
                    string = string + speedunit
                else:
                    string = _(set.wind_speed.lower())
                output = string
            elif datatype == "WG":
                if self.isNumeric(set.wind_gusts) == True:
                    if beaufort == True:
                        string = self.convertMPHtoBeaufort(set.wind_gusts)
                    elif metrespersecond == True:
                        string = self.convertMPHtoMS(set.wind_gusts)
                    elif imperial == True:
                        string = set.wind_gusts
                    else:
                        string = self.convertMilesToKilometres(set.wind_gusts)

                    string = string + speedunit
                else:
                    string = _(set.wind_gusts) # need to define translations
                output = string              
            elif datatype == "BR":
                if self.isNumeric(set.bar_read) == True:
                    if imperial == True:
                        string = self.convertMillibarsToInches(set.bar_read,2)
                    else:
                        string = set.bar_read
                    string = string + pressureunit
                else:
                    string = _(set.bar_read)
                output = string
            elif datatype == "BD":
                output = _(set.bar_desc) # need to define translations
            elif datatype == "UI":
                output = _(set.uv_index)
            elif datatype == "UT":
                output = _(set.uv_text)
            elif datatype == "DP":
                if self.isNumeric(set.dew_point) == True:
                    if imperial == True:
                        string = self.convertCelsiusToFahrenheit(set.dew_point)
                    else:
                        string = set.dew_point
                    string = string + tempunit
                else:
                    string = _(set.dew_point)
                output = string
            elif datatype == "OB":
                output = set.observatory
            elif datatype == "VI":
                if self.isNumeric(set.visibility) == True:
                    if imperial == True:
                        string = self.convertKilometresToMiles(set.visibility,1)
                    else:
                        string = set.visibility
                    string = string + distanceunit
                else:
                    string = _(set.visibility)
                output = string            
            elif datatype == "CN":
                output = set.city
            elif datatype == "CO":
                output = set.country
            else:
                self.logError("Unknown datatype requested: " + datatype)

        except KeyError, e:
            self.logError("Unknown value %s encountered for datatype '%s'! Please report this!" % (e.__str__(), datatype))
        
        # set the width if it is set, either left trimming or centering the text in spaces as requested
        if centeredwidth != None and self.isNumeric(centeredwidth) == True:
            if centeredwidth < len(output):
                output = output[:centeredwidth]
            else:
                output = output.center(int(centeredwidth))    
                            
        return output


    def getDatasetOutput(self, location, datatype, startday, endday, night, shortweekday, imperial, beaufort, metrespersecond, hideunits, hidedegreesymbol, spaces, minuteshide, centeredwidth):

        output = u""

        # Check if the location is loaded, if not, load it. If it can't be loaded, there was an error
        if not self.checkAndLoad(location):
            self.logError("Failed to load the location cache")
            return u""
        
        # define current units for output
        if hideunits == False:
            if imperial == False:
                tempunit = _(u"°C")
                speedunit = _(u"kph")
                distanceunit = _(u"km")
                pressureunit = _(u"mb")
            else:
                tempunit = _(u"°F")
                speedunit = _(u"mph")
                distanceunit = _(u"m")
                pressureunit = _(u"in")
                
            # override speed units if beaufort selected
            if beaufort == True:
                speedunit = u""
                
            if metrespersecond == True:
                speedunit = u"m/s"
        else:
            # remove degree symbol if not required
            if hidedegreesymbol == False:
                tempunit = u"°"
            else:
                tempunit = u""
                
            speedunit = u""
            distanceunit = u""
            pressureunit = u""

        if startday == None:
            output += self.getDatatypeFromSet(location, datatype, self.forecast_data[location].current, shortweekday, imperial, beaufort, metrespersecond, tempunit, speedunit, distanceunit, pressureunit, minuteshide, centeredwidth)
        else: # forecast data

            # ensure startday and enday are within the forecast limit
            
            if startday < 0:
                startday = 0
                self.logError("--startday set beyond forecast limit, reset to minimum of 0")
            elif startday > self.config.MAXIMUM_DAYS_FORECAST:
                startday = self.config.MAXIMUM_DAYS_FORECAST
                self.logError("--startday set beyond forecast limit, reset to maximum of " + str(self.config.MAXIMUM_DAYS_FORECAST))
                
            if endday == None: # if no endday was set use startday
                endday = startday
            elif endday < 0:
                endday = 0
                self.logError("--endday set beyond forecast limit, reset to minimum of 0")
            elif endday > self.config.MAXIMUM_DAYS_FORECAST:
                endday = self.config.MAXIMUM_DAYS_FORECAST
                self.logError("--endday set beyond forecast limit, reset to maximum of " + str(self.config.MAXIMUM_DAYS_FORECAST))
                
            for daynumber in range(startday, endday + 1):
                
                # if AUTO_NIGHT config is true then handle N/A output, by using the night option between 2pm and 2am, when the startday = 0. 
                if self.config.AUTO_NIGHT == True and daynumber == 0:
                    now = datetime.now()
                    hour = now.hour
                    if hour > 13 or hour < 2:
                        night = True
                
                if night == True:
                    output += self.getDatatypeFromSet(location, datatype, self.forecast_data[location].night[daynumber], shortweekday, imperial, beaufort, metrespersecond, tempunit, speedunit, distanceunit, pressureunit, minuteshide, centeredwidth)
                else:
                    output += self.getDatatypeFromSet(location, datatype, self.forecast_data[location].day[daynumber], shortweekday, imperial, beaufort, metrespersecond, tempunit, speedunit, distanceunit, pressureunit, minuteshide, centeredwidth)
                    
                if daynumber != endday:
                    output += self.getSpaces(spaces)

        return output

    def getTemplateItemOutput(self, template_text):
        
        # keys to template data
        LOCATION_KEY = "location"
        DATATYPE_KEY = "datatype"
        STARTDAY_KEY = "startday"
        ENDDAY_KEY = "endday"
        NIGHT_KEY = "night"
        SHORTWEEKDAY_KEY = "shortweekday"
        IMPERIAL_KEY = "imperial"
        BEAUFORT_KEY = "beaufort"
        METRESPERSECOND_KEY = "metrespersecond"
        HIDEUNITS_KEY = "hideunits"
        HIDEDEGREESYMBOL_KEY = "hidedegreesymbol"
        SPACES_KEY = "spaces"
        MINUTESHIDE_KEY = "minuteshide"
        CENTEREDWIDTH_KEY = "centeredwidth"
        
        location = self.options.location
        datatype = self.options.datatype
        startday = self.options.startday
        endday = self.options.endday
        night = self.options.night
        shortweekday = self.options.shortweekday
        imperial = self.options.imperial
        beaufort = self.options.beaufort
        metrespersecond = self.options.metrespersecond
        hideunits = self.options.hideunits
        hidedegreesymbol = self.options.hidedegreesymbol
        spaces = self.options.spaces
        minuteshide = self.options.minuteshide
        centeredwidth = self.options.centeredwidth
        
        for option in template_text.split('--'):
            if len(option) == 0 or option.isspace():
                continue
            
            # not using split here...it can't assign both key and value in one call, this should be faster
            x = option.find('=')
            if (x != -1):
                key = option[:x].strip()
                value = option[x + 1:].strip()
                if value == "":
                    value = None
            else:
                key = option.strip()
                value = None
            
            try:
                if key == LOCATION_KEY:
                    location = value
                elif key == DATATYPE_KEY:
                    datatype = value
                elif key == STARTDAY_KEY:
                    startday = int(value)
                elif key == ENDDAY_KEY:
                    endday = int(value)
                elif key == NIGHT_KEY:
                    night = True
                elif key == SHORTWEEKDAY_KEY:
                    shortweekday = True
                elif key == IMPERIAL_KEY:
                    imperial = True
                elif key == BEAUFORT_KEY:
                    beaufort = True
                elif key == METRESPERSECOND_KEY:
                    metrespersecond = True
                elif key == HIDEUNITS_KEY:
                    hideunits = True
                elif key == HIDEDEGREESYMBOL_KEY:
                    hidedegreesymbol = True
                elif key == SPACES_KEY:
                    spaces = int(value)
                elif key == MINUTESHIDE_KEY:
                    if value != None:
                        minuteshide = int(value)
                    else:
                        minuteshide = -1
                elif key == CENTEREDWIDTH_KEY:
                    centeredwidth = value
                else:
                    self.logError("Unknown template option: " + option)

            except (TypeError, ValueError):
                self.logError("Cannot convert option argument to number: " + option)
                return u""

        #REMOVED
        # Check if the location is loaded, if not, load it. If it can't be loaded, there was an error
        #if not self.checkAndLoad(location):
        #    self.logError("Failed to load the location cache")
        #    return u""
        
        if datatype != None:
            return self.getDatasetOutput(location, datatype, startday, endday, night, shortweekday, imperial, beaufort, metrespersecond, hideunits, hidedegreesymbol, spaces, minuteshide, centeredwidth)
        else:
            self.logError("Template item does not have datatype defined")
            return u""

    def getOutputFromTemplate(self, template):
        output = u""
        end = False
        a = 0
        
        # a and b are indexes in the template string
        # moving from left to right the string is processed
        # b is index of the opening bracket and a of the closing bracket
        # everything between b and a is a template that needs to be parsed
        while not end:
            b = template.find('[', a)
            
            if b == -1:
                b = len(template)
                end = True
            
            # if there is something between a and b, append it straight to output
            if b > a:
                output += template[a : b]
                # check for the escape char (if we are not at the end)
                if template[b - 1] == '\\' and not end:
                    # if its there, replace it by the bracket
                    output = output[:-1] + '['
                    # skip the bracket in the input string and continue from the beginning
                    a = b + 1
                    continue
                    
            if end:
                break
            
            a = template.find(']', b)
            
            if a == -1:
                self.logError("Missing terminal bracket (]) for a template item")
                return u""
            
            # if there is some template text...
            if a > b + 1:
                output += self.getTemplateItemOutput(template[b + 1 : a])
            
            a = a + 1

        return output

    def writeOutput(self):
                
        if self.options.template != None:
            #load the file
            try:
                fileinput = codecs.open(os.path.expanduser(self.options.template), encoding='utf-8')
                template = fileinput.read()
                fileinput.close()
            except Exception, e:
                self.logError("Error loading template file: " + e.__str__())
            else:
                output = self.getOutputFromTemplate(template)
        else:         
            
            output = self.getDatasetOutput(self.options.location, self.options.datatype, self.options.startday, self.options.endday, self.options.night, self.options.shortweekday, self.options.imperial, self.options.beaufort, self.options.metrespersecond, self.options.hideunits, self.options.hidedegreesymbol, self.options.spaces, self.options.minuteshide, self.options.centeredwidth)
            
        print output.encode("utf-8")

    def logInfo(self, text):
        if self.options.verbose == True:
            print >> sys.stdout, "INFO: " + text

        if self.options.infologfile != None:
            datetimestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") 
            fileoutput = open(self.options.infologfile, "ab")
            fileoutput.write(datetimestamp+" INFO: "+text+"\n")
            fileoutput.close()
            
    def logError(self, text):
        print >> sys.stderr, "ERROR: " + text
        
        if self.options.errorlogfile != None:
            datetimestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") 
            fileoutput = open(self.options.errorlogfile, "ab")
            fileoutput.write(datetimestamp+" ERROR: "+text+"\n")
            fileoutput.close()

    def getText(self, parentNode, name):
        try:
            node = parentNode.getElementsByTagName(name)[0]
        except IndexError:
            raise Exception, "Data element <%s> not present under <%s>" % (name, parentNode.tagName)

        rc = ""
        for child in node.childNodes:
            if child.nodeType == child.TEXT_NODE:
                rc = rc + child.data
        return rc
    
    def getChild(self, parentNode, name, index = 0):
        try:
            return parentNode.getElementsByTagName(name)[index]
        except IndexError:
            raise Exception, "Data element <%s> is not present under <%s> (index %i)" % (name, parentNode.tagName, index)

    def getSpaces(self, spaces=1):
        string = u""
        for dummy in range(0, spaces):
            string = string + u" "
        return string

    def isNumeric(self, string):
        try:
            dummy = float(string)
            return True
        except:
            return False
        
    def parseBoolString(self, string):
        #return string[0].upper()=="T"
        
        if string is True or string is False:
            return string
        string = str(string).strip().lower()
        return not string in ['false','f','n','0','']

    def convertCelsiusToFahrenheit(self, temp, dp=0):
        value = ((float(temp) * 9.0) / 5.0) + 32
        if dp == 0:
            return str(int(round(value,dp))) # lose the dp
        else:
            return str(round(value,dp))

    def convertKilometresToMiles(self, dist, dp=0):
        value = float(dist) * 0.621371192
        if dp == 0:
            return str(int(round(value,dp))) # lose the dp
        else:
            return str(round(value,dp))

    def convertMilesToKilometres(self, dist, dp=0):
        value = float(dist) * 1.609344001
        if dp == 0:
            return str(int(round(value,dp))) # lose the dp
        else:
            return str(round(value,dp))
        
    def convertKPHtoBeaufort(self, kph, dp=0):
        value = pow(float(kph) * 0.332270069, 2.0 / 3.0)
        if dp == 0:
            return str(int(round(value,dp))) # lose the dp
        else:
            return str(round(value,dp))
    
    def convertMPHtoBeaufort(self, mph, dp=0):
        value = pow(float(self.convertMilesToKilometres(mph)) * 0.332270069, 2.0 / 3.0)
        if dp == 0:
            return str(int(round(value,dp))) # lose the dp
        else:
            return str(round(value,dp))
            
    def convertKPHtoMS(self, kph, dp=0):
        value = float(kph) * 0.27777778
        if dp == 0:
            return str(int(round(value,dp))) # lose the dp
        else:
            return str(round(value,dp))

    def convertMPHtoMS(self, mph, dp=0):
        value = float(self.convertMilesToKilometres(mph)) * 0.27777778
        if dp == 0:
            return str(int(round(value,dp))) # lose the dp
        else:
            return str(round(value,dp))
                
    def convertMillibarsToInches(self,mb,dp=0):
        value = float(mb)/33.8582
        if dp == 0:
            return str(int(round(value,dp))) # lose the dp
        else:
            return str(round(value,dp))
    
    def getWindLevel(self, speed):
        beaufort = int(self.convertMPHtoBeaufort(speed))
        if beaufort < 4:
            return 0
        elif beaufort < 7:
            return 1
        elif beaufort < 10:
            return 2
        else:
            return 3

    def getFormattedTimeFromSeconds(self,seconds,showseconds=False):
        time = int(seconds)
        hours, time = divmod(time, 60*60)
        minutes, seconds = divmod(time, 60)
        
        if showseconds == True:
            output = "%02d:%02d:%02d"%(hours, minutes, seconds)
        else:
            output = "%02d:%02d"%(hours, minutes)
            
        return output
        
    def getImageSrcForCondition(self, url, condition):
        imagesrc = ""
        imgfilepath = os.path.join(self.config.CACHE_FOLDERPATH, self.CONDITION_IMAGE_FILENAME.replace("<CONDITION>",condition.replace(" ","-")))       

        if os.path.exists(imgfilepath) == False:

            try:
                self.logInfo("Fetching image from " + imagesrc)
    
                usock = urllib2.urlopen(url)
                img = usock.read()
            except Exception, e:
                self.logError("Error downloading the image file: " + e.__str__()+"\n"+traceback.format_exc())
            else:
                # save the image and contruct an image tag
                
                imgfile = open(imgfilepath,'wb')
                imgfile.write(img)
                self.logInfo("Saved image to " + imgfilepath)
     
            finally:
                usock.close()
                imgfile.close()

        return imgfilepath
    
    def getImagePathForBearing(self, bearingcode):
        #TODO: Once gif supported properly in conky re-enable gif output
        #if int(bearingcode) > 0 and int(bearingcode) <= 4:
        #    fileext = "gif" # use animated gif for VAR output
        #else:
        #    fileext = "png"
            
        fileext = "png" #force to always be png until animated gifs are supported
        imagesrc = "%s/images/bearingicons/%s.%s"%(app_path, str(bearingcode).rjust(2,"0"),fileext)
        return imagesrc
    
def main():

    parser = CommandLineParser()
    (options, args) = parser.parse_args()

    if options.version == True:
        
        print >> sys.stdout,"conkyForecast v.2.21"
        
    else:
        
        if options.verbose == True:
            print >> sys.stdout, "*** INITIAL OPTIONS:"
            print >> sys.stdout, "    config:", options.config
            print >> sys.stdout, "    location:", options.location
            print >> sys.stdout, "    datatype:", options.datatype
            print >> sys.stdout, "    start day:", options.startday
            print >> sys.stdout, "    end day:", options.endday
            print >> sys.stdout, "    spaces:", options.spaces
            print >> sys.stdout, "    template:", options.template
            print >> sys.stdout, "    locale:", options.locale
            print >> sys.stdout, "    imperial:", options.imperial
            print >> sys.stdout, "    beaufort:", options.beaufort
            print >> sys.stdout, "    metrespersecond:", options.metrespersecond
            print >> sys.stdout, "    night:", options.night
            print >> sys.stdout, "    shortweekday:", options.shortweekday
            print >> sys.stdout, "    hideunits:", options.hideunits
            print >> sys.stdout, "    hidedegreesymbol:", options.hidedegreesymbol
            print >> sys.stdout, "    minuteshide:", options.minuteshide
            print >> sys.stdout, "    centeredwidth:", options.centeredwidth
            print >> sys.stdout, "    refetch:", options.refetch
            print >> sys.stdout, "    verbose:", options.verbose
            print >> sys.stdout, "    errorlogfile:",options.errorlogfile
            print >> sys.stdout, "    infologfile:",options.infologfile        
    
        forecastinfo = ForecastInfo(options)
        forecastinfo.writeOutput()

if __name__ == '__main__':
    main()
    sys.exit()