#!/usr/bin/perl

# -*- coding: utf-8 -*-

# Author: Franck Sajous
# Copyright: CNRS/CLLE-ERSS
# Last update: 2015-10-06
# See info and licence at: http://redac.univ-tlse2.fr/lexiques/glawi.html

use strict;
use warnings;
use utf8; 
use POSIX qw(floor);

if ( $#ARGV != 3 )
{
    print  ("Usage: $0 xml_dump nbSplit dstDir filePrefix\n");
    die ("\tSplit dump into several files.\n");
} # if ( $#ARGV != 3 )

my $ROOTTAG = "split";

my $xmlDumpFile = $ARGV[0];
my $nbSplit = $ARGV[1];
my $outDir      = $ARGV[2];
my $prefix      = $ARGV[3];

my $nbArticlesPerSplit;

$outDir =~ s/\\\s*$//;

my $nbArticle = 0;
my $nbFile    = 0;
my $currentFile;
my $line;
my $inPage = 0;

&openNewFile ();

binmode (STDOUT, ":encoding(utf8)");
binmode (STDERR, ":encoding(utf8)");

open (INFILE, "<", $xmlDumpFile) or die ("Unable to read: $xmlDumpFile\n");
binmode (INFILE, ":encoding(utf8)");


my $nbTotalArticles = `grep '<page>' $xmlDumpFile |wc -l`;
$nbArticlesPerSplit = 1 + floor($nbTotalArticles / $nbSplit);
#print "nbTotalArticle: $nbTotalArticles \n";
#print "nbArticlesPerSplit: $nbArticlesPerSplit \n";

while ($line = <INFILE>)
{
    if ($line =~ /<page>/)
    {
	$inPage = 1;
	print OUTFILE $line;
    } # if ($line =~ /<page>/)
    elsif ($line =~ /<\/page>/)
    {
	$inPage = 0;
	print OUTFILE $line;
	$nbArticle++;

	&openNewFile () if ($nbArticle >= $nbArticlesPerSplit);
    } # elsif ($line =~ /<\/page>/)
    elsif ($inPage)
    {
	print OUTFILE $line;
    } # elsif ($inPage)
} # while ($line = <INFILE>)

close (INFILE);
close (OUTFILE);

########## END OF MAIN PGM ##########

sub openNewFile ()
{
    if (defined ($currentFile))
    {
	print OUTFILE "</" . $ROOTTAG . ">\n";
	close (OUTFILE);
    } # if (defined ($currentFile))

    $nbFile++;
    $currentFile = $outDir . "/" . $prefix . "_" . $nbFile . ".xml";
    open (OUTFILE, ">", $currentFile) or die ("Unable to write: $currentFile\n");
    binmode (OUTFILE, ":encoding(utf8)");
    print OUTFILE "<" . $ROOTTAG . ">\n";

    $nbArticle = 0;
} # openNewFile ()
