summaryrefslogtreecommitdiff
path: root/perc
blob: 9ec1c7fe579d7f1dc8bf5cbea67d044cec9a9b92 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
#! /usr/bin/env python

# McAuthor: CarpNet (thanks to a paradigm shifting idea by Bikeman) (some changes by wjoe)

# TODO 1: some crazy AI heuristics stuff, see The Terminator and Skynet for ideas.

# TODO 2: Add time travel capability (note: mind the butterfly effect and for god's sake don't 
# sleep with your relatives in the past we don't want anyone ending up as their own Grandad or 
# Grandma. Just because your Gran looked fetching in that photo of her on the beach in the 1950's 
# doesn't mean you should hit on her and end up creating a paradox that could potentially end the 
# universe, fucking hell guys this is just for telling percentages of time!)

# TODO 5: Extend chart to be different types (bar, pie, raised-arm-man etc.)
# Raised arm man chart: \o/ = 1 hour, \ = 20 minutes, \o = 40 minutes etc.
# TODO 6: Web trawling important date finder
# TODO 8: Birthdays
# TODO 9: Recurring events

# CHANGE LOG:
# 3.21: - Bug fix for option --NICK. Changed option back to --nick
#		- Change log added
# 3.22: - Fix bug fix to fix the fix that was fixed in the last bug fix
# 3.23: - Assumes end time if given one argument, start and end if given two.
#       - Restructuring of code in parseArgs function
#		- Added "halloween" as an IMPORTANT TEMPORAL EVENT
# 3.3:
#		- Added 'mode' as second argument, choices are 'user' and 'admin':
#			- Users are allowed to check times and dates
#			- Admins can create and remove custom events	
#		- Allows creation and removal of custom temporal events (stored in perc.cfg)
#		- Maintains a list of admins allowed to perform admin actions
# 3.4:
#		- Ability to add new users added
# 3.4.1:
#		- Can now clone (-c/--clone) existing users to create new users (also allows other options in addition such as -s -f to further customise a new user)
# 3.5:
#		- Created Config class to more cleanly get/set config options
#		- Split config files into perc.cfg and custom_perc.cfg for options that can change on commit and custom user specified options that are persistent
# 3.6:
#       - Added a 'count' output option to display a countdown of days until the finish
#       - wjoe ruined everything
# 3.61:
#		- Fixed count output, was failing to count days before
#
# 3.62:
#		- Removed the weekend check for now, so it works at weekends
#	
# 3.63:
#       - Changed the count output to say the name of the event
#
# 3.4:
#       - Added -i --info option to display start/end dates

import copy
import decimal
import json
import optparse
import random
import re
import string
import sys
import math

from datetime import datetime, date, timedelta, time

PROG = "perc"
VERSION = "3.63"

CONFIG_FILE = "perc.cfg"
CUSTOM_CONFIG_FILE = "custom_perc.cfg"

NOW = datetime.now()

ONE_MINUTE = timedelta(minutes=1)
ONE_DAY = timedelta(days=1)

MODES = ["user", "admin"]

USER = None
DEFAULT_USER = None
CONFIG = None
CUSTOM_CONFIG = None

EVENT_DATETIME_FORMAT = "%d-%m-%Y %H:%M"
INFO_DATETIME_FORMAT = "%a %d %b %Y %H:%M"
MONDAY = 0
TUESDAY = 1
WEDNESDAY = 2
THURSDAY = 3
FRIDAY = 4
SATURDAY = 5
SUNDAY = 6

WEEK_DAY_NAMES = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

WEEK_LENGTH = 7
WEEKEND = [ SATURDAY, SUNDAY ]
WORK_WEEK = [ MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY ]

IMPORTANT_TEMPORAL_EVENTS = ["LATER", "tomorrow", "friday", "new year", "newyear", "christmas", "xmas", "weekend", "midday", "noon", "lunch", "easter", "halloween"]
RECURRANCE_PERIODS = ["hourly", "daily", "weekly", "fortnightly", "monthly", "yearly"]

OUTPUT_TYPES = ["perc", "bar", "ram", "pint", "count"]

VERB_FORMS = ["is", "is not", "should be", "could be", "would be", "ought to be", "might be", "may become"]

def clamp(value, min_value, max_value):
	if value < min_value:
		return min_value
	elif value > max_value:
		return max_value
	
	return value

def float_to_decimal(f):
    # http://docs.python.org/library/decimal.html#decimal-faq
    "Convert a floating point number to a Decimal with no loss of information"
    
    n, d = f.as_integer_ratio()
    numerator, denominator = decimal.Decimal(n), decimal.Decimal(d)
    ctx = decimal.Context(prec=60)
    result = ctx.divide(numerator, denominator)
    
    while ctx.flags[decimal.Inexact]:
        ctx.flags[decimal.Inexact] = False
        ctx.prec *= 2
        result = ctx.divide(numerator, denominator)
        
    return result

def delta_in_seconds(delta):
	return (delta.microseconds + (delta.seconds + delta.days * 24 * 3600) * 10**6) / 10**6

def calculate_count(start, finish):
	delta = (finish - NOW)
	return delta

def calculate_ratio(start, finish):
	total = float(delta_in_seconds(finish - start))
	done = float(delta_in_seconds(NOW - start))
	
	ratio = 0.0
	if total != 0.0:
		ratio = done / total
	
	return ratio

def round_to_sigfig(number, sigfig):
    # http://stackoverflow.com/questions/2663612/nicely-representing-a-floating-point-number-in-python/2663623#2663623
    
    assert(sigfig > 0)
    
    try:
        d = decimal.Decimal(number)
    except TypeError:
        d = float_to_decimal(float(number))
        
    sign, digits, exponent = d.as_tuple()
    
    if len(digits) < sigfig:
        digits = list(digits)
        digits.extend([0] * (sigfig - len(digits)))  
          
    shift = d.adjusted()
    result = int(''.join(map(str, digits[:sigfig])))
    
    # Round the result
    if len(digits) > sigfig and digits[sigfig] >= 5: result += 1
    result = list(str(result))
    
    # Rounding can change the length of result
    # If so, adjust shift
    shift += len(result) - sigfig
    
    # reset len of result to sigfig
    result = result[:sigfig]
    if shift >= sigfig-1:
        # Tack more zeros on the end
        result += ['0'] * (shift - sigfig + 1)
    elif 0 <= shift:
        # Place the decimal point in between digits
        result.insert(shift + 1, '.')
    else:
        # Tack zeros on the front
        assert(shift < 0)
        result = ['0.'] + ['0'] * (-shift - 1) + result
        
    if sign:
        result.insert(0, '-')
        
    return ''.join(result)

def parseTime(timestr):
	for key, value in CONFIG["FORMAT"]["time"].items():
		try:
			t = datetime.strptime(timestr, value)
			return (datetime.combine(NOW.date(), t.time()), value)
		except ValueError:
			pass
	
	print "Not a correctly formatted time: '%s'" % timestr
	sys.exit(1)

def isImportantTemporalEvent(event):
	events = IMPORTANT_TEMPORAL_EVENTS + CUSTOM_CONFIG.get("EVENTS", {}).keys()
		
	return event in events

def getDayOfWeek(day):
	return (NOW - day_of_week() * ONE_DAY).replace(hour=0, minute=0, second=0, microsecond=0) + day * ONE_DAY

def parseTemporalEvent(event, user):
	start, finish = None, None
	
	if event in CUSTOM_CONFIG["EVENTS"]:
		start = datetime.strptime(CUSTOM_CONFIG["EVENTS"][event]["start"], EVENT_DATETIME_FORMAT)
		finish = datetime.strptime(CUSTOM_CONFIG["EVENTS"][event]["finish"], EVENT_DATETIME_FORMAT)
		format = CUSTOM_CONFIG["EVENTS"][event]["format"]
		
		start_formatted = start.strftime(format).format(name=event)
		finish_formatted = finish.strftime(format).format(name=event)
	elif event == "LATER":
		start = NOW - ONE_MINUTE * random.randint(1, 400)
		finish = NOW + ONE_MINUTE * random.randint(1, 400)
		
		start_formatted = start.strftime("%H:%M")
		finish_formatted = finish.strftime("%H:%M")
	elif event == "tomorrow":
		start = datetime.combine(NOW.date(), time())
		finish = datetime.combine(NOW.date(), time()) + ONE_DAY
		
		start_formatted = WEEK_DAY_NAMES[day_of_week()]
		finish_formatted = WEEK_DAY_NAMES[day_of_week(date.today() + ONE_DAY)]
	elif event in ["christmas", "xmas"]:
		xmas = date(year=1900, month=12, day=25)
		start = datetime.combine(xmas.replace(NOW.year - 1), time())
		finish = datetime.combine(xmas.replace(NOW.year), time())
		
		start_formatted = "%s %d" % (string.capwords(event), start.year)
		finish_formatted = "%s %d" % (string.capwords(event), finish.year)
	elif event in ["new year", "newyear"]:
		newyear = date(year=1900, month=1, day=1)
		start = datetime.combine(newyear.replace(year=NOW.year), time())
		finish = datetime.combine(newyear.replace(year=NOW.year + 1), time())
		
		start_formatted = str(start.year)
		finish_formatted = str(finish.year)
	elif event == "weekend":
		start = getDayOfWeek(MONDAY)
		finish = getDayOfWeek(FRIDAY)
		
		start = datetime.combine(start.date(), user.start.time())
		finish = datetime.combine(finish.date(), user.finish.time())
		
		start_formatted = "Monday"
		finish_formatted = "Weekend"
	elif event == "friday":
		start = getDayOfWeek(MONDAY)
		finish = getDayOfWeek(FRIDAY)
		
		start = datetime.combine(start.date(), user.start.time())
		
		start_formatted = "Monday"
		finish_formatted = "Friday"
	elif event in ["midday", "noon"]:
		start = datetime.combine(NOW.date(), time())
		finish = datetime.combine(NOW.date(), time(hour=12))
		
		start_formatted = "Midnight"
		finish_formatted = string.capwords(event)
	elif event == "halloween":
		halloween = date(year=1900, month=10, day=31)
		start = datetime.combine(halloween.replace(NOW.year - 1), time())
		finish = datetime.combine(halloween.replace(NOW.year), time())
		
		start_formatted = "Halloween %d" % start.year
		finish_formatted = "Halloween %d" % finish.year
	elif event == "lunch":
		if NOW < user.lunch.start:
			start = user.start
			finish = user.lunch.start
		
			finish_formatted = "Lunch (%s)" % finish.strftime(user.format)
		else:
			start = user.lunch.start
			finish = user.lunch.finish
			
			finish_formatted = finish.strftime(user.format)
		
		start_formatted = start.strftime(user.format)
	
	return start, finish, start_formatted, finish_formatted

def day_of_week(day=date.today()):
	return date.weekday(day)

def isWeekend():
	return day_of_week() in WEEKEND

def combination_pairs(first, second):
	combined = []
	
	for x in first:
		for y in second:
			combined.append("%s %s" % (x, y))
			combined.append("%s %s" % (y, x))
	
	return combined

def parseDatetime(datetimestring, today_relative=False):
	date_formats = CONFIG["FORMAT"]["date"].values()
	time_formats = CONFIG["FORMAT"]["time"].values()
	combined_formats = combination_pairs(date_formats, time_formats)
	
	for format in date_formats:
		try:
			t = datetime.strptime(datetimestring, format)
			return t, format
		except ValueError:
			pass
	
	for format in time_formats:
		try:
			t = datetime.strptime(datetimestring, format)
			return datetime.combine(NOW.date(), t.time()), format
		except ValueError:
			pass
	
	for format in combined_formats:
		try:
			t = datetime.strptime(datetimestring, format)
			if today_relative:
				t = datetime.combine(NOW.date(), t.time())
			
			return t, format
		except ValueError:
			pass
	
	print "Not a recognised date/time '%s'" % datetimestring
	sys.exit(1)

def addEvent(name, start, finish, format="{name} %Y"):
	if start > finish:
		print "Event cannot have a start time later than the finish"
		sys.exit(1)
	
	event = {
		"start": start.strftime(EVENT_DATETIME_FORMAT),
		"finish": finish.strftime(EVENT_DATETIME_FORMAT),
		"format": format
	}
	
	if "EVENTS" not in CUSTOM_CONFIG:
		CUSTOM_CONFIG["EVENTS"] = {}
		
	CUSTOM_CONFIG["EVENTS"][name] = event

def removeEvent(name):
	if "EVENTS" in CUSTOM_CONFIG and name in CUSTOM_CONFIG["EVENTS"]:
		del CUSTOM_CONFIG["EVENTS"][name]

def info(name):
    if "EVENTS" in CUSTOM_CONFIG and name in CUSTOM_CONFIG["EVENTS"]:
        start = CUSTOM_CONFIG["EVENTS"][name]["start"]
        stime = datetime.strptime(start, EVENT_DATETIME_FORMAT)
        finish = CUSTOM_CONFIG["EVENTS"][name]["finish"]
        ftime = datetime.strptime(finish, EVENT_DATETIME_FORMAT)
        print name+" info - Start: "+stime.strftime(INFO_DATETIME_FORMAT)+", Finish: "+ftime.strftime(INFO_DATETIME_FORMAT)

def parseUserArgs(args, user):
	start, finish, start_formatted, finish_formatted = user.start, user.finish, user.start.strftime(user.format), user.finish.strftime(user.format)
	
	if args and isImportantTemporalEvent(args[0]):
		start, finish, start_formatted, finish_formatted = parseTemporalEvent(args[0], user)
	else:
		format = None
		times = args[0:2]
		
		if len(times) == 1:
			finish, format = parseDatetime(times[0], True)
		elif len(times) >= 2:
			start, format = parseDatetime(times[0], True)
			finish, format = parseDatetime(times[1], True)
		
		if options.start:
			start, format = parseDatetime(options.start, True)
		if options.finish:
			finish, format = parseDatetime(options.finish, True)
			
		if format:
			start_formatted = start.strftime(format)
			finish_formatted = finish.strftime(format)
	
	output_type = options.output if options.output else user.output
	
	ratio = clamp(calculate_ratio(start, finish), 0.0, 1.0)
	delta = calculate_count(start, finish)

	return start_formatted, finish_formatted, ratio, output_type, delta

class Output(object):
	
	def perc(self, ratio, start, finish, delta):
		print CONFIG["OUTPUT"]["PERCENTAGE"].format(ratio=ratio, start=start, finish=finish)

	def bar(self, ratio, start, finish, delta):
		length = CONFIG["OUTPUT"]["BAR"]["length"] if not options.mobile else CONFIG["OUTPUT"]["BAR"]["length_mobile"]
		char = CONFIG["OUTPUT"]["BAR"]["character"]
	
		current = clamp(int(ratio * length), 0, length)
	
		space = " " * (length - current)
		if space: space = ">" + space[1:]
	
		ratiostr = "{0}%".format(round_to_sigfig(ratio * 100, CONFIG["RATIO_SIGFIGS"])) if current >= 7 else ""
	
		print "{start} [{ratio:{char}^{current}}{space}] {finish}".format(ratio=ratiostr, char=char, current=current, space=space, start=start, finish=finish)

	def ram(self, ratio, start, finish, delta):
		# 10 raised arm men indicates a complete day
	
		# Raised arm men parts (3 parts per raised arm man and 10 of them)
		ram_parts = 1.0 / (3.0 * 10.0)
		
		print "Not implemented"

	def pint(self, ratio, start, finish, delta):
		print "Not implemented"

	def count(self, ratio, start, finish, delta):
		seconds = delta.seconds
		days = delta.days
		hours = int(math.floor(seconds/60/60))
		seconds = seconds - (hours*60*60)
		minutes = int(math.floor(seconds/60))
		seconds = int(seconds - (minutes*60))
		print finish + ' in ' + str(days) + ' day(s), ' + str(hours) + ' hour(s), ' + str(minutes) + ' minute(s), ' + str(seconds) + ' second(s).'

	def output(self, type, ratio, start, finish, count):
		func = getattr(self, type, self.perc)
		
		func(ratio, start, finish, count)

class TimeRange(object):
	
	def __init__(self, start, finish, user):
		self._start = start
		self._finish = finish
		self.user = user
	
	def __datetimeGetter(self, name):
		return datetime.combine(NOW.date(), datetime.strptime(getattr(self, name), "%H:%M").time())
	
	def __datetimeSetter(self, name, value):
		self._data[name] = value
	
	@property
	def start(self):
		return self.__datetimeGetter("_start")
	
	@start.setter
	def start(self, value):
		self.__datetimeSetter("_start", value)
	
	@property
	def finish(self):
		return self.__datetimeGetter("_finish")
	
	@finish.setter
	def finish(self, value):
		self.__datetimeSetter("_finish", value)
	
	@property
	def format(self):
		return self.user.format
	
	def toDict(self):
		return { "start": self._start, "finish": self._finish }
	
	def __copy__(self):
		return TimeRange(self._start, self._finish, self.user)
	
	def __deepcopy__(self, memo):
		return TimeRange(self._start, self._finish, self.user)

class User(object):
	
	PROPERTIES = ["start", "finish", "format", "output", "lunch"]

	Name = property(fget=lambda self: self._name, fset=lambda self, value: setattr(self, "_name", value))
	
	def __init__(self, name, data=None):
		self._name = name.lower()
		
		if data:
			self.data = data
		else:
			try:
				self.data = self.__parseData(CONFIG["USERS"][name])
			except KeyError:
				self.data = {}
	
	def __parseData(self, data):
		data = copy.deepcopy(data)
		
		for key, value in data.items():
			if isinstance(value, dict) and set(["start", "finish"]).issubset(set(value.keys())):
				data[key] = TimeRange(value["start"], value["finish"], self)
		
		return data
	
	def __convertToDict(self):
		data = copy.deepcopy(self.data)
		
		for key, value in data.items():
			if isinstance(value, TimeRange):
				data[key] = value.toDict()
			
		return data
	
	def commit(self):
		if self.Name in CONFIG["USERS"] and USER.Name != self.Name:
			print "Cannot edit someone else's perc settings!"
			sys.exit(1)
		
		if self.Name == "default":
			print "Cannot edit default user"
			sys.exit(1)
			
		CONFIG["USERS"][self.Name] = self.__convertToDict()
	
	def __datetimeGetter(self, name):
		try:
			return datetime.combine(NOW.date(), datetime.strptime(self.data[name], "%H:%M").time())
		except KeyError:
			return getattr(DEFAULT_USER, name)
	
	def __defaultSetter(self, name, value):
		self.data[name] = value
	
	def __defaultDeleter(self, name):
		try:
			del self.data[name]
		except KeyError:
			pass
	
	def __defaultGetter(self, name):
		try:
			return self.data[name]
		except KeyError:
			return getattr(DEFAULT_USER, name)
	
	def __getattr__(self, name):
		if name in User.PROPERTIES:
			if name in ["start", "finish"]:
				return self.__datetimeGetter(name)
			else:
				return self.__defaultGetter(name)
		else:
			return self.__getattribute__(name)
	
	def __setattr__(self, name, value):
		if name in User.PROPERTIES:
			self.__defaultSetter(name, value)
		else:
			super(User, self).__setattr__(name, value)
	
	def __delattr__(self, name):
		if name in User.PROPERTIES:
			self.__defaultDeleter(name)
		else:
			super(User, self).__delattr__(name)
	
	def __copy__(self):
		return User(copy.copy(self.data))
	
	def __deepcopy__(self, memo):
		return User(self.Name, copy.deepcopy(self.data))

class Config(dict):
	
	def __init__(self, *args, **kwargs):
		if kwargs.get("filename"):
			self._filename = kwargs["filename"]
			data = Config.__parse(self._filename)
			super(Config, self).__init__(data)
		else:
			super(Config, self).__init__(*args, **kwargs)
			Config.__convert(self)
		
		self.__isdirty = False
	
	@staticmethod
	def __convert(data):
		for key, value in data.items():
			if isinstance(value, dict):
				data[key] = Config(value)
		
		return data
	
	@staticmethod
	def __parse(filename):
		try:
			with open(filename) as f:
				return Config.__convert(json.load(f))
		except IOError:
			return {}
	
	def __setitem__(self, key, value):
		if isinstance(value, dict):
			value = Config(value)
			
		super(Config, self).__setitem__(key, value)
		self.__isdirty = True
	
	def __delitem__(self, key):
		super(Config, self).__delitem__(key)
		self.__isdirty = True
	
	def clear(self):
		super(Config, self).clear()
		self.__isdirty = True
	
	def isDirty(self):
		if self.__isdirty:
			return True
		
		for key, value in self.items():
			if hasattr(value, "isDirty"):
				if value.isDirty():
					return True
		
		return False
	
	def save(self):
		if self.isDirty():
			with open(self._filename, "w") as f:
				json.dump(self, f, indent=4)
			
			print "%s updated" % self._filename

def admin(args):
	if USER.Name not in CONFIG["ADMINS"]:
		print "You do not have admin permissions"
		sys.exit(1)
	
	global options
	
	parser = optparse.OptionParser()
	parser.add_option("-v", "--version", action="store_true", dest="version", help="Display the version of %s" % PROG)
	parser.add_option("-a", "--add-event", action="store", dest="add_event", help="Add the named event to {prog} to be used in the usual !{prog} <event_name> way".format(prog=PROG))
	parser.add_option("-u", "--user", action="store", dest="user", help="Reference the named user. Used in tandem with -l and -s and -f commands. If only used with -s and/or -f then sets start and finish times of entire day for user. If used with -l and -s and/or -f commands sets the lunch times of that user.")
	parser.add_option("-c", "--clone", action="store", dest="clone", help="")
	parser.add_option("-l", "--lunch", action="store_true", default=False, dest="lunch", help="Indicate that lunch times are to be set.")
	parser.add_option("-r", "--remove-event", action="store", dest="remove_event", help="Remove a named event from %s" % PROG)
	parser.add_option("-n", "--recurring", action="store", type="choice", choices=RECURRANCE_PERIODS, dest="recurring", help="Designates that the event to be added is recurring and requires type of recurrance. Choices are: %s" % ", ".join(RECURRANCE_PERIODS))
	parser.add_option("-s", "--start", action="store", dest="start", help="Used in conjunction with -a/--add-event option. The start date/time of the event.")
	parser.add_option("-f", "--finish", action="store", dest="finish", help="Used in conjunction with -a/--add-event option. The finish date/time of the event.")
	parser.add_option("-p", "--format", action="store", default="", dest="format", help="Used in conjunction with -a/--add-event option. The format of the printed event date/time, uses python strftime formatting and accepts {name} keyword to display name of event.")
	parser.add_option("-o", "--output", action="store", type="choice", choices=OUTPUT_TYPES, dest="output", help="The output display type for the user. Options are %s" % ", ".join(OUTPUT_TYPES))
	(options, args) = parser.parse_args(args)
	
	if options.version:
		print "v%s" % VERSION
		sys.exit(0)
	
	if options.user:
		user = None
		
		if options.clone:
			user = copy.deepcopy(User(options.clone))
			user.Name = options.user
		else:
			user = User(options.user)
			
		if options.lunch:
			lunch_start = "13:00"
			lunch_finish = "14:00"
		
			if options.start:
				lunch_start, f = parseTime(options.start)
				lunch_start = lunch_start.strftime("%H:%M")
			if options.finish:
				lunch_finish, f = parseTime(options.finish)
				lunch_finish = lunch_finish.strftime("%H:%M")
		
			lunch = TimeRange(lunch_start, lunch_finish, user)
			user.lunch = lunch
		else:
			if options.start:
				start, f = parseTime(options.start)
				user.start = start.strftime("%H:%M")
			
			if options.finish:
				finish, f = parseTime(options.finish)
				user.finish = finish.strftime("%H:%M")
	
		if options.format:
			user.format = options.format
		if options.output:
			user.output = options.output
		
		user.commit()
	else:
		if options.add_event:
			if not options.start or not options.finish:
				print "--add-event option requires --start and --finish date/time options to be set"
				sys.exit(1)
		
			name = options.add_event
			start, f = parseDatetime(options.start)
			finish, f = parseDatetime(options.finish)
			format = options.format if options.format else "{name} %Y"
		
			addEvent(name, start, finish, format)
	
		if options.remove_event:
			removeEvent(options.remove_event)
	    
	saveConfig()
	
def user(args):
    global options
    
    parser = optparse.OptionParser("{0} <finish> [options] | {0} <start> <finish> [options]. Custom Events: {1}".format(PROG, ", ".join(CUSTOM_CONFIG["EVENTS"].keys() if "EVENTS" in CUSTOM_CONFIG else [])))
    parser.add_option("-v", "--version", action="store_true", dest="version", help="Display the version of %s" % PROG)
    parser.add_option("-s", "--start", action="store", dest="start", help="The start time of your particular day")
    parser.add_option("-f", "--finish", action="store", dest="finish", help="The finish time of your particular day")
    parser.add_option("-n", "--nick", action="store", dest="nick", help="Nickname of someone (e.g. fuckwad, l_bratch, bikeman or something)")
    parser.add_option("-o", "--output", action="store", type="choice", choices=OUTPUT_TYPES, dest="output", help="Output display type. Options are %s" % ", ".join(OUTPUT_TYPES))
    parser.add_option("-m", "--mobile", action="store_true", default=False, dest="mobile", help="Indicate this should be displayed appropriately for a mobile device (i.e. smaller character display width)")
    parser.add_option("-i", "--info", action="store", dest="info", help="Display info from %s" % PROG)
    
    (options, args) = parser.parse_args(args)
    
#	if isWeekend():
#		print "It's the freekin' Weekend!!!!"
#		sys.exit(0)
    
    if options.version:
        print "v%s" % VERSION
        sys.exit(0)
    
    if options.info:
       	info(options.info)
        sys.exit(0)
    
    # Choose which user to display percentages for
    user = USER
    if options.nick:
        nick = options.nick.lower()
        user = User(nick)

    start, finish, ratio, output_type, delta = parseUserArgs(args, user)
	
    # Finally output the percentage in the specified way
    output = Output()
    output.output(output_type, ratio, start, finish, delta)

def readConfig():
	global CONFIG, CUSTOM_CONFIG
	
	CONFIG = Config(filename=CONFIG_FILE)
	CUSTOM_CONFIG = Config(filename=CUSTOM_CONFIG_FILE)

def saveConfig():
	CONFIG.save()
	CUSTOM_CONFIG.save()

def main():
	readConfig()
	
	# Fix for bb's retardedness
	args = sys.argv[1:]
	if "perc" in args:
		args.remove("perc")
	
	global DEFAULT_USER
	DEFAULT_USER = User("default")
	
	# Set the user variable to the user who ran the script
	global USER
	USER = User("default")
	if args:
		nick = args.pop(0).lower()
		USER = User(nick)
	
	# Obtain the mode if set, otherwise default to 'user'
	mode = "user"
	if args:
		if args[0] in MODES:
			mode = args.pop(0)
		
	if mode == "user":
		user(args)
	elif mode == "admin":
		admin(args)
	else:
		print "Not a recognised mode '%s'" % mode
		sys.exit(1)

if __name__ == "__main__":
	main()