; Save All Layers as Brushes rel 0.02
; Created by Graechan
; Comments directed to http://gimpchat.com or http://gimpscripts.com
;
; License: GPLv3
;    This program is free software: you can redistribute it and/or modify
;    it under the terms of the GNU General Public License as published by
;    the Free Software Foundation, either version 3 of the License, or
;    (at your option) any later version.
;
;    This program is distributed in the hope that it will be useful,
;    but WITHOUT ANY WARRANTY; without even the implied warranty of
;    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;    GNU General Public License for more details.
;
;    To view a copy of the GNU General Public License
;    visit: http://www.gnu.org/licenses/gpl.html
;
;
; ------------
;| Change Log |
; ------------ 
; Rel 0.01 - Initial Release
; Rel 0.02 - Added convert to GrayScale option
;
(define (script-fu-save-all-layers-as-brushes image drawable
                                                            name
															folder
															gray)
 (let* (
        (dup-img (car (gimp-image-duplicate image))) ;create a duplicate image
		(type (car (gimp-image-base-type dup-img)))
		(layerList 0)
		(layerId 0)
		(cnt 1)
		)
		
	(if (and (= gray TRUE) (not (= type 1))) (gimp-image-convert-grayscale dup-img)) ;convert the duplicated image to grayscale 
	
	(set! layerList (vector->list (cadr (gimp-image-get-layers dup-img)))) ;------create a layer list from the duplicated image

;;;;save each layer of the duplicated image as a brush    
	(while (not (null? layerList))
    (set! layerId (car layerList))	
	(file-gbr-save RUN-NONINTERACTIVE 
               dup-img 
			   layerId 
			   (string-append folder DIR-SEPARATOR name "-" (number->string cnt) ".gbr") ;filename 
			   (string-append folder DIR-SEPARATOR name "-" (number->string cnt) ".gbr") ;raw-filename 
			   100 ;spacing 
			   (string-append name (number->string cnt))) ;description
			   (set! cnt (+ cnt 1))
			   (set! layerList (cdr layerList))
	) ;endwhile
	(gimp-brushes-refresh) ;----------------------------refresh the brushes
	
	(gimp-image-delete dup-img) ;------------------------delete the duplicated image
	
 )	
)

(script-fu-register "script-fu-save-all-layers-as-brushes"        		    
  "Save All Layers as Brushes..."
  "Creates a .gbr brush from every layer of an image"
  "Graechan"
  "Graechan - http://gimpchat.com"
  "2013"
  "RGB* GRAY* INDEXED*"
  SF-IMAGE      "image"      0
  SF-DRAWABLE   "drawable"   0
  SF-STRING     "Brush Name" "My Brush"
  SF-DIRNAME   "Directory" (string-append gimp-directory "/brushes/") 
  SF-TOGGLE     "convert to GrayScale"    FALSE
)

(script-fu-menu-register "script-fu-save-all-layers-as-brushes" "<Image>/Script-Fu/Brushes")
