#!/usr/bin/env perl
# $Id: adjalign,v 1.2 2002/09/14 20:34:39 euske Exp $

# * public domain * by 1@2ch

# usage: ./adjalign {l | r} < IN > OUT

die "usage: adjalign {l | r}" if (!$ARGV[0] && $ARGV[0] ne 'l' &&$ ARGV[0] ne 'r');
$adjl = ($ARGV[0] eq 'l');

sub lshift { map { substr($_, 1) . substr($_, 0, 1) } (@_); }
sub rshift { map { substr($_, length($_)-1, 1) . substr($_, 0, length($_)-1) } (@_); }

# read
$b = 0;
while(<STDIN>) {
    chop;
    if (/^BITMAP/) {
	if ($e < 32 ||
	    (8509 <= $e && $e <= 8515) || 
	    (10273 <= $e && $e <= 10304)) { ; }
	else { $_ = ''; $b = 1; @p = (); }
    } elsif (/^ENDCHAR/ && $b) {
	$b = 0; @x = ();
	die "zero" if (0 == @p);
	$w = length($p[0]);
	foreach $i (@p) {
	    die "invalid" if (length($i) != $w); 
	    for($j = 0; $j < length($i); $j++) {
		$x[$j]++ if ('@' eq substr($i, $j, 1));
	    }
	}
	# m0: left margin, m1: right margin
	for($m0 = 0; $m0 < $w; $m0++) { last if ($x[$m0]); }
	for($m1 = 0; $m1 < $w; $m1++) { last if ($x[$w-$m1-1]); }
	$comment = '';
	if ($adjl) {
	    if ($m0 > $m1) {
		@p = &lshift(@p);
		print STDERR "$e\n";
		$comment = ' # left-aligned';
	    }
	} else {
	    if ($m0 < $m1) {
		@p = &rshift(@p);
		print STDERR "$e\n";
		$comment = ' # right-aligned';
	    }
	}
	print "BITMAP$comment\n";
	foreach $i (@p) { print $i,"\n"; }
    } elsif (/^ENCODING/) {
	@f = split(/\s/); $e = $f[1];
    } else {
	if ($b) {
	    push(@p, $_);
	    $_ = '';
	}
    }
    print $_, "\n" if ($_);
}
