;; -*-scheme-*-

;; Michael Schumacher, 2016.  Public Domain.

(define (script-fu-guide-new-unit image
				   drawable
				   direction
				   position
				   unit)
  (let* (
        (width (car (gimp-image-width image)))
        (height (car (gimp-image-height image)))
	(hposition (round position))
	(vposition (round position))
        )

    ;; unit is not pixels
    (if (<> unit 0)
	(let* (
	       (resolution (gimp-image-get-resolution image))
	       (xresolution (car resolution))
	       (yresolution (cadr resolution))
	       (factor (car (gimp-unit-get-factor unit)))
	       )
	  ;; this will only get "pretty close" because guides are
	  ;; always located at pixels boundaries 
	  (set! hposition (round (* yresolution (/ position factor))))
	  (set! vposition (round (* xresolution (/ position factor))))
	)
	    
    )
	    
    (if (= direction 0)
        ;; check position is inside the image boundaries
        (if (<= hposition height) (gimp-image-add-hguide image hposition))
        (if (<= vposition width) (gimp-image-add-vguide image vposition))
    )

    (gimp-displays-flush)
  )
  )

(define (script-fu-get-units)
  (define (range a b step)
    (if (> a b)
	'()
	(cons a (range (+ step a) b step))))
  (let* (
	 (numunits (car (gimp-unit-get-number-of-units)))
	)
    (map (lambda (n)
	   (car (gimp-unit-get-identifier n)))
	 (range 0 (- numunits 1) 1))
  )
)

  
(script-fu-register "script-fu-guide-new-unit"
  _"New _Guide (by unit)..."
  _"Add a guide at the orientation and position specified"
  "Michael Schumacher"
  "Michael Schumacher, 2016.  Public Domain."
  "2016-09-05"
  "*"
  SF-IMAGE      "Image"      0
  SF-DRAWABLE   "Drawable"   0
  SF-OPTION     _"Direction" '(_"Horizontal" _"Vertical")
  SF-ADJUSTMENT _"Position"  (list 0 0 MAX-IMAGE-SIZE 1 10 2 1)
  SF-OPTION     _"Unit"      (script-fu-get-units)
)

(script-fu-menu-register "script-fu-guide-new-unit"
                         "<Image>/Image/Guides")
