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

# Author: Franck Sajous
# Copyright: CNRS/CLLE-ERSS
# Last update: 2018-04-04
# See info and licence at: http://redac.univ-tlse2.fr/lexicons/tools/

use strict;
use warnings;
use utf8; 
use File::stat;
use File::Spec;

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

if ( $#ARGV != 3 )
{
    print "Usage : ", $0, " GLAWI.xml size(Mo) dstDir filePrefix\n";
    die ("\tSplits GLAWI file into several files of size Mo.\n");
} # if ( $#ARGV != 3 )

my $fileSeparator = File::Spec->catfile('', '');

my $ROOT_TAG = "glawiSplit";

my $glawiFile = $ARGV[0];
my $sizeMax   = $ARGV[1] * (1024 * 1024);
my $outDir    = $ARGV[2];
my $prefix    = $ARGV[3];

my ($nbFile, $inArticle) = (0, 0);
my ($currentFile, $currentTitle, $relevantTitle);
my $line;

$outDir =~ s/($fileSeparator)*\s*$//;
&openNewFile ();

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

while ($line = <GLAWI>)
{
    if ($line =~ /<article>/)
    {
	$inArticle = 1;
    } # if ($line =~ /<article>/)
    elsif ($line =~ /<\/article>/)
    {
	$inArticle = 0;
	&checkOutFileSize ();
    } # elsif ($line =~ /<\/article>/)
    elsif ($inArticle)
    {
	print OUTFILE $line;
    } # elsif ($inArticle)
} # while ($line = <GLAWI>)

close (GLAWI);
print OUTFILE "</" . $ROOT_TAG . ">\n";
close (OUTFILE);

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

    $nbFile++;
    $currentFile = $outDir . $fileSeparator . $prefix . "_" . $nbFile . ".xml";

    open (OUTFILE, ">", $currentFile) or die ("Unable to write: $currentFile\n");
    binmode (OUTFILE, ":encoding(utf8)");

    print OUTFILE "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
    print OUTFILE "<" . $ROOT_TAG . ">\n";
} # openNewFile ()

sub checkOutFileSize ()
{
    my $currentSize = stat($currentFile)->size;

    &openNewFile () if ($currentSize > $sizeMax);
} # checkOutFileSize ()
