#!/usr/bin/perl
#
# This script rotates characters in 90-degree increments clockwise.
# Narrow input characters are widened before rotation by adding four-pixel-wide
# margins to the left and right.
#
# Author: David Corbett, February 2019
#
# Copyright (C) 2019 David Corbett
#
# LICENSE:
#
#     This program is free software: you can redistribute it and/or modify
#     it under the terms of the GNU General Public License as published by
#     the Free Software Foundation, either version 2 of the License, or
#     (at your option) any later version.
#
#     This program is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU General Public License for more details.
#
#     You should have received a copy of the GNU General Public License
#     along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

use warnings;
use strict;

use Getopt::Long;

use constant SIZE_HEX => 64;
use constant WIDTH_BIN => 16;

my $quarter_turns = 1;
GetOptions (
	'n=i' => \$quarter_turns,
) or die "Error in command line options\n";
$quarter_turns %= 4;

while (<>) {
	chomp;
	my @data = split (':', $_);
	my $codepoint = $data[0];
	my $char = $data[1];
	if (length ($char) * 2 == SIZE_HEX) {
		$char =~ s/../0$&0/g;
	} elsif (length ($char) != SIZE_HEX) {
		warn "Unsupported character width: $_\n";
		next;
	}
	$char =~ s/./sprintf ('%04b', hex ($&))/eg;
	my @char = split ('', $char);
	my @output = ();
	for my $i (0 .. $#char) {
		my $bit = $char[$i];
		my $x = $i % WIDTH_BIN;
		my $y = int ($i / WIDTH_BIN);
		for (1 .. $quarter_turns) {
			($x, $y) = ($y, WIDTH_BIN - $x - 1);
		}
		push (@output, $char[$x + $y * WIDTH_BIN]);
	}
	my $output = join ('', @output);
	$output =~ s/..../sprintf ('%X', oct ("0b$&"))/eg;
	print "$codepoint:$output\n";
}
