#!/usr/bin/ruby -w
# -*- ruby -*-


# Generates a single Ruby script from a target one. Each require statement that
# references a local file (i.e., beginning with "./") will be expanded such that
# the contents of the required file are included in the output. Files are added
# to the script only once, at the point where they are first referenced.

# Except for the primary (target) file, the first two lines of each loaded file
# are removed if they contain the pound-bang or the ruby-style (Emacs) line.

# Each block between "if __FILE__ == $0" and its matching end statement is
# removed. This allows modules to contain their own tests.

# If the __END__ statement is found in a loaded file, the rest of the file is
# not loaded.

# This script is mostly for cvsdelta only, and has not been made very generic.

class Generator
  
  def initialize(fname)
    @included = Hash.new
    @out = Array.new

    read_file(fname, true)
    puts @out
  end

  def read_file(fname, istop)
    return if @included[fname]
    @included[fname] = true
    
    lines = IO.readlines(fname)
    lnum = 0
    while lnum < lines.size
      line = lines[lnum]
      #puts line
      if line.index(/^\s*require \'\.\/(\w+)\'/)
        req = $1
        #puts "req = #{req}"
        read_file(req + ".rb", false)
      elsif !istop && lnum < 2 && (line.index("#!/usr/bin/ruby -w") == 0 || line.index("# -*- ruby -*-") == 0)
        # skip
      elsif line.index(/^if __FILE__ == \$0/)
        until lines[lnum].index(/^(else|end)/)
          lnum += 1
        end
        # skip
      elsif line.index(/^__END__/)
        break
      else
        @out.push(line)
      end
      lnum += 1
    end
  end

end

Generator.new(ARGV.shift)
