
sub stars
{
  my $count=shift;
  my $i=0;
  my $line = "";
  for ($i;$i < $count ; $i++) {
    $line .= "*";
  }
  return $line;
}

################################################################################
# Get xml-files from tvmovie online
################################################################################
sub GetFiles {
	my $anzahl =0;
        foreach $sender (keys(%chan)) {
		if ($chan_wanted{$sender} eq "1") {
			$anzahl++;
		}
	}

	return unless $anzahl;


	for ($days=0;$days < $days2download ;$days++) {
		doexit() if $please_exit;

		$now_string = DateCalc($heute,"+ $days tage",\$err,0);
		$now_string = UnixDate($now_string, "%Y%m%d");
		foreach $rfcid (keys %chan) {
			doexit() if $please_exit;

			# Kanal für tvmovie konfiguriert ?
			next if $chan_wanted{$rfcid} != "1";

			$filenamexml = "$now_string"."_$chan{$rfcid}[1].xml";
			$filenamexmltvm = "$filenamexml.tvm";
			$filenamexmlgz = "$filenamexml.gz";

			if (! -e "$downloadprefix"."tvmovie_"."$filenamexml") {
			print "tvmovie: downloading $baseurl$filenamexmltvm for $rfcid\n";
			my $dummy=GetContent("$baseurl$filenamexmltvm","$downloadprefix"."tvmovie_"."$filenamexmltvm",0,0);
			unscramble ("$downloadprefix"."tvmovie_"."$filenamexmltvm","$downloadprefix"."tvmovie_"."$filenamexmlgz");
			system("gunzip", "-f", "$downloadprefix"."tvmovie_"."$filenamexmlgz") == 0
				or warn "gunzip failed";
			}
		}
	}
}

################################################################################
# Get update xml-files from tvmovie online
################################################################################
sub GetUpdateFiles {
	$now_string = UnixDate($heute, "%Y%m%d");
	foreach $rfcid (keys %chan) {
		doexit() if $please_exit;

		# Kanal für tvmovie konfiguriert ?
		next if $chan_wanted{$rfcid} != "1";

		$filenamexml = "$now_string"."_$chan{$rfcid}[1].xml";
		$filenamexmltvm = "$filenamexml.tvm";
		$filenamexmlgz = "$filenamexml.gz";

		# Updatefiles werden IMMER neu geladen
		unlink "$updateprefix"."tvmovie_"."$filenamexmltvm"; 
		unlink "$updateprefix"."tvmovie_"."$filenamexmlgz"; 
		unlink "$updateprefix"."tvmovie_"."$filenamexml";

		if (! -e "$updateprefix"."tvmovie_"."$filenamexml") {
			print "tvmovie: downloading update file $aendurl"."tvmovie_"."$filenamexmltvm for $rfcid\n";
			my $dummy=GetContent("$aendurl$filenamexmltvm","$updateprefix"."tvmovie_"."$filenamexmltvm",0,0);
			unscramble ("$updateprefix"."tvmovie_"."$filenamexmltvm","$updateprefix"."tvmovie_"."$filenamexmlgz");
			system("gunzip", "-f", "$updateprefix"."tvmovie_"."$filenamexmlgz") == 0
				or warn "gunzip failed";
		}
	}
}

sub unscramble
{
    #Position .gz, Positon .tvm, Länge
    #0x0000, 0x006A, 6
    #0x0006, 0x0064, 6
    #0x000C, 0x0070, 88
    #0x0064, 0x0320, 17
    #0x0075, 0x0011, 83
    #0x00C8, 0x012C, 100
    #0x012C, 0x0000, 17
    #0x013D, 0x0331, 183
    #0x01F4, 0x0258, 200
    #0x02BC, 0x0190, 200
    #0x0384, 0x00C8, 100
    #0x03E8, 0x03E8, Rest
    my $oldfilename = shift;
    my $filename = shift;
    print "tvmovie: descrambling $oldfilename to $filename\n";
    $size = -s $oldfilename;
	if ($size <= 1000) {
        rename $oldfilename, $filename;
        return;
    }

	open(OUT, "> $filename") || die "cannot write $filename: $!";
    open(IN,  "< $oldfilename") || warn "cannot read $oldfilename: $!";
    $outstring = "";
    seek (IN,0x006a,0) && read (IN,$outstring,  6) && print OUT $outstring;
    seek (IN,0x0064,0) && read (IN,$outstring,  6) && print OUT $outstring;
    seek (IN,0x0070,0) && read (IN,$outstring, 88) && print OUT $outstring;
    seek (IN,0x0320,0) && read (IN,$outstring, 17) && print OUT $outstring;
    seek (IN,0x0011,0) && read (IN,$outstring, 83) && print OUT $outstring;
    seek (IN,0x012c,0) && read (IN,$outstring,100) && print OUT $outstring;
    seek (IN,0x0000,0) && read (IN,$outstring, 17) && print OUT $outstring;
    seek (IN,0x0331,0) && read (IN,$outstring,183) && print OUT $outstring;
    seek (IN,0x0258,0) && read (IN,$outstring,200) && print OUT $outstring;
    seek (IN,0x0190,0) && read (IN,$outstring,200) && print OUT $outstring;
    seek (IN,0x00c8,0) && read (IN,$outstring,100) && print OUT $outstring;
    seek (IN,0x03e8,0) && read (IN,$outstring,10240000) && print OUT $outstring;
    close IN;
    close OUT;
    return;
exit;
}

sub ReadXMLFile
{
	$mode = shift;
	open(XMLFILE, "$xmlfile") || warn "cannot open $xmlfile: $!";
	undef $xml;
	while(<XMLFILE>) {
		chomp;
		s|^\s*(.*?)\s*$|$1|g;
		$xml .= $_;
		}
	close (XMLFILE);
		$xml=xmltvtranslate($xml);
	
	# Aufraeumen
	$xml =~ s|^.*?(<Sendung>.*</Sendung>).*?$|$1|sig;		

	while($xml =~ s|^(<Sendung>.*?</Sendung>)||) {
		undef $event;
		$event=$1;

		# diverse TVMovie-Sonderzeichen entfernen
		$event =~ s|\342\200\242|*|g;
		$event =~ s|\342\200\246|...|g;
		$event =~ s|\342\200\223|-|g;
		$event =~ s|\342\200\224|-|g;
		$event =~ s|\342\200\236|'|g;
		$event =~ s|\342\200\234|'|g;
		$event =~ s|\342\200\231|'|g;
		$event =~ s|\342\202\254|Eur|g; 
		$event =~ s|\342\200\240|gestorben |g;
		$event =~ s|\277||g; # umgekehrtes Fragezeichen
		$event =~ s|\240||g;
		
		my $event_id=$title=$subtitle=$datum=$zeit=$dauer= "";
		my $tmptext=$compare=$tmpwertung2=$origtitle=$kategory=$texts="";
		my $genre=$land=$jahr=$fsk=$keywords=$tmptext=$text=$textt=$kritik="";
		my $tmpwertung=$wertung=$flags=$kurztext=$darsteller=$regie=$tmpdata= "";
		my $summary=$audio=$format=$rate=$infotext=$type="";
		my $imagecounter=0;
		$event_id = $1%65536		if $event =~ m|<SendungID>(.*?)</SendungID>|;
		$title = $1			if $event =~ m|<Titel>(.*?)</Titel>|;
		$datum = $1			if $event =~ m|<Datum>(.*?)</Datum>|;	# 2003-10-30
		$zeit = $1			if $event =~ m|<Zeit>(.*?)</Zeit>|;		# 20:15:00
		$dauer = $1	* 60		if $event =~ m|<Dauer>(.*?)</Dauer>|;
		$audio = "Dolby"		if $event =~ m|<dolby />|;
		$audio = "DolbyDigital"		if $event =~ m|<dolbydigital />|;
		$audio = "Stereo"		if $event =~ m|<stereo />|;
		$audio = "Surround"		if $event =~ m|<surroundsound />|;
		$audio = "Zweikanal"		if $event =~ m|<zweikanal />|;
		$audio .= " - O-Ton"		if $event =~ m|<originaltitel />|;
		$format = "16:9"		if $event =~ m|<breitband />|;
		$flags .= " [Premiere]"		if $event =~ m|<tvpremiere />|;
		$flags .= " [SchwarzWeiß]"	if $event =~ m|<sw />|;
		$flags .= " [Untertitel]"	if $event =~ m|<untertitel />|;
		$flags .= " [Live]"		if $event =~ m|<live />|;
		$flags .= " [Neu]"		if $event =~ m|<neu />|;
		$rate = "Tipp"			if $event =~ m|<BewKategorieID>Tipp</BewKategorieID>|;
		$rate = "TopTipp"		if $event =~ m|<BewKategorieID>TopTipp</BewKategorieID>|;
		$rate = "TagesTipp"		if $event =~ m|<BewKategorieID>TagesTipp</BewKategorieID>|;
		$subtitle = $1			if $event =~ m|<UnterTitel>(.*?)</UnterTitel>|;
		$genre = $1			if $event =~ m|<GenreText>(.*?)</GenreText>|;
		$genre =~ s/film$//; $genre =~ s/-?serie$//i; $genre =~ s/reihe$//i; $genre =~ s/show$//i; $genre =~ s/\/$//; $genre =~ s/-$//;
		$kategory = $1			if $event =~ m|<RZPKategorieID>(.*?)</RZPKategorieID>|;
		$origtitle = $1			if $event =~ m|<OriginalTitel>(.*?)</OriginalTitel>|;
		$land = $1			if $event =~ m|<Land>(.*?)</Land>|;
		$jahr = $1			if $event =~ m|<Jahr>(.*?)</Jahr>|;
		$fsk = $1			if $event =~ m|<FSK>(.*?)</FSK>|;
		$infotext = $1			if $event =~ m|<Text Kategorie="Info"><Text>(.*?)</Text>|;
		$textt .= $1 . "|"		if $event =~ m|<Text Kategorie="Thema"><Text>(.*?)</Text>|;
		$texts = $1			if $event =~ m|<Text Kategorie="Sendertext"><Text>(.*?)</Text>|;
		$kurztext = $1			if $event =~ m|<Text Kategorie="Kurzbeschreibung"><Text>(.*?)</Text>|;
		$kurztext = ""			if $kurztext =~ m/Lauftext/;
		$kritik = "Kurzkritik: $1"	if $event =~ m|<Text Kategorie="Kurzkritik"><Text>(.*?)</Text>|;
		$type = "Serie"			if $event =~ m|<Folge>|;
		$type = "Sport"			if $event =~ m|<Sport>|;
		$type = "Show"			if $event =~ m|<TVShow>|;
		$type = "Film"			if $event =~ m|<Film>|;
		$type = "Kultur"		if $event =~ m|<Kultur>|;
		$type = "Spielfilm"		if $event =~ m|<Spielfilm>|;
		$regie = "$2 $1"		if $event =~ m|<Mensch Kategorie="Regisseur"><Name>(.*?)</Name><Vorname>(.*?)</Vorname></Mensch>|;
		
		# evtl. Mehrere Inhalte. Dann den laengeren nehmen
		while ($event =~ s|<Text Kategorie="Inhalt"><Text>(.*?)</Text></Text>||) {
			$text = $1 if length($1) > length($text);
			}

		# Alle Schauspieler einsammeln
		while ($event =~ s|<Mensch Kategorie="Schauspieler">(.*?)</Mensch>||) {
			$darstellertmp=$1;
			$darsteller .= ", $1"	if $darstellertmp =~ m|<Vorname>(.*?)</Vorname>|;
			$darsteller .= " $1"	if $darstellertmp =~ m|<Name>(.*?)</Name>|;
			$darsteller .= " ($1)"	if $darstellertmp =~m|<RollenName>(.*?)</RollenName>|;
			}
		$darsteller =~ s|^, ||; # Saeubern

		while ($event =~ s|<Bewertung>(.*?)</Bewertung>||) {
			$bewertungtmp = $1;
			# Tipps haben keine Bewertung
			next if $bewertungtmp =~ m|Tipp</BewKategorieID>|;

			$bewertungcat =$1 	if $bewertungtmp =~ m|<BewKategorieID>(.*?)</BewKategorieID>|;
			$wertung .= " / $bewertungcat " . stars($1) if $bewertungtmp =~ m|<Wertung>(.*?)</Wertung>|;
			}
		$wertung =~ s|^ / ||; # Saeubern

		# Bilderdownload	
		while ($event =~ s|<BildURL>(.*?)</BildURL>||) {
			$image = $1;
			if ($imagecounter == 0) {
				$targetimage = $event_id;
				$imagecounter++;
			} else {
				$targetimage = $event_id . "_" . $imagecounter;
				$imagecounter++;
				}
				
			if ($image && $writeimages && ! -e "$imagepath/$targetimage$imagetype") {
				print "schreibe $tvmimgurl$image nach $imagepath/$targetimage$imagetype ..\n";
				my $dummy=GetContent("$tvmimgurl$image","$imagepath/$targetimage.jpg",0,0);

				if (length($dummy)) {
					open(IMAGE, "$imagepath/$targetimage.jpg");
					our $ckimage = Image::Magick->new;
					my $err=$ckimage->Read(file=>\*IMAGE);
					close(IMAGE);
					unlink "$imagepath/$targetimage.jpg";

					if (! $err) {
						$ckimage->Resize($imagesize);
						$ckimage->Write(filename=>"$imagepath/$targetimage$imagetype");
						} else {
						warn "##### $err ####";
						}
					}
				}
			}

		doexit() if $please_exit;
		$start = UnixDate("$datum $zeit", "%s");
		next if (UnixDate($heute, "%s") > $start+$dauer); # ist die Sendung schon vorbei ?
		
		$flags .= " [16:9]" if $format;
		$flags .= " [$audio]" if $audio;
		$flags .= " [$rate]" if $rate;
		$format = "4:3" unless $format;

		$text=$texts if $texts ne "";
		$text =~ s|</Text>||;

		$text     = pack "U0C*", unpack "C*", $text;
		$kurztext = pack "U0C*", unpack "C*", $kurztext;
		$textt    = pack "U0C*", unpack "C*", $textt;
		$infotext = pack "U0C*", unpack "C*", $infotext;
		$summary = "";
		$summary .= "$kurztext.|"		if $kurztext;
		$summary .= "Thema: $textt|" 		if $textt;
		$summary .= "$text" 			if $text;
		$summary .= "||Info: $infotext|"	if $infotext;

		makeEPGevent(	$event_id,$start,$dauer,$title,$subtitle,$id,$mode,
				$summary,$regie,$darsteller,$genre,$type,$country,
				$jahr,$audio,$format,$flags,$origtitle,$fsk,"",$rate,
				"",$kritik,$wertung);

		$id++;
		}
	}


# Process info from XMLTV file / channels.conf 
sub ReadExternalEPG_tvmovie
{
	GetFiles();
	GetUpdateFiles() unless ($useupdate == 0);

	foreach $sender (keys(%chan)) {
		# Kanal für tvmovie konfiguriert ?
		next if $chan_wanted{$sender} != "1";
		doexit() if $please_exit;

		$id=1;
		$firstchannel=1;
		$found_orig_event=0;
		$orig_epg_id=0;
		$laststreamid = 0;
		our @events = "";
		# Find XML events
		$state="";

		my ($state,$event_id,$title,$subtitle,$datum,$zeit,$dauer,$tmptext,$text,$kritik,$tmpwertung,$wertung,$flags,$kurztext,$compare,$darsteller,$regie,$tmpdata) = "";
		for ($days=0;$days < $days2download ;$days++) {
			doexit() if $please_exit;

			$now_string = DateCalc($heute,"+ $days tage",\$err,0);
			$now_string = UnixDate($now_string, "%Y%m%d");
			$xmlfile = "$downloadprefix"."tvmovie_"."$now_string"."_"."$chan{$sender}[1].xml";
			print "tvmovie: reading $downloadprefix"."tvmovie_"."$now_string"."_"."$chan{$sender}[1].xml into memory\n";
			ReadXMLFile("original");
		} # for ($days=0;$days < $days2download ;$days++) {

		# EPG-Daten sortieren
		my($last) = 0;
		my(@temp);
		for(sort({ $a->{start} <=> $b->{start} } @events)) {
			doexit() if $please_exit;
			next if($last == $_->{start});
			push(@temp, $_); 
			$last = $_->{start};
		}
		$XML{$sender} = [ @temp ];

		next unless ($useupdate == 1);
		# XML enthält jetzt alle Daten des Senders. jetzt Updatefiles parsen und Einträge aktualisieren
		$now_string = UnixDate($heute, "%Y%m%d");
		$xmlfile = "$updateprefix"."tvmovie_"."$now_string"."_"."$chan{$sender}[1].xml";
		print "tvmovie: reading $updateprefix"."tvmovie_"."$now_string"."_"."$chan{$sender}[1].xml into memory\n";
		ReadXMLFile("update");

		# EPG-Daten sortieren, jetzt mit aktualisierte Sendungen
		my($last) = 0;
		my(@temp);
		for(sort({ $a->{start} <=> $b->{start} } @events)) {
			doexit() if $please_exit;
			push(@temp, $_); 
			$last = $_->{start};
		}
		$XML{$sender} = [ @temp ];
		# XML enthält jetzt auch die Änderungen, 
		# aber leider auch die durch updates ausgefallenen Sendungen ..


		# Updatesendung, die andere Sendungen ausblendet?
		for ($j=0; $j<$#{$XML{$sender}}-1;$j++) {
			if (@{$XML{$sender}}[$j]->{state} eq 2 &&				# aktualisierte Sendung
				@{$XML{$sender}}[$j+1]->{state} eq 1 &&				# Originalsendung
				@{$XML{$sender}}[$j+1]->{start}  >= @{$XML{$sender}}[$j]->{start} &&
				@{$XML{$sender}}[$j+1]->{stop}  <= @{$XML{$sender}}[$j]->{stop}) {
# wird auskommentiert, weil nichtmal der clickfinder das korrekt kann.
#
#				@{$XML{$sender}}[$j+1]->{state}        = 0; # gelöschte Sendung
# print "@{$XML{$sender}}[$j+1]->{title} @{$XML{$sender}}[$j+1]->{event_id} @{$XML{$sender}}[$j+1]->{state} wird gelöscht\n";
			}
		} # for 



	
	} # foreach $sender (keys(%chan))
} # sub ProcessEpg

return 1;
