; reverse-layers.scm:
;
; Reverse (or remove) a range of layers.
;
; The involved layers must belong to the same image.
;
; This is free software, with NO warranty at all.
; See the GNU General Public License for details:
; http://www.gnu.org/copyleft/gpl.html
;
; Casper Maarbjerg,  http://www.nyx.net/~cmaarbj/
; December 31, 1998
;
(define (script-fu-reverse-layers image active top bottom remove)

(let*
  ((layers (gimp-image-get-layers image))
   (first 0)
   (last 0)
   (next 0)
   (steps 0)
   (total 0)
   (count 0)
   (index 0))

  (gimp-undo-push-group-start image) ; in case of unintended removal

  (define (reverse layer steps)
    (while (> steps 0)
      (set! steps (- steps 1))
      (gimp-image-raise-layer image layer)))

  ; compute index range
  (set! total (car layers))
  (set! layers (cadr layers))
  (set! index (- total 1))
  (while (>= index 0)
    (set! next (aref layers index))
    (if (= bottom next)
      (set! first index))
    (if (= top next)
      (set! last index))
    (set! index (- index 1)))

  ; don't bother user with computation order
  (if (< last first)
    (begin
      (set! next last)
      (set! last first)
      (set! first next)))

  ; Bottom layer needs alpha to be raised
  (set! next (aref layers last))
  (if (= (car (gimp-drawable-has-alpha next)) FALSE)
    (gimp-layer-add-alpha next))
  (set! index last)
  (set! count (- last first))
  (while (> index first)
    (set! next (aref layers index))
    (set! index (- index 1))
    (if (> remove 0)
      (gimp-image-remove-layer image next)
      (reverse next count))
    (set! count (- count 1)))

  (if (> remove 0) ; loop count is for reversal - remove last in range
    (gimp-image-remove-layer image (aref layers first)))

  (gimp-displays-flush)
  (gimp-undo-push-group-end image)
  (gimp-displays-flush))) ; increase chance of layer-and-channels updating

(script-fu-register
                    "script-fu-reverse-layers"
                    "<Image>/Script-Fu/Animators/Reverse"
                    "Reverse or remove a range of layers"
                    "Casper Maarbjerg"
                    "Casper Maarbjerg, http://www.nyx.net/~cmaarbj/"
                    "31-Dec-1998"
                    "RGB* GRAY* INDEXED*"
                    SF-IMAGE "Image"  0
                    SF-DRAWABLE "Active layer (not used)" 0
                    SF-DRAWABLE "Top layer" 0
                    SF-DRAWABLE "Bottom layer" 0
                    SF-TOGGLE "Remove layers" 0)

