#!/usr/bin/perl -w
#
##########################################################################
#
#
$Version = "0.0.2";
#
# Date:    2006-12-04
#
# Author: Mike Constabel <vejoun @ vdrportal . de>
#                        <vejoun @ toppoint . de>
#
# See "eps2xml.pl --help" for help.
#
##########################################################################

###########
# Modules #
###########
use Getopt::Long;
use Pod::Usage;
use File::Basename;
use Encode;
use warnings;

###########

my %Config = (InFile => "", OutFile => "", man => 0, help => 0, quiet => 0);
my @EpisodesFile;

Getopt::Long::Configure ("bundling_override");
GetOptions (\%Config,   'InFile|i=s', 'OutFile|o=s', 'help|h|?', 'quiet|q:+', 'man', 'version');

if ( $Config{version} )				{ print ($0." Version ".$Version."\n"); exit; }
pod2usage(-exitstatus => 0, -verbose => 2)	if ( $Config{man} );
pod2usage(1)					if ( $Config{help} || ! $Config{InFile} );

if ( -d $Config{InFile} && $Config{InFile} !~ /\/$/ ) {
  $Config{InFile} .= "/";
}

if ( -d $Config{OutFile} && $Config{OutFile} !~ /\/$/ ) {
  $Config{OutFile} .= "/";
}

my @Files;

if ( $Config{InFile} =~ /\/$/ && -d $Config{InFile} ) {
  my @Episoden_Dir = glob $Config{InFile}."*.episodes";
  foreach ( @Episoden_Dir ) {
    push(@Files, $_) if ( ! -l $_ );
  }
} elsif ( $Config{InFile} && -f $Config{InFile} ) {
  push(@Files, $Config{InFile});
} else {
  print "Please provide an existing file or a path with parameter -i.\n";
  exit 1;
}

my $InFile = $OutFile = "";
$OutFile = "";

my @Data	= ();
  
push @Data, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<manual type=\"base\">\n<language name=\"Deutsch\">\n<menu>";

foreach ( @Files ) {
  $InFile = $_;
  my @Msg = ();

  my ($SeriesName, $directories, $suffix) = fileparse($_, qr/\.episodes/);

  open (FILE, "<".$InFile) || die("Error opening ".$InFile);
  @EpisodesFile = <FILE>;
  close FILE;

  $SeriesName =~ s/&/&amp;/g;

  push @Data, sprintf("\t<chapter>\n\t\t<name>%s</name>\n\t\t<menu>", encode_utf8($SeriesName) ); #<chapter><name>Staffel 01 - Folge 01-06 (1998)</name><text>");

  my %LineField = ();

  $linenumber		= 0;
  $firstline		= 1;
  my %LastLineField	= ();
  my @TmpData;

  foreach( @EpisodesFile ) {
    chomp;
    $Line = $_;
    $Line =~ s/(\s*$|\r|\n)//g;

    $linenumber++;

    if ( $Line =~ /^#\s*\/?SEASONLIST/ ) { next; }

    my $spacer = '(\t|~|\ {3,})';

    if ( $Line =~ /^\s*(\d+)\s*${spacer}\s*(\d+)\s*${spacer}\s*(\d+)\s*${spacer}\s*(.*?)\s*${spacer}\s*(.*?)\s*$/ || $Line =~ /^\s*(\d+)\s*${spacer}\s*(\d+)\s*${spacer}\s*(\d+)\s*${spacer}\s*(.*?)\s*$/ || $Line =~ /^\s*(\d+)\s*${spacer}\s*(\d+)\s*${spacer}\s*(\d+)\s*$/ ) {
      %LineField = ( Season => $1+0, Episode => $3+0, EpisodeOverAll => $5+0, Subtitle => ( defined $7 && $7 ) ? $7 : "n.n.", Miscellaneous => ( defined $9 && $9 ) ? $9 : "");

      $LineField{Subtitle} =~ s/^\s*n\.?n\.?\s*$/n\.n\./;
      $LineField{Subtitle} =~ s/ +/ /g;
      $LineField{Subtitle} =~ s/&/&amp;/g;
      
      %LastLineField = %LineField unless (%LastLineField);

      if ( ( $LineField{Season} > $LastLineField{Season} && $LineField{Episode} == 1 ) ||
           ( $LineField{Season} == $LastLineField{Season} && $LineField{Episode} == $LastLineField{Episode}+1 ) ||
           $firstline ) {

        if ( $LineField{Season} > $LastLineField{Season} ) {
          push @Data, sprintf("%s\t\t\t<chapter>\n\t\t\t\t<name>Staffel %02i, Folgen %02i bis %02i</name>\n\t\t\t\t<text>", (! $firstline) ? "\t\t\t\t</text>\n\t\t\t</chapter>\n" : "", $LineField{Season} - 1, substr($TmpData[0], 0, 2),  substr($TmpData[$#TmpData], 0, 2) );
          $firstline = 0;
          push @Data, @TmpData;
          @TmpData = ();
        }

        push @TmpData, sprintf("%02i %s", $LineField{Episode}, encode_utf8($LineField{Subtitle}) );
      }
      %LastLineField = %LineField;
    }
  }	

  push @Data, sprintf("%s\t\t\t<chapter>\n\t\t\t\t<name>Staffel %02i, Folgen %02i bis %02i</name>\n\t\t\t\t<text>", (! $firstline) ? "\t\t\t\t</text>\n\t\t\t</chapter>\n" : "", $LineField{Season}, substr($TmpData[0], 0, 2),  substr($TmpData[$#TmpData], 0, 2) );
  $firstline = 0;
  push @Data, @TmpData;
  @TmpData = ();

  push @Data, "\t\t\t\t</text>\n\t\t\t</chapter>\n\t\t</menu>\n\t</chapter>";

}


push @Data, "</menu>\n</language>\n</manual>";

my $Output = join("\n", @Data)."\n";

$Output =~ s/<text>\n/<text>/g;
$Output =~ s/\n\t*<\/text>/<\/text>/g;

$Output =~ s/<text>\n/<text>/g;

print $Output;
      

__END__

