#!/usr/bin/perl -w
#
# mpskip version 0.1
#
# Skips forward through mpd's playlist to next track matching the
# regexp argument, wrapping around the end of the list. The effect of
# running this repeatedly is a little like the XMMS "Jump to file"
# function.
#
# Requires mpc to be on the user's path.
#
# Written by Hannes Reich (hannesATskynetDOTie), 16/04/2004.
# This code is in the public domain.
#

use strict;
use sigtrap;

use Shell qw(mpc);

my $search = join ' ', @ARGV;

# Grab the current playlist postion

my $current_track = 0;
for (mpc)
{
    # match things like "[playing] #1/4086   0:00 (0%)"
    if(/^\[(playing|paused)\] \#(\d+)\//)
    {
	$current_track = $2;
	last;
    }
}

# Find the next matching playlist entry after $current_track

my ($match_num, $match_name);
PLAYLIST_ENTRY:
for (mpc 'playlist')
{
    # match things like "#4071) NOFX - Take Two Placebos"
    if( /^\#(\d+)\) (.*$search.*)$/i )
    {
	($match_num, $match_name) = ($1, $2)
	    if
	    # remember the first match in case we don't find anything else
	    # so we can wrap around
	      (not defined $match_num)
	    # but really, we're looking for a match after the current
	    # playlist position
	      or $1 > $current_track;

	last PLAYLIST_ENTRY 
	    if $match_num > $current_track;
    }
}

# Play the matching track

if(defined $match_num)
{
    print "#$match_num) $match_name\n";
    mpc('play', $match_num);
}
else
{
    print "$0: no matching tracks found\n";
}
