#! /usr/bin/perl
#########################################################################
#        This Perl script is Copyright (c) 2011, Peter J Billam         #
#                          www.pjb.com.au                               #
#                                                                       #
#     This script is free software; you can redistribute it and/or      #
#            modify it under the same terms as Perl itself.             #
#########################################################################
my $Version       = '1.0';
my $VersionDate   = '4oct2011';
use open ':locale';
use MIDI::ALSA;

my $List    = 0;
my $Reverse = 0;
my $Name    = '';
my $Num     = '';

while ($ARGV[$[] =~ /^-([a-z])/) {
	if ($1 eq 'v')      { shift;
		my $n = $0; $n =~ s{^.*/([^/]+)$}{$1};
		print "$n version $Version $VersionDate\n";
		exit 0;
	} elsif ($1 eq 'l') { $List    = 1; shift;
	} elsif ($1 eq 'r') { $Reverse = 1; shift;
	} else {
		print "usage:\n";  my $synopsis = 0;
		while (<DATA>) {
			if (/^=head1 SYNOPSIS/)     { $synopsis = 1; next; }
			if ($synopsis && /^=head1/) { last; }
			if ($synopsis && /\S/)      { s/^\s*/   /; print $_; next; }
		}
		exit 0;
	}
}
MIDI::ALSA::client( "alsanum pid=$$", 1, 1, 0 );
my %num2name = MIDI::ALSA::listclients();
if ($List) {
	foreach my $num (sort {$a <=> $b} keys %num2name) {
		my $name = $num2name{$num};
		if ($name !~ /^alsanum pid=/) {
			print "$num $name\n";
		}
	}
	exit 0;
}
$Arg = $ARGV[$[];
if (! $Arg) { exit 1; }
if ($Reverse) {
	print "$num2name{0+$Arg}\n";
} else {
	foreach my $num (sort {$a <=> $b} keys %num2name) {
		my $name = $num2name{$num};
		if ($name =~ /$Arg/i) {
			print "$num\n";
			exit 0;
		}
	}
	exit 1;
}

__END__

=pod

=head1 NAME

alsanum - Perl script to convert an ALSA client to its number

=head1 SYNOPSIS

 $> alsanum xv-2020
 20
 $> alsanum -r 128
 TiMidity
 $> aconnect `alsanum prokeys` `alsanum xv`
 $>

=head1 DESCRIPTION

This script searches (case-insensitive) through the ALSA client names
and returns the number of the first client which matches.

With the B<-r> option and a number,
this script B<R>everses the lookup,
and returns the name of the corresponding ALSA client.

With the B<-l> option,
this script B<L>ists all the ALSA clients and their numbers.

This is useful because the number of the particular devices or clients vary,
since they depend on the order in which they are switched on,
connected, or started up.

=head1 OPTIONS

=over 3

=item I<-l>

Lists all the alsa-client-numbers with their names.

=item I<-r 28>

Returns the name of the ALSA client corresponding to the given number
(28 in this example)

=item I<-v>

Prints version number.

=back

=head1 CHANGES

 20111004  1.0  first working version

=head1 AUTHOR

Peter J Billam   http://www.pjb.com.au/comp/contact.html

=head1 CREDITS

Based on the MIDI::ALSA CPAN module.

=head1 SEE ALSO

 http://search.cpan.org/perldoc?MIDI::ALSA
 http://www.pjb.com.au/
 perl(1).

=cut

