#!/usr/bin/env bash

# From http://unix.stackexchange.com/a/31181/64687

### Help ###
: '
# same as pushd +1
$ pd 1

# show a prompt, choose by number
$ pd
 0 ~/Dropbox/Projects/ds/test
 1 /Project/Warnest/docs
 2 /tmp
? 2
/tmp ~/Dropbox/Projects/ds/test /Project/Warnest/docs

# or choose by substring match
$ pd
 0 /tmp
 1 ~/Dropbox/Projects/ds/test
 2 /Project/Warnest/docs
? doc
/Project/Warnest/docs /tmp ~/Dropbox/Projects/ds/test

# substring without prompt
$ pd test
~/Dropbox/Projects/ds/test /Project/Warnest/docs /tmp
'

function pd()
{
    if [[ $# -ge 1 ]];
    then
        choice="$1"
    else
        dirs -v
        echo -n "? "
        read choice
    fi
    if [[ -n $choice ]];
    then
        declare -i cnum="$choice"
        if [[ $cnum != $choice ]];
        then #choice is not numeric
            choice=$(dirs -v | grep $choice | tail -1 | awk '{print $1}')
            cnum="$choice"
            if [[ -z $choice || $cnum != $choice ]];
            then
                echo "$choice not found"
                return
            fi
        fi
        choice="+$choice"
    fi
    pushd $choice
}

