require 'libpng'

include Graphics::PNG

print "PNG image catenating.\n"
print "Sample for CGI counter.\n"

unless number = ARGV.shift
  number = "1234"
end
unless out_name = ARGV.shift
  out_name = "cat.png"
end

in_name = []
rpng = []

wpng = Writer.new out_name

print "PNG image writer creater. (for #{out_name})\n"

for i in 0..3
  in_name[i] = number[i].chr + ".png"
  rpng[i] = Reader.new in_name[i]
  print "PNG image reader created (for #{in_name[i]}).\n"
end


width, height, bit_depth, color_type,
interlace_type, compression_type, filter_type = rpng[0].get_IHDR

print "Original width: #{width}\n"


width *= number.to_s.size

print "Catenated width: #{width}\n"


wpng.set_IHDR width, height, bit_depth, color_type,
              interlace_type, compression_type, filter_type

if gamma = rpng[0].get_gAMA_fixed
  wpng.set_gAMA gamma
end
if palette = rpng[0].get_PLTE
  wpng.set_PLTE palette
end
if background = rpng[0].get_bKGD
  wpng.set_bKGD background
end
if sig_bit = rpng[0].get_sBIT
  wpng.set_sBIT sig_bit
end
wpng.write_info


in_images = []

for i in 0..3
  in_images[i] = rpng[i].read_image
  print "Reading image data from #{in_name[i]}\n"
end


out_image = []

print "Horizontal catenate: #{in_name[0]}+#{in_name[1]}+#{in_name[2]}+#{in_name[3]}\n"

for i in 0..in_images[0].size-1
  out_image[i] = in_images[0][i] + in_images[1][i] +
                 in_images[2][i] + in_images[3][i]
end

print "Catenated done.\n"

wpng.write_image out_image

wpng.write_end

print "Image created..\n"
