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

join = os.path.join

def pre_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)
		img.attrs['src'] = src
		
		if 'scale' in e.attrs:
			scale = float(e['scale'])
		else:
			scale = None

		if scale:
			src = unquote(src)
			unscaled = join("full",src)
			scaled = join("resized",src)

			if not os.path.exists(scaled):
				import subprocess as s
				scale = str(int(scale*100))+'%'
				print('scaling',src,'to',scale)
				temp = '.temp'+src
				s.check_call(['magick',
				              unscaled,
											'-resize',scale,
				              temp])
				os.rename(temp,scaled)
