#!/bin/bash

dispatch () {
	test -z "$SUB" && SUB=0
	test -z "$MAXSUB" && MAXSUB=$(grep ^processor /proc/cpuinfo | tail -n 1 | sed 's/.*:\s*//') && MAXSUB=$((MAXSUB + 1))
	if [ $MAXSUB -gt 1 ]
		then
		while [ $SUB -ge $MAXSUB ]
			do sleep 0.001
			SP=$MAXSUB
			while [ $SP -gt 0 ]
				# If child process terminates, remove it.
			 	do if ! kill -0 ${SUBPID[$SP]} 2>/dev/null
					then
					DEL=$SP
					while [ $DEL -lt $SUB ]
						do
						DEL2=$((DEL + 1))
						SUBPID[$DEL]="${SUBPID[$DEL2]}"
						DEL=$DEL2 
					done
					unset SUBPID[$SUB]
					SUB=$((SUB - 1))
				fi
				SP=$((SP - 1))
			done
		done
		SUB=$((SUB + 1))
		$@ &
		SUBPID[$SUB]=$!
	else $@
	fi
}

