#!/usr/bin/perl
<<DOC;
Usage:
perl xml_to_DTM.pl nom_du_fichier_corpus.xml
DOC

use strict;
use XML::Parser;
use encoding("utf-8");

open( DTM1, ">:utf8", "$ARGV[0]_DTM.txt" );
open( DTM2, ">:utf8", "$ARGV[0]_variables_DTM.txt" );
open( INDEX, ">:utf8", "index_textes.txt" );

# variables communes
my %variables;
# les infirmations sur les textes
my %textes;
my $current_source;
my $t = 0;

my $parser = new XML::Parser(Handlers => {
											Start => \&start,
                                          	Char  => \&text,
										  	End   => \&end });
$parser->parsefile( $ARGV[0] );


my @variables = keys %variables;
my @variables_sorted  = sort @variables;

foreach ( @variables_sorted ){
	print DTM2 "     ", $_, "\n";
}

foreach my $num_t ( sort { $a <=> $b } keys %textes ){

	print DTM1 "\n'$num_t'      ";
	
	foreach ( @variables_sorted ){
		if( exists( $textes{$num_t}{$_} ) ){
			print DTM1 $textes{$num_t}{$_}, " ";
		}
		else{
			print DTM1 "0 ";
		}
	}
}


sub start {
	my ( $self, $el, $attr, $val, $attr2, $val2 ) = @_;
	if( $el eq 'TEI.2' ){
		# numéro du texte
		$t++;
	}
	
	if( $el eq 'sourceDesc' ){
		$current_el = $el;
		print INDEX $t, "\t";
	}
	
	# Si vous voulez rajouter les tags à compter, c'est ici:
	# à rajouter à la fin de la liste :
	# or ($el eq 'nom_de_tag')
	elsif( ($el eq 'p') or ($el eq 'div') or ($el eq 'head') or ($el eq 'front') or ($el eq 'table') or ($el eq 'list') or ($el eq 's')){
		if( exists( $textes{$t}{$el} )){
			$textes{$t}{$el}++;
			$variables{$el}++;
		}
		else{
			$textes{$t}{$el} = 1;
			$variables{$el}++;
		}
	}
	elsif( $el eq 'w' ){
		if( $attr eq 'ana' ){
			if( exists($textes{$t}{$val} ) ){
				$textes{$t}{$val}++;
				$variables{$val}++;
			}
			else{
				$textes{$t}{$val} = 1;
				$variables{$val}++;
			}
		}
		elsif( $attr2 eq 'ana' ){
			if( exists( $textes{$t}{$val2} ) ){
				$textes{$t}{$val2}++;
				$variables{$val2}++;
			}
			else{
				$textes{$t}{$val2} = 1;
				$variables{$val2} = 1;
			}
		}
	}
}

sub end {
	my ( $self, $el ) = @_;
	if( $el eq 'sourceDesc' ){
	    print INDEX $current_source;
		$current_source = '';
		print INDEX "\n";
	}
}

sub text {
	my ( $self, $el ) = @_;
	if( $current_el eq 'sourceDesc' ){
		chomp($el);
		$current_source .=$el.' ';
	}
}
