def get_image(panoid, heading, yaw, alt_yaw):
    yaw_dist = science.angular_difference(yaw, heading)
    alt_dist = science.angular_difference(alt_yaw, heading)        

    if yaw_dist <= alt_dist:
        url_left = "http://cbk0.google.com/cbk?output=tile&panoid=%s&zoom=3&x=2&y=1" % panoid
        url_right = "http://cbk0.google.com/cbk?output=tile&panoid=%s&zoom=3&x=3&y=1" % panoid
    else:
        url_left = "http://cbk0.google.com/cbk?output=tile&panoid=%s&zoom=4&x=12&y=3" % panoid
        url_right = "http://cbk0.google.com/cbk?output=tile&panoid=%s&zoom=4&x=0&y=3" % panoid
        
    filepath_left = "sv_images/%s_left.jpg" % i
    filepath_right = "sv_images/%s_right.jpg" % i
    try:
        urllib.urlretrieve(url_left, filepath_left)
        urllib.urlretrieve(url_right, filepath_right)        
    except Exception as e:
        print("Image download failed")
        return None, None    
    image_left = Image.open(filepath_left)        
    image_right = Image.open(filepath_right)    
    image = Image.new('RGB', (1024, 512))
    image.paste(image_left, (0, 0))
    image.paste(image_right, (512, 0))        
    os.remove(filepath_left)
    os.remove(filepath_right)
    
    global image_id
    filepath = "sv_images/%s.png" % image_id
    image.save(filepath, 'PNG')
    image_id += 1
    
    cv.ShowImage("streetview", drawing.pil_to_ipl(image))                
    cv.WaitKey(5)    
    print(url_left)
    print(url_right)                                    
def get_closest_link(links, heading):
    min_difference = 1000
    next_panoid = None
    next_heading = None
    for l, link in enumerate(links):
        link_heading = float(link['yawDeg'])
        difference = science.angular_difference(link_heading, heading)        
        # print("--> %f (%f)" % (link_heading, difference))        
        if difference < min_difference:
            min_difference = difference
            next_heading = link_heading
            next_panoid = link['panoId']
    print("LINK HEADING: %s" % next_heading)     
    if min_difference > 90:
        return None
    else:           
        return next_panoid