#! ruby

require "RMagick"
include Magick
require "getopt/long"
include Getopt

def debug_puts(*args)
    puts(*args)
end

def rename_filename( filename, width, height )
    dir  = File.dirname  filename
    ext  = File.extname  filename
    file = File.basename filename, ext
    
    new_filename = File.join dir, file + " (#{width}x#{height})" + ext 
end

def resize_to_size args
    images = ImageList.new( *args[:filenames] )
    width, height = args[:size]
    images.each{|img|
        debug_puts "    #{File.basename(img.filename)}"
        new_filename = rename_filename img.filename, width, height
        new_size = size_to_rotatable_box img.columns, img.rows, width, height
        
        i2 = img.resize( *new_size )
        i2.write( new_filename )
    }
end

def resize_to_box args
end

def size_to_rotatable_box( width, height, box_width, box_height )
    
    err_msg = [width, height, box_width, box_height].
        zip(%w{width  height  box_width  box_height}).
        map{|x,str| str if x == 0 }.compact.join(", ")
    raise ArgumentError.new("zero "+err_msg) if ! err_msg.empty?
    
    image_orientation  = Float(width)/Float(height) - 1.0
    box_orientation    = Float(box_width)/Float(box_height) - 1.0
    if image_orientation * box_orientation < 0.0
        box_height, box_width = box_width, box_height
        box_orientation    = Float(box_width)/Float(box_height) - 1.0
    end
    
    float_dimensions = 
        if (image_orientation - box_orientation).abs < 0.001
        # Resize width and height equally
            [box_width, box_height]
            
        elsif  image_orientation > box_orientation
        # Fit width exactly, make height smaller
            [box_width, Float(height)*Float(box_width)/Float(width)]
    
        else
        # Fit height exactly, make width smaller
            [Float(width)*Float(box_height)/Float(height), box_height ]
        end
    
    float_dimensions.map{|x| x.round.to_i }
end

def resize_to_width args
    images = args
end
def resize_percent args
    images = args
end


if __FILE__ == $0
    if ARGV.size == 0
        puts "No images specified. Exiting"
        exit -1
    end

=begin
    opts = Long.getopts(["--size", "-s", REQUIRED ])
    
    puts ARGV.inspect
    
    size = if opts["size"]
            case opts["size"]
            when /^(\d+)x(\d+)$/i  
                resize_to_size :size=>[$1.to_i, $2.to_i],   :filenames=>ARGV
            when /^\d+$/          
                resize_to_width :width=>opts["size"].to_i,  :filenames=>ARGV
            when /^\d+%$/         
                resize_percent  :percent=>opts["size"].to_i,:filenames=>ARGV
            end
        else
            [640, 360]
        end
    
    puts ARGV.inspect
=end
    resize_to_size :size=>[1024,768], :filenames=>ARGV

end


