# -*- 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/lexicons/glawi/tools/

use strict;
use warnings;
use utf8;

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

if ( ($#ARGV < 1) || ($#ARGV > 2))
{
    print ("Usage: $0 GLAWIfile articleTitle [outFile]\n");
    die  ("\tExtracts the (single) article matching the specified title and prints the result into outFile or STDOUT.\n");
} # if ( ($#ARGV < 1) || ($#ARGV > 2))

my $glawiFile     = $ARGV[0];
my $searchedTitle = $ARGV[1];
my $outFile       = $ARGV[2];

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

if (defined ($outFile))
{
    open (OUTFILE, ">", $outFile) or die ("Unable to write: $outFile\n");
    binmode (OUTFILE, ":encoding(utf8)");
} # if (defined ($outFile))

my ($line, $currentTitle);
my $currentBuffer = "";
my $found = 0;

while (!$found && ($line = <INFILE>))
{
    if ($line =~ /<article>/)
    {
	$currentBuffer = $line;
    } # if ($line =~ /<article>/)
    else
    {
	$currentBuffer .= $line;

	if ($line =~ /<title>(.*?)<\/title>/)
	{
	    $currentTitle = $1;
	} # if ($line =~ /<title>(.*?)<\/title>/)
	elsif ($line =~ /<\/article>/)
	{
	    if ($currentTitle eq $searchedTitle)
	    {
		$found = 1;

		if (defined ($outFile))
		{
		    print OUTFILE $currentBuffer;
		} # if (defined ($outFile))
		else
		{
		    print $currentBuffer;		
		} # if (defined ($outFile)) else {
	    } # if ($currentTitle eq $searchedTitle)
	} # elsif ($line =~ /<\/article>/)
    } # if ($line =~ /<article>/) else {
} # while (!$found && ($line = <INFILE>))

close (OUTFILE) if (defined ($outFile));
close (INFILE);

