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

# Author: Franck Sajous
# Copyright: CNRS/CLLE-ERSS
# Last update: 2018-03-21
# 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 labelValueRegexp [outFile]\n");
    die  ("\tExtracts titles of articles having a definition including a label whose value matches the specified one.\n");
} # if ( ($#ARGV < 1) || ($#ARGV > 2))

my $glawiFile  = $ARGV[0];
my $labelValue = $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, $matches, $currentTitle);
my $currentBuffer = "";
my ($inArticle, $inGloss) = (0, 0);

while ($line = <INFILE>)
{
    if ($line =~ /<article>/)
    {
	$inArticle = 1;
	$matches = 0;
	$currentBuffer = $line;	
	&parseLine ($'); #'
    } # if ($line =~ /<article>/)
    elsif ($inArticle)
    {
	$currentBuffer .= $line;

	if ($line =~ /<\/article>/)
	{
	    &parseLine ($`);
	    $inArticle = 0;
	    if ($matches)
	    {
		if (defined ($outFile))
		{
		    print OUTFILE $currentTitle . "\n";
		} # if (defined ($outFile))
		else
		{
		    print $currentTitle . "\n";		
		} # if (defined ($outFile)) else {
	    } # if ($matches)
	} # elsif ($line =~ /<\/article>/)
	else
	{
	    &parseLine ($line);
	} # elsif ($line =~ /<\/article>/) else {
    } # elsif ($inArticle)
} # while (<INFILE>)

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

sub parseLine ()
{
    my $currentLine = shift;

    if ($currentLine =~ /<title>(.*?)<\/title>/)
    {
	$currentTitle = $1;
    } # if ($currentLine =~ /<title>(.*?)<\/title>/)
    elsif ($currentLine =~ /<gloss>/)
    {
	my ($l, $r) = ($`, $'); #'
	&parseLine ($l);
	$inGloss = 1;
	&parseLine ($r);
    } # elsif ($currentLine =~ /<gloss>/)
    elsif ($currentLine =~ /<\/gloss>/)
    {
	my ($l, $r) = ($`, $'); #'
	&parseLine ($l);
	$inGloss = 0;
	&parseLine ($r);
    } # elsif ($currentLine =~ /<\/gloss>/)
    elsif ($inGloss)
    {
	if ($line =~ /<label .*?value="([^"]*?)"/)
	{
	    my $currentValue = $1;
	    $matches = $matches || ($currentValue =~ /$labelValue/i);
	} # if ($line =~ /<label .*?value="([^"]*?)"/)
    } # elsif ($inGloss)
} # parseLine ()
