#!/usr/bin/perl -w
use strict;

# Usage: o words in file
# Usage: o -index

my $INDEX_FILE = "C:/open.index";
my @INDEX;

my @index = (
    { folder => "C:/Program Files", depth => 2, filter => qq[-name "*.exe"], },
    { folder => "D:/Apps",          depth => 1, filter => "", },
    { folder => "D:/Entertainment", depth => 9, filter => "", },
    { folder => "D:/My Pictures",   depth => 9, filter => "", },

    #
    # Add what you want here.
    #
);

sub load	{ map { split $/, slurp($_) } @_ }
sub slurp	{ join "", map { local (@ARGV, $/) = $_; <> } @_ };
sub vomit	{ open OUT, ">:utf8", shift; print OUT join("\n", @_); close OUT; }

sub save_index {
    print STDERR "Creating index...\n";
    vomit $INDEX_FILE, join "", map {
        print STDERR "$_->{folder}\n";
        `find "$_->{folder}" -maxdepth $_->{depth} -type f $_->{filter} -print`
    } @index;
    print STDERR "Done.\n";
}

sub run_file {
    print $_[0], "\n";
    exec qq["$_[0]"];
    exit(0);
}

sub filter_index {
    for my $key (@_) {
        my @newindex = grep { /$key/i } @INDEX;
        if ($#newindex >= 0) { @INDEX = @newindex; }
        if ($#INDEX == 0) {
            run_file($INDEX[0]);
            return;
        }
    }
    if ($#INDEX > 0) {
        my $i;
        for ($i=0; ($i<=$#INDEX) && ($i <= 9); $i++) {
            print "    $i: $INDEX[$i]\n";
        }
        if ($i < $#INDEX) {
            print "    ... more\n";
        }
        $i--;
        print "> (0-$i, q, any word): ";
        my $response = <STDIN>;
        if      ($response =~ /^\s*([0-9])\s*$/) { run_file($INDEX[$1]); }
        elsif   ($response =~ /^\s*q\s*$/) { return; }
        else    { filter_index(split /\s+/, $response) }
    }
}

if (($#ARGV >= 0) && ($ARGV[0] eq "-index")) { save_index(); }
else {
    @INDEX = load $INDEX_FILE;
    filter_index(@ARGV);
}
