﻿#!/usr/bin/perl -w
use strict;
use warnings;
use utf8;
use open qw(:std :utf8);
use integer;
use Unicode::Normalize;


# Song_seitenzahlen.pl
# 2010-08-24
# Wolfgang Schmidle


# text input

my @text;
while(<>) { push @text, $_; }


# go through the text

my $pb; 
my $ab;
my $n;

my $digit = "[一二三四五六七八九]";
my %chinese = ( 0 => "", 1 => "一", 2 => "二", 3 => "三", 4 => "四", 
							5 => "五", 6 => "六", 7 => "七", 8 => "八", 9 => "九" );  


sub chinMitShi {
	my $n = shift;
	
	my $zehner = $n / 10;
	my $einer = $n % 10;

	# 1 bis 9 ohne shi; 10 bis 19 ohne yi aber mit shi; 20, 30, etc. mit shi:

	if ($zehner == 0) { return $chinese{$einer}; }
	if ($zehner == 1) { return "十$chinese{$einer}"; }
	if ($einer == 0) { return "$chinese{$zehner}十"; } 
	
	# ansonsten mit shi:
		
	return "$chinese{$zehner}十$chinese{$einer}";
}

sub chin {
	my $n = shift;
	
	my $zehner = $n / 10;
	my $einer = $n % 10;
	
	# 1 bis 9 ohne shi; 10 bis 19 ohne yi aber mit shi; 20, 30, etc. mit shi:

	if ($zehner == 0) { return $chinese{$einer}; }
	if ($zehner == 1) { return "十$chinese{$einer}"; }
	if ($einer == 0) { return "$chinese{$zehner}十"; } 
		
	# ansonsten ohne shi:
	
	return "$chinese{$zehner}$chinese{$einer}";
}



foreach (@text) {

	next unless m!<pb file="X06\.01\.(\d\d\d)([AB])" n="(\d+)"/>!;
	$pb = $1;
	$ab = lc $2;
	$n = $3;
	
	my $o = "";
	
	if ($pb >= 1 && $pb <= 3) { $o = chin($pb); }
	
	if ($pb >= 6 && $pb <= 85) { $o = chin($pb-5); }

	if ($pb >= 86 && $pb <= 110) { $o = chin($pb-85); }
	if ($pb >= 111 && $pb <= 113) { $o = chinMitShi($pb-85); }
	if ($pb >= 114 && $pb <= 162) { $o = chin($pb-85); }

	if ($pb >= 163 && $pb <= 184) { $o = chinMitShi($pb-162); }
	if ($pb == 185) { $o.= "二十三　四"; }
	if ($pb == 186) { $o = chin($pb-161); }
	if ($pb == 187) { $o = chinMitShi($pb-161); }
	if ($pb >= 188 && $pb <= 227) { $o = chin($pb-161); }

	if ($o) {
		$o .= $ab;
		s!(<pb[^/]+)/>!$1 o="$o"/>!;
	}
}

# text output

print @text;


# TO DO:
# ...
