#! /usr/bin/env python

import urllib, re, sys
from time import strftime, localtime, time

# regexp for fidning the image
regexp = '="(http://www.userfriendly.org/cartoons/archives/[0-9a-zA-Z]+/[0-9a-zA-Z]+.gif)"'

def main ():
	"Main function. Does all the gory work."

	# create the final filename
	image = strftime ( 'UserFriendly-%Y.%m.%d.gif', localtime (time ()))
	url  = strftime ( 'http://ars.userfriendly.org/cartoons/?id=%Y%m%d', 
						localtime (time ()))    

	# create our main regular expression
	exp = re.compile ( regexp )

	# retrieve the main page and loop over all lines
   	for line in urllib.urlopen ( url ).readlines ():
		# perform match
		match = exp.search ( line )

		# does this line match?
		if match != None:
			# we have it here, so create the full image url
			urllib.urlretrieve ( match.group(1), image ) 
		
			# done
			sys.exit ( 0 )

	# we got this far, not good
	sys.exit ( 1 )


if __name__ == '__main__':
	# run main function
	main ()

