#!/usr/bin/env perl
# Convert Serbian Cyrillic text from stdin to Serbian Latin at stdout.
#
# Input text must be UTF-8 encoded, and output is too.
#
# NOTE: This script is used instead of Gettext's own recode-sr-latin because
# the latter cannot be forced to use UTF-8 independent of the locale setup.
# Remove this script when Gettext's recode-sr-latin becomes capable of that.
#
# Chusslove Illich <caslav.ilic@gmx.net>
# Last change: $Date$
# (first use June 30th, 2008.)

use strict;
use warnings;
use utf8;

binmode(STDIN, ":utf8");
binmode(STDOUT, ":utf8");

sub show_usage {
    die "Usage: $0\n";
}

@ARGV == 0 or show_usage();

# Transliteration table Serbian Cyrillic->Latin.
my %dict_c2l = (
    'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'ђ' => 'đ',
    'е' => 'e', 'ж' => 'ž', 'з' => 'z', 'и' => 'i', 'ј' => 'j', 'к' => 'k',
    'л' => 'l', 'љ' => 'lj','м' => 'm', 'н' => 'n', 'њ' => 'nj','о' => 'o',
    'п' => 'p', 'р' => 'r', 'с' => 's', 'т' => 't', 'ћ' => 'ć', 'у' => 'u',
    'ф' => 'f', 'х' => 'h', 'ц' => 'c', 'ч' => 'č', 'џ' => 'dž','ш' => 'š',
    'А' => 'A', 'Б' => 'B', 'В' => 'V', 'Г' => 'G', 'Д' => 'D', 'Ђ' => 'Đ',
    'Е' => 'E', 'Ж' => 'Ž', 'З' => 'Z', 'И' => 'I', 'Ј' => 'J', 'К' => 'K',
    'Л' => 'L', 'Љ' => 'Lj','М' => 'M', 'Н' => 'N', 'Њ' => 'Nj','О' => 'O',
    'П' => 'P', 'Р' => 'R', 'С' => 'S', 'Т' => 'T', 'Ћ' => 'Ć', 'У' => 'U',
    'Ф' => 'F', 'Х' => 'H', 'Ц' => 'C', 'Ч' => 'Č', 'Џ' => 'Dž','Ш' => 'Š',
    # accented (the keys are now 2-char):
    'а̑' => 'â', 'о̑' => 'ô',
);

while (<STDIN>) {
    my $text = $_;
    my $tlen = length($text);
    my $ntext = "";
    for (my $i = 0; $i < $tlen; ++$i) {
        my $c = substr($text, $i, 1);
        my $c2 = substr($text, $i, 2);
        my $r = ($dict_c2l{$c2} or $dict_c2l{$c});
        if ($r) {
            my $cp = $i + 1 < $tlen ? substr($text, $i + 1, 1) : "";
            my $cn = $i > 0 ? substr($text, $i - 1, 1) : "";
            if (    length($r) > 1 and $c =~ /[[:upper:]]/
                and ($cn =~ /[[:upper:]]/ or $cp =~ /[[:upper:]]/))
            {
                $ntext .= uc($r);
            } else {
                $ntext .= $r;
            }
        } else {
            $ntext .= $c;
        }
    }
    print $ntext;
}
