#!/usr/bin/perl
#require 5.008;
our $VERSION = "0.01"; # 2010-03-15

use utf8;
use strict;
use warnings;

use Image::Magick;

our $SHIFT_TIME = 0.0;

my $line = 0;
my $num = 1;
my $cont = 0;

binmode(STDIN, ":utf8");
binmode(STDOUT, ":utf8");

while (<>) {
  s/\x0a$//s;
  s/\x0d$//s;

  $line++;

  if (/^\s*\#/) {
    next;
  }
  
  if (/^\s*$/) {
    if ($cont) {
      $cont = 0;
      $num++;
      print "\n";
    }
  } else {
    if (! $cont) {
      print "$num\n";
      $cont = 1;
    }

    if (/\s*-->\s*/) {
      my $s = $`;
      my $e = $';
      $s = norm_time($s);
      $e = norm_time($e);
      print "$s --> $e\n";
    } else {
      print norm_line($_) . "\n";
    }
  }
}
print "\n";

sub norm_time {
  my ($s) = @_;
  $s =~ s/^\s+//;
  $s =~ s/\s+$//;

  my $t = 0;

  if ($s =~ /(.*):(.*):(.*)\.(.*)/) {
    $t = $1 * 60 * 60 + $2 * 60 + $3 + ("0." . $4);
  } elsif ($s =~ /(.*):(.*)\.(.*)/) {
    $t = $1 * 60 + $2 + ("0." . $3);
  } elsif ($s =~ /(.*):(.*)/) {
    $t = $1 * 60 + $2;
  } else {
    die "Illegal format time: $s";
  }

  $t += $SHIFT_TIME;

  my $h = int($t / (60 * 60));
  $t -= $h * 60 * 60;
  my $m = int($t / 60);
  $t -= $m * 60;
  my $sec = int($t);
  $t -= $sec;
  my $ms = sprintf("%.03g", $t);
  $ms =~ s/^0//;
  $ms =~ s/^\.//;
  $ms .= "0" x (3 - length($ms));

  return sprintf("%d:%02d:%02d.%s", $h, $m, $sec, $ms);
}

sub norm_line {
  my ($s) = @_;
  
  $s =~ s/\{ss\}/\x{DF}/sg;
  $s =~ s/a\"/\x{E4}/sg;
  $s =~ s/o\"/\x{F6}/sg;
  $s =~ s/u\"/\x{FC}/sg;
  $s =~ s/A\"/\x{C4}/sg;
  $s =~ s/O\"/\x{D6}/sg;
  $s =~ s/U\"/\x{DC}/sg;

  return $s;
}
