# $p0 - Edge thickness (0-10) [0]
# $p1 - Edge intensity (0-100) [80]
# $p2 - Posterize (# colors) [10]
# $p3 - Smoothing [5]
# $p4 - Black threshold [36]

&rfx_sendmsg (
  qq{
    (let* ((input-file (string-append "$curtmpdir" DIR-SEPARATOR "$in"))
           (image (car (gimp-file-load RUN-NONINTERACTIVE input-file input-file)))
           (layer (car (gimp-image-get-active-layer image))) )
      (gimp-image-undo-disable image)
      (let ((buffer (car (gimp-edit-named-copy layer "orig")))
            (retinex-layer (car (gimp-layer-copy layer TRUE)))
            (retinex-mask 0)
            (edge-layer 0) )
        (unless (zero? $p2)
          (unless (zero? $p3)
            (plug-in-gauss RUN-NONINTERACTIVE image layer $p3 $p3 0) )
          (gimp-image-convert-indexed image NO-DITHER  MAKE-PALETTE $p2 FALSE FALSE "")
          (gimp-image-convert-rgb image) )
        (gimp-image-add-layer image retinex-layer 0)
        (plug-in-retinex RUN-NONINTERACTIVE image retinex-layer 16 3 0 0.1)
        (set! retinex-mask (car (gimp-layer-create-mask retinex-layer 0)))
        (gimp-layer-add-mask retinex-layer retinex-mask)
        (gimp-floating-sel-anchor (car (gimp-edit-named-paste retinex-mask buffer TRUE)))
        (unless (zero? $p4)
          (gimp-threshold retinex-mask $p4 255)
          (plug-in-gauss RUN-NONINTERACTIVE image retinex-mask (* 0.01 $width) (* 0.01 $width) 0) )
        (gimp-layer-remove-mask retinex-layer MASK-APPLY)
        (gimp-buffer-delete buffer)
        (gimp-layer-set-mode retinex-layer VALUE-MODE)
        (set! edge-layer (car (gimp-layer-copy (car (gimp-image-merge-down image retinex-layer CLIP-TO-IMAGE)) TRUE)))
        (gimp-image-add-layer image edge-layer 0)
        (plug-in-gauss RUN-NONINTERACTIVE image edge-layer 2.0 2.0 0)
        (plug-in-laplace RUN-NONINTERACTIVE image edge-layer)
        (plug-in-despeckle RUN-NONINTERACTIVE image edge-layer 1 1 0 255)
        (unless (zero? $p0)
          (plug-in-vpropagate RUN-NONINTERACTIVE image edge-layer
                              6 ; propagate-mode 
                              3 ; propagating-channel 
                              (/ $p0 10) ; propagating-rate 
                              15 ; direction-mask 
                              0 ; lower-limit 
                              255 ; upper-limit
                              ))
        (gimp-layer-set-opacity edge-layer $p1)
        (gimp-desaturate-full edge-layer 1) )
      (gimp-image-flatten image)
      (rfx-save-frame image "$out") )
    }
  );

