#!/bin/bash
#set -n		# read but do not execute commands (check on syntax errors)
#
# File: /usr/local/bin/musicplay
#
# Player for the textconsole to play MP3s
#
#    Copyright (C) 2009  Juergen Kaesmann (JK)
#
##############################################################################
# GPL NOTICE
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
##############################################################################
# FIND SAMPLES
#
##############################################################################
# FILTER SAMPLES
#
##############################################################################
# AWK SAMPLES
#
#############################################################################
# SED SAMPLES
#
##############################################################################
# RSYNC OPTIONS
#
##############################################################################
# DIALOG SAMPLES
#
# Given/selected answer goes to STDERR
#
# if list-height|form-height|menu-height used then:
# set lh|mh=h-7, fh=h-6
# Optimum for a standard 25x80 terminal h w lh|mh: 25 80 18, fh: 25 80 19
# For automatic size set h w lh fh mh to 0
#
# buildlist: display 2 lists side-by-side,move items between,h w lh = 25 80 18
#dialog --title "$dtitle" --ok-label "Ok" --extra-button --extra-label "Extra" --cancel-label "Cancel" --help-button --help-label "Help" --no-shadow --visit-items --buildlist "$wtitle" height width list-height [ tag item status ] ... 2>$ansfile
#
# calendar: display and edit a date, h w = 15 60
#dialog --title "$dtitle" --ok-label "Ok" --cancel-label "Cancel" --no-shadow --calendar "$wtitle" height width day month year 2>$ansfile
#
# checklist: show a list with (de)selectable entries, h w lh = 25 80 18
#dialog --title "$dtitle" --ok-label "Ok" --extra-button --extra-label "Extra" --cancel-label "Cancel" --help-button --help-label "Help" --no-shadow --no-tags --checklist "$wtitle" height width list-height [tag item status] ... 2>$ansfile
#
# dselect: display and input a directory, lh w = 15 80
#dialog --title "$dtitle" --ok-label "Ok" --extra-button --extra-label "Extra" --cancel-label "Cancel" --help-button --help-label "Help" --no-shadow --dselect filepath list-height width 2>$ansfile
#
# editbox: display and edit a file, h w = 25 80
#dialog --title "$dtitle" --ok-label "Ok" --extra-button --extra-label "Extra" --cancel-label "Cancel" --help-button --help-label "Help" --no-shadow --editbox filepath height width 2>$ansfile
#
# form: show a formula with editable entries, h w fh = 25 80 19, x,y count from top,left, flen(fieldlen)=0|-len ilen(inputlen)=0|len, FixFields=-flen
#dialog --title "$dtitle" --ok-label "Ok" --extra-button --extra-label "Extra" --cancel-label "Cancel" --help-button --help-label "Help" --no-shadow --form "$wtitle" height width form-height [ label y x item y x flen ilen ] ... 2>$ansfile
#
# fselect: show a file selection box, lh w = 15 80
#dialog --title "$dtitle" --ok-label "Ok" --extra-button --extra-label "Extra" --cancel-label "Cancel" --help-button --help-label "Help" --no-shadow --fselect filepath list-height width 2>$ansfile
#
# gauge: display a meter, h w = 15 60
#dialog --title "$dtitle" --no-shadow --gauge "$wtitle" height width [percent]
#
# infobox: display a msg and exit, h w = 5 60
#dialog --title "$dtitle" --ok-label "Ok" --no-shadow --infobox "$wtitle" height width
#
# inputbox: show a msg, input an ans, h w = 8 60
#dialog --title "$dtitle" --ok-label "Ok" --cancel-label "Cancel" --no-shadow --inputbox "$text" height width ["$init"] 2>$ansfile
#
# inputmenu: like menu but with button RENAME to rename one of the entries, h w mh = 25 80 18
#dialog --title "$dtitle" --ok-label "Ok" --extra-button --extra-label "Extra" --cancel-label "Cancel" --help-button --help-label "Help" --no-shadow --inputmenu "$wtitle" height width menu-height [ tag item ] ... 2>$ansfile
#
# menu: show a menu, h w mh = 25 80 18
#dialog --title "$dtitle" --ok-label "Ok" --extra-button --extra-label "Extra" --cancel-label "Cancel" --help-button --help-label "Help" --no-shadow --no-tags --menu "$wtitle" height width menu-height [tag item] ... 2>$ansfile
#
# mixedform: like form but with field-type each, h w fh = 25 80 18
#dialog --title "$dtitle" --ok-label "Ok" --extra-button --extra-label "Extra" --cancel-label "Cancel" --help-button --help-label "Help" --no-shadow --mixedform "$wtitle" height width formheight [ label y x item y x flen ilen itype ] ... 2>$ansfile
#
# mixedgauge: like gauge but with tag item pairs, h w = 15 60
#dialog --title "$dtitle" --no-shadow --mixedgauge "$wtitle" height width percent [ tag1 item1 ] ...
#
# msgbox: show a msg, h w = 7 60
#dialog --title "$dtitle" --no-shadow --msgbox "$msgtxt" height width
#
# passwordbox: like inputbox with invisible input, h w = 8 60
#dialog --title "$dtitle" --ok-label "Ok" --cancel-label "Cancel" --no-shadow --passwordbox "$wtitle" height width [init] 2>$ansfile
#
# passwordform: like form but with all fields are password widgets, h w fh = 25 80 18
#dialog --title "$dtitle" --ok-label "Ok" --extra-button --extra-label "Extra" --cancel-label "Cancel" --help-button --help-label "Help" --no-shadow --passwordform "$wtitle" height width form-height [ label y x item y x flen ilen ] ... 2>$ansfile
#
# pause: display seconds to remain, h w = 8 39
#dialog --title "$dtitle" --ok-label "Ok" --cancel-label "Cancel" --no-shadow --pause "$wtitle" height width seconds
#
# prgbox: display output of command and enable to quit, h w = 25 80
#dialog --title "$dtitle" --no-shadow --prgbox ["$wtitle"] command height width
#
# programbox: display piped output of command with button OK, h w = 25 80
#dialog --title "$dtitle" --ok-label "Ok" --no-shadow --programbox "$wtitle" [text] height width
#
# progressbox: display piped output of command, no button, h w = 25 80
#dialog --title "$dtitle" --no-shadow --progressbox ["$wtitle"] height width
#
# radiolist: select one status to ON, h w lh = 25 80 18
#dialog --title "$dtitle" --ok-label "Ok" --extra-button --extra-label "Extra" --cancel-label "Cancel" --help-button --help-label "Help" --no-shadow --radiolist "$wtitle" height width list-height [ tag item status ] ... 2>$ansfile
#
# rangebox: select with slider from a range of values, h w lh =25 80 18
#dialog --title "$dtitle" --ok-label "Ok" --extra-button --extra-label "Extra" --cancel-label "Cancel" --help-button --help-label "Help" --no-shadow --rangebox "$wtitle" height width list-height min-value max-value default-value 2>$ansfile
#
# tailbox: display text from a file like 'tail -f', h w = 25 80
#dialog --title "$dtitle" --ok-label "Ok" --no-shadow --tailbox "$file" height width
#
# tailboxbg: display text from a file like 'tail -f' in the background, h w = 25 80
#dialog --title "$dtitle" --no-shadow --tailboxbg "$file" height width
#
# textbox: show a file's content, h w = 25 80
#dialog --title "$dtitle" --no-shadow --tab-correct --textbox "$file" height width
#
# timebox: display and edit a time, h w = 3 39
#dialog --title "$dtitle" --ok-label "Ok" --cancel-label "Cancel" --no-shadow --timebox "$wtitle" height width [ hour minute second ] 2>$ansfile
#
# treeview: display tree data and select one of them, h w lh = 25 80 18
#dialog --title "$dtitle" --ok-label "Ok" --extra-button --extra-label "Extra" --cancel-label "Cancel" --help-button --help-label "Help" --no-shadow --treeview "$wtitle" height width list-height [ tag item status depth ] ... 2>$ansfile
#
# yesno: show a msg, select yes or no, h w = 6 60, Ret 0=yes 1=no other=cancel
#dialog --title "$dtitle" --no-shadow --yesno "$question\nOverwrite?" height width
#
##############################################################################
# REPLACE STRINGS
#
##############################################################################
# EXIT CODES

##############################################################################
# SOURCE FILES
#
. /usr/local/etc/main.conf				# config main
#. $LLIBDIR/libfuncerr-sh				# functions error
. $LLIBDIR/libfuncstd-sh				# functions standard
#. $LLIBDIR/libfuncmath-sh				# functions math
#. $LLIBDIR/libfuncip-sh				# functions IP
. /usr/local/etc/multimedia.conf			# config multimedia

#if [ ! -e ~/.samplerc ]; then				# install config user
#	cp /usr/local/share/ksm-sample/samplerc.templ ~/.samplerc
#	echo "Please configure your ~/.samplerc"
#	exit 1
#fi
. ~/.multimediarc					# config user

# Select config global OR config local. Config local gets priority.
#if [ -e ~/.samplerc ]; then
#	. ~/.samplerc					# config user
#else
#	. /usr/local/etc/sample.conf			# config global
#fi

##############################################################################
# DECLARATION OF STANDARD CONSTANTS AND VARIABLES
#
readonly package=Multimedia                             # package name
readonly package_file=ksm-multimedia                    # package file name
readonly vinfopath="/usr/local/share/$package_file"	# path to package dir
readonly version=$(cat $vinfopath/VERSION)		# package version
readonly release=$(cat $vinfopath/RELEASE)		# package release
readonly scriptname=$(basename $0)			# name of script
readonly tempfile=$TEMPDIR/$scriptname.$UID.tmp	# temporary file name
#readonly tempfile=$(mktemp -u $TEMPDIR/$scriptname.$UID.XXXXXX)	# temporary file name
#readonly lockfile=$TEMPDIR/lock/$scriptname.$UID.lock	# lock file name
readonly debuglog="/usr/bin/logger -p user.debug -t $scriptname -- DEBUG:"	# log dbg msg
readonly errlog="/usr/bin/logger -p user.err -t $scriptname -- ERROR:"		# log err msg
readonly infolog="/usr/bin/logger -p user.info -t $scriptname -- INFO:"		# log inf msg
cmd=''							# sub command
debug=no						# debug=yes/no
verbose=''						# verbose=yes/''/no
err=${_ERR_OK_}                                         # error code

##############################################################################
# USER FILL IN AT FIRST RUN

##############################################################################
# SYSTEM

##############################################################################
# USER-CONSTANTS

##############################################################################
# USER-VARIABLES
#
# STRINGS
ansfile="$TEMPDIR/$scriptname.$UID.ans"
tlst="$TEMPDIR/$scriptname.$UID.m3u"            # name of temp playlist
queue="$TEMPDIR/$scriptname.$UID.queue"         # name of queue
tempqueue="${queue}.tmp"                        # name of temp queue
eqfile="$HOME/.jomp/mpg123eq01"                 # name of equalizer file

mhead="+------------------------------------------------------------------------
|                                 MusicPlay                                   |
+-----------------------------------------------------------------------------+
| h       = Full help                  l       = List Playlist                |
| v       = Incr. verbosity to 3 times p       = Loop around cur. Position    |
| d       = Jump to previous song      f       = Jump to next song            |
| b       = Jump to begin of song      1-0     = Jump to %Pos. (f.i. 9=90%)   |
| ,       = Rewind                     .       = Forward                      |
| ;       = Fast Rewind                :       = Fast Forward                 |
| s|SPACE = Pause/Unpause              q       = Stop playing                 |
+-----------------------------------------------------------------------------+"

shead="+------------------------------------------------------------------------
|                                 MusicPlay                                   |
+-----------------------------------------------------------------------------+
| h       = Full help                  1-0     = Jump to %Pos. (f.i. 9=90%)   |
| b       = Jump to begin of song      f       = Jump to next song            |
| ,       = Rewind                     .       = Forward                      |
| ;       = Fast Rewind                :       = Fast Forward                 |
| s|SPACE = Pause/Unpause              q       = Stop playing                 |
+-----------------------------------------------------------------------------+"

args=''					# all args from cmdline
#arg1=''				# 1. arg from cmdline
#opt_o=''				# option -o (yes)
					# option --output (yes)
#opt_i=''				# option -i (arg)
					# option --infile (arg)
#opt_o=''				# option -o (arg)
					# option --outfile (arg)
#opt_p=''				# option -p (arg)
					# option --pages (arg)
opt_e=''                                # option -e (arg)
opt_l=''                                # option -l (yes)
opt_t=''                                # option -t (yes)
sopt_e=''
sopt_l=''
sopt_t=''
startdir="/"
wtitle=''                               # selected m3u for dialog
plst=''                                 # name of playlist
dlst=''                                 # playlist for dialog
qlst=''                                 # queue for dialog
m=''
s=''

# NUMBERS
#p_first=0				# first page
#p_last=0				# last page
dialog_h=0				# actual screen height
dialog_w=0				# actual screen width
moveline=0
entry=0                                 # entry to play

# ARRAYS
# Indexed arrays are always zero based string arrays.
# If index starts with 1 and all members are assigned then
# count of members of array = last index of array
declare -a arr
#maxarr="${#arr[@]}"			# get number of elements in arr
#unset arr[@]				# remove the entire array

##############################################################################
# SIGNAL HANDLING

##############################################################################
# FUNCTIONS
##############################################################################
#
##############################################################################
# HELP
#
#=============================================================================
function helptext ()
{
# Output helptext
# Uses cat, echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG helptext: $# $@" >&2
	$debuglog helptext: $# $@
fi

cat <<EOT
NAME
$scriptname - play MP3s

SYNOPSIS
$scriptname [options] [mp3[ mp3]...]

DESCRIPTION
Player for the textconsole to play MP3s. It is able to show a levelmeter
and short/long ID3-TAG infos. Furthermore it has an 32 band equalizer with
unlimited profiles.

Handling is devided in several parts:
1. Playlist/Dir selection
2. Song selection from the previous selected Playlist/Dir
3. Play songs from a queue

Defaults:  Equalizer is off, Levelmeter is off, TAG infos are short.

OPTIONS
Gnu style options:

  -h|--help    = Output help, then exit.
  -V|--version = Output version info, then exit.
  -d|--debug   = Turn on DEBUG mode.
  -q|--quiet   = Be quiet.
  -v|--verbose = Be verbose.
  -e n         = Equalizer <n> is on.
  -l           = Level meter is on while playing (def. if giv. an mp3).
  -t           = TAG infos are long while playing.
  --           = End of options.

ARGUMENTS
Give if needed:

  mp3 = MP3s to play. If MP3s are given then play theese MP3s and exit.

EXIT STATUS
On program exit:

  Code 0 = OK

  See output of 'showerrmsg'.

FILES
Used directories and files:

  Config Global                = /usr/local/etc/multimedia.conf
  Config User                  = ~/.multimediarc
  Equalizer file (XX = number) = ~/.jomp/mpg123eqXX

SEE ALSO
Related manpages:

  showerrmsg(1), aplay(1), mpg123(1).

AUTHORS
Juergen Kaesmann <juergen@kaesmann-online.de>
EOT
#  -o|--output  = Output to STDOUT.
#  -i f         = Input from file <f>.
#  --infile=f   = Input from file <f>.
#  -o f         = Output to file <f>.
#  --outfile=f  = Output to file <f>.
#  -p s,e       = Pages s=START e=END.
#  --pages=s,e  = Pages s=START e=END.

#EXAMPLES
#For instance:
#
#  Do it:
#  $scriptname

return
}

#=============================================================================
function show_about ()
{
# Show info about program.
# Uses echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG show_about: $# $@" >&2
	$debuglog show_about: $# $@
fi

local dtitle='' msgtxt=''
local prog="Musicplay"
local vr="Version ${version}-${release}"
local auth="by Juergen Kaesmann"
local ret=0

CSet 28 "$prog"
ret=$?
if [ $ret -eq 0 ]; then Pop prog; fi

CSet 28 "$vr"
ret=$?
if [ $ret -eq 0 ]; then Pop vr; fi

CSet 28 "$auth"
ret=$?
if [ $ret -eq 0 ]; then Pop auth; fi

msgtxt="
$prog

$vr

$auth"

# msgbox: show a msg, h w = 7 60
#dialog --title "$dtitle" --no-shadow --msgbox "$msgtxt" height width
dialog --title "$dtitle" --no-shadow --msgbox "$msgtxt" 11 32
ret=$?

return $ret
}

#=============================================================================
function init_dialog ()
{
# Get dialog values for sizing.
# par1 = 
# Uses echo, logger
# Uses global vars: dialog_h dialog_w
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG init_dialog: $# $@" >&2
	$debuglog init_dialog: $# $@
fi

local dialog_size=''			# actual screen size (text)
local dialog_numbers=''			# number part from dialog_size (text)
local ret=0

dialog_size=$(dialog --stdout --print-maxsize)
dialog_numbers=$(echo $dialog_size | cut -d ':' -f2 | tr -d ' ')
dialog_h=$(echo "$dialog_numbers" | cut -d ',' -f1)
dialog_w=$(echo "$dialog_numbers" | cut -d ',' -f2)

return $ret
}

#=============================================================================
function show_msg ()
{
# Show a msg text.
# par1 = msgtxt
# Uses dialog, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG show_msg: $# $@" >&2
	$debuglog show_msg: $# $@
fi

local dtitle="MESSAGE" msgtxt="$1"
local ret=0

# msgbox: show a msg, h w = 7 60
#dialog --title "$dtitle" --no-shadow --msgbox "$msgtxt" height width
dialog --title "$dtitle" --no-shadow --msgbox "$msgtxt" 7 60
ret=$?

return $ret
}

#=============================================================================
function show_error ()
{
# Show the error text.
# par1 = errcode
# par2 = additional errtext
# Uses dialog, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG show_error: $# $@" >&2
	$debuglog show_error: $# $@
fi

local dtitle='ERROR' msgtxt="\Z1${ErrMsg[$1]}\Zn $2"
local ret=0

# msgbox: show a msg, h w = 7 60
#dialog --title "$dtitle" --no-shadow --msgbox "$msgtxt" height width
dialog --title "$dtitle" --no-shadow --colors --msgbox "$msgtxt" 7 60
ret=$?

return $ret
}

#=============================================================================
function show_debug ()
{
# Show a msg text.
# par1 = msgtxt
# Uses dialog, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG show_debug: $# $@" >&2
	$debuglog show_debug: $# $@
fi

local dtitle="DEBUG" msgtxt="$1"
local ret=0

# msgbox: show a msg, h w = 7 60
#dialog --title "$dtitle" --no-shadow --msgbox "$msgtxt" height width
dialog --title "$dtitle" --no-shadow --msgbox "$msgtxt" 7 60
ret=$?

return $ret
}

#=============================================================================
function show_info ()
{
# Show an info and exit.
# par1 = msgtxt
# Uses dialog, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG show_info: $# $@" >&2
	$debuglog show_info: $# $@
fi

local dtitle="INFO" wtitle="$1"
local ret=0

# infobox: display a msg and exit, h w = 7 60
#dialog --title "$dtitle" --ok-label "Ok" --no-shadow --infobox "$wtitle" height width
dialog --title "$dtitle" --no-shadow --infobox "$wtitle" 7 60
ret=$?

return $ret
}

#=============================================================================
function show_textfile ()
{
# Show content of a text file.
# par1 = dtitle
# par2 = filename
# Uses dialog, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG show_textfile: $# $@" >&2
	$debuglog show_textfile: $# $@
fi

local dtitle="$1" file="$2"
local ret=0

# textbox: show a file's content, h w = 25 80
#dialog --title "$dtitle" --no-shadow --tab-correct --textbox "$file" height width
dialog --title "$dtitle" --no-shadow --tab-correct --scrollbar --textbox "$file" 0 0
ret=$?

return $ret
}

#=============================================================================
function pause ()
{
# Make a Pause.
# par1 = wtitle
# par2 = Seconds to pause
# Uses dialog, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG pause: $# $@" >&2
	$debuglog pause: $# $@
fi

local dtitle="PAUSE" wtitle="$1" s="$2"
local ret=0

# pause: display seconds to remain, h w = 8 39
#dialog --title "$dtitle" --ok-label "Ok" --cancel-label "Cancel" --no-shadow --pause "$wtitle" height width seconds
dialog --title "$dtitle" --ok-label "Ok" --cancel-label "Cancel" --no-shadow --pause "$wtitle" 8 39 $s
ret=$?

return $ret
}

#=============================================================================
function get_input ()
{
# Get input from user.
# par1 = text
# par2 = value (startvalue)
# Push result onto stack (1 string).
# Uses global ansfile
# Uses cat, dialog, logger, rm
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG get_input: $# $@" >&2
	$debuglog get_input: $# $@
fi

local dtitle="INPUT" txt="$1" val="$2" s=''
local ret=0

if [ -z "$3" ]; then					# parameter count ok
	# inputbox: show a msg, input an ans, h w = 8 60
	#dialog --title "$dtitle" --ok-label "Ok" --cancel-label "Cancel" --no-shadow --inputbox "$text" height width ["$init"] 2>$ansfile
	dialog --title "$dtitle" --ok-label "Ok" --cancel-label "Cancel" --no-shadow --inputbox "$txt" 8 60 "$val" 2>$ansfile
	ret=$?
	if [ "$ret" -eq 0 ]; then
		s=$(cat $ansfile)
		if [ -n "$s" ]; then
			Push "$s"
		else
			ret=10
		fi
	fi
	rm -f $ansfile
else
	show_error 2 "in get_input"
	ret=2
fi

return $ret
}

#=============================================================================
function get_yesno ()
{
# Get a yes/no answer from user.
# par1 = text
# Uses global ansfile
# Uses dialog, logger, rm
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
#	echo "DEBUG get_yesno: $# $@" >&2
	$debuglog get_yesno: $# $@
fi

local dtitle="YES or NO" txt="$1"
local ret=0

# yesno: show a msg, select yes or no, h w = 6 60, Ret 0=yes 1=no other=cancel
#dialog --title "$dtitle" --no-shadow --yesno "$question\nOverwrite?" height width
dialog --title "$dtitle" --no-shadow --yesno "$txt" 6 60
ret=$?
rm -f $ansfile

return $ret
}

#=============================================================================
function build_qlst_no_path ()
{
# Build the qlst from queue without path
# par1 = 
# Uses echo, logger
# If OK then push result (1 string) onto stack
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	echo "DEBUG build_qlst_no_path: $# $@" >&2
	$debuglog build_qlst_no_path: $# $@
fi

local SEDCMD1=""
local ret=0
SEDCMD1="s/\(.*\/\)\(.*\)/\2/"			# rm path from pathname

qlst=$(cat $queue | sed -e ${SEDCMD1} | cat -n)
ret=$?

return $ret
}

#=============================================================================
function build_qlst_full ()
{
# Build the qlst from queue without path and append 'TAB off'
# par1 = 
# Uses echo, logger
# If OK then push result (1 string) onto stack
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	echo "DEBUG build_qlst_full: $# $@" >&2
	$debuglog build_qlst_full: $# $@
fi

local SEDCMD1='' SEDCMD2=''
local ret=0
SEDCMD1="s/\(.*\/\)\(.*\)/\2/"			# rm path from pathname
SEDCMD2="s/.*/&\toff/"				# append: 'TAB off'

qlst=$(cat $queue | sed -e ${SEDCMD1} | sed -e ${SEDCMD2} | cat -n)
ret=$?

return $ret
}

#=============================================================================
function build_dlst_from_plst ()
{
# Build the plst from queue without path and append 'TAB off'
# par1 = 
# Uses echo, logger
# If OK then push result (1 string) onto stack
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	echo "DEBUG build_dlst_from_plst: $# $@" >&2
	$debuglog build_dlst_from_plst: $# $@
fi

local SEDCMD1='' SEDCMD2=''
local ret=0
SEDCMD1="s/\(.*\/\)\(.*\)/\2/"			# rm path from pathname
SEDCMD2="s/.*/&\toff/"				# append: 'TAB off'

dlst=$(cat $plst | sed -e ${SEDCMD1} | sed -e ${SEDCMD2} | cat -n)
ret=$?

return $ret
}

#=============================================================================
function delete_songs ()
{
# Delete songs from the queue
# Uses cat, echo, logger, rm, sed
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG delete_songs: $# $@" >&2
	$debuglog delete_songs: $# $@
fi

local ret=0

if [ -s "$queue" ]; then
	build_qlst_full
	ret=$?
	checklist2_dialog "CHECKLIST" "Delete Songs From Queue" "$qlst"
fi

return $ret
}

#=============================================================================
function sort_queue ()
{
# Move songs in the queue
# Uses cat, cp, echo, logger, rm, wc
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG sort_queue: $# $@" >&2
	$debuglog sort_queue: $# $@
fi

local n=0 ret=0

n=$(cat $queue | wc -l)
if [ "$n" -gt 1 ]; then				# more than 1 line in queue
	menu3_dialog
fi

return $ret
}

#=============================================================================
function show_save_queue ()
{
# List and save the queue
# Uses cat, cp, dialog, echo, logger, rm, sed
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG show_save_queue: $# $@" >&2
	$debuglog show_save_queue: $# $@
fi

local ret=0

if [ -s "$queue" ]; then
	menu4_dialog
fi

return $ret
}

#=============================================================================
function play_queue ()
{
# Play songs
# Uses clear, echo, logger, mpg123, reset
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG play_queue: $# $@" >&2
	$debuglog play_queue: $# $@
fi

local sopt_e='' sopt_t=''
local ret=0

if [ -n "$opt_e" ]; then
	sopt_e="-E $eqfile"
else
	sopt_e=''
fi
if [ -n "$opt_t" ]; then
	sopt_t='--long-tag'
else
	sopt_t=''
fi

clear
echo "$mhead"
mpg123 -C $sopt_e -y $sopt_t -@ $queue
ret=$?
test $ret -ne 0 && reset

return $ret
}

#=============================================================================
function play_from_entry ()
{
# Play all songs from entry till end of playlist
# Uses clear, echo, logger, mpg123, reset, rm, wc
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG play_from_entry: $# $@" >&2
	$debuglog play_from_entry: $# $@
fi

local l='' sopt_e='' sopt_t=''
local n=0 ret=0

if [ -n "$opt_e" ]; then
	sopt_e="-E $eqfile"
else
	sopt_e=''
fi
if [ -n "$opt_t" ]; then
	sopt_t='--long-tag'
else
	sopt_t=''
fi

n=`cat $queue | wc -l`
if [ "$n" -eq 0 ]; then
	return 1
fi
get_input "Give start entry (1-$n)" $entry
ret=$?
if [ "$ret" -eq 0 ]; then
	Pop entry
	if [ "$entry" -gt 0 ] && [ "$entry" -le $n ]; then
		# cp all from entry in queue to tempqueue
		rm -f $tempqueue
		l=`Get_Lines $queue $entry $n`
		ret=$?
		echo "$l" > $tempqueue

		# play
		clear
		echo "$mhead"
		mpg123 -C $sopt_e -y $sopt_t -@ $tempqueue
		ret=$?
		test $ret -ne 0 && reset
		rm -f $tempqueue
	fi
fi

return $ret
}

#=============================================================================
function play_clean_queue ()
{
# Play songs, rm each song from queue before playing
# Uses aplay, cat, clear, cp, echo, logger, mpg123, rm, wc
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG play_clean_queue: $# $@" >&2
	$debuglog play_clean_queue: $# $@
fi

local cs='' l='' s='' sl='' sopt_e='' sopt_l='' sopt_t=''
local ll=0 n=0 ret=0
cs='                                                                                '

if [ -n "$opt_e" ]; then
	sopt_e="-E $eqfile"
else
	sopt_e=''
fi
if [ -n "$opt_l" ]; then
	sopt_l='-V stereo'
else
	sopt_l=''
fi
if [ -n "$opt_t" ]; then
	sopt_t='--long-tag'
else
	sopt_t=''
fi

n=$(cat $queue | wc -l)
ret=$?
while [ "$ret" -eq 0 ] && [ "$n" -gt 0 ]; do
	l=`Get_Lines $queue 1 1`
	ret=$?
	Remove_Lines $queue 1 1 > $tempfile
	ret=$?
	if [ "$ret" -eq 0 ]; then
		cp $tempfile $queue
		if [ -e "$l" ]; then
			clear
			echo "$shead"
			ll=${#n}
			#let --ll
			let ll=(60-$ll)
			s="${cs:0:$ll}"
			echo "| Songs in queue: ${n}${s}|"
			sl=${l##*/}
			ll=${#sl}
			let ll=(67-$ll)
			if [ "$ll" -gt 0 ]; then
				s="${cs:0:$ll}"
			else
				s=""
			fi
			echo "+-----------------------------------------------------------------------------+"
			echo "| Playing: ${sl}${s}|"
			echo "+-----------------------------------------------------------------------------+"

			mpg123 -C $sopt_e -q $sopt_t --cdr - $l | aplay -q -t raw -f cdr $sopt_l

			let --n
		else
			show_error 5 "$l"
			ret=5
		fi
	fi
	rm -f $tempfile
done

return $ret
}

#=============================================================================
function setup ()
{
# Setup system
# Uses dialog, echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG setup: $# $@" >&2
	$debuglog setup: $# $@
fi

local se='' se1='' sl='' st='' sopt_e='' sopt_e1='' sopt_l='' sopt_t=''
local i=0 ret=0

if [ -n "$opt_e" ]; then
	sopt_e=on
	sopt_e1="$opt_e"
else
	sopt_e=off
	sopt_e1="1"
fi
if [ -n "$opt_l" ]; then
	sopt_l=on
else
	sopt_l=off
fi
if [ -n "$opt_t" ]; then
	sopt_t=on
else
	sopt_t=off
fi

form_dialog "Setup" "Edit Values" "$sopt_e" "$sopt_e1" "$sopt_l" "$sopt_t"
ret=$?
if [ "$ret" -eq 0 ]; then
	Pop st
	Pop sl
	Pop se1
	Pop se

	if [ "$se" == on ]; then
		opt_e='-E'
	else
		opt_e=''
	fi

	if [ -n "$opt_e" ]; then
		if ! ( [ "$se1" -ge 1 ] && [ "$se1" -le 99 ] ); then # error
			show_error 9 "option -e $se1"
			opt_e=""
			ret=9
		else					# ok
			if [ "${#se1}" -lt 2 ]; then
				eqfile="$HOME/.jomp/mpg123eq0${se1}"
			else
				eqfile="$HOME/.jomp/mpg123eq${se1}"
			fi
			opt_e="$se1"
		fi
	fi

	if [ "$sl" == on ]; then
		opt_l='-l'
	else
		opt_l=''
	fi

	if [ "$st" == on ]; then
		opt_t='-t'
	else
		opt_t=''
	fi
fi

return $ret
}

#=============================================================================
function form_ok ()
{
# Do form things.
# par1 = ans
# Uses logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG form_ok: $# $@" >&2
	$debuglog form_ok: $# $@
fi

local ans="$1"
local ret=0

#show_msg "form_ok: Ok Button, ans=$ans"

while read; do
	Push "$REPLY"					# Push line onto Stack
	ret=$?
	if [ "$ret" -ne 0 ]; then			# on error break loop
		if [ "$verbose" != no ]; then
			show_error 1 "Cannot Push line"
		else
			$errlog ${ErrMsg[1]} Cannot Push line
		fi
		break					# leave loop
	fi
done<$ansfile
ret=$?

return $ret
}

#=============================================================================
function form_extra ()
{
# Do extra things.
# par1 = ans
# Uses logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG form_extra: $# $@" >&2
	$debuglog form_extra: $# $@
fi

local ans="$1"
local ret=0

# do something
show_msg "form_extra: Extra Button, ans=$ans"
ret=$?

return $ret
}

#=============================================================================
function form_help ()
{
# Show the form help text.
# par1 = 
# Uses echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG form_help: $# $@" >&2
	$debuglog form_help: $# $@
fi

local dtitle='HELP FOR FORM' msgtxt=""
local ret=0

msgtxt="Set Values, OK to get the values, Cancel to quit"
echo "$msgtxt" > $tempfile

show_textfile "$dtitle" "$tempfile"
ret=$?
rm -f $tempfile

return $ret
}

#=============================================================================
function form_dialog ()
{
# Edit a set of data.
# Don't call another dialog - ansfile stays in use until end of dialog.
# par1 = Dialog Title
# par2 = Window Title
# par3 = se
# par4 = se1
# par5 = sl
# par6 = st
# If OK then Push resulting data onto Stack
# Uses ansfile, dialog
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG form_dialog: $# $@" >&2
	$debuglog form_dialog: $# $@
fi

local dtitle="$1" wtitle="$2"
local se="$3" se1="$4" sl="$5" st="$6"
local ans='' datarec='' quit='no'
local ret=0

while [ "$quit" != yes ]; do
	init_dialog
	# form: show a formula with editable entries, h w fh = 25 80 18, x,y count from top,left, flen(fieldlen)=0|-len ilen(inputlen)=0|len, FixFields=-flen
	#dialog --title "$dtitle" --ok-label "Ok" --extra-button --extra-label "Extra" --cancel-label "Cancel" --help-button --help-label "Help" --no-shadow --form "$wtitle" height width formheight [ label y x item y x flen ilen ] ... 2>$ansfile
	dialog --title "$dtitle" --cancel-label "Cancel" --no-shadow --form "$wtitle" 11 50 4 \
	"Use_Equalizer____(on|off):" 1 1 $se 1 30 4 3 \
	"Equalizer_number___(1-99):" 2 1 $se1 2 30 3 2 \
	"Show_Levelmeter__(on|off):" 3 1 $sl 3 30 4 3 \
	"Use_Long_TAGs____(on|off):" 4 1 $st 4 30 4 3 \
	2>$ansfile
	ret=$?
	ans=$(cat $ansfile)
	case "$ret" in
	    0)						# Yes or OK button
		form_ok $ans
		ret=$?
		quit=yes
		;;
	    1|255)					# No or Cancel or ESC
		quit=yes
		ret=1
		;;
	    2)						# Help button
		form_help
		ret=0
		;;
	    3)						# Extra button
		form_extra "$ans"
		ret=$?
		#quit=yes
		;;
	    *)						# Others
		show_error 99 "From dialog = $ret"
		quit=yes
		ret=99
		;;
	esac
	rm -f $ansfile
done

return $ret
}

#=============================================================================
function form_edit ()
{
# Edit data.
# Par1 = title
# Par2 = subject
# Par3 = keywords
# If OK then leave pars on stack in following order (3 strings):
# title subject keywords
# Uses logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG form_edit: $# $@" >&2
	$debuglog form_edit: $# $@
fi

local dtitle="EDIT DATA" wtitle="Edit Fields:"
local etit="" esub="" ekey=""
local ret=0

# set vars
etit="somestring"
esub="somestring"
ekey="somestring"

form_dialog "$dtitle" "$wtitle" "$etit" "$esub" "$ekey"
ret=$?
if [ "$ret" -eq 0 ]; then
	Pop ekey
	Pop esub
	Pop etit
	ret=$?
fi

return $ret
}

#=============================================================================
function checklist2_ok ()
{
# Do checklist2 things.
# par1 = ans
# Uses echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG checklist2_ok: $# $@" >&2
	$debuglog checklist2_ok: $# $@
fi

local ans="$1"
local ret=0

# do something
#show_msg "checklist2_ok: OK Button, ans=$ans"
#ret=$?

cp /dev/null $queue
ret=$?

return $ret
}

#=============================================================================
function checklist2_extra ()
{
# Do extra things.
# par1 = ans
# Uses echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG checklist2_extra: $# $@" >&2
	$debuglog checklist2_extra: $# $@
fi

local ans="$1" m="" mm="" s=""
local ret=0

# do something
#show_msg "checklist2_extra: Extra Button, ans=$ans"
#ret=$?

m=$(echo $ans | tr -d \")
if [ -n "$m" ]; then
	mm=''
	for s in $m; do
		mm="${s} ${mm}"
	done
	for s in $mm; do
		Remove_Lines $queue $s $s > $tempfile
		ret=$?
		cp $tempfile $queue
		rm -f $tempfile
	done
fi

return $ret
}

#=============================================================================
function checklist2_help ()
{
# Show the checklist2 help text.
# par1 = 
# Uses dialog, echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG checklist2_help: $# $@" >&2
	$debuglog checklist2_help: $# $@
fi

local dtitle='HELP FOR CHECKLIST' msgtxt=""
local ret=0

msgtxt="To delete all entries: Hit [All]
To delete various entries:
Switch entries on/off by hitting SPACE. If satisfied then hit [Delete]."
echo "$msgtxt" > $tempfile

show_textfile "$dtitle" "$tempfile"
ret=$?
rm -f $tempfile

return $ret
}

#=============================================================================
function checklist2_dialog ()
{
# Select items from a list
# par1 = dtitle
# par2 = wtitle
# par3 = String with data
# Uses globals, arr, ansfile
# Uses cat, dialog, echo, logger, rm
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG checklist2_dialog: $# $@" >&2
	$debuglog checklist2_dialog: $# $@
fi

local dtitle="$1" wtitle="$2" data="$3" s='' ans="" quit=no
#local tis_list=""
local i=0 ret=0

# NO-BREAK SPACE = ' '
# [tag item status] ...				separate with TAB or NL
#tis_list="1 item1 off
#2 item2 off"

# Store listing in array
# input termine from datafile
#unset arr[@]						# remove entire array
#i=0
#while read s; do
#	s=${s// /_}					# ch all spaces to _
#	s=${s//	/_}					# ch all spaces to _
#	arr[$i]="$i ${s} off"
#	let ++i
#done<$datafile

while [ "$quit" != yes ]; do
	init_dialog
	# checklist2: show a list with (de)selectable entries, h w lh = 25 80 18
	#dialog --title "$dtitle" --ok-label "Ok" --extra-button --extra-label "Extra" --cancel-label "Cancel" --help-button --help-label "Help" --no-shadow --no-tags --checklist "$wtitle" height width list-height [tag item status] ... 2>$ansfile
	dialog --title "$dtitle" --ok-label "All" --extra-button --extra-label "Delete" --cancel-label "Cancel" --help-button --help-label "Help" --no-shadow --no-tags --scrollbar --checklist "$wtitle" $dialog_h $dialog_w $[${dialog_h}-7] $data 2>$ansfile
	ret=$?
	ans=$(cat $ansfile)
	rm -f $ansfile
	case "$ret" in
	    0)						# Yes or OK button
		checklist2_ok "$ans"
		ret=$?
		quit=yes
		;;
	    1|255)					# No or Cancel or ESC
		quit=yes
		ret=1
		;;
	    2)						# Help button
		checklist2_help
		ret=$?
		;;
	    3)						# Extra button
		checklist2_extra "$ans"
		quit=yes
		;;
	    *)						# Others
		show_error 99 "From dialog = $ret"
		quit=yes
		ret=99
		;;
	esac
done

return $ret
}

#=============================================================================
function checklist_ok ()
{
# Do checklist things.
# par1 = ans
# Uses echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG checklist_ok: $# $@" >&2
	$debuglog checklist_ok: $# $@
fi

local ans="$1"
local ret=0

# do something
#show_msg "checklist_ok: OK Button, ans=$ans"
#ret=$?

cat $plst >> $queue
qlst=
ret=$?

return $ret
}

#=============================================================================
function checklist_extra ()
{
# Do extra things.
# par1 = ans
# Uses echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG checklist_extra: $# $@" >&2
	$debuglog checklist_extra: $# $@
fi

local ans="$1" m="" l=""
local i=0 ret=0

# do something
#show_msg "checklist_extra: Extra Button, ans=$ans"
#ret=$?

m=$(echo $ans | tr -d \")
if [ -n "$m" ]; then
	for i in $m; do
		l=$(Get_Lines $plst $i $i)
		ret=$?
		echo "$l" >> $queue
	done
else
	show_msg "No MP3 selected!"
fi

return $ret
}

#=============================================================================
function checklist_help ()
{
# Show the checklist help text.
# par1 = 
# Uses dialog, echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG checklist_help: $# $@" >&2
	$debuglog checklist_help: $# $@
fi

local dtitle='HELP FOR CHECKLIST' msgtxt=""
local ret=0

msgtxt="To get all entries: Hit [All]
To select various entries:
Switch entries on/off by hitting SPACE. If satisfied then hit [Add]"
echo "$msgtxt" > $tempfile

show_textfile "$dtitle" "$tempfile"
ret=$?
rm -f $tempfile

return $ret
}

#=============================================================================
function checklist_dialog ()
{
# Select items from a list
# par1 = dtitle
# par2 = wtitle
# par3 = String with data
# Uses globals, arr, ansfile
# Uses cat, dialog, echo, logger, rm
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG checklist_dialog: $# $@" >&2
	$debuglog checklist_dialog: $# $@
fi

local dtitle="$1" wtitle="$2" data="$3" s='' ans="" quit=no
#local tis_list=""
local i=0 ret=0

# NO-BREAK SPACE = ' '
# [tag item status] ...				separate with TAB or NL
#tis_list=
#arr[0]="1 Alle Maenner off"
#arr[1]="2 Alle Frauen off"
#arr[2]="3 Alle Kinder off"

# Store listing in array
# input data from datafile
#unset arr[@]						# remove entire array
#i=0
#while read s; do
#	s=${s// /_}					# ch all spaces to _
#	s=${s//	/_}					# ch all spaces to _
#	arr[$i]="$i ${s} off"
#	let ++i
#done<$datafile

while [ "$quit" != yes ]; do
	init_dialog
	# checklist: show a list with (de)selectable entries, h w lh = 25 80 18
	#dialog --title "$dtitle" --ok-label "Ok" --extra-button --extra-label "Extra" --cancel-label "Cancel" --help-button --help-label "Help" --no-shadow --no-tags --checklist "$wtitle" height width list-height [tag item status] ... 2>$ansfile
	dialog --title "$dtitle" --ok-label "All" --extra-button --extra-label "Add" --cancel-label "Cancel" --help-button --help-label "Help" --no-shadow --no-tags --scrollbar --checklist "$wtitle" $dialog_h $dialog_w $[${dialog_h}-7] $data 2>$ansfile
	ret=$?
	ans=$(cat $ansfile)
	rm -f $ansfile
	case "$ret" in
	    0)						# Yes or OK button
		checklist_ok "$ans"
		ret=$?
		quit=yes
		;;
	    1|255)					# No or Cancel or ESC
		quit=yes
		ret=1
		;;
	    2)						# Help button
		checklist_help
		ret=$?
		;;
	    3)						# Extra button
		checklist_extra "$ans"
		quit=yes
		;;
	    *)						# Others
		show_error 99 "From dialog = $ret"
		quit=yes
		ret=99
		;;
	esac
done

return $ret
}

#=============================================================================
function dselect_ok ()
{
# Do dselect things.
# par1 = dir
# Uses echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG dselect_ok: $# $@" >&2
	$debuglog dselect_ok: $# $@
fi

local ans="$1"
local ret=0

#show_msg "dselect_ok: OK Button pressed, ans=$ans"
#ret=$?

if [ -n "$ans" ]; then
	ls ${ans}/*.mp3 > $tlst
	plst="$tlst"
	build_dlst_from_plst
	ret=$?
fi

return $ret
}

#=============================================================================
function dselect_extra ()
{
# Do extra things.
# par1 = dir
# Uses echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG dselect_extra: $# $@" >&2
	$debuglog dselect_extra: $# $@
fi

local dtitle="TREE" ans="$1"
local ret=0

# build tree from ans
tree $ans > $tempfile

show_textfile "$dtitle" "$tempfile"
ret=$?
rm -f $tempfile

return $ret
}

#=============================================================================
function dselect_help ()
{
# Show the dselect help text.
# par1 = 
# Uses dialog, echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG dselect_help: $# $@" >&2
	$debuglog dselect_help: $# $@
fi

local dtitle='HELP FOR DSELECT' msgtxt=""
local ret=0

msgtxt="The screen is divided into 3 areas.

+--------------------------------------------------------------------+
|                                                                    |
|       Directory window                                             |
|                                                                    |
|                                                                    |
|                                                                    |
|                                                                    |
|                                                                    |
|                                                                    |
|                                                                    |
|                                                                    |
|                                                                    |
+--------------------------------------------------------------------+
|  Input line                                                        |
+--------------------------------------------------------------------+
|                            Button area                             |
+--------------------------------------------------------------------+

Moving between the 3 areas is done by UP DN LEFT RIGHT HOME END.

The main thing is the input line.
Dir selection is only done from the input line.
It exist a line completion function. Enter the beginning of a dir
and hit SPACE. The input line will be completed if possible.

To enter a dir name use one of the following ways:
a) Go to the directory window, select your directory then hit SPACE.
   The directory will appear in the input line and the cursor is 
   positioned at the directory name.
b) From the input line enter a directory name or at least the first few 
   characters and hit SPACE. The input line will be completed if possible."

echo "$msgtxt" > $tempfile

show_textfile "$dtitle" "$tempfile"
ret=$?
rm -f $tempfile

return $ret
}

#=============================================================================
function dselect_dialog ()
{
# List all dirs and select one dir
# par1 = dtitle
# par2 = startdir
# Uses global ansfile, startdir
# Uses cat, dialog, echo, logger, rm
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG dselect_dialog: $# $@" >&2
	$debuglog dselect_dialog: $# $@
fi

local dtitle="$1" dir="$2" ans="" quit=no
local ret=0

while [ "$quit" != yes ]; do
	init_dialog
	# dselect: show a directory selection box, lh w = 15 80
	#dialog --title "$dtitle" --ok-label "Ok" --extra-button --extra-label "Extra" --cancel-label "Cancel" --help-button --help-label "Help" --no-shadow --dselect filepath height width 2>$ansfile
	dialog --title "$dtitle" --ok-label "Ok" --extra-button --extra-label "Tree" --cancel-label "Cancel" --help-button --help-label "Help" --no-shadow --dselect $dir $[$dialog_h-10] $dialog_w 2>$ansfile
	ret=$?
	ans=$(cat $ansfile)
	rm -f $ansfile
	case "$ret" in
	    0)						# Yes or OK button
		startdir=${ans}
		dselect_ok "$ans"
		ret=$?
		quit=yes
		;;
	    1|255)					# No or Cancel or ESC
		quit=yes
		ret=1
		;;
	    2)						# Help button
		startdir="${ans}"			# return to last dir
		dselect_help
		ret=$?
		;;
	    3)						# Extra button
		startdir="${ans}"			# return to last dir
		dselect_extra "$ans"
		ret=$?
		#quit=yes
		;;
	    *)						# Others
		show_error 99 "From dialog = $ret"
		quit=yes
		ret=99
		;;
	esac
done

return $ret
}

#=============================================================================
function menu5_ok ()
{
# Rm actual line from queue and insert at given pos
# par1 = menu5 number
# Uses echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG menu5_ok: $# $@" >&2
	$debuglog menu5_ok: $# $@
fi

local ans="$1" l=""
local ret=0

#show_msg "OK Button pressed, menu5 number=$ans"
#ret=$?

if [ -n "$ans" ]; then
	l=$(Get_Lines $queue $moveline $moveline)
	ret=$?
	if [ $moveline -lt $ans ]; then
		let --ans
		Insert_Line $queue $ans $l > $tempfile
		ret=$?
		cp $tempfile $queue

		Remove_Lines $queue $moveline $moveline > $tempfile
		ret=$?
		cp $tempfile $queue

		rm -f $tempfile
		build_qlst_no_path
		ret=$?
	elif [ $moveline -gt $ans ]; then
		Remove_Lines $queue $ans $ans > $tempfile
		ret=$?
		cp $tempfile $queue

		let --ans
		Insert_Line $queue $ans $l > $tempfile
		ret=$?
		cp $tempfile $queue

		rm -f $tempfile
		build_qlst_no_path
		ret=$?
	else
		show_error 80 "Move and insert line."
		ret=80
	fi
fi

return $ret
}

#=============================================================================
function menu5_extra ()
{
# Do extra things. Show the helptext.
# par1 = menu5 number
# Uses echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG menu5_extra: $# $@" >&2
	$debuglog menu5_extra: $# $@
fi

local ans="$1" l=""
local ret=0

#show_msg "Extra Button pressed, menu5 number=$ans"
#ret=$?

if [ -n "$ans" ]; then
	l=$(Get_Lines $queue $moveline $moveline)
	ret=$?
	if [ $moveline -lt $ans ]; then
		Insert_Line $queue $ans $l > $tempfile
		ret=$?
		cp $tempfile $queue

		Remove_Lines $queue $moveline $moveline > $tempfile
		ret=$?
		cp $tempfile $queue

		rm -f $tempfile
		build_qlst_no_path
		ret=$?
	elif [ $moveline -gt $ans ]; then
		Remove_Lines $queue $ans $ans > $tempfile
		ret=$?
		cp $tempfile $queue

		Insert_Line $queue $ans $l > $tempfile
		ret=$?
		cp $tempfile $queue

		rm -f $tempfile
		build_qlst_no_path
		ret=$?
	else
		show_error 80 "Move and insert line."
		ret=80
	fi
fi

return $ret
}

#=============================================================================
function menu5_help ()
{
# Show the menu5 help text.
# par1 = 
# Uses dialog, echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG menu5_help: $# $@" >&2
	$debuglog menu5_help: $# $@
fi

local dtitle='HELP FOR MENU' msgtxt=""
local ret=0

msgtxt="Select an entry with UP/DOWN then hit [Before Pos] or [After Pos]"
echo "$msgtxt" > $tempfile

show_textfile "$dtitle" "$tempfile"
ret=$?
rm -f $tempfile

return $ret
}

#=============================================================================
function menu5_dialog ()
{
# Show a menu5 with dialog.
# par1 = 
# Uses global ansfile
# Uses cat, dialog, echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG menu5_dialog: $# $@" >&2
	$debuglog menu5_dialog: $# $@
fi

local dtitle='MENU' wtitle='Move Song to' ans='' quit=no
#local ti_list=''
local ret=0
#local -a arr
#local maxarr="${#arr[@]}"		# get number of elements in arr
#unset arr[@]				# remove the entire array

# NO-BREAK SPACE = ' '
# [tag item] ...				separate with TAB or NL
#ti_list="1 Select Items
#2 Select File"

while [ "$quit" != yes ]; do
	init_dialog
	# menu5: show a menu5, h w mh = 25 80 18
	#dialog --title "$dtitle" --ok-label "Ok" --extra-button --extra-label "Extra" --cancel-label "Cancel" --help-button --help-label "Help" --no-shadow --no-tags --menu "$wtitle" height width menu5-height [tag item] ... 2>$ansfile
	dialog --title "$dtitle" --ok-label "Before Pos" --extra-button --extra-label "After Pos" --cancel-label "Cancel" --help-button --help-label "Help" --no-shadow --no-tags --scrollbar --menu "$wtitle" $dialog_h $dialog_w $[${dialog_h}-7] $qlst 2>$ansfile
	ret=$?
	ans=$(cat $ansfile)
	rm -f $ansfile
	case "$ret" in
	    0)						# Yes or OK button
		menu5_ok "$ans"
		ret=$?
		quit=yes
		;;
	    1|255)					# No or Cancel or ESC
		quit=yes
		ret=1
		;;
	    2)						# Help button
		menu5_help
		ret=$?
		;;
	    3)						# Extra button
		menu5_extra "$ans"
		ret=$?
		quit=yes
		;;
	    *)						# Others
		show_error 99 "From dialog = $ret"
		quit=yes
		ret=99
		;;
	esac
done

return $ret
}

#=============================================================================
function menu4_ok ()
{
# Do menu4 things.
# par1 = menu4 number
# Uses echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG menu4_ok: $# $@" >&2
	$debuglog menu4_ok: $# $@
fi

local ans="$1"
local ret=0

#show_msg "OK Button pressed, menu4 number=$ans"

case "$ans" in
    1)
	show_msg "Select 1"
	;;
    2)
	show_msg "Select 2"
	;;
    *)
	;;
esac
ret=$?

return $ret
}

#=============================================================================
function menu4_extra ()
{
# Do extra things.
# par1 = menu4 number
# Uses echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG menu4_extra: $# $@" >&2
	$debuglog menu4_extra: $# $@
fi

local ans="$1" f='' m='' s=""
local ret=0

#show_msg "Extra Button pressed, menu4 number=$ans"
#ret=$?

s="$M3uDir/${scriptname}.m3u"
# dialog                                 --fselect filepath height width
dialog --title "$wtitle" --ok-label Save --fselect $s 14 78 2>$ansfile
ret=$?
if [ "$ret" -eq 0 ]; then
	m=$(cat $ansfile)
	if [ -n "$m" ]; then
		f=${m##*/}				# rm path
		s=${f%.m3u}				# rm ext if any
		if [ "$f" == "$s" ]; then		# no ext given
			f="${f}.m3u"
		fi
		s="$M3uDir/$f"
		if [ -e "$s" ]; then			# file exists
			# dialog                 --yesno text height width
			dialog --title "$wtitle" --yesno "${f} exists\nOverwrite?" 6 46
			ret=$?
			if [ "$ret" -eq 0 ]; then
				cp $queue $s
			fi
		else
			cp $queue $s
		fi
	fi
fi
rm -f $ansfile

return $ret
}

#=============================================================================
function menu4_help ()
{
# Show the menu4 help text.
# par1 = 
# Uses dialog, echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG menu4_help: $# $@" >&2
	$debuglog menu4_help: $# $@
fi

local dtitle='HELP FOR MENU' msgtxt=""
local ret=0

msgtxt="Select an entry with UP/DOWN then hit [OK] or [Save]"
echo "$msgtxt" > $tempfile

show_textfile "$dtitle" "$tempfile"
ret=$?
rm -f $tempfile

return $ret
}

#=============================================================================
function menu4_dialog ()
{
# Show a menu4 with dialog.
# par1 = 
# Uses global ansfile
# Uses cat, dialog, echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG menu4_dialog: $# $@" >&2
	$debuglog menu4_dialog: $# $@
fi

local dtitle='MENU' wtitle='Show/Save Queue' ans='' quit=no
#local ti_list=''
local ret=0
#local -a arr
#local maxarr="${#arr[@]}"		# get number of elements in arr
#unset arr[@]				# remove the entire array

# NO-BREAK SPACE = ' '
# [tag item] ...				separate with TAB or NL
#ti_list="1 Select Items
#2 Select File"

build_qlst_no_path
ret=$?

while [ "$quit" != yes ]; do
	init_dialog
	# menu4: show a menu4, h w mh = 25 80 18
	#dialog --title "$dtitle" --ok-label "Ok" --extra-button --extra-label "Extra" --cancel-label "Cancel" --help-button --help-label "Help" --no-shadow --no-tags --menu "$wtitle" height width menu4-height [tag item] ... 2>$ansfile
	dialog --title "$dtitle" --ok-label "Ok" --extra-button --extra-label "Save" --cancel-label "Cancel" --help-button --help-label "Help" --no-shadow --no-tags --scrollbar --menu "$wtitle" $dialog_h $dialog_w $[${dialog_h}-7] $qlst 2>$ansfile
	ret=$?
	ans=$(cat $ansfile)
	rm -f $ansfile
	case "$ret" in
	    0)						# Yes or OK button
		#menu4_ok "$ans"
		ret=$?
		quit=yes
		;;
	    1|255)					# No or Cancel or ESC
		quit=yes
		ret=1
		;;
	    2)						# Help button
		menu4_help
		ret=$?
		;;
	    3)						# Extra button
		menu4_extra "$ans" "$q"
		ret=$?
		#quit=yes
		;;
	    *)						# Others
		show_error 99 "From dialog = $ret"
		quit=yes
		ret=99
		;;
	esac
done

return $ret
}

#=============================================================================
function menu3_ok ()
{
# Do menu3 things.
# par1 = menu3 number
# Uses echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG menu3_ok: $# $@" >&2
	$debuglog menu3_ok: $# $@
fi

local ans="$1" l=""
local ret=0

#show_msg "OK Button pressed, menu3 number=$ans"
#ret=$?

if [ -n "$ans" ]; then
	moveline=$ans
	menu5_dialog
	ret=$?
fi

return $ret
}

#=============================================================================
function menu3_extra ()
{
# Do extra things.
# par1 = menu3 number
# Uses echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG menu3_extra: $# $@" >&2
	$debuglog menu3_extra: $# $@
fi

local ans="$1"
local ret=0

show_msg "Extra Button pressed, menu3 number=$ans"
ret=$?

return $ret
}

#=============================================================================
function menu3_help ()
{
# Show the menu3 help text.
# par1 = 
# Uses dialog, echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG menu3_help: $# $@" >&2
	$debuglog menu3_help: $# $@
fi

local dtitle='HELP FOR MENU' msgtxt=""
local ret=0

msgtxt="Select ONE entry with UP/DOWN then hit [Move]"
echo "$msgtxt" > $tempfile

show_textfile "$dtitle" "$tempfile"
ret=$?
rm -f $tempfile

return $ret
}

#=============================================================================
function menu3_dialog ()
{
# Show a menu3 with dialog.
# par1 = 
# Uses global ansfile
# Uses cat, dialog, echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG menu3_dialog: $# $@" >&2
	$debuglog menu3_dialog: $# $@
fi

local dtitle='MENU' wtitle='Select Song To Move' ans='' quit=no
#local ti_list=''
local ret=0
#local -a arr
#local maxarr="${#arr[@]}"		# get number of elements in arr
#unset arr[@]				# remove the entire array

# NO-BREAK SPACE = ' '
# [tag item] ...				separate with TAB or NL
#ti_list="1 Select Items
#2 Select File"

build_qlst_no_path
ret=$?

while [ "$quit" != yes ]; do
	init_dialog
	# menu3: show a menu3, h w mh = 25 80 18
	#dialog --title "$dtitle" --ok-label "Ok" --extra-button --extra-label "Extra" --cancel-label "Cancel" --help-button --help-label "Help" --no-shadow --no-tags --menu "$wtitle" height width menu3-height [tag item] ... 2>$ansfile
	dialog --title "$dtitle" --ok-label "Move" --cancel-label "Cancel" --help-button --help-label "Help" --no-shadow --no-tags --scrollbar --menu "$wtitle" $dialog_h $dialog_w $[${dialog_h}-7] $qlst 2>$ansfile
	ret=$?
	ans=$(cat $ansfile)
	rm -f $ansfile
	case "$ret" in
	    0)						# Yes or OK button
		menu3_ok "$ans"
		ret=$?
		#quit=yes
		;;
	    1|255)					# No or Cancel or ESC
		quit=yes
		ret=1
		;;
	    2)						# Help button
		menu3_help
		ret=$?
		;;
	    3)						# Extra button
		menu3_extra "$ans"
		ret=$?
		#quit=yes
		;;
	    *)						# Others
		show_error 99 "From dialog = $ret"
		quit=yes
		ret=99
		;;
	esac
done

return $ret
}

#=============================================================================
function menu2_ok ()
{
# Do menu2 things.
# par1 = menu2 number
# Uses echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG menu2_ok: $# $@" >&2
	$debuglog menu2_ok: $# $@
fi

local ans="$1" l='' s=''
local ret=0

#show_msg "OK Button pressed, menu2 number=$ans"
#ret=$?

cd $M3uDir
ls | cat -n > $tempfile
cd $OLDPWD

l=$(Get_Lines $tempfile $ans $ans)
ret=$?
s=${l#*[[:cntrl:]]}
s="$M3uDir/$s"
plst="$s"
wtitle=${plst##*/}
cat $plst | grep -v '#' > $tempfile
cp $tempfile $plst
build_dlst_from_plst
ret=$?
rm -f $tempfile

return $ret
}

#=============================================================================
function menu2_extra ()
{
# Do extra things. Show the helptext.
# par1 = menu2 number
# Uses echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG menu2_extra: $# $@" >&2
	$debuglog menu2_extra: $# $@
fi

local ans="$1" l='' s=''
local ret=0

#show_msg "Extra Button pressed, menu2 number=$ans"
#ret=$?

cd $M3uDir
ls | cat -n > $tempfile
cd $OLDPWD

l=$(Get_Lines $tempfile $ans $ans)
ret=$?
s=${l#*[[:cntrl:]]}
s="$M3uDir/$s"
plst="$s"
wtitle=${plst##*/}
cat $plst | grep -v '#' > $tempfile
cp $tempfile $plst
build_dlst_from_plst
ret=$?
rm -f $tempfile
while read l; do
	echo "$l" >> $tempfile
done<$plst

if [ -e "$tempfile" ]; then
	show_textfile $tempfile
	ret=$?
fi
rm -f $tempfile

return $ret
}

#=============================================================================
function menu2_help ()
{
# Show the menu2 help text.
# par1 = 
# Uses dialog, echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG menu2_help: $# $@" >&2
	$debuglog menu2_help: $# $@
fi

local dtitle='HELP FOR MENU' msgtxt=""
local ret=0

msgtxt="Select an entry with UP/DOWN then hit OK"
echo "$msgtxt" > $tempfile

show_textfile "$dtitle" "$tempfile"
ret=$?
rm -f $tempfile

return $ret
}

#=============================================================================
function menu2_dialog ()
{
# Show a menu2 with dialog.
# par1 = 
# Uses global ansfile
# Uses cat, dialog, echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG menu2_dialog: $# $@" >&2
	$debuglog menu2_dialog: $# $@
fi

local dtitle='MENU' wtitle='Select Playlist' ans='' quit=no s=""
#local ti_list=''
local ret=0
#local -a arr
#local maxarr="${#arr[@]}"		# get number of elements in arr
#unset arr[@]				# remove the entire array

# NO-BREAK SPACE = ' '
# [tag item] ...				separate with TAB or NL
#ti_list="1 Select Items
#2 Select File"

cd $M3uDir
s=`ls | cat -n`
cd $OLDPWD

while [ "$quit" != yes ]; do
	init_dialog
	# menu2: show a menu2, h w mh = 25 80 18
	#dialog --title "$dtitle" --ok-label "Ok" --extra-button --extra-label "Extra" --cancel-label "Cancel" --help-button --help-label "Help" --no-shadow --no-tags --menu "$wtitle" height width menu2-height [tag item] ... 2>$ansfile
	dialog --title "$dtitle" --ok-label "Ok" --extra-button --extra-label "Check" --cancel-label "Cancel" --help-button --help-label "Help" --no-shadow --no-tags --scrollbar --menu "$wtitle" $dialog_h $dialog_w $[${dialog_h}-7] $s 2>$ansfile
	ret=$?
	ans=$(cat $ansfile)
	rm -f $ansfile
	case "$ret" in
	    0)						# Yes or OK button
		menu2_ok "$ans"
		ret=$?
		quit=yes
		;;
	    1|255)					# No or Cancel or ESC
		quit=yes
		ret=1
		;;
	    2)						# Help button
		menu2_help
		ret=$?
		;;
	    3)						# Extra button
		menu2_extra "$ans"
		ret=$?
		#quit=yes
		;;
	    *)						# Others
		show_error 99 "From dialog = $ret"
		quit=yes
		ret=99
		;;
	esac
done

return $ret
}

#=============================================================================
function menu_ok ()
{
# Do menu things.
# par1 = menu number
# Uses echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG menu_ok: $# $@" >&2
	$debuglog menu_ok: $# $@
fi

local ans="$1"
local ret=0

case "$ans" in
    1)
	# select_plist
	menu2_dialog
	err=$?
	;;
    2)
	# select_dir
	dselect_dialog "Select Directory" "$MP3Dir/"
	err=$?
	;;
    3)
	# add_songs
	checklist_dialog "CHECKLIST" "Add songs to queue" "$dlst"
	err=$?
	;;
    4)
	delete_songs
	err=$?
	;;
    5)
	sort_queue
	err=$?
	;;
    6)
	show_save_queue
	err=$?
	;;
    7)
	play_queue
	err=$?
	;;
    8)
	play_from_entry
	err=$?
	;;
    9)
	play_clean_queue
	err=$?
	;;
    10)
	setup
	err=$?
	;;
    11)
	show_about
	err=$?
	;;
    *)
	;;
esac
ret=$?

return $ret
}

#=============================================================================
function menu_extra ()
{
# Do extra things. Show the helptext.
# par1 = menu number
# Uses echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG menu_extra: $# $@" >&2
	$debuglog menu_extra: $# $@
fi

local dtitle="MANPAGE" ans="$1"
local ret=0

#show_msg "menu_extra: Extra Button, ans=$ans"

helptext > $tempfile

show_textfile "$dtitle" "$tempfile"
ret=$?
rm -f $tempfile

return $ret
}

#=============================================================================
function menu_help ()
{
# Show the menu help text.
# par1 = 
# Uses dialog, echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG menu_help: $# $@" >&2
	$debuglog menu_help: $# $@
fi

local dtitle='HELP FOR MENU' msgtxt=""
local ret=0

msgtxt="Select an entry with UP/DOWN then hit OK"
echo "$msgtxt" > $tempfile

show_textfile "$dtitle" "$tempfile"
ret=$?
rm -f $tempfile

return $ret
}

#=============================================================================
function mainproc ()
{
# Show the main menu with dialog.
# par1 = 
# Uses global ansfile
# Uses cat, dialog, echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG mainproc: $# $@" >&2
	$debuglog mainproc: $# $@
fi

local dtitle='MAIN MENU' wtitle='Select a menu entry' ans='' quit=no
local ti_list=''
local w=0 ret=0
#local -a arr
#local maxarr="${#arr[@]}"		# get number of elements in arr
#unset arr[@]				# remove the entire array

# NO-BREAK SPACE = ' '
# [tag item] ...				separate with TAB or NL
ti_list="1 Select Playlist
2 Select Directory
3 Add Songs To Queue
4 Delete Songs From Queue
5 Sort Queue Manually
6 Show/Save Queue
7 Play Queue
8 Step into Queue
9 Play+Clean Queue
10 Setup
11 About Musicplay"

while [ "$quit" != yes ]; do
	init_dialog
	if [ $dialog_w -gt 60 ]; then
		w=60
	else
		w=$dialog_w
	fi

	# menu: show a menu, h w mh = 25 80 18
	#dialog --title "$dtitle" --ok-label "Ok" --extra-button --extra-label "Extra" --cancel-label "Cancel" --help-button --help-label "Help" --no-shadow --no-tags --menu "$wtitle" height width menu-height [tag item] ... 2>$ansfile
	dialog --title "$dtitle" --ok-label "Ok" --extra-button --extra-label "Man" --cancel-label "Quit" --help-button --help-label "Help" --no-shadow --no-tags --scrollbar --menu "$wtitle" 18 $w 11 $ti_list 2>$ansfile
	ret=$?
	ans=$(cat $ansfile)
	rm -f $ansfile
	case "$ret" in
	    0)						# Yes or OK button
		menu_ok "$ans"
		ret=$?
		#quit=yes
		;;
	    1|255)					# No or Cancel or ESC
		quit=yes
		ret=1
		;;
	    2)						# Help button
		menu_help
		ret=$?
		;;
	    3)						# Extra button
		menu_extra "$ans"
		ret=$?
		#quit=yes
		;;
	    *)						# Others
		show_error 99 "From dialog = $ret"
		quit=yes
		ret=99
		;;
	esac
done
clear

return $ret
}

##############################################################################
# GET OPTIONS
##############################################################################
# Give 2 strings and all cmdline_args to func GetOpt
# (POSIX_options Gnu_long_options cmdline_args):
# GetOpt 'hVdqvi:m:' 'help version debug quiet verbose infile= myval=' $@
#
# A ':' after a POSIX option means this option needs an arg.
# A '=' after a Gnu long option means this option needs an arg.
#
# All cmd/options have to be initialised to ''!
#
# POSIX options are classified in 2 categories:
#   a) cmds (mutually exclusive). All cmds are given to var 'cmd'.
#   b) options (as many as you like). Each option is given to it's own var.
# As a general rule: If cmds/options are given multiple then last given wins.
#
# Options can take 1 argument (no whitespace in arg). If you want to give more
# than 1 arg or want to use multiple strings as 1 arg then concatenate them
# together with ',' as delimiter:
# sampleprog -m val1,val2
# sampleprog --myval=val1,val2
# It's at the programmers responsibility to do meaningfull things with the
# content of the options.
#
# If err != 0 then all args are processed, else continue to look for options.
# When GetOpt finishes then all cmds/options are removed from actual
# cmdline args.
#
err=0
while [ "$err" -eq 0 ]; do
	GetOpt 'hVde:lt' 'help version debug' $@
	err=$?
	#echo "DEBUG GET OPTIONS: err=${err}  _OPTNAME_=${_OPTNAME_}  _OPTVAL_=${_OPTVAL_}  _OPTPOS_=${_OPTPOS_}  _OPTIDX_=${_OPTIDX_}" >&2
	if [ $err -eq 0 ]; then
		case "$_OPTNAME_" in
		    h|help)	cmd="-h";;
		    V|version)	cmd="-V";;
#		    a)		cmd="-${_OPTNAME_}";;
		    d|debug)	debug=yes;;
#		    q|quiet)	verbose=no;;
#		    v|verbose)	verbose=yes;;
		    l)		opt_l=yes;;
		    t)		opt_t=yes;;
#		    o|output)	opt_o=yes;;
#		    i|infile)	opt_i="${_OPTVAL_}";;
#		    o|outfile)	opt_o="${_OPTVAL_}";;
#		    p|pages)	opt_p="${_OPTVAL_}";;
		    e)		opt_e="$_OPTVAL_";;
		    --)		break;;
		    :)	Show_Err ${_ERR_MISSING_ARG_FOR_OPT_} "-${_OPTVAL_}"
			exit ${_ERR_MISSING_ARG_FOR_OPT_};;
		    ?)	Show_Err ${_ERR_UNKNOWN_OPT_} "-${_OPTVAL_}"
			exit ${_ERR_UNKNOWN_OPT_};;
		    *)	Show_Err ${_ERR_UNKNOWN_ERR_} "_OPTNAME_=${_OPTNAME_} _OPTVAL_=${_OPTVAL_}"
			exit ${_ERR_UNKNOWN_ERR_};;
		esac
	fi
done
err=0
shift ${_OPTIDX_}				# rm all opts from cmdline
#
# Uncomment if giving a cmd is mandatory
#if [ -z "$cmd" ]; then					# error no cmd given
#	Show_Err 7 ""
#	exit 7
#fi

##############################################################################
# CHECK LINK NAMES

##############################################################################
# CHECK OPTIONS

##############################################################################
# CHECK VERSION
#
# check version of config files. Conf file = global, Rc file = user specific
#if [ "$version" != "$Sample_Conf" ] || [ "$version" != "$Sample_Rc" ]; then
if [ "$version" != "$Multimedia_Conf" ] || [ "$version" != "$Multimedia_Rc" ]; then
	Show_Err ${_ERR_WRONG_VER_OF_CONF_FILE_} ""
	exit ${_ERR_WRONG_VER_OF_CONF_FILE_}
fi

##############################################################################
# CHECK ARGUMENTS
#
case "$cmd" in
    '')
	if [ "$#" -eq 0 ]; then				# parameter count ok
		:
	elif [ "$#" -ge 1 ]; then			# parameter count ok
		#arg1="$1"
		#shift
		args="$@"
		shift $#
#	else						# error in param count
#		if [ "$verbose" != no ]; then
#			echo "${ErrMsg[2]}" >&2
#		else
#			$errlog ${ErrMsg[2]}
#		fi
#		exit 2
	fi
	;;
    *)
	if [ "$#" -ne 0 ]; then				# error in param count
		Show_Err ${_ERR_WRONG_PAR_COUNT_} ""
		exit ${_ERR_WRONG_PAR_COUNT_}
	fi
	;;
esac

##############################################################################
# LOCK

##############################################################################
# MAINPROGRAM
##############################################################################
#
if [ "$debug" == "yes" ]; then				# DEBUG
	#echo "DEBUG Main: $# $@" >&2
	$debuglog Main: $# $@
fi

if [ -n "$opt_e" ]; then
	sopt_e="-E $eqfile"
else
	sopt_e=''
fi
if [ -n "$opt_l" ]; then
	sopt_l='-V stereo'
else
	sopt_l=''
fi
if [ -n "$opt_t" ]; then
	sopt_t='--long-tag'
else
	sopt_t=''
fi

# Check what to do (sub commands, options and args are removed from cmdline)
case "$cmd" in
    '')
#	if [ -n "$args" ]; then
#		if [ -n "$opt_t" ]; then
#			sopt_t='--long-tag'
#		else
#			sopt_t=''
#		fi
#		for s in $args; do
#			clear
#			echo "$mhead"
#			mpg123 -C -y $sopt_t $s
#			ret=$?
#		done
#		reset
#		exit 0
#	fi

	if [ -n "$args" ]; then
		sopt_l='-V stereo'
		for s in $args; do
			clear
			echo "$mhead"
			echo "$s"
			mpg123 -C -q --cdr - $s | aplay -q -t raw -f cdr $sopt_l
			ret=$?
		done
		reset
		exit 0
	fi

	# check options
	if [ -n "$opt_e" ]; then
		if ! ( [ "$opt_e" -ge 1 ] && [ "$opt_e" -le 99 ] ); then
			show_error 9 "option -e $opt_e"
			exit 9
		fi
		if [ "${#opt_e}" -lt 2 ]; then
			eqfile="$HOME/.jomp/mpg123eq0${opt_e}"
		else
			eqfile="$HOME/.jomp/mpg123eq${opt_e}"
		fi
	fi

	rm -f $tlst
	rm -f $queue
	mainproc
	err=$?
	rm -f $tlst
	rm -f $queue
	;;
    -h)
	helptext
	exit 0
	;;
    -V)
	echo "${scriptname}: (${package}) $package_file ${version}-${release}"
	exit 0
	;;
    *)							# error
	Show_Err ${_ERR_SUB_CMD_NOT_FOUND_} ""
	err=${_ERR_SUB_CMD_NOT_FOUND_}
	;;
esac

#rm -f $lockfile

exit $err
