#!/usr/bin/perl

use strict;
use warnings;

my $sdl_config_out = `sdl-config --cflags`;
if ($sdl_config_out =~ /-I(\S+)\s/)
{
    my $sdl_path = $1;
    open(my $fh, '<', "$sdl_path/SDL_keysym.h");

    my %keys;
    while (my $line = <$fh>)
    {
        if ($line =~ /SDLK_(\S+)\s*=\s*(\d+)/)
        {
            my $keyname = lc($1);
            my $keynum = $2;
            $keys{$keynum} = $keyname;
        }
    }
    close($fh);

    open(my $output, '>', 'sdl_keymap.cc');
    print $output <<EOP;

#include <SDL.h>

const char * sdl_keymap[SDLK_LAST+1] = {
EOP

    my $current_id = 0;
    for my $id (sort { $a <=> $b } keys(%keys))
    {
        while ($current_id < $id)
        {
            printf $output "    %-20s, /* %d */\n", '""', $current_id++;
        }
        printf $output "    %-20s, /* %d */\n", '"' . $keys{$id} . '"', $id;
        $current_id++;
    }
    print $output "    \"last\"\n};\n";
    close($output);
}

exit(0);
