#!/usr/bin/perl

use warnings;
use strict;

my $f_in = $ARGV[0];
my $f_out = $ARGV[1];

if ( ! $ARGV[1] ) {
 print "Usage: $0 url outfile\n";
 exit 1;
}

my $agent = 'Mozilla/5.0 (iPad; U; CPU OS OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B367 Safari/531.21.10';
my $html = `curl -s -A "$agent" "$f_in"`;
#print $html;
$html =~ m/data-media\s*=\s*"(.+?)".*/mg;
my $master = $1;
#print "$master\n";
$html =~ m/data-subtitlesurl\s*=\s*"(.+?)".*/mg;
my $tv = 'http://tv.nrk.no';
my $suburl = $tv.$1;
my $srt = html2srt($suburl);
open OUT, ">$f_out.srt" or die "Cannot open $f_out.srt for write: $!";
print OUT $srt;
close OUT;
my $index_4 = `curl -s -A "$agent" "$master" | grep index_4_av.m3u8 |sed 's/"//g'`;
my $cliplist = `curl -s -A "$agent" "$index_4" |grep -v ^#`;
my @cliplist = split "\n", $cliplist; 
foreach my $clip ( @cliplist ) {
 print "#";
 my $ret = `curl -s -A "$agent" --limit-rate 1m "$clip" >> "$f_out.mts"`;
 sleep 1;
}

# ingvar

sub html2srt {

use Text::Iconv;
use HTML::TokeParser::Simple;
use utf8;

my $subtitles_xml = shift;
my $converter = Text::Iconv->new("UTF-8", "ISO-8859-1");
my $tp = HTML::TokeParser::Simple->new(url => $subtitles_xml);
my $counter = 0;
my $text = "";
my $style_i = 0;
my $ret = "";
while (my $token = $tp->get_token) {
	if ($token->as_is =~ /
			<p\s+
			begin="(\d\d):(\d\d):(\d\d\.\d\d?\d?)"\s+
			dur="(\d\d):(\d\d):(\d\d\.\d\d?\d?)"
		/x) {
		my $tehh = $1 + $4; # Time End Hour
		my $temm = $2 + $5; # Time End Minute
		my $tess = $3 + $6; # Time End Second.Millisecond

		if ($tess > 59.999) {
			++$temm;
			$tess -= 60;
		}
		if ($temm > 59) {
			++$tehh;
			$temm -= 60;
		}

		my $start = sprintf("%02d:%02d:%06.3f", $1, $2, $3);
		my $end = sprintf("%02d:%02d:%06.3f", $tehh, $temm, $tess);

		# Now, find the text.
		# Should probably rather use something like HTML::FormatText
		$text = "";
		while ($token = $tp->get_token) {
			# Skip an empty newline
			next if $token->as_is =~ /\n\s*$/;
			# Replace HTML newline with ASCII counterpart.
			if ($token->is_start_tag('br')) {
				$text .= "\n";
				next;
			}
			# Skip closing BR-tag
			next if $token->is_end_tag('br');
			# Replace style span styled tags with SubRip-tags
			# others with space. (Haven't seen bold, underline or font on NRK)
			if ($token->is_start_tag('span')) {
				if ($token->get_attr('style') eq 'italic') {
					$style_i = 1;
					$text .= "<i>";
				} else {
					$text .= " ";
				}
				next;
			}
			# Close Style-tags
			if ($token->is_end_tag('span')) {
				if ($style_i) {
					$style_i = 0;
					$text .= "</i>";
				}
				next;			
			}

			# Store the rest
			$text .= $token->as_is 
				unless $token->is_tag;

			last if $token->as_is =~ /<p begin/ 
				|| $token->is_end_tag('p');
		}

		# Totem and mplayer wants iso8859-1, so we convert, but 
		# hyphen is inconvertible. Also; NRK-subs does not use space 
		# after hyphen which (I) find bad to read.
		$text =~ s/—/-/g;
		$text =~ s/(^|\n)-(?=[^\s])/$1- /g;

		# Whitespace fix
		#$text =~ s/^\s+//g;	# Remove leading spaces
		#$text =~ s/\n\s+/\n/g;	# Ditto within a line
		$text =~ s/> />/g;	# Remove space after > tag
		$text =~ s/  / /g;	# Remove double spaces, may come from 
							# span tags

		# Finally, produce .srt output
		# Position can be added after $end (before \n) – but I see no 
		# effect of positioning in mplayer, VLC etc.
		# if (style_pos=left ) $pos = "X1:100 X2:100 Y1:100 Y2:100";
		$ret .= ++$counter . "\n" . 
			"$start --> $end\n" . 
			$converter->convert("$text") . "\n\n";
	}
   }
   return $ret;
}
