; Luigi Chiesa 2008.  No copyright.  Public Domain.
; Add a grid of guides
; 2012 R. Antonishen - modified to allow creating a grid of guides based of the active layer rather than the image canvas

(define (script-fu-grid-guides InImage InSource InHGrid InVGrid InMode InBorder)
  (gimp-image-undo-group-start InImage)
  (let* (
        (width (if (= InSource 0) (car (gimp-image-width InImage)) (car (gimp-drawable-width (car (gimp-image-get-active-drawable InImage))))))
      	(height (if (= InSource 0) (car (gimp-image-height InImage)) (car (gimp-drawable-height (car (gimp-image-get-active-drawable InImage))))))
        (divH (if (= InMode 0) (/ width InHGrid) InHGrid))
        (divV (if (= InMode 0) (/ height InVGrid) InVGrid))
        (InHGrid (if (= InMode 0) InHGrid (/ width InHGrid)))
        (InVGrid (if (= InMode 0) InVGrid (/ height InVGrid)))
        (hcount 1)
        (vcount 1)
        (xoff (if (= InSource 0) 0 (car (gimp-drawable-offsets (car (gimp-image-get-active-drawable InImage))))))
        (yoff (if (= InSource 0) 0 (cadr (gimp-drawable-offsets (car (gimp-image-get-active-drawable InImage))))))
        )
        
    (if (= InBorder TRUE)
      (begin
        (if (and (>= yoff 0) (<= yoff (car (gimp-image-height InImage))))(gimp-image-add-hguide InImage yoff))
        (if (and (>= (+ yoff height) 0) (<= (+ yoff height) (car (gimp-image-height InImage)))) (gimp-image-add-hguide InImage (+ yoff height)))
        (if (and (>= xoff 0) (<= xoff (car (gimp-image-width InImage)))) (gimp-image-add-vguide InImage xoff))
        (if (and (>= (+ xoff width) 0) (<= (+ xoff width) (car (gimp-image-width InImage)))) (gimp-image-add-vguide InImage (+ xoff width)))
      )
    )
	
    (while (< hcount InVGrid) 
      (if (and (>= (+ yoff (* divV hcount)) 0) (<= (+ yoff (* divV hcount)) (car (gimp-image-height InImage)))) (gimp-image-add-hguide InImage (+ yoff (* divV hcount))))
      (set! hcount (+ hcount 1))
    )

    (while (< vcount InHGrid) 
      (if (and (>= (+ xoff (* divH vcount)) 0) (<= (+ xoff (* divH vcount)) (car (gimp-image-width InImage)))) (gimp-image-add-vguide InImage (+ xoff (* divH vcount))))
      (set! vcount (+ vcount 1))
    )

	(gimp-image-undo-group-end InImage)
  (gimp-displays-flush)
  )
)

(script-fu-register
  "script-fu-grid-guides"
  "Grid"
   "Add a grid of guides by specifying either the number of guides or the guide spacing"
  "Luigi Chiesa and Rob Antonishen"
  "Public Domain"
  "November 2009"
  "*"
    SF-IMAGE      "Image"   0
	SF-OPTION       "Based on" '("Image Canvas" "Active Layer")	
	SF-ADJUSTMENT	"Horizontal"	'(2 1 500 1 10 0 1)
	SF-ADJUSTMENT	"Vertical"	'(2 1 500 1 10 0 1)
	SF-OPTION       "Mode" '("Number of Divisions" "Spacing of Guides (px)")	
    SF-TOGGLE "Border guides?" FALSE
)
(script-fu-menu-register "script-fu-grid-guides"  "<Image>/Image/Guides")
