#!/usr/bin/env python
#
#
# INFO:
# - This module gets a weather radar map image from weather.com and puts it in
#   a temporary file in the /tmp directory.
# - calling the get_map() function requires a postal code to be passed to it.
# - the get_map() function returns the location of the image ie.) img_file
#
#

import re
import urllib
import os, sys

def get_map(ZIP):
        try:
		usock = urllib.urlopen('http://www.weather.com/outlook/travel/businesstraveler/map/' + ZIP)
                lines = usock.readlines()
                iframe_re = re.compile(".*[iI][fF][rR][aA][mM][eE].*")
                for line in lines:
			if iframe_re.match(line):
                        	frame_src_start = line.find("src")
                                frame_src_end = line.find("?")
                                if frame_src_start > -1 and frame_src_end > -1:
                                	frame_src = line[frame_src_start+5 : frame_src_end]
                                        usock2 =  urllib.urlopen('http://www.weather.com' + frame_src)
                                        frame_lines = usock2.readlines()
                                        img_re = re.compile(".*[iI][mM][gG] [nN][aA][mM][eE]=\"mapImg\".*")
                                   	for frame_line in frame_lines:
                                        	if img_re.match(frame_line):
                                                	img_src_start = frame_line.find("SRC")
                                                        img_src_end = frame_line.find("jpg")
                                                       	img_src = frame_line[img_src_start+5 : img_src_end+3]
                                       	                img_file = urllib.urlretrieve(img_src)[0]
							return img_file ###Unsure if needed
                                        usock2.close()
                usock.close()
	except:
		print "Unable to download weather map. ", sys.exc_info()[0], sys.exc_info()[1]
	
