#!/usr/bin/env perl
# maketimcfg - To be documented.
# License:  BSD
# Revision: 070322

#---------------------------------------------------------------------
#                            module setup
#---------------------------------------------------------------------

require 5.8.1;
use strict;
use Carp;
use warnings;
                                # Trap warnings
$SIG {__WARN__} = sub { die @_; };

#---------------------------------------------------------------------
#                           basic constants
#---------------------------------------------------------------------

use constant ZERO  => 0;        # Zero
use constant ONE   => 1;        # One

use constant FALSE => 0;        # Boolean FALSE
use constant TRUE  => 1;        # Boolean TRUE

#---------------------------------------------------------------------
#                         program parameters
#---------------------------------------------------------------------

my $PRODTREE = $ENV {PRODTREE};
                                # Sanity check
die "Internal error: PRODTREE isn't set correctly\n"
    unless defined ($PRODTREE) && length ($PRODTREE) && -d $PRODTREE;

#---------------------------------------------------------------------
#                            main routine
#---------------------------------------------------------------------

sub Main
{
    my $PrevNum;
    my $CurNum;
    my $Type = 'Drum';
    my $n;
    my $str;

    open (IFD, "<$PRODTREE/freepats/freepats.cfg") ||
        die "Error #1\n";

    open (OFD, ">$PRODTREE/timidity/etc/timidity.cfg") ||
        die "Error #2\n";

    select OFD;
    print "# Automatically generated by \"maketimcfg\"\n";

    while (<IFD>)
    {
        next if m@^# Automatically generated@;
        next if m@^# by http://freepats.opensrc.org/@;

        if (m@^drumset@)
        {
            print "dir $PRODTREE/freepats\n\n";
        }

        $Type = 'Instrument' if m@^bank@;
        ($n) = m@^\s+(\d+)\s@;

        if (defined ($n))
        {
            if (defined ($PrevNum))
            {
                while (++$PrevNum < $n)
                {
                    $str = " $PrevNum\tDefault$Type.pat";
                    print "$str\n";
                }
            }

            $PrevNum = $n;
        }

        print;
    }

    select STDOUT;
    close OFD;
    close IFD;

    print "Created timidity.cfg\n";
    undef;
}

#---------------------------------------------------------------------
#                            main program
#---------------------------------------------------------------------

&Main();                        # Call the main routine
exit ZERO;                      # Normal exit
