import vapoursynth as vs

import muvsfunc

def UnsharpMask(clip, strength=64, radius=3, threshold=8):
        """Ported by Myrsloik"""
        
        core = vs.core
        
        maxvalue = (1 << clip.format.bits_per_sample) - 1
        
        threshold = threshold * maxvalue // 255
        blurclip = clip.std.Convolution(matrix=[1] * (radius * 2 + 1), planes=0, mode='v')
        blurclip = blurclip.std.Convolution(matrix=[1] * (radius * 2 + 1), planes=0, mode='h')
        
        expressions = ['x y - abs {} > x y - {} * x + x ?'
                                                .format(threshold, strength / 128)]
                                                
        if clip.format.color_family != vs.GRAY:
            expressions.append("")
            
        return core.std.Expr(clips=[clip, blurclip], expr=expressions)
    

