def get_booktitle(infile, title):
    if title is None: return None
    title = unicode(title, sys.stdin.encoding)
    if title == 'auto':
        files = mobiunpack32.fileNames(infile, "tmpdir2.$$$")
        mu = mobiunpack32.mobiUnpack(files)
        metadata = mu.getMetaData()
        title = unicode(mu.title, mu.codec)
        shutil.rmtree("tmpdir2.$$$")
    return title
def extractThumbnail(infile, tmpdir, asin):
    files = mobiunpack32.fileNames(infile, tmpdir)
    
    # Instantiate the mobiUnpack class    
    mu = mobiunpack32.mobiUnpack(files)
    metadata = mu.getMetaData()
    proc = mobiunpack32.processHTML(files, metadata)
    imgnames = proc.processImages(mu.firstimg, mu.sect)
    imgdir = os.path.join(tmpdir, "images")
    destdir = "images.$$$"
    os.mkdir(destdir)
    imageName = None
    if 'ThumbOffset' in metadata:
        imageNumber = int(metadata['ThumbOffset'][0])
        imageName = imgnames[imageNumber]
        if imageName is None:
            print "Error: Cover Thumbnail image %s was not recognized as a valid image" % imageNumber
        else:
            print 'Cover ThumbNail Image "%s"' % imageName
            copyCover(destdir, infile, os.path.join(imgdir, imageName), ".thumbnail")
    if 'CoverOffset' in metadata:
        imageNumber = int(metadata['CoverOffset'][0])
        imageName = imgnames[imageNumber]
        if imageName is None:
            print "Error: Cover image %s was not recognized as a valid image" % imageNumber
        else:
            print 'Cover Image "%s"' % imageName
            copyCover(destdir, infile, os.path.join(imgdir, imageName), ".cover")
    if imageName is None:
        print 'Neither Cover nor ThumbNail found'
        imgpath = max(glob.glob(os.path.join(imgdir, "*")), key=os.path.getsize)
        if os.path.splitext(os.path.split(imgpath)[1])[1]=='.jpeg':
            print 'Fake Cover Image "%s"' % os.path.split(imgpath)[1]
            copyCover(destdir, infile, imgpath, ".cover")
        else:
            if asin==None:
                print 'No candidate for cover image found. Execution interrupted.'
                shutil.rmtree(tmpdir)
                shutil.rmtree(destdir)
                sys.exit(0)