#!/usr/bin/perl -w

# sort a font in psftools .txt format, by unicode codepoint.
# only the *first* codepoint per glyph is used as the key.

undef $/;
$_ = <>;
@glyphs = split "%";
shift @glyphs;
$header = "%" . (shift @glyphs);

# 0 is a special case because fonts intended to become PSFs will
# be padded with extra characters with encoding 0. only the first
# one seen is the real one.
$zeroseen = 0;

for(@glyphs) {
	my($cp, $dcp);
	($cp) = (/Unicode: \[([0-9a-fA-F]+)/);
	$dcp = eval "0x$cp";
	if($dcp == 0) {
		next if $zeroseen++;
	}
	if(defined $sortme{$dcp}) {
		warn "duplicate codepoint 0x$cp\n";
	}
	$sortme{$dcp} = $_;
}

for(sort { $a <=> $b } keys %sortme) {
	push @sorted, $sortme{$_};
}
print join("%", $header, @sorted);
