"""Return a lie from Dave's Web Of Lies.

Usage: 
* Call tellalie.py from the command line with no arguments to retrieve a random lie from DWOL.
* Call with the -d option to retrieve the Lie of the Day.

All lies are sourced from http://www.davesweboflies.com and copyright remains as stated on that website. """

import urllib.request, re, sys

if len(sys.argv)==1 or sys.argv[1]=="-r" : 
    url = "http://www.davesweboflies.com/random.cgi"
    lieLine = 21 
    junk = re.compile(r">([^<>]+?)<")
    # matches everything between end of one tag and start of next, returning just the bit between
    morejunk = re.compile(r"(.*\.)(?=Source)")
    # matches everything up until the Source statement (which comes just after the lie itself)
elif sys.argv[1]=="-d" :
    url = "http://www.davesweboflies.com/index.cgi"
    lieLine = 22
    junk = re.compile(r"LIE=(.*\.)\s*\-\-\>")
    # matches from "LIE=" prompt until end of comment,  returning just the lie itself (in parentheses)
    morejunk = re.compile(r".*")
    # this is here to cope with the necessity of a second regex in the random settings
else :
    print(__doc__)
    raise SystemExit

try : 
    page = urllib.request.urlopen(url)
    pageLines = page.readlines()
    page.close()
except urllib.error.URLError :
    print("""Tellalie cannot access the internet to retrieve a lie.\nPlease check your network connection.""")
    raise SystemExit

htmlLie = repr(pageLines[lieLine])
cleanerLie = junk.findall(htmlLie)
cleanLie = morejunk.findall("".join(cleanerLie))
print(re.sub(r"\\","","".join(cleanLie)))