#!/usr/bin/perl

# Copyright 2012-2020, Alexander Shibakov
# This file is part of SPLinT
#
# SPLinT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# SPLinT is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with SPLinT.  If not, see <http://www.gnu.org/licenses/>.

use Getopt::Long;
use Pod::Usage;

my $man = 0;
my $help = 0;

#Getopt::Long::Configure ("bundling"); # to allow -abc to set a, b, and c

GetOptions ("help|?" => \$help, 
             man => \$man,
    ) or pod2usage(2);

pod2usage(-exitval => 0, -verbose => 1) if $help;
pod2usage(-exitval => 0, -verbose => 2) if $man;

for ($i = 0; $i <= $#ARGV; $i++) {

    open FILE, "<$ARGV[$i]" or die "Cannot open file $ARGV[$i]!\n";
    $filename = $ARGV[$i];

    while(<FILE>) {

        $text = $_;
        
        while( $text =~ /(\\newcount|\\newtoks|\\newdimen|\\newif|\\let|\\([exg]|char|toks|count)?def)\w*(\\[a-zA-Z@]+)/g ) {

            $cs = $3;
	    push @all, $cs;

	    if ( defined $secse{$cs}->{$filename} ) { $secse{$cs}->{$filename}++; }
	    else { $secse{$cs}->{$filename} = 1; };
	    
	}
	
    }
}
#print keys %secse;
@alphsecs = sort keys %secse;

foreach $ocs (@alphsecs) {

    print "$ocs \% ". ref $secse{$osc};
    @fnames = sort keys %{$secse{$ocs}};
    foreach $fname (@fnames) { 
	print " $fname ($secse{$ocs}->{$fname} occurence";
        if ( $secse{$ocs}->{$fname} > 1 ) {print "s";}   
        print ")"; 
    }
    print "\n";
}

print "\n";
$i = $#alphsecs;
$i++;
print "total sequences: $i\n";

__END__

=head1 CSLIST

cslist.pl - output a list of all control sequences in the input files.

=head1 SYNOPSIS

cslist.pl [options] input_files


 Options:
   --help|-h|-?      brief help message
   --man|-m          full documentation

=head1 OPTIONS

=over 8

=item B<--help>

Print a brief help message and exit.

=item B<--man>

Print the manual page and exit.

=back

=head1 DESCRIPTION

B<cslist.pl> will read the given <input_files>, and produce a list of all the
B<TeX> control sequences defined in those files (a contorl sequence is considered
I<defined> in a file B<foo.tex> if one of B<\def>, B<\let>, B<\new...>, or similar
preceeds it in B<foo.tex>. 

=cut
