# pre-setup.rb
curr_srcdir = '.' unless curr_srcdir

# read the ISO definition and make a library script
srcs = Dir.glob(File.join(curr_srcdir, 'data', '*.sgml'))
dst = File.join('lib', 'entity-reference', 'references.rb')
srcs_mtime = [srcs.map{|p| File.mtime(p)}, File.mtime(__FILE__)].flatten.max
dst_mtime = File.exist?(dst) ? File.mtime(dst) : Time.at(0)

if dst_mtime < srcs_mtime then
	$:.unshift(File.join(curr_srcdir, 'lib'))
	require 'entity-reference/sgml-list'
	require 'entity-reference/ucs-transformation'

	refs = Hash.new
	srcs.each do |p|
		b = File.basename(p, '.sgml')
		refs[b] =  EntityReference::SgmlList::Entities.parse(File.open(p){|f| f.read})
	end

	bases = srcs.map{|p| File.basename(p, '.sgml')}.sort

	refs['utf-8'] = EntityReference::SgmlList::Entities.new
	bases.each do |b|
		refs[b].entities.each do |e|
			refs['utf-8'].push(EntityReference::SgmlList::Entity.new(e.reference, EntityReference::UcsTransformation::ucs_to_utf8(e.code), e.comment))
		end
	end

	library_code = <<_END
#
# Entity reference list
#
# This file is generated by #{File.basename(__FILE__)} in ruby-entity-reference
# With definitions taken from http://www.w3.org/TR/html401/sgml/entities.html
#

module EntityReference
	References = {
_END
	[bases, 'utf-8'].flatten.each do |b|
		library_code += "\t\t#{b.dump} => "
		library_code += refs[b].reference_hash_literal(nil, "\t\t") + ",\n"
	end
	library_code += "\t}\nend\n"
	File.open(dst, 'w') do |f|
		f.write library_code
	end
end
