#!/bin/bash
# mod/modplay script to go with mikmod
#============================================================================
#    If invoked as "mod", will search the $MODPATH and grep for the rest of
# the command line arguments, then play the resulting mods in a random 
# order, looping and re-randomising when the list is exhausted. Also, if 
# run in an xterm it will change the title to "modplay".
#    "modplay" will just play the specified mod files, in a random order if 
# the first argument is "-r".
# new hacked mikmod will now deal with mods in zip files so long as there
# is just the mod in it... 
# Released under GPL Steve McIntyre 26/7/96. 
# Thanks to Jon Rabone for the awk randomiser script.
#============================================================================

# XXX - this does not currently work correctly on SunOS unless bash
# is installed

# Set this correctly to point to the directory containing the mod files...
#
MOD_PATH="/sounds/mod"

# Change this to match the path of the script. 
#
BIN_PATH="/usr/local/bin"

# Default sound quality settings. Not used with drv_sun
#
export MM_FRAGSIZE=10
export MM_NUMFRAGS=10

# Default sounds quality. This is for Sun ulaw audio
#
quality="-m8f 8000"

#============================================================================
#No user-serviceable parts below!!!	   No user-serviceable parts below!!!
#============================================================================

# These _should_ be unique!
#
NEWNDX="/tmp/$UID.newmod"
FULLNDX="/tmp/$UID.fullmod"
quit=0
mod_list=$*
random=$1

if [ $0 = $BIN_PATH/mod ] ; then
	if [ $TERM = xterm ] ; then
	      echo -e -n "\033]0;modplay\007"
	fi
	random="-r"
	echo Indexing...
	find $MOD_PATH |grep "\." > $FULLNDX
	mv $NEWNDX $NEWNDX.1
	> $NEWNDX
	if [ $# -gt 0 ] ; then
		while [ $# -gt 0 ] ;
		do
			echo "Finding \"$1\"..."
			cat $FULLNDX |grep $1 >> $NEWNDX
			shift
		done
	mv $NEWNDX $FULLNDX
	fi
fi

function MOD ()
{
if ($BIN_PATH/mikmod $quality $*) ; then
	quit=1;
fi
}

function RANDOM ()
{
echo Randomising...
cat $FULLNDX | awk '
BEGIN { lines=1; srand(); }

{ fname[lines] = $1
  lines+=1 }

END { for (i=1; i<lines; i++) {
		x=int((lines-1) * rand())+1
		while (used[x] == 1) {
		 	x=int((lines-1) * rand())+1
	 	}
		used[x]=1
		printf ("%s ",fname[x]);
	}
}

'>$NEWNDX
}
case $random in

-r)
        while [ $quit==0 ]
        do
                RANDOM
                MOD `cat $NEWNDX`
                if [ $quit = 1 ] ; then
	                echo "quit!"
                        exit 1;
                else
                        echo Repeating......;
                fi
        done;;
  
*)

	MOD $mod_list;;

esac

