#!/usr/bin/python
from gimpfu import *
import math

def my_downscale(img, drawable, factor=1):
	nn=int(math.log(1/factor,2))
	
	ww=pdb.gimp_image_width(img)
	hh=pdb.gimp_image_height(img)
	
	nw=int(round(ww*factor))
	nh=int(round(hh*factor))
	
	sw=int(round(ww*factor))*(2**nn)
	sh=int(round(hh*factor))*(2**nn)
	
	pdb.gimp_image_undo_group_start(img)
	
	if (sw < ww):
		pdb.gimp_image_scale_full(img,sw,sh,INTERPOLATION_LANCZOS)
	
	for i in range(1,nn+1):
		pdb.gimp_image_scale_full(img,pdb.gimp_image_width(img)/2,pdb.gimp_image_height(img)/2,INTERPOLATION_LANCZOS)

	pdb.gimp_image_undo_group_end(img)


register(
	 "python_fu_my_downscale",
	 "Smart downscale",                  	
	 "Smart downscale",                  	
	 "Serge Gavrilov",
	 "Serge Gavrilov",
	 "2008",                                
	 "<Image>/Mine/Smart downscale",
	 "RGB*",
	 [
 		(PF_FLOAT, "factor", "Downscale factor", "1"),
         ],
	 [], 
	 my_downscale)

main()


