#!/usr/bin/perl
#
# svgakeymap - by Brion Vibber (brion@pobox.com), 6/30 - 7/3/1998
# Generates a keymap conversion file for svgalib from two keytable definitions.
#
# Usage:
#   svgakeymap [physical_map [program_map]] > output.keymap
#
# The conversion map is output to stdout; you may wish to redirect it.
# Keymaps are searched for in /usr/lib/kbd/keytables and are automatically
# filtered through gzip if necessary.
#
# Read the file README.keymap from the svgalib distribution for more info.

$ktd = "/usr/lib/kbd/keytables/";
if(scalar(@ARGV) > 0) {
    $inmap = $ARGV[0];
} else {
    $inmap = "us";
}
if(scalar(@ARGV) > 1) {
    $outmap = $ARGV[1];
} else {
    $outmap = $inmap;
}
    

foreach $bob ($inmap, $outmap) {
    #print "$bob\n";
    unless(-e $bob) {
        # Tack the keytable dir on it
        $bob = $ktd . $bob;
        #print "$bob\n";

        unless(-e $bob) {
            # Tack a .gz on it
            $bob .= ".map";
            #print "$bob\n";
            
            unless(-e $bob) {
                # Tack a .gz on it
                $bob .= ".gz";
                #print "$bob\n";
                
                unless(-e $bob) {
                    die "Couldn't find $bob\n.";
                }
            }
        }
    }
}

if($inmap =~ m/\.gz$/) {
    # Filter thru gzip
    open INMAP, "gzip -dc $inmap |" or die "Could not open $inmap!\n";
} else {
    open INMAP, "<$inmap" or die "Could not open $inmap!\n";
}

if($outmap =~ m/\.gz$/) {
    # Filter thru gzip
    open OUTMAP, "gzip -dc $outmap |" or die "Could not open $outmap!\n";
} else {
    open OUTMAP, "<$outmap" or die "Could not open $outmap!\n";
}

print "# This is a svgalib scancode conversion map generated by svgakeymap.\n",
      "# Read the file README.keymap from the svgalib distribution for more info.\n#\n",
      "# Physical keyboard layout: $inmap\n",
      "# Program's expected keyboard layout: $outmap\n#\n",
      "# physical_scancode program_scancode key_name\n";


while($kc = <OUTMAP>) {
    if($kc =~ m/^keycode\s+([0-9]+)\s*\=\s*(\S+)/) {
        # Store scancodes and names for future reference
        #print stderr "- $1 - $2 -\n";
        $keys{$1} = $2;
        $keys{$2} = $1;
    } else {
        # We ignore anything else - including modifiers
    }
}

while($kc = <INMAP>) {
    if($kc =~ m/^keycode\s+([0-9]+)\s*\=\s*(\S+)/) {
        if($keys{$2}) {
            # Matching scancodes!
            #unless($keys{$1} eq $2) {
                # Find the other code with the same key...
                #print "$1 $keys{$2}\t# $keys{$1} <-> $2\n";
            #print "$1 $keys{$2}\t# $2\n";
            print "$1 $keys{$2} $2\n";
                #}
        }
    }
}

