#!/usr/bin/ruby
# Splits up a collage of rectangular images that are separated by a transparent border

# Requires:  rmagick
# Docs:      https://github.com/rmagick/rmagick
# Install (Ubuntu):
# % sudo apt-get install libmagickwand-dev
# % sudo gem install rmagick
require 'rmagick'


require 'forwardable'

OUT_FORMAT = "image.%d.png"

class Collage
	extend Forwardable
	def_delegators :@image, :crop

	attr_reader :width, :height

	def initialize(file)
		# Load the collage image
		@file = file
		#@borderColor = borderColor

		@image = Magick::Image.read(file).first

		# Get the dimensions of the collage image
		@width = @image.columns
		@height = @image.rows
	end

	# Delegator!
	def __getobj__
		@image
	end

	def borderPixel?(x,y)
		pixel = @image.pixel_color(x, y)
		pixel.alpha < 500
		#pixel.fcmp(@borderColor, COMPARE_FUZZ)
	end

	def splitRows
		# Walk down 10% from the left and find all the start/stops of images
		x = @width/10
		#puts "Walking down at x=#{x}"
		lastWasBorder = true
		startRow = 0
		(0..@height).each { |y|
			isBorder = borderPixel?(x,y)

			startRow = y if lastWasBorder && !isBorder
			yield startRow, y-1 if !lastWasBorder && isBorder

			lastWasBorder = isBorder
		}
	end

	def splitColumns(y)
		#puts "Walking across at y=#{y}"
		lastWasBorder = true
		startCol = 0
		(0..@width).each { |x|
			isBorder = borderPixel?(x,y)

			startCol = x if lastWasBorder && !isBorder
			yield startCol, x-1 if !lastWasBorder && isBorder

			lastWasBorder = isBorder
		}
	end

	def cropXY(file, x0,y0, x1,y1)
		puts "%-50s #{x0},#{y0} - #{x1},#{y1}" % file
  	@image.crop(x0, y0, x1-x0, y1-y0).write(file)
	end
end

def main
	collageFile = ARGV.shift
	collage = Collage.new(collageFile)
	count = 0
	collage.splitRows { |startRow, stopRow|
		if stopRow-startRow < 5
			warn("too small of a slice from y=#{startRow} to #{stopRow}?")
			next
		end

		# Now split columns through the middle
		splitY = startRow + (stopRow-startRow)/2
		#puts "Split row from y=#{startRow} to #{stopRow} at #{splitY}"

		collage.splitColumns(splitY) { |startCol, stopCol|
			#puts "BOOM: #{startCol}, #{startRow}   to #{stopCol}, #{stopRow}"
			file = OUT_FORMAT.gsub('%d', count.to_s)
			collage.cropXY(file, startCol, startRow, stopCol, stopRow)
			count += 1
		}
	}
end
main
