from PIL import Image
import os
from urllib.parse import unquote

join = os.path.join

def fixup(doc,location):
    for e in tuple(doc.findAll('reveal')):
        a = doc.new_tag('a')
        e.replace_with(a)
        
        src = e['src']
        href = e['href']
        title = e['title']
        
        a.attrs['title'] = title
        a.attrs['href'] = href
        img = doc.new_tag('img')
        a.append(img)
        if 'scale' in e.attrs:
            scale = float(e['scale'])
        else:
            scale = None
        img.attrs['src'] = src

        if scale:
            src = unquote(src)
            scaled = join(location,'.scaled'+src)
            temp = join(location,'.temp'+src)
            src = join(location,src)
            if not os.path.exists(scaled):
                print('scaling',src,'to',scale)
                import subprocess as s
                s.check_call(['convert',
                        '-resize',str(int(scale*100))+'%',
                        src,
                        temp])
                os.rename(temp,src)
                with open(scaled,'wb'): pass
