require "rake/clean"

task :default => ["knxt.psfu", "knxt.pcf", :clean]
task :psf => ["knxt.psfu", :clean]
task :psf => ["knxt.pcf", :clean]

CLEAN.add '*.bdf512', '*.sorted', '*.uni'
CLOBBER.add '*.psfu', '*.pcf'

def chars(filename)
	a = open(filename).read.split(/\s*/).sort
	a[96..127] + [' '] + a[0..95] + a[128..511];
end

rule '.sorted' => '.glyphs' do |t|
	c = chars t.source
	open(t.name, 'w'){ |f|
		c.each_index{ |i|
			ahead = i != 0
			ii = i + 1
			f.print c[i],
				if ahead && ii % 128 == 0 && ii != c.length
					"\n\n"
				elsif ahead && ii % 32 == 0 
					"\n"
				else
					' '
				end
		}
	}
end

rule '.uni' => '.glyphs' do |r|
	open(r.name, "w"){|f| chars(r.source).join.unpack("U*").each{|c| f.puts("%04X" % c) }}
end

rule '.bdf512' => ['.bdf', '.uni'] do |r|
	sh "./ucstoany.pl +f -o #{r.name} #{r.source} k 1 #{r.prerequisites[1]} "
end

rule '.psfu' => ['.bdf512', '.dup'] do |r|
	sh "./bdftopsf.pl -- #{r.source} #{r.prerequisites[1]} > #{r.name}"
end

rule '.pcf' => ['.bdf'] do |r|
	sh "bdftopcf -o #{r.name} #{r.source}"
end
