#!/usr/bin/perl
			$version="1.5"; $date="24 Aug 2018"; #  by Nick Manini
sub print_help {
    print STDERR <<EOF;
accenti: fix latex accents according to ITALIAN rules
	(corregge gli accenti latex secondo le regole dell\'ITALIANO)

USAGE   : accenti file_with_doubtful_accents.tex [-s]
OPTIONS :
-s	: output using special latin1 characters for accented letters
-h	: print this help
			               version $version, $date    
EOF
    return;
}

$input="-";
$spe=0;

while($p=shift(@ARGV)){
# [ file ] check existence of 'file'
    if($p=~/^[^\-]/){
	if($input ne "-"){
	    die "specify only one input file!\n";
	}
	if(!(-e  $p)){
	    die "file $p cannot be accessed\n";
	}
	$input=$p;
	next;
    }
# [-s] use special ascii characters for accented letters
    if($p eq "-s"){
	$spe=1;
	next;
    }
# [-h] printa un breve help
    if($p eq "-h"){
	print_help;
	exit;
    }
    print_help;
    print STDERR "Error: invalid option $p\n ";
    exit;
}



$narg=$#ARGV+1;

open(INF, $input);       #       Open for input
    
while ($_ = <INF>)
{
    s/\\[`']\{([aieouAEIOU])\}/\\\`\1/g; # remove useless curly brackets
    s/\\\'([aieouAEIOU])/\\\`\1/g;	# general rule: all accents are grave \`
    s/[àá]/\\\`a/g;	# apply general rule to special characters
    s/[èé]/\\\`e/g;
    s/[ìí]/\\\`i/g;
    s/[òó]/\\\`o/g;
    s/[ùú]/\\\`u/g;

#                  special rules:
    s/\\\`i/{\\\`\\\i}/g;		# remove dot from accented i
    s/(ch|pot|combatt|ventitr|ntatr|\sn)\\\`e/\1\\\'e/g; # "e" exceptions

    if($spe){	# use latin1 characters for \usepackage[latin1]{inputenc}
	s/\\\`a/à/g;
	s/\\\`e/è/g;
	s/\\\'e/é/g;
	s/{\\\`\\i}/ì/g;
	s/\\\`o/ò/g;
	s/\\\`u/ù/g;
    }
    print;
}
close(INF);
