#!/usr/bin/ruby -w

$oldPack = ARGV[0]

$keysFile = File.join("Pack","keys.txt")
`rm #{$keysFile}`

$name = Hash.new
Dir.entries("Capture").select{|path| path =~ /keys\.txt$/}.each do |path|
    File.foreach(File.join("Capture",path)) do |line|
        case line when /^(.*) (.*)$/ then $name[$1] = $2; `echo #{$1} #{$2}.png >> #{$keysFile}` end
    end
end

$titleBits = [["8880FD9B651C257778549A7EE7A2E450", "E7504AFB7D3264410C74C2EA777AB1F3", "8F2FA7061AB2E84279F2292FDD537C46"],
              ["00AE19B7C0B2D045AE54A1683C076786", "9DB0846B3F90F68744D01237BFCE59CB", "C1135A3AA842C8E3CDD2493E48CFAE7F"]]

$title = Hash.new

$titleBits.each_with_index{|line,y| line.each_with_index{|code,x| $title[code] = [x*256, y*256]}}

def process(code,xmin,xmax,ymin,ymax,imagePath)
    if $title[code]
        sourceImage = File.join($oldPack,imagePath)
        packImage = File.join("Pack","TITLEH.png")
        if not File.exist?(packImage)
            `convert -size 640x480 xc:black #{packImage}`
        end
        cmd = "composite -geometry +#{$title[code][0]}+#{$title[code][1]} -compose Replace \"#{sourceImage}\" #{packImage} #{packImage}"
        puts cmd
        `#{cmd}`
    elsif $name[code]
        sourceImage = File.join($oldPack,imagePath)
        captureImage = File.join("Capture",code,"Complete.bmp")
        packImage = File.join("Pack","#{$name[code]}.png")
        if not File.exist?(packImage)
            puts "#{packImage} -- #{captureImage}"
            `convert #{captureImage} -transparent cyan -resize 400% #{packImage}`
        end

        width = xmax-xmin
        height = ymax-ymin
        cmd = "composite -geometry #{width*4}x#{height*4}\\!+#{xmin*4}+#{ymin*4} -compose Replace \"#{sourceImage}\" #{packImage} #{packImage}"
        if File.exist?(sourceImage)
            puts cmd
            `#{cmd}`
        else
            puts "missing: #{sourceImage}"
        end
    end
end

File.foreach(File.join($oldPack,"texture.log")) do |line|
    case line when /^(.*)\((.*)--(.*)\)\((.*)--(.*)\) "(.*)"/ then process($1,$2.to_i,$3.to_i,$4.to_i,$5.to_i,$6.strip.gsub(/\\/,'/').gsub(/\.\//,'')) end
end
