#!/usr/bin/env python


import math
from gimpfu import *

def python_smart_sharpen(timg, tdrawable, edge=6, low_input=12, gamma=1.0, high_input=240, blur=7.0, unsharp_radius = 1.0,	unsharp_amount = 2.0, unsharp_thesold = 0):
	#Make a copy of original layer
	new_layer = timg.active_drawable.copy()
	new_layer.name = 'Smart Sharpen'
	timg.add_layer(new_layer)
    #Decompose
	decomposed_image = pdb.plug_in_decompose(timg,timg.active_drawable,"LAB",1)
	decomposed_image = decomposed_image[0]
	#Find and select Layer 'L'
	for layer in decomposed_image.layers:
		if layer.name == 'L':
			l_layer = layer
			break
	#Duplicate L layer
	mask_layer = l_layer.copy()
	decomposed_image.add_layer(mask_layer, 0)
	#Select mask layer
	decomposed_image.active_layer = mask_layer
	#Edge
	pdb.plug_in_edge(decomposed_image,decomposed_image.active_drawable,edge,1,0)
	#Levels
	pdb.gimp_levels(decomposed_image.active_drawable, 0, low_input, high_input, gamma, 0, 255)
	#Blur
	pdb.plug_in_gauss_rle(decomposed_image, mask_layer, blur, 1, 1)
	#Levels again
	#skip
	#New channel from layer
	pdb.gimp_selection_all(decomposed_image)
	pdb.gimp_edit_copy(mask_layer)
	channel = gimp.Channel(decomposed_image, 'Selection mask', decomposed_image.width, decomposed_image.height, 1.0, gimpcolor.RGB(1.0, 1.0, 1.0, 1.0))
	decomposed_image.add_channel(channel)
	float_sel = pdb.gimp_edit_paste(decomposed_image.active_drawable,1)
	pdb.gimp_floating_sel_anchor(float_sel)
	#Create selection from channel
	pdb.gimp_selection_load(channel)
	#Remove unused layers/channels
	decomposed_image.remove_channel(channel)
	decomposed_image.remove_layer(mask_layer)
	#Unsharp mask to "L"
	pdb.plug_in_unsharp_mask(decomposed_image,l_layer,unsharp_radius,unsharp_amount,unsharp_thesold)
	pdb.gimp_selection_clear(decomposed_image)
	#Recompose
	pdb.plug_in_recompose(decomposed_image,decomposed_image.active_drawable)
	
register(
        "python_fu_smart_sharpen",
        "Smart sharpening for current layer",
        "Smart sharpening for current layer",
        "Konstantin Dmitriev",
        "Konstantin Dmitriev",
        "2008",
        "<Image>/Filters/Enhance/_Smart Sharpen...",
        "RGB*",
        [
                (PF_INT, "edge", "Edge detection - Amount", 6),
                (PF_INT, "low_input", "Levels - Low", 12),
                (PF_FLOAT, "gamma", "Levels - Gamma", 1.0),
                (PF_INT, "high_input", "Levels - High", 240),
                (PF_FLOAT, "blur", "Mask blur", 7.0),
                (PF_FLOAT, "unsharp_radius", "Unsharp mask - Radius", 1.0),
                (PF_FLOAT, "unsharp_amount", "Unsharp mask - Amount", 2.0),
                (PF_INT, "unsharp_thesold", "Unsharp mask - Thesold", 0)
        ],
        [],
        python_smart_sharpen)

main()
