; 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 2 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.

; Scales the layer to match the selection size while maintaining
; original aspect ration. If no selection is present, scales 
; layer to image size. Note: if the layer is floated (for example,
; after an Edit->Paste has been performed) there is no selection
; present even though there are marching ants around the originally
; selected region -- if this script is run without first making
; a new selection then the floating selection will be scaled to
; the image size. 

(define (script-fu-sg-kumar-kovuru image layer)
  (let* ((width (car (gimp-drawable-width layer)))
         (height (car (gimp-drawable-height layer)))
         (aspect (/ height width))
      )
    (gimp-image-undo-group-start image)
    (gimp-context-push)
    (if (< (/ 300 width) (/ 300 height))
        (gimp-layer-scale layer
                          300
                          (* 300 aspect) 
                          TRUE)
        (gimp-layer-scale layer 
                          (/ 300 aspect)
                          300 
                          TRUE ))
    (gimp-context-set-background '(255 255 255))
    (gimp-layer-resize layer 
                       320 
                       320 
                       (/ (- 320 (car (gimp-drawable-width layer))) 2) 
                       (/ (- 320 (car (gimp-drawable-height layer))) 2))
    (gimp-layer-flatten layer)
    ; (gimp-image-resize-to-layers image) ; Uncomment if image should be scaled
    (gimp-context-pop)
    (gimp-image-undo-group-end image)
    (gimp-displays-flush)
    )
  )
(script-fu-register "script-fu-sg-kumar-kovuru"
 "Scale layer per Kumar Kovuru"
 "Fit layer in 300x300 with white border"
 "Saul Goode"
 "Saul Goode"
 "September 2013"
 "RGB*,GRAY*"
 SF-IMAGE    "Image"    0
 SF-DRAWABLE "Drawable" 0
 )

(script-fu-menu-register "script-fu-sg-kumar-kovuru"
 "<Image>/Filters/Misc/"
 )
 
