dslinux/user/mpc/src Makefile.am Makefile.in charConv.c charConv.h command.c command.h libmpdclient.c libmpdclient.h list.c list.h main.c mpc.h options.c options.h password.c password.h status.c status.h util.c util.h

stsp stsp at user.in-berlin.de
Mon Aug 21 17:43:36 CEST 2006


Update of /cvsroot/dslinux/dslinux/user/mpc/src
In directory antilope:/tmp/cvs-serv21800/src

Added Files:
	Makefile.am Makefile.in charConv.c charConv.h command.c 
	command.h libmpdclient.c libmpdclient.h list.c list.h main.c 
	mpc.h options.c options.h password.c password.h status.c 
	status.h util.c util.h 
Log Message:
Adding pristine copy of mpc so I can branch from it.


--- NEW FILE: options.h ---
/* mpc
 * (c) 2004 by Daniel Brown (danb at cs.utexas.edu)
 * This project's homepage is: http://www.musicpd.org
 *
 * 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
 */

#ifndef OPTIONS_H
#define OPTIONS_H

struct mpc_option
{
	const char * name;	// long name of the option
	int has_value;		// whether a value should follow this option
	int set;			// whether this option is on/off
	char * value;		// the value of the option (null if ! has_value)
};

/* i like this type/instance naming scheme better than _mpc_table/mpc_table
    - danb */
extern struct mpc_option mpc_options [];

struct mpc_option * get_option (char option[]);
int parse_options (int * argc_p, char ** argv);

#endif /* OPTIONS_H */	

--- NEW FILE: command.h ---
/* mpc
 * (c) 2003-2004 by normalperson and Warren Dukes (warren.dukes at gmail.com)
 * This project's homepage is: http://www.musicpd.org
 *
 * 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
 */

#ifndef COMMAND_H
#define COMMAND_H
#include "libmpdclient.h"
int cmd_status ( int argc, char ** argv, mpd_Connection *conn );
int cmd_add ( int argc, char ** argv, mpd_Connection * conn ) ;
int cmd_crop ( int argc, char ** argv, mpd_Connection * conn );
int cmd_del ( int argc, char ** argv, mpd_Connection * conn );
int cmd_play ( int argc, char ** argv, mpd_Connection * conn );
int cmd_next ( int argc, char ** argv, mpd_Connection * conn );
int cmd_prev ( int argc, char ** argv, mpd_Connection * conn );
int cmd_pause ( int argc, char ** argv, mpd_Connection * conn );
int cmd_stop ( int argc, char ** argv, mpd_Connection * conn );
int cmd_seek ( int argc, char ** argv, mpd_Connection * conn );
int cmd_clear ( int argc, char ** argv, mpd_Connection * conn ) ;
int cmd_shuffle ( int argc, char ** argv, mpd_Connection * conn );
int cmd_move ( int argc, char ** argv, mpd_Connection * conn );
int cmd_playlist ( int argc, char ** argv, mpd_Connection * conn );
int cmd_listall ( int argc, char ** argv, mpd_Connection * conn );
int cmd_ls ( int argc, char ** argv, mpd_Connection * conn );
int cmd_lsplaylists ( int argc, char ** argv, mpd_Connection * conn );
int cmd_load ( int argc, char ** argv, mpd_Connection * conn );
int cmd_search ( int argc, char ** argv, mpd_Connection * conn ) ;
int cmd_save ( int argc, char ** argv, mpd_Connection * conn ) ;
int cmd_rm ( int argc, char ** argv, mpd_Connection * conn );
int cmd_volume ( int argc, char ** argv, mpd_Connection * conn ) ;
int cmd_repeat ( int argc, char ** argv, mpd_Connection * conn );
int cmd_random ( int argc, char ** argv, mpd_Connection * conn );
int cmd_crossfade ( int argc, char ** argv, mpd_Connection * conn );
int cmd_enable( int argc, char ** argv, mpd_Connection * conn );
int cmd_disable( int argc, char ** argv, mpd_Connection * conn );
int cmd_outputs ( int argc, char ** argv, mpd_Connection * conn );
int cmd_update ( int argc, char ** argv, mpd_Connection * conn );
int cmd_version ( int argc, char ** argv, mpd_Connection * conn );
int cmd_loadtab ( int argc, char ** argv, mpd_Connection * conn );
int cmd_lstab ( int argc, char ** argv, mpd_Connection * conn );
int cmd_tab ( int argc, char ** argv, mpd_Connection * conn );
int cmd_stats ( int argc, char ** argv, mpd_Connection *conn );
int cmd_toggle ( int argc, char ** argv, mpd_Connection *conn );
#endif /* COMMAND_H */

--- NEW FILE: password.h ---
/* mpc
 * (c) 2003-2004 by normalperson and Warren Dukes (warren.dukes at gmail.com)
 * This project's homepage is: http://www.musicpd.org
 *
 * 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
 */

#ifndef PASSWORD_H
#define PASSWORD_H
#include "libmpdclient.h"
void parse_password (const char * host, int * pass_len, int * parsed_len);
void send_password (const char * host, int pass_len, mpd_Connection * conn);
#endif /* PASSWORD_H */

--- NEW FILE: Makefile.in ---
# Makefile.in generated by automake 1.6.3 from Makefile.am.
# @configure_input@

# Copyright 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002
# Free Software Foundation, Inc.
# This Makefile.in is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.

@SET_MAKE@
SHELL = @SHELL@

srcdir = @srcdir@
top_srcdir = @top_srcdir@
VPATH = @srcdir@
prefix = @prefix@
exec_prefix = @exec_prefix@

bindir = @bindir@
sbindir = @sbindir@
libexecdir = @libexecdir@
datadir = @datadir@
sysconfdir = @sysconfdir@
sharedstatedir = @sharedstatedir@
localstatedir = @localstatedir@
libdir = @libdir@
infodir = @infodir@
mandir = @mandir@
includedir = @includedir@
oldincludedir = /usr/include
pkgdatadir = $(datadir)/@PACKAGE@
pkglibdir = $(libdir)/@PACKAGE@
pkgincludedir = $(includedir)/@PACKAGE@
top_builddir = ..

ACLOCAL = @ACLOCAL@
AUTOCONF = @AUTOCONF@
AUTOMAKE = @AUTOMAKE@
AUTOHEADER = @AUTOHEADER@

am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
INSTALL = @INSTALL@
INSTALL_PROGRAM = @INSTALL_PROGRAM@
INSTALL_DATA = @INSTALL_DATA@
install_sh_DATA = $(install_sh) -c -m 644
install_sh_PROGRAM = $(install_sh) -c
install_sh_SCRIPT = $(install_sh) -c
INSTALL_SCRIPT = @INSTALL_SCRIPT@
INSTALL_HEADER = $(INSTALL_DATA)
transform = @program_transform_name@
NORMAL_INSTALL = :
PRE_INSTALL = :
POST_INSTALL = :
NORMAL_UNINSTALL = :
PRE_UNINSTALL = :
POST_UNINSTALL = :

EXEEXT = @EXEEXT@
OBJEXT = @OBJEXT@
PATH_SEPARATOR = @PATH_SEPARATOR@
AMTAR = @AMTAR@
AWK = @AWK@
CC = @CC@
DEPDIR = @DEPDIR@
INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
PACKAGE = @PACKAGE@
STRIP = @STRIP@
VERSION = @VERSION@
am__include = @am__include@
am__quote = @am__quote@
install_sh = @install_sh@
bin_PROGRAMS = mpc

# lots of += lines makes diffs easier to apply :)
mpc_headers = libmpdclient.h  list.h password.h charConv.h status.h util.h command.h mpc.h options.h

mpc_SOURCES = libmpdclient.c  main.c list.c  password.c  charConv.c status.c util.c command.c options.c $(mpc_headers)
subdir = src
mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs
CONFIG_HEADER = $(top_builddir)/config.h
CONFIG_CLEAN_FILES =
bin_PROGRAMS = mpc$(EXEEXT)
PROGRAMS = $(bin_PROGRAMS)

am__objects_1 =
am_mpc_OBJECTS = libmpdclient.$(OBJEXT) main.$(OBJEXT) list.$(OBJEXT) \
	password.$(OBJEXT) charConv.$(OBJEXT) status.$(OBJEXT) \
	util.$(OBJEXT) command.$(OBJEXT) options.$(OBJEXT) \
	$(am__objects_1)
mpc_OBJECTS = $(am_mpc_OBJECTS)
mpc_LDADD = $(LDADD)
mpc_DEPENDENCIES =
mpc_LDFLAGS =

DEFS = @DEFS@
DEFAULT_INCLUDES =  -I. -I$(srcdir) -I$(top_builddir)
CPPFLAGS = @CPPFLAGS@
LDFLAGS = @LDFLAGS@
LIBS = @LIBS@
depcomp = $(SHELL) $(top_srcdir)/depcomp
am__depfiles_maybe = depfiles
@AMDEP_TRUE at DEP_FILES = ./$(DEPDIR)/charConv.Po ./$(DEPDIR)/command.Po \
@AMDEP_TRUE@	./$(DEPDIR)/libmpdclient.Po ./$(DEPDIR)/list.Po \
@AMDEP_TRUE@	./$(DEPDIR)/main.Po ./$(DEPDIR)/options.Po \
@AMDEP_TRUE@	./$(DEPDIR)/password.Po ./$(DEPDIR)/status.Po \
@AMDEP_TRUE@	./$(DEPDIR)/util.Po
COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
CCLD = $(CC)
LINK = $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@
CFLAGS = @CFLAGS@
DIST_SOURCES = $(mpc_SOURCES)
DIST_COMMON = Makefile.am Makefile.in
SOURCES = $(mpc_SOURCES)

all: all-am

.SUFFIXES:
.SUFFIXES: .c .o .obj
$(srcdir)/Makefile.in:  Makefile.am  $(top_srcdir)/configure.ac $(ACLOCAL_M4)
	cd $(top_srcdir) && \
	  $(AUTOMAKE) --gnu  src/Makefile
Makefile:  $(srcdir)/Makefile.in  $(top_builddir)/config.status
	cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)
binPROGRAMS_INSTALL = $(INSTALL_PROGRAM)
install-binPROGRAMS: $(bin_PROGRAMS)
	@$(NORMAL_INSTALL)
	$(mkinstalldirs) $(DESTDIR)$(bindir)
	@list='$(bin_PROGRAMS)'; for p in $$list; do \
	  p1=`echo $$p|sed 's/$(EXEEXT)$$//'`; \
	  if test -f $$p \
	  ; then \
	    f=`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
	   echo " $(INSTALL_PROGRAM_ENV) $(binPROGRAMS_INSTALL) $$p $(DESTDIR)$(bindir)/$$f"; \
	   $(INSTALL_PROGRAM_ENV) $(binPROGRAMS_INSTALL) $$p $(DESTDIR)$(bindir)/$$f; \
	  else :; fi; \
	done

uninstall-binPROGRAMS:
	@$(NORMAL_UNINSTALL)
	@list='$(bin_PROGRAMS)'; for p in $$list; do \
	  f=`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/'`; \
	  echo " rm -f $(DESTDIR)$(bindir)/$$f"; \
	  rm -f $(DESTDIR)$(bindir)/$$f; \
	done

clean-binPROGRAMS:
	-test -z "$(bin_PROGRAMS)" || rm -f $(bin_PROGRAMS)
mpc$(EXEEXT): $(mpc_OBJECTS) $(mpc_DEPENDENCIES) 
	@rm -f mpc$(EXEEXT)
	$(LINK) $(mpc_LDFLAGS) $(mpc_OBJECTS) $(mpc_LDADD) $(LIBS)

mostlyclean-compile:
	-rm -f *.$(OBJEXT) core *.core

distclean-compile:
	-rm -f *.tab.c

@AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/charConv.Po at am__quote@
@AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/command.Po at am__quote@
@AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libmpdclient.Po at am__quote@
@AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/list.Po at am__quote@
@AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/main.Po at am__quote@
@AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/options.Po at am__quote@
@AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/password.Po at am__quote@
@AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/status.Po at am__quote@
@AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/util.Po at am__quote@

distclean-depend:
	-rm -rf ./$(DEPDIR)

.c.o:
@AMDEP_TRUE@	source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
@AMDEP_TRUE@	depfile='$(DEPDIR)/$*.Po' tmpdepfile='$(DEPDIR)/$*.TPo' @AMDEPBACKSLASH@
@AMDEP_TRUE@	$(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
	$(COMPILE) -c `test -f '$<' || echo '$(srcdir)/'`$<

.c.obj:
@AMDEP_TRUE@	source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
@AMDEP_TRUE@	depfile='$(DEPDIR)/$*.Po' tmpdepfile='$(DEPDIR)/$*.TPo' @AMDEPBACKSLASH@
@AMDEP_TRUE@	$(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
	$(COMPILE) -c `cygpath -w $<`
CCDEPMODE = @CCDEPMODE@
uninstall-info-am:

ETAGS = etags
ETAGSFLAGS =

tags: TAGS

ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
	list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
	unique=`for i in $$list; do \
	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
	  done | \
	  $(AWK) '    { files[$$0] = 1; } \
	       END { for (i in files) print i; }'`; \
	mkid -fID $$unique

TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
		$(TAGS_FILES) $(LISP)
	tags=; \
	here=`pwd`; \
	list='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
	unique=`for i in $$list; do \
	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
	  done | \
	  $(AWK) '    { files[$$0] = 1; } \
	       END { for (i in files) print i; }'`; \
	test -z "$(ETAGS_ARGS)$$tags$$unique" \
	  || $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
	     $$tags $$unique

GTAGS:
	here=`$(am__cd) $(top_builddir) && pwd` \
	  && cd $(top_srcdir) \
	  && gtags -i $(GTAGS_ARGS) $$here

distclean-tags:
	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH
DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)

top_distdir = ..
distdir = $(top_distdir)/$(PACKAGE)-$(VERSION)

distdir: $(DISTFILES)
	@list='$(DISTFILES)'; for file in $$list; do \
	  if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
	  dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
	  if test "$$dir" != "$$file" && test "$$dir" != "."; then \
	    dir="/$$dir"; \
	    $(mkinstalldirs) "$(distdir)$$dir"; \
	  else \
	    dir=''; \
	  fi; \
	  if test -d $$d/$$file; then \
	    if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
	    fi; \
	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
	  else \
	    test -f $(distdir)/$$file \
	    || cp -p $$d/$$file $(distdir)/$$file \
	    || exit 1; \
	  fi; \
	done
check-am: all-am
check: check-am
all-am: Makefile $(PROGRAMS)

installdirs:
	$(mkinstalldirs) $(DESTDIR)$(bindir)

install: install-am
install-exec: install-exec-am
install-data: install-data-am
uninstall: uninstall-am

install-am: all-am
	@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am

installcheck: installcheck-am
install-strip:
	$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
	  INSTALL_STRIP_FLAG=-s \
	  `test -z '$(STRIP)' || \
	    echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
mostlyclean-generic:

clean-generic:

distclean-generic:
	-rm -f Makefile $(CONFIG_CLEAN_FILES)

maintainer-clean-generic:
	@echo "This command is intended for maintainers to use"
	@echo "it deletes files that may require special tools to rebuild."
clean: clean-am

clean-am: clean-binPROGRAMS clean-generic mostlyclean-am

distclean: distclean-am

distclean-am: clean-am distclean-compile distclean-depend \
	distclean-generic distclean-tags

dvi: dvi-am

dvi-am:

info: info-am

info-am:

install-data-am:

install-exec-am: install-binPROGRAMS

install-info: install-info-am

install-man:

installcheck-am:

maintainer-clean: maintainer-clean-am

maintainer-clean-am: distclean-am maintainer-clean-generic

mostlyclean: mostlyclean-am

mostlyclean-am: mostlyclean-compile mostlyclean-generic

uninstall-am: uninstall-binPROGRAMS uninstall-info-am

.PHONY: GTAGS all all-am check check-am clean clean-binPROGRAMS \
	clean-generic distclean distclean-compile distclean-depend \
	distclean-generic distclean-tags distdir dvi dvi-am info \
	info-am install install-am install-binPROGRAMS install-data \
	install-data-am install-exec install-exec-am install-info \
	install-info-am install-man install-strip installcheck \
	installcheck-am installdirs maintainer-clean \
	maintainer-clean-generic mostlyclean mostlyclean-compile \
	mostlyclean-generic tags uninstall uninstall-am \
	uninstall-binPROGRAMS uninstall-info-am

# Tell versions [3.59,3.63) of GNU make to not export all variables.
# Otherwise a system limit (for SysV at least) may be exceeded.
.NOEXPORT:

--- NEW FILE: password.c ---
/* mpc
 * (c) 2003-2004 by normalperson and Warren Dukes (warren.dukes at gmail.com)
 * This project's homepage is: http://www.musicpd.org
 *
 * 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
 */

#include "password.h"
#include "libmpdclient.h"
#include "util.h"
#include "mpc.h"

#include <string.h>
#include <stdlib.h>

void parse_password ( const char * host,
		int * password_len,
		int * parsed_len )
{
	/* parse password and host */
	char * ret = strstr(host,"@");
	int len = ret-host;

	if(ret && len == 0) parsed_len++;
	else if(ret) {
		* password_len = len;
		* parsed_len += len+1;
	}
}

void send_password ( const char * host,
		int password_len,
		mpd_Connection * conn)
{
	char * dup = strdup(host);
	dup[password_len] = '\0';

	mpd_sendPasswordCommand(conn,dup);
	printErrorAndExit(conn);
	mpd_finishCommand(conn);
	printErrorAndExit(conn);

	free(dup);
}


--- NEW FILE: options.c ---
/* mpc
 * (c) 2004 by Daniel Brown (danb at cs.utexas.edu)
 * This project's homepage is: http://www.musicpd.org
 *
 * 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
 */

#include "options.h"

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* i like this type/instance naming scheme better than _mpc_table/mpc_table
    - danb */
struct mpc_option mpc_options [] =
{
	{ "format", 1, 0, 0 },

	/* other ideas for options...
	{ "host", 1, 0, 0 },
	{ "port", 1, 0, 0 },
	{ "verbose", 0, 0, 0 },
	*/

	{}
};

/* why don't all languages have dictionary built-ins...? */
struct mpc_option * get_option (char option[])
{
	int i;

	for (i = 0; mpc_options[i].name; ++i)
		if (strcmp(option, mpc_options[i].name) == 0)
			return &mpc_options[i];

	return 0;
}

/* removes the index-th element from arr (*size gets decremented) */
void remove_index (int index, char ** arr, int * size)
{
	int i;

	/* these would be dumb... */
	assert(arr);
	assert(size);
	assert(index >= 0);
	assert(*size >= 0);
	assert(index < *size);

	/* shift everything past index one to the left and decrement the size */
	for (i = index; i < *size - 1; ++i)
		arr[i] = arr[i + 1];
	--*size;
}

/* check and extract options from argv (between argv[0] and the first command
   argument, since other locations could be ambiguous) */
int parse_options (int * argc_p, char ** argv)
{
	int i;
	struct mpc_option * option;

	for (i = 1; i < *argc_p; )
	{
		/* args with a "--" prefix are options, until we find the "--" option */
		if (strncmp(argv[i], "--", 2) == 0)
		{
			/* quit parsing on the first "--" */
			if (strcmp(argv[i], "--") == 0)
				return 0;

			/* strip the prefix from our option and try to look it up */
			option = get_option(argv[i] + 2);
			if (option)
			{
				option->set = 1;

				/* do we need to grab a parameter for this option? */
				if (option->has_value)
				{
					/* are there any arguments left? */
					if (i < *argc_p - 1)
					{
						/* grab and extract the value */
						option->value = argv[i + 1];
						remove_index(i + 1, argv, argc_p);
					}
					else
					{
						fprintf(stderr, "Option %s expects a value\n",
								argv[i]);
						return -1;
					}
				}
			}
			else
			{
				fprintf(stderr, "Invalid option: %s\n", argv[i]);
				return -1;
			}

			/* remove the i-th element from argv */
			remove_index(i, argv, argc_p);
		}
		else
		{
			/* increment iff we don't remove an element of argv */
			++i;
		}
	}

	return 0;
}

--- NEW FILE: list.c ---
/* the Music Player Daemon (MPD)
 * (c)2003-2004 by Warren Dukes (warren.dukes at gmail.com)
 * This project's homepage is: http://www.musicpd.org
 *
 * 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
 */


#include "list.h"

#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <time.h>
#include <stdio.h>

void makeListNodesArray(List * list) {
	ListNode * node = list->firstNode;
	long i;

	list->nodesArray = malloc(sizeof(ListNode *)*list->numberOfNodes);

	for(i=0;i<list->numberOfNodes;i++) {
		list->nodesArray[i] = node;
		node = node->nextNode;
	}
}

void freeListNodesArray(List * list) {
	free(list->nodesArray);
	list->nodesArray = NULL;
}

List * makeList(ListFreeDataFunc * freeDataFunc) {
	List * list = malloc(sizeof(List));

	assert(list!=NULL);

	list->firstNode = NULL;
	list->lastNode = NULL;
	list->freeDataFunc = freeDataFunc;
	list->numberOfNodes = 0;
	list->nodesArray = NULL;

	return list;
}

int insertInList(List * list,char * key,void * data) {
	ListNode * node;

	assert(list!=NULL);
	assert(key!=NULL);
	assert(data!=NULL);

	node = malloc(sizeof(ListNode));
	assert(node!=NULL);

	if(list->nodesArray) freeListNodesArray(list);

	if(list->firstNode==NULL) {
		assert(list->lastNode==NULL);
		list->firstNode = node;
	}
	else {
		assert(list->lastNode!=NULL);
		assert(list->lastNode->nextNode==NULL);
		list->lastNode->nextNode = node;
	}
	
	node->key = malloc((strlen(key)+1)*sizeof(char));
	assert(node->key!=NULL);
	strcpy(node->key,key);
	node->data = data;
	node->nextNode = NULL;
	node->prevNode = list->lastNode;

	list->lastNode = node;

	list->numberOfNodes++;
	
	return 1;
}

int insertInListWithoutKey(List * list, void * data) {
	ListNode * node;

	assert(list!=NULL);
	assert(data!=NULL);

	node = malloc(sizeof(ListNode));
	assert(node!=NULL);
	
	if(list->nodesArray) freeListNodesArray(list);

	if(list->firstNode==NULL) {
		assert(list->lastNode==NULL);
		list->firstNode = node;
	}
	else {
		assert(list->lastNode!=NULL);
		assert(list->lastNode->nextNode==NULL);
		list->lastNode->nextNode = node;
	}

	node->key = NULL;
	node->data = data;
	node->nextNode = NULL;
	node->prevNode = list->lastNode;

	list->lastNode = node;

	list->numberOfNodes++;
	
	return 1;
}

int findInList(List * list,char * key,void ** data) {
	static long high;
	static long low;
	static long cur;
	static ListNode * tmpNode;
	static int cmp;

	assert(list!=NULL);

	if(list->nodesArray) {
		high = list->numberOfNodes-1;
		low = 0;
		cur = high;

		while(high>low) {
			cur = (high+low)/2;
			tmpNode = list->nodesArray[cur];
			cmp = strcmp(tmpNode->key,key);
			if(cmp==0) {
				(*data) = tmpNode->data;
				return 1;
			}
			else if(cmp>0) high = cur;
			else {
				if(low==cur) break;
				low = cur;
			}
		}

		cur = high;
		if(cur>=0) {
			tmpNode = list->nodesArray[cur];
			if(strcmp(tmpNode->key,key)==0) {
				(*data) = tmpNode->data;
				return 1;
			}
		}
	}
	else {
		tmpNode = list->firstNode;
	
		while(tmpNode!=NULL && strcmp(tmpNode->key,key)!=0) {
			tmpNode = tmpNode->nextNode;
		}
	
		if(tmpNode!=NULL) {
			(*data) = tmpNode->data;
			return 1;
		}
	}

	return 0;
}

int deleteFromList(List * list,char * key) {
	ListNode * tmpNode;

	assert(list!=NULL);

	tmpNode = list->firstNode;

	while(tmpNode!=NULL && strcmp(tmpNode->key,key)!=0) {
		tmpNode = tmpNode->nextNode;
	}

	if(tmpNode!=NULL)
		deleteNodeFromList(list,tmpNode);
	else
		return 0;

	return 1;
}

void deleteNodeFromList(List * list,ListNode * node) {
	assert(list!=NULL);
	assert(node!=NULL);
	
	if(node->prevNode==NULL) {
		list->firstNode = node->nextNode;
	}
	else {
		node->prevNode->nextNode = node->nextNode;
	}
	if(node->nextNode==NULL) {
		list->lastNode = node->prevNode;
	}
	else {
		node->nextNode->prevNode = node->prevNode;
	}
	if(list->freeDataFunc) {
		list->freeDataFunc(node->data);
	}
	free(node->key);
	free(node);
	list->numberOfNodes--;

	if(list->nodesArray) {
		freeListNodesArray(list);
		makeListNodesArray(list);
	}

}
		
void freeList(void * list) {
	ListNode * tmpNode;
	ListNode * tmpNode2;

	assert(list!=NULL);

	tmpNode = ((List *)list)->firstNode;

	if(((List *)list)->nodesArray) free(((List *)list)->nodesArray);

	while(tmpNode!=NULL) {
		tmpNode2 = tmpNode->nextNode;
		free(tmpNode->key);
		if(((List *)list)->freeDataFunc) {
			((List *)list)->freeDataFunc(tmpNode->data);
		}
		free(tmpNode);
		tmpNode = tmpNode2;
	}

	free(list);
}

void clearList(List * list) {
	ListNode * tmpNode;
	ListNode * tmpNode2;

	assert(list!=NULL);

	tmpNode = ((List *)list)->firstNode;

	while(tmpNode!=NULL) {
		tmpNode2 = tmpNode->nextNode;
		free(tmpNode->key);
		if(((List *)list)->freeDataFunc) {
			((List *)list)->freeDataFunc(tmpNode->data);
		}
		free(tmpNode);
		tmpNode = tmpNode2;
	}

	if(list->nodesArray) freeListNodesArray(list);

	list->firstNode = NULL;
	list->lastNode = NULL;
	list->numberOfNodes = 0;
}

void swapNodes(ListNode * nodeA, ListNode * nodeB) {
	char * key;
	void * data;
	
	assert(nodeA!=NULL);
	assert(nodeB!=NULL);

	key = nodeB->key;
	data = nodeB->data;
	
	nodeB->key = nodeA->key;
	nodeB->data = nodeA->data;

	nodeA->key = key;
	nodeA->data = data;
}

void moveNodeAfter(List * list, ListNode * moveNode, ListNode * beforeNode) {
	ListNode * prev;
	ListNode * next;

	assert(moveNode!=NULL);

	prev = moveNode->prevNode;
	next = moveNode->nextNode;

	if(prev) prev->nextNode = next;
	else list->firstNode = next;
	if(next) next->prevNode = prev;
	else list->lastNode = prev;

	if(beforeNode) {
		next = beforeNode->nextNode;
		moveNode->nextNode = next;
		moveNode->prevNode = beforeNode;
		next->prevNode = moveNode;
		beforeNode->nextNode = moveNode;
		if(beforeNode==list->lastNode) list->lastNode = moveNode;
	}
	else {
		moveNode->prevNode = NULL;
		moveNode->nextNode = list->firstNode;
		list->firstNode = moveNode;
		if(list->lastNode==NULL) list->lastNode = moveNode;
	}
}

void bubbleSort(ListNode ** nodesArray, long start, long end) {
	long i;
	long j;
	ListNode * node;

	if(start>=end) return;

	for(j=start;j<end;j++) {
		for(i=end-1;i>=start;i--) {
			node = nodesArray[i];
			if(strcmp(node->key,node->nextNode->key)>0) {
				swapNodes(node,node->nextNode);
			}
		}
	}
}

void quickSort(ListNode ** nodesArray, long start, long end) {
	if(start>=end) return;
	else if(end-start<5) bubbleSort(nodesArray,start,end);
	else {
		long i;
		ListNode * node;
		long pivot;
		ListNode * pivotNode;
		char * pivotKey;

		List * startList = makeList(free);
		List * endList = makeList(free);
		long * startPtr = malloc(sizeof(long));
		long * endPtr = malloc(sizeof(long));
		*startPtr = start;
		*endPtr = end;
		insertInListWithoutKey(startList,(void *)startPtr);
		insertInListWithoutKey(endList,(void *)endPtr);

		while(startList->numberOfNodes) {
			start = *((long *)startList->lastNode->data);
			end = *((long *)endList->lastNode->data);

			if(end-start<5) {
				bubbleSort(nodesArray,start,end);
				deleteNodeFromList(startList,startList->lastNode);
				deleteNodeFromList(endList,endList->lastNode);
			}
			else {
				pivot = (start+end)/2;
				pivotNode = nodesArray[pivot];
				pivotKey = pivotNode->key;

				for(i=pivot-1;i>=start;i--) {
					node = nodesArray[i];
					if(strcmp(node->key,pivotKey)>0) {
						pivot--;
						if(pivot>i) {
							swapNodes(node,nodesArray[pivot]);
						}
						swapNodes(pivotNode,nodesArray[pivot]);
						pivotNode = nodesArray[pivot];
					}
				}
				for(i=pivot+1;i<=end;i++) {
					node = nodesArray[i];
					if(strcmp(pivotKey,node->key)>0) {
						pivot++;
						if(pivot<i) {
							swapNodes(node,nodesArray[pivot]);
						}
						swapNodes(pivotNode,nodesArray[pivot]);
						pivotNode = nodesArray[pivot];
					}
				}

				deleteNodeFromList(startList,startList->lastNode);
				deleteNodeFromList(endList,endList->lastNode);

				if(pivot-1-start>0) {
					startPtr = malloc(sizeof(long));
					endPtr = malloc(sizeof(long));
					*startPtr = start;
					*endPtr = pivot-1;
					insertInListWithoutKey(startList,(void *)startPtr);
					insertInListWithoutKey(endList,(void *)endPtr);
				}

				if(end-pivot-1>0) {
					startPtr = malloc(sizeof(long));
					endPtr = malloc(sizeof(long));
					*startPtr = pivot+1;
					*endPtr = end;
					insertInListWithoutKey(startList,(void *)startPtr);
					insertInListWithoutKey(endList,(void *)endPtr);
				}
			}
		}

		freeList(startList);
		freeList(endList);
	}
}

void sortList(List * list) {
	assert(list!=NULL);

	if(list->numberOfNodes<2) return;
	
	if(list->nodesArray) freeListNodesArray(list);
	makeListNodesArray(list);

	quickSort(list->nodesArray,0,list->numberOfNodes-1);
}

--- NEW FILE: list.h ---
/* the Music Player Daemon (MPD)
 * (c)2003-2004 by Warren Dukes (warren.dukes at gmail.com)
 * This project's homepage is: http://www.musicpd.org
 *
 * 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
 */


#ifndef LIST_H
#define LIST_H

#include <stdlib.h>

/* used to make a list where free() will be used to free data in list */
#define DEFAULT_FREE_DATA_FUNC	free

/* typedef for function to free data stored in the list nodes */
typedef void ListFreeDataFunc(void *);

typedef struct _ListNode {
	/* used to identify node (ie. when using findInList) */
	char * key;
	/* data store in node */
	void * data;
	/* next node in list */
	struct _ListNode * nextNode;
	/* previous node in list */
	struct _ListNode * prevNode;
} ListNode;

typedef struct _List {
	/* first node in list */
	ListNode * firstNode;
	/* last node in list */
	ListNode * lastNode;
	/* function used to free data stored in nodes of the list */
	ListFreeDataFunc * freeDataFunc;
	/* number of nodes */
	long numberOfNodes;
	/* array for searching when list is sorted */
	ListNode ** nodesArray;
} List;

/* allocates memory for a new list and initializes it
 *  _freeDataFunc_ -> pointer to function used to free data, use 
 *                    DEFAULT_FREE_DATAFUNC to use free()
 * returns pointer to new list if successful, NULL otherwise
 */
List * makeList(ListFreeDataFunc * freeDataFunc);

/* inserts a node into _list_ with _key_ and _data_
 *  _list_ -> list the data will be inserted in
 *  _key_ -> identifier for node/data to be inserted into list
 *  _data_ -> data to be inserted in list
 * returns 1 if successful, 0 otherwise
 */ 
int insertInList(List * list,char * key,void * data);

int insertInListWithoutKey(List * list,void * data);

/* deletes the first node in the list with the key _key_
 *  _list_ -> list the node will be deleted from
 *  _key_ -> key used to identify node to delete
 *  returns 1 if node is found and deleted, 0 otherwise
 */
int deleteFromList(List * list,char * key);

void deleteNodeFromList(List * list,ListNode * node);

/* finds data in a list based on key
 *  _list_ -> list to search for _key_ in
 * _key_ -> which node is being searched for
 * _data_ -> a pointer to where data will be placed, 
 *	_data_ memory should not by allocated or freed
 * returns 1 if successful, 0 otherwise
 */
int findInList(List * list, char * key, void ** data);

/* frees memory malloc'd for list and its nodes
 *  _list_ -> List to be free'd
 */
void freeList(void * list);

void clearList(List * list);

void sortList(List * list);

#endif

--- NEW FILE: command.c ---
/* mpc
 * (c) 2003-2004 by normalperson and Warren Dukes (warren.dukes at gmail.com)
 *              and Daniel Brown (danb at cs.utexas.edu)
 * This project's homepage is: http://www.musicpd.org
 *
 * 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
 */

[...1003 lines suppressed...]
		t = stats->dbUpdateTime;
		printf("Artists: %6d\n", stats->numberOfArtists);
		printf("Albums:  %6d\n", stats->numberOfAlbums);
		printf("Songs:   %6d\n", stats->numberOfSongs);
		printf("\n");
		printf("Play Time:    %s\n", DHMS(stats->playTime));
		printf("Uptime:       %s\n", DHMS(stats->uptime));
		printf("DB Updated:   %s", ctime(&t));	/* no \n needed */
		printf("DB Play Time: %s\n", DHMS(stats->dbPlayTime));
		mpd_freeStats(stats);
	} else {
		printf("Error getting mpd stats\n");
	}
	return 0;
}

int cmd_status ( int argc, char ** argv, mpd_Connection * conn )
{
	return 1;
}

--- NEW FILE: libmpdclient.c ---
/* libmpdclient
   (c)2003-2004 by Warren Dukes (warren.dukes at gmail.com)
   This project's homepage is: http://www.musicpd.org
  
   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:
                                                                                
   - Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
                                                                                
   - Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
                                                                                
   - Neither the name of the Music Player Daemon nor the names of its
   contributors may be used to endorse or promote products derived from
   this software without specific prior written permission.
                                                                                
[...1434 lines suppressed...]
}

void mpd_sendEnableOutputCommand(mpd_Connection * connection, int outputId) {
	char * string = malloc(strlen("enableoutput")+25);
	sprintf(string,"enableoutput \"%i\"\n",outputId);
	mpd_executeCommand(connection,string);
	free(string);
}

void mpd_sendDisableOutputCommand(mpd_Connection * connection, int outputId) {
	char * string = malloc(strlen("disableoutput")+25);
	sprintf(string,"disableoutput \"%i\"\n",outputId);
	mpd_executeCommand(connection,string);
	free(string);
}

void mpd_freeOutputElement(mpd_OutputEntity * output) {
	free(output->name);
	free(output);
}

--- NEW FILE: util.c ---
/* mpc
 * (c) 2003-2005 by normalperson and Warren Dukes (warren.dukes at gmail.com)
 *              and Daniel Brown (danb at cs.utexas.edu)
 * This project's homepage is: http://www.musicpd.org
 *
 * 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
 */

#include "util.h"
#include "libmpdclient.h"
#include "charConv.h"
#include "list.h"
#include "mpc.h"
#include "options.h"

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <sys/param.h>

void printErrorAndExit(mpd_Connection * conn)
{
	if(conn->error) {
		fprintf(stderr,"error: %s\n",fromUtf8(conn->errorStr));
		exit(EXIT_FAILURE);
	}
}

int stdinToArgArray(char *** array)
{
	List * list = makeList(NULL);
	ListNode * node;
	char buffer[STRING_LENGTH+1];
	int size;
	int i;
	char * sp;

	while(fgets(buffer,STRING_LENGTH,stdin)) {
		if((sp = strchr(buffer,'\n'))) *sp = '\0';
		insertInListWithoutKey(list,strdup(buffer));
	}

	size = list->numberOfNodes;
	*array = malloc((sizeof(char *))*size);
	i = 0;
	node = list->firstNode;
	while(node) {
		(*array)[i++] = (char *)node->data;
		node = node->nextNode;
	}
	assert(i==size);

	freeList(list);

	return size;
}

void free_pipe_array (int max, char ** array)
{
	int i;
	for ( i=0 ;i<max; ++i) free(array[i]);
}

int get_boolean (const char * arg)
{
	int i;
	struct _bool_table {
		const char * on;
		const char * off;
	} bool_table [] = {
		{ "on", "off" },
		{ "1", "0" },
		{ "true", "false" },
		{ "yes", "no" },
		{}
	};

	for (i=0; bool_table[i].on; ++i) {
		if (! strcasecmp(arg,bool_table[i].on))
			return 1;
		else if (! strcasecmp(arg,bool_table[i].off))
			return 0;
	}
	
	fprintf(stderr,"\"%s\" is not boolean value: <",arg);
	
	for (i=0; bool_table[i].on; ++i) {
		fprintf(stderr,"%s|%s%s", bool_table[i].on,
			bool_table[i].off,
			( bool_table[i+1].off ? "|" : ">\n"));
	}  
	return -1;
}

/* note - return value is success; the parsed int itself is in ret */

int parse_int(const char * str, int * ret)
{
        char * test;
        int temp;

        temp = strtol(str, &test, 10);

        if(*test != '\0')
                return 0; /* failure */

        *ret = temp;
        return 1; /* success */
}

/* note - simply strips number out of formatting; does not -1 or +1 or change
 * the number in any other way for that matter */
int parse_songnum(const char * str, int * ret)
{
        int song;
        char * endptr;

        if(!str)
                return 0;
        if(*str == '#')
                str++;

        song = strtol(str, &endptr, 10);

        if(str == endptr || (*endptr != ')' && *endptr != '\0') || song < 0)
                return 0;

        *ret = song;

        return 1;
}

int parse_int_value_change(const char * str, struct int_value_change * ret)
{
        int len;
        int change;
        int relative = 0;

        len = strlen(str);

        if(len < 1)
                return 0;

        if(*str == '+')
                relative = 1;
        else if(*str == '-')
                relative = -1;

        if(!parse_int(str, &change))
                return 0;

        ret->value = change;
        ret->is_relative = (relative != 0);

        return 1;
}

char * appendToString(char * dest, const char * src, int len) {
	int destlen;

	if(dest == NULL) {
		dest = malloc(len+1);
		memset(dest, 0, len+1);
		destlen = 0;
	}
	else {
		destlen = strlen(dest);
		dest = realloc(dest, destlen+len+1);
	}

	memcpy(dest+destlen, src, len);
	dest[destlen+len] = '\0';

	return dest;
}

char * skipFormatting(char * p) {
	int stack = 0;
		
	while (*p != '\0') {
		if(*p == '[') stack++;
		if(*p == '#' && p[1] != '\0') {
			/* skip escaped stuff */
			++p;
		}
		else if(stack) {
			if(*p == ']') stack--;
		}
		else {
			if(*p == '&' || *p == '|' || *p == ']') {
				break;
			}
		}
		++p;
	}

	return p;
}

/* this is a little ugly... */
char * songToFormatedString (mpd_Song * song, const char * format, char ** last)
{
	char * ret = NULL;
	char *p, *end;
	char * temp;
	int length;
	int found = 0;
	int labelFound = 0;

	/* we won't mess up format, we promise... */
	for (p = (char *)format; *p != '\0'; )
	{
		if (p[0] == '|') {
			++p;
			if(!found) {
				if(ret) {
					free(ret);
					ret = NULL;
				}
			}
			else {
				p = skipFormatting(p);
			}
			continue;
		}
		
		if (p[0] == '&') {
			++p;
			if(found == 0) {
				p = skipFormatting(p);
			}
			else {
				found = 0;
			}
			continue;
		}
		
		if (p[0] == '[')
		{
			temp = songToFormatedString(song, p+1, &p);
			if(temp) {
				ret = appendToString(ret, temp, strlen(temp));
				found = 1;
			}
			continue;
		}

		if (p[0] == ']')
		{
			if(last) *last = p+1;
			if(!found && ret) {
				free(ret);
				ret = NULL;
			}
			return ret;
		}

		/* pass-through non-escaped portions of the format string */
		if (p[0] != '#' && p[0] != '%')
		{
			ret = appendToString(ret, p, 1);
			++p;
			continue;
		}

		/* let the escape character escape itself */
		if (p[0] == '#' && p[1] != '\0')
		{
			ret = appendToString(ret, p+1, 1);
			p+=2;
			continue;
		}

		/* advance past the esc character */

		/* find the extent of this format specifier (stop at \0, ' ', or esc) */
		temp = NULL;

		end  = p+1;
		while(*end >= 'a' && *end <= 'z')
		{
			end++;
		}
		length = end - p + 1;

		labelFound = 0;
		
		if(*end != '%')
			length--;
		else if (strncmp("%file%", p, length) == 0) {
			temp = fromUtf8(song->file);
		}
		else if (strncmp("%artist%", p, length) == 0) {
			labelFound = 1;
			temp = song->artist ? fromUtf8(song->artist) : NULL;
		}
		else if (strncmp("%title%", p, length) == 0) {
			labelFound = 1;
			temp = song->title ? fromUtf8(song->title) : NULL;
		}
		else if (strncmp("%album%", p, length) == 0) {
			labelFound = 1;
			temp = song->album ? fromUtf8(song->album) : NULL;
		}
		else if (strncmp("%track%", p, length) == 0) {
			labelFound = 1;
			temp = song->track ? fromUtf8(song->track) : NULL;
		}
		else if (strncmp("%name%", p, length) == 0) {
			labelFound = 1;
			temp = song->name ? fromUtf8(song->name) : NULL;
		}
		else if (strncmp("%time%", p, length) == 0) {
			labelFound = 1;
			if (song->time != MPD_SONG_NO_TIME) {
				char s[10];
				snprintf(s, 9, "%d:%02d", song->time / 60, 
						song->time % 60);
				/* nasty hack to use static buffer */
				temp = fromUtf8(s);
			}
		}

		if( temp == NULL && !labelFound ) {
			ret = appendToString(ret, p, length);
		}
		else if( temp != NULL ) {
			found = 1;
			ret = appendToString(ret, temp, strlen(temp));
		}

		/* advance past the specifier */
		p += length;
	}

	if(last) *last = p;
	return ret;
}

void print_formatted_song (mpd_Song * song, const char * format)
{
	char * str = songToFormatedString(song, format, NULL);

	if(str) {
		printf("%s", str);
		free(str);
	}
}

#define DEFAULT_FORMAT "[%name%: &[%artist% - ]%title%]|%name%|[%artist% - ]%title%|%file%"

void pretty_print_song (mpd_Song * song)
{
	/* was a format string specified? */
	if (get_option("format")->set)
	{
		print_formatted_song(song, get_option("format")->value);
	}
	/* just do something pretty */
	else
	{
		print_formatted_song(song, DEFAULT_FORMAT);
	}
}

--- NEW FILE: status.h ---
/* mpc
 * (c) 2003-2004 by normalperson and Warren Dukes (warren.dukes at gmail.com)
 * This project's homepage is: http://www.musicpd.org
 *
 * 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
 */

#ifndef STATUS_H
#define STATUS_H

#include "libmpdclient.h"

void print_status (mpd_Connection *conn);

#endif /* STATUS_H */

--- NEW FILE: charConv.c ---
/* the Music Player Daemon (MPD)
 * (c)2003-2004 by Warren Dukes (warren.dukes at gmail.com)
 * This project's homepage is: http://www.musicpd.org
 *
 * 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
 */

#include "charConv.h"

#include "mpc.h"

#include <stdlib.h>
#include <errno.h>
#include <string.h>
/*#include <stdio.h>*/

#ifdef HAVE_LOCALE
#ifdef HAVE_LANGINFO_CODESET
#include <locale.h>
#include <langinfo.h>
#endif
#endif

static char * localeCharset = NULL;

#ifdef HAVE_ICONV
#include <iconv.h>
iconv_t char_conv_iconv;
char * char_conv_to = NULL;
char * char_conv_from = NULL;
#endif

#define BUFFER_SIZE	1024

int setCharSetConversion(char * to, char * from) {
#ifdef HAVE_ICONV
	if(char_conv_to && strcmp(to,char_conv_to)==0 &&
			char_conv_from && strcmp(from,char_conv_from)==0)
	{ 
		return 0;
	}

	closeCharSetConversion();

	if((char_conv_iconv = iconv_open(to,from))==(iconv_t)(-1)) return -1;

	char_conv_to = strdup(to);
	char_conv_from = strdup(from);

	return 0;
#endif
	return -1;
}

char * convStrDup(char * string) {
#ifdef HAVE_ICONV
	char buffer[BUFFER_SIZE];
	size_t inleft = strlen(string);
	char * ret;
	size_t outleft;
	size_t retlen = 0;
	size_t err;
	char * bufferPtr;

	if(!char_conv_to) return NULL;

	ret = strdup("");

	while(inleft) {
		bufferPtr = buffer;
		outleft = BUFFER_SIZE;
		err = iconv(char_conv_iconv,&string,&inleft,&bufferPtr,
					&outleft);
		if(outleft==BUFFER_SIZE || (err<0 && errno!=E2BIG)) {
			free(ret);
			return NULL;
		}

		ret = realloc(ret,retlen+BUFFER_SIZE-outleft+1);
		memcpy(ret+retlen,buffer,BUFFER_SIZE-outleft);
		retlen+=BUFFER_SIZE-outleft;
		ret[retlen] = '\0';
	}

	return ret;
#endif
	return NULL;
}

void closeCharSetConversion() {
#ifdef HAVE_ICONV
	if(char_conv_to) {
		iconv_close(char_conv_iconv);
		free(char_conv_to);
		free(char_conv_from);
		char_conv_to = NULL;
		char_conv_from = NULL;
	}
#endif
}

void setLocaleCharset() {
#ifdef HAVE_LOCALE
#ifdef HAVE_LANGINFO_CODESET
        char * originalLocale;
        char * charset = NULL;
                                                                                
        if((originalLocale = setlocale(LC_CTYPE,""))) {
                char * temp;
                                                                                
                if((temp = nl_langinfo(CODESET))) {
                        charset = strdup(temp);
                }
                if(!setlocale(LC_CTYPE,originalLocale));
        }
	
	if(localeCharset) free(localeCharset);
                                                                                
        if(charset) {
		localeCharset = strdup(charset);
                free(charset);
		return;
        }
	/*printf("localCharset: %s\n",localeCharset);*/
#endif
#endif
        localeCharset = strdup("ISO-8859-1");

}

char * toUtf8(char * from) {
	static char * to = NULL;

	if(to) free(to);

	setCharSetConversion("UTF-8", localeCharset);
	to = convStrDup(from);

	if(!to) to = strdup(from);

	return to;
}

char * fromUtf8(char * from) {
	static char * to = NULL;

	if(to) free(to);

	setCharSetConversion(localeCharset, "UTF-8");
	to = convStrDup(from);

	if(!to) {
		/*printf("not able to convert: %s\n",from);*/
		to = strdup(from);
	}

	return to;
}

--- NEW FILE: util.h ---
/* mpc
 * (c) 2003-2004 by normalperson and Warren Dukes (warren.dukes at gmail.com)
 *              and Daniel Brown (danb at cs.utexas.edu)
 * This project's homepage is: http://www.musicpd.org
 *
 * 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
 */

#ifndef MPC_UTIL_H
#define MPC_UTIL_H

#include "libmpdclient.h"

#define VALUE_CHANGE(type) \
struct type##_value_change { \
        type value; \
        int is_relative; \
};

VALUE_CHANGE(int) /* struct int_value_change */

void printErrorAndExit(mpd_Connection * conn);
void free_pipe_array (int max, char ** array);
int stdinToArgArray(char *** array);
int get_boolean (const char * arg);
int parse_int(const char *, int *);
int parse_songnum(const char *, int *);
int parse_int_value_change(const char *, struct int_value_change *);
void pretty_print_song (mpd_Song * song);

#endif /* MPC_UTIL_H */	

--- NEW FILE: mpc.h ---
/* mpc
 * (c) 2003-2004 by normalperson and Warren Dukes (warren.dukes at gmail.com)
 * This project's homepage is: http://www.musicpd.org
 *
 * 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
 */

#ifndef MPC_H
#define MPC_H

#include "../config.h"

#include "libmpdclient.h"
#define STRING_LENGTH	(2*MAXPATHLEN)

#define STDIN_SYMBOL	"-"

#ifndef DEFAULT_HOST
#  define DEFAULT_HOST "localhost"
#endif /* DEFAULT_HOST */

#ifndef DEFAULT_PORT
#  define DEFAULT_PORT "6600"
#endif /* DEFAULT_PORT */

#ifndef MIN_COLUMNS
#  define MIN_COLUMNS	80
#endif /* MIN_COLUMNS */

typedef int (* cmdhandler)(int argc, char ** argv, mpd_Connection * conn);

#ifdef DEBUG
#  define dbg(fmt, arg...) do { printf("%s: "fmt,__func__, ## arg); } while (0)
#else
#  define dbg(fmt, arg...) do { } while (0)
#endif /* DEBUG */

#endif /* MPC_H */

--- NEW FILE: libmpdclient.h ---
/* libmpdclient
   (c)2003-2004 by Warren Dukes (warren.dukes at gmail.com)
   This project's homepage is: http://www.musicpd.org
  
   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:
                                                                                
   - Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
                                                                                
   - Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
                                                                                
   - Neither the name of the Music Player Daemon nor the names of its
   contributors may be used to endorse or promote products derived from
   this software without specific prior written permission.
                                                                                
   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef LIBMPDCLIENT_H
#define LIBMPDCLIENT_H

#include <sys/time.h>

#define MPD_BUFFER_MAX_LENGTH	50000
#define MPD_WELCOME_MESSAGE	"OK MPD "

#define MPD_ERROR_TIMEOUT	10 /* timeout trying to talk to mpd */
#define MPD_ERROR_SYSTEM	11 /* system error */
#define MPD_ERROR_UNKHOST	12 /* unknown host */
#define MPD_ERROR_CONNPORT	13 /* problems connecting to port on host */
#define MPD_ERROR_NOTMPD	14 /* mpd not running on port at host */
#define MPD_ERROR_NORESPONSE	15 /* no response on attempting to connect */
#define MPD_ERROR_SENDING	16 /* error sending command */
#define MPD_ERROR_CONNCLOSED	17 /* connection closed by mpd */
#define MPD_ERROR_ACK		18 /* ACK returned! */
#define MPD_ERROR_BUFFEROVERRUN	19 /* Buffer was overrun! */

#define MPD_ACK_ERROR_UNK	-1
#define MPD_ERROR_AT_UNK	-1

#define MPD_ACK_ERROR_NOT_LIST			1
#define MPD_ACK_ERROR_ARG			2
#define MPD_ACK_ERROR_PASSWORD			3
#define MPD_ACK_ERROR_PERMISSION		4
#define MPD_ACK_ERROR_UNKNOWN_CMD		5

#define MPD_ACK_ERROR_NO_EXIST			50
#define MPD_ACK_ERROR_PLAYLIST_MAX		51
#define MPD_ACK_ERROR_SYSTEM			52
#define MPD_ACK_ERROR_PLAYLIST_LOAD		53
#define MPD_ACK_ERROR_UPDATE_ALREADY		54
#define MPD_ACK_ERROR_PLAYER_SYNC		55
#define MPD_ACK_ERROR_EXIST			56

#ifdef __cplusplus
extern "C" {
#endif

/* internal stuff don't touch this struct */
typedef struct _mpd_ReturnElement {
	char * name;
	char * value;
} mpd_ReturnElement;

/* mpd_Connection
 * holds info about connection to mpd
 * use error, and errorStr to detect errors
 */
typedef struct _mpd_Connection {
	/* use this to check the version of mpd */
	int version[3];
	/* IMPORTANT, you want to get the error messages from here */
	char errorStr[MPD_BUFFER_MAX_LENGTH+1];
	int errorCode;
	int errorAt;
	/* this will be set to MPD_ERROR_* if there is an error, 0 if not */
	int error;
	/* DON'T TOUCH any of the rest of this stuff */
	int sock; 
	char buffer[MPD_BUFFER_MAX_LENGTH+1];
	int buflen;
	int bufstart;
	int doneProcessing;
	int listOks;
	int doneListOk;
	int commandList;
	mpd_ReturnElement * returnElement;
	struct timeval timeout;
} mpd_Connection;

/* mpd_newConnection
 * use this to open a new connection
 * you should use mpd_closeConnection, when your done with the connection,
 * even if an error has occurred
 * _timeout_ is the connection timeout period in seconds
 */
mpd_Connection * mpd_newConnection(const char * host, int port, float timeout);

void mpd_setConnectionTimeout(mpd_Connection * connection, float timeout);

/* mpd_closeConnection
 * use this to close a connection and free'ing subsequent memory
 */
void mpd_closeConnection(mpd_Connection * connection);

/* mpd_clearError
 * clears error
 */
void mpd_clearError(mpd_Connection * connection);

/* STATUS STUFF */

/* use these with status.state to determine what state the player is in */
#define MPD_STATUS_STATE_UNKNOWN	0
#define MPD_STATUS_STATE_STOP		1
#define MPD_STATUS_STATE_PLAY		2
#define MPD_STATUS_STATE_PAUSE		3

/* us this with status.volume to determine if mpd has volume support */
#define MPD_STATUS_NO_VOLUME		-1

/* mpd_Status
 * holds info return from status command
 */
typedef struct mpd_Status {
	/* 0-100, or MPD_STATUS_NO_VOLUME when there is no volume support */
	int volume;
	/* 1 if repeat is on, 0 otherwise */
	int repeat;
	/* 1 if random is on, 0 otherwise */
	int random;
	/* playlist length */
	int playlistLength;
	/* playlist, use this to determine when the playlist has changed */
	long long playlist;
	/* use with MPD_STATUS_STATE_* to determine state of player */
	int state;
	/* crossfade setting in seconds */
	int crossfade;
	/* if a song is currently selected (always the case when state is
	 * PLAY or PAUSE), this is the position of the currently
	 * playing song in the playlist, beginning with 0
	 */
	int song;
	/* Song ID of the currently selected song */
	int songid;
	/* time in seconds that have elapsed in the currently playing/paused
	 * song
	 */
	int elapsedTime;
	/* length in seconds of the currently playing/paused song */
	int totalTime;
	/* current bit rate in kbs */
	int bitRate;
	/* audio sample rate */
	unsigned int sampleRate;
	/* audio bits */
	int bits;
	/* audio channels */
	int channels;
	/* 1 if mpd is updating, 0 otherwise */
	int updatingDb;
	/* error */
	char * error;
} mpd_Status;

void mpd_sendStatusCommand(mpd_Connection * connection);

/* mpd_getStatus
 * returns status info, be sure to free it with mpd_freeStatus()
 * call this after mpd_sendStatusCommand()
 */
mpd_Status * mpd_getStatus(mpd_Connection * connection);

/* mpd_freeStatus
 * free's status info malloc'd and returned by mpd_getStatus
 */
void mpd_freeStatus(mpd_Status * status);

typedef struct _mpd_Stats {
	int numberOfArtists;
	int numberOfAlbums;
	int numberOfSongs;
	unsigned long uptime;
	unsigned long dbUpdateTime;
	unsigned long playTime;
	unsigned long dbPlayTime;
} mpd_Stats;

void mpd_sendStatsCommand(mpd_Connection * connection);

mpd_Stats * mpd_getStats(mpd_Connection * connection);

void mpd_freeStats(mpd_Stats * stats);

/* SONG STUFF */

#define MPD_SONG_NO_TIME	-1
#define MPD_SONG_NO_NUM		-1
#define MPD_SONG_NO_ID		-1

/* mpd_Song
 * for storing song info returned by mpd
 */
typedef struct _mpd_Song {
	/* filename of song */
	char * file;
	/* artist, maybe NULL if there is no tag */
	char * artist;
	/* title, maybe NULL if there is no tag */
	char * title;
	/* album, maybe NULL if there is no tag */
	char * album;
	/* track, maybe NULL if there is no tag */
	char * track;
	/* name, maybe NULL if there is no tag; it's the name of the current
	 * song, f.e. the icyName of the stream */
	char * name;
	/* date */
	char *date;
	/* length of song in seconds, check that it is not MPD_SONG_NO_TIME  */
	int time;
	/* if plchanges/playlistinfo/playlistid used, is the position of the 
	 * song in the playlist */
	int pos;
	/* song id for a song in the playlist */
	int id;
} mpd_Song;

/* mpd_newSong
 * use to allocate memory for a new mpd_Song
 * file, artist, etc all initialized to NULL
 * if your going to assign values to file, artist, etc
 * be sure to malloc or strdup the memory
 * use mpd_freeSong to free the memory for the mpd_Song, it will also
 * free memory for file, artist, etc, so don't do it yourself
 */
mpd_Song * mpd_newSong();

/* mpd_freeSong
 * use to free memory allocated by mpd_newSong
 * also it will free memory pointed to by file, artist, etc, so be careful
 */
void mpd_freeSong(mpd_Song * song);

/* mpd_songDup
 * works like strDup, but for a mpd_Song
 */
mpd_Song * mpd_songDup(mpd_Song * song);

/* DIRECTORY STUFF */

/* mpd_Directory
 * used to store info fro directory (right now that just the path)
 */
typedef struct _mpd_Directory {
	char * path;
} mpd_Directory;

/* mpd_newDirectory
 * allocates memory for a new directory
 * use mpd_freeDirectory to free this memory
 */
mpd_Directory * mpd_newDirectory ();

/* mpd_freeDirectory
 * used to free memory allocated with mpd_newDirectory, and it frees
 * path of mpd_Directory, so be careful
 */
void mpd_freeDirectory(mpd_Directory * directory);

/* mpd_directoryDup
 * works like strdup, but for mpd_Directory
 */
mpd_Directory * mpd_directoryDup(mpd_Directory * directory);

/* PLAYLISTFILE STUFF */

/* mpd_PlaylistFile
 * stores info about playlist file returned by lsinfo
 */
typedef struct _mpd_PlaylistFile {
	char * path;
} mpd_PlaylistFile;

/* mpd_newPlaylistFile
 * allocates memory for new mpd_PlaylistFile, path is set to NULL
 * free this memory with mpd_freePlaylistFile
 */
mpd_PlaylistFile * mpd_newPlaylistFile();

/* mpd_freePlaylist
 * free memory allocated for freePlaylistFile, will also free
 * path, so be careful
 */
void mpd_freePlaylistFile(mpd_PlaylistFile * playlist);

/* mpd_playlistFileDup
 * works like strdup, but for mpd_PlaylistFile
 */
mpd_PlaylistFile * mpd_playlistFileDup(mpd_PlaylistFile * playlist);

/* INFO ENTITY STUFF */

/* the type of entity returned from one of the commands that generates info
 * use in conjunction with mpd_InfoEntity.type
 */
#define MPD_INFO_ENTITY_TYPE_DIRECTORY		0
#define MPD_INFO_ENTITY_TYPE_SONG		1
#define MPD_INFO_ENTITY_TYPE_PLAYLISTFILE	2

/* mpd_InfoEntity
 * stores info on stuff returned info commands
 */
typedef struct mpd_InfoEntity {
	/* the type of entity, use with MPD_INFO_ENTITY_TYPE_* to determine
	 * what this entity is (song, directory, etc...)
	 */
	int type;
	/* the actual data you want, mpd_Song, mpd_Directory, etc */
	union {
		mpd_Directory * directory;
		mpd_Song * song;
		mpd_PlaylistFile * playlistFile;
	} info;
} mpd_InfoEntity;

mpd_InfoEntity * mpd_newInfoEntity();

void mpd_freeInfoEntity(mpd_InfoEntity * entity);

/* INFO COMMANDS AND STUFF */

/* use this function to loop over after calling Info/Listall functions */
mpd_InfoEntity * mpd_getNextInfoEntity(mpd_Connection * connection);

/* fetches the currently seeletect song (the song referenced by status->song
 * and status->songid*/
void mpd_sendCurrentSongCommand(mpd_Connection * connection);

/* songNum of -1, means to display the whole list */
void mpd_sendPlaylistInfoCommand(mpd_Connection * connection, int songNum);

/* songId of -1, means to display the whole list */
void mpd_sendPlaylistIdCommand(mpd_Connection * connection, int songId);

/* use this to get the changes in the playlist since version _playlist_ */
void mpd_sendPlChangesCommand(mpd_Connection * connection, long long playlist);

/* recursivel fetches all songs/dir/playlists in "dir* (no metadata is 
 * returned) */
void mpd_sendListallCommand(mpd_Connection * connection, const char * dir);

/* same as sendListallCommand, but also metadata is returned */
void mpd_sendListallInfoCommand(mpd_Connection * connection, const char * dir);

/* non-recursive version of ListallInfo */
void mpd_sendLsInfoCommand(mpd_Connection * connection, const char * dir);

#define MPD_TABLE_ARTIST	0
#define MPD_TABLE_ALBUM		1
#define MPD_TABLE_TITLE		2
#define MPD_TABLE_FILENAME	3

void mpd_sendSearchCommand(mpd_Connection * connection, int table, 
		const char * str);

void mpd_sendFindCommand(mpd_Connection * connection, int table, 
		const char * str);

/* LIST TAG COMMANDS */

/* use this function fetch next artist entry, be sure to free the returned 
 * string.  NULL means there are no more.  Best used with sendListArtists
 */
char * mpd_getNextArtist(mpd_Connection * connection);

char * mpd_getNextAlbum(mpd_Connection * connection);

/* list artist or albums by artist, arg1 should be set to the artist if
 * listing albums by a artist, otherwise NULL for listing all artists or albums
 */
void mpd_sendListCommand(mpd_Connection * connection, int table, 
		const char * arg1);

/* SIMPLE COMMANDS */

void mpd_sendAddCommand(mpd_Connection * connection, const char * file);

void mpd_sendDeleteCommand(mpd_Connection * connection, int songNum);

void mpd_sendDeleteIdCommand(mpd_Connection * connection, int songNum);

void mpd_sendSaveCommand(mpd_Connection * connection, const char * name);

void mpd_sendLoadCommand(mpd_Connection * connection, const char * name);

void mpd_sendRmCommand(mpd_Connection * connection, const char * name);

void mpd_sendShuffleCommand(mpd_Connection * connection);

void mpd_sendClearCommand(mpd_Connection * connection);

/* use this to start playing at the beginning, useful when in random mode */
#define MPD_PLAY_AT_BEGINNING	-1

void mpd_sendPlayCommand(mpd_Connection * connection, int songNum);

void mpd_sendPlayIdCommand(mpd_Connection * connection, int songNum);

void mpd_sendStopCommand(mpd_Connection * connection);

void mpd_sendPauseCommand(mpd_Connection * connection, int pauseMode);

void mpd_sendNextCommand(mpd_Connection * connection);

void mpd_sendPrevCommand(mpd_Connection * connection);

void mpd_sendMoveCommand(mpd_Connection * connection, int from, int to);

void mpd_sendMoveIdCommand(mpd_Connection * connection, int from, int to);

void mpd_sendSwapCommand(mpd_Connection * connection, int song1, int song2);

void mpd_sendSwapIdCommand(mpd_Connection * connection, int song1, int song2);

void mpd_sendSeekCommand(mpd_Connection * connection, int song, int time);

void mpd_sendSeekIdCommand(mpd_Connection * connection, int song, int time);

void mpd_sendRepeatCommand(mpd_Connection * connection, int repeatMode);

void mpd_sendRandomCommand(mpd_Connection * connection, int randomMode);

void mpd_sendSetvolCommand(mpd_Connection * connection, int volumeChange);

/* WARNING: don't use volume command, its depreacted */
void mpd_sendVolumeCommand(mpd_Connection * connection, int volumeChange);

void mpd_sendCrossfadeCommand(mpd_Connection * connection, int seconds);

void mpd_sendUpdateCommand(mpd_Connection * connection, char * path);

/* returns the update job id, call this after a update command*/
int mpd_getUpdateId(mpd_Connection * connection);

void mpd_sendPasswordCommand(mpd_Connection * connection, const char * pass);

/* after executing a command, when your done with it to get its status
 * (you want to check connection->error for an error)
 */
void mpd_finishCommand(mpd_Connection * connection);

/* command list stuff, use this to do things like add files very quickly */
void mpd_sendCommandListBegin(mpd_Connection * connection);

void mpd_sendCommandListOkBegin(mpd_Connection * connection);

void mpd_sendCommandListEnd(mpd_Connection * connection);

/* advance to the next listOk 
 * returns 0 if advanced to the next list_OK,
 * returns -1 if it advanced to an OK or ACK */
int mpd_nextListOkCommand(mpd_Connection * connection);

typedef struct _mpd_OutputEntity {
	int id;
	char * name;
	int enabled;
} mpd_OutputEntity;

void mpd_sendOutputsCommand(mpd_Connection * connection);

mpd_OutputEntity * mpd_getNextOutput(mpd_Connection * connection);

void mpd_sendEnableOutputCommand(mpd_Connection * connection, int outputId);

void mpd_sendDisableOutputCommand(mpd_Connection * connection, int outputId);

void mpd_freeOutputElement(mpd_OutputEntity * output);

#ifdef __cplusplus
}
#endif

#endif

--- NEW FILE: main.c ---
/* mpc
 * (c) 2003-2004 by Warren Dukes (warren.dukes at gmail.com)
 *                  Daniel Brown (danb at cs.utexas.edu)
 * This project's homepage is: http://www.musicpd.org
 *
 * 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
 */

#include "libmpdclient.h"
#include "list.h"
#include "charConv.h"
#include "password.h"
#include "util.h"
#include "status.h"
#include "command.h"
#include "mpc.h"
#include "options.h"

#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/param.h>

struct _mpc_table {
	const char * command; 
	const int min, max;	/* min/max arguments allowed, -1 = unlimited */
	int pipe;		/* 
				1: implicit pipe read, `-' optional as argv[2]
				2: explicit pipe read `-' needed as argv[2]
				3: explicit pipe read `-' needed as argv[3]
				multipled by -1 if used, so that it can signal a free()
				before the program exits
				*/
	cmdhandler handler;
	const char * usage;
	char * help;		/* NULL means they won't be shown in help */
} mpc_table [] = {
	/* Command Name, Minimum Arguments, Maximium args, pipe read (see above), Argument description, command description */
	{"add", 0, -1, 1, cmd_add,"<filename>","Add a song to the current playlist" },
	{"crop", 0, 0, 0, cmd_crop,"","Remove all songs except for the currently playing song" },
	{"del", 0, -1, 1, cmd_del,"<playlist #>","Remove a song from the current playlist" },
	{"play", 0, -1, 2, cmd_play,"<number>","Start playing at <number> (default: 1)" },
	{"next", 0, 0, 0, cmd_next, "","Play the next song in the current playlist"},
	{"prev", 0, 0, 0, cmd_prev,"","Play the previous song in the current playlist"},
	{"pause", 0, 0, 0, cmd_pause, "", "Pauses the currently playing song"},
	{"toggle", 0, 0, 0, cmd_toggle, "", "Toggles Play/Pause, plays if stopped"},
	{"stop", 0, 0, 0, cmd_stop,"", "Stop the currently playing playlists"},
	{"seek", 1, 1, 0, cmd_seek,"[+-][HH:MM:SS] or <0-100>%","Seeks to the specified position"},
	{"clear", 0, 0, 0, cmd_clear,"", "Clear the current playlist"},
	/*
	{"outputs", 0, 0, 0, cmd_outputs,"", "Show the current outputs"},
	{"enable", 1, 1, 0, cmd_enable, "<output #>", "Enable a output"},
	{"disable", 1, 1, 0, cmd_disable, "<output #>", "Disable a output"},
	*/
	{"shuffle", 0, 0, 0, cmd_shuffle,"", "Shuffle the current playlist"},
	{"move", 2, 2, 0, cmd_move,"<from> <to>", "Move song in playlist"},
	{"playlist", 0, 0, 0, cmd_playlist, "", "Print the current playlist"},
	{"listall", 0, -1, 2, cmd_listall,"[<song>]","List all songs in the music dir"},
	{"ls", 0, -1, 2, cmd_ls,"[<dir>]","List the contents of <dir>"},
	{"lsplaylists", 0, -1, 2, cmd_lsplaylists,"", "Lists currently available playlists"},
	{"load", 0, -1, 1, cmd_load,"<file>","Load <file> as a playlist"},
	{"save", 1, 1, 0, cmd_save,"<file>", "Saves a playlist as <file>"},
	{"rm", 1, 1, 0, cmd_rm,"<file>","Removes a playlist"},
	{"volume", 0, 1, 0, cmd_volume,"[+-]<num>","Sets volume to <num> or adjusts by [+-]<num>"},
	{"repeat", 0, 1, 0, cmd_repeat,"<on|off>", "Toggle repeat mode, or specify state"},
	{"random", 0, 1, 0, cmd_random,"<on|off>", "Toggle random mode, or specify state"},
	{"search", 2, -1, 3, cmd_search, "<type> <queries>",	"Search for a song"},
	{"crossfade", 0, 1, 0, cmd_crossfade,"[sec]","Set and display crossfade settings"},
	{"update", 0, -1, 2, cmd_update,	"", "Scans music directory for updates"},
	{"stats", 0, -1, 0, cmd_stats, "", "Displays statistics about MPD"}, 
	{"version", 0, 0, 0, cmd_version,"", "Reports version of MPD"},
	/*  loadtab, lstab, and tab used for completion-scripting only */
	{"loadtab",0, 1, 0, cmd_loadtab,"<directory>",}, 
	{"lstab",0, 1, 0, cmd_lstab,"<directory>",}, 
	{"tab",0, 1, 0, cmd_tab,"<directory/file>",},
	/* status was added for pedantic reasons */
	{"status", 0, -1, 0, cmd_status, "", NULL }, 
	/* don't remove this, when mpc_table[i].command is NULL it will terminate the loop */
	{}
};

void print_help (int max, char * progname, char * command)
{
	int i;

	if(command && strcmp(command,"help"))
			fprintf(stderr,"unknown command \"%s\"\n",command);
	fprintf(stderr,"Usage: %s <command> [command args]...\n"
		"mpc version: "VERSION"\n",progname);
	fprintf(stderr,	"%s %*s  Displays status\n",progname,max," ");
	
	for (i=0; mpc_table[i].command; ++i) {
		int spaces;
		
		if (!mpc_table[i].help)
			continue ;
		spaces = max-(strlen(mpc_table[i].command)+strlen(mpc_table[i].usage));
		spaces += !spaces ? 0 : 1;

		fprintf(stderr,"%s %s %s%*s%s\n",progname,
			mpc_table[i].command,mpc_table[i].usage,
			spaces," ",mpc_table[i].help);
		
	}
	fprintf(stderr,"For more information about these and other options look at man 1 mpc\n");
}

mpd_Connection * setup_connection ()
{
	char * host = DEFAULT_HOST;
	char * port = DEFAULT_PORT;
	int iport;
	char * test;
	int port_env = 0;
	int host_env = 0;
	int password_len= 0;
	int parsed_len = 0;
	mpd_Connection * conn;
	
	if((test = getenv("MPD_HOST"))) {
		host =test;
		host_env = 1;
	}

	if((test = getenv("MPD_PORT"))) {
		port = test;
		port_env = 1;
	}

	iport = strtol(port,&test,10);
	
	if(iport<0 || *test!='\0') {
		fprintf(stderr,"MPD_PORT \"%s\" is not a positive integer\n",
				port);
		exit(EXIT_FAILURE);
	}

	parse_password(host, &password_len, &parsed_len);
	
	conn = mpd_newConnection(host+parsed_len,iport,10);

	if(conn->error && (!port_env || !host_env)) 
		fprintf(stderr,"MPD_HOST and/or MPD_PORT environment variables"
			" are not set\n");
	
	printErrorAndExit(conn);

	if(password_len) 
		send_password (host, password_len, conn);

	return conn;
}

void print_status_and_exit () 
{
	mpd_Connection * conn = setup_connection();
	print_status(conn);
	mpd_closeConnection(conn);
	fclose(stdout);
	exit(EXIT_SUCCESS);
}

/* check arguments to see if they are valid */
char ** check_args (int idx, int * argc, char ** argv)
{
	char ** array;
	int i;
	
	if ( ( mpc_table[idx].pipe==1 &&
		(2==*argc || (3==*argc && 0==strcmp(argv[2],STDIN_SYMBOL) )))
	|| (mpc_table[idx].pipe==2 && (3==*argc && 0==strcmp(argv[2],STDIN_SYMBOL)))
	|| (mpc_table[idx].pipe==3 && (4==*argc && 0==strcmp(argv[3],STDIN_SYMBOL)))
	){
		*argc = stdinToArgArray(&array);
		mpc_table[idx].pipe *= -1;
	} else {
		*argc -= 2;
		array = malloc( (*argc * (sizeof(char *))));
		for(i=0;i<*argc;++i) {
			array[i]=argv[i+2];
		}
	}
	if (	(-1!=mpc_table[idx].min && (*argc)<mpc_table[idx].min)
	||	(-1!=mpc_table[idx].max && (*argc)>mpc_table[idx].max) ) {
		fprintf(stderr,"usage: %s %s %s\n", argv[0], mpc_table[idx].command,
			mpc_table[idx].usage);
			exit (EXIT_FAILURE);
	}
	return array;
}

int main(int argc, char ** argv)
{
	int i = 0;
	int helplen = 0;
	int ret = 0;
	setLocaleCharset();

	if(parse_options(&argc, argv) < 0) {
		print_help(helplen,argv[0],NULL);
		exit(EXIT_FAILURE);
	}

	if (argc==1)
		print_status_and_exit ();

	for (i = 0; mpc_table[i].command; ++i) {
		if ( ! strcmp(argv[1], mpc_table[i].command) ) {
			char ** array = check_args (i, &argc , argv);
			mpd_Connection * conn = setup_connection();
			
			/* not a typo, assignment intended */
			if( (ret=mpc_table[i].handler(argc, array, conn)))
				print_status(conn);
			
			if (0>mpc_table[i].pipe)
				free_pipe_array(argc,array);
			
			free(array);
			mpd_closeConnection(conn);
			fclose(stdout);
			return EXIT_SUCCESS;
		} else if (mpc_table[i].help) {
			int tmp = strlen(mpc_table[i].command) + strlen(mpc_table[i].usage);
			helplen = (tmp > helplen) ? tmp : helplen;
		}
	}
	print_help(helplen,argv[0],argv[1]);
	fclose(stdout);
	return EXIT_SUCCESS;
}


--- NEW FILE: Makefile.am ---
bin_PROGRAMS = mpc
# lots of += lines makes diffs easier to apply :)

mpc_headers  = libmpdclient.h 
mpc_headers += list.h
mpc_headers += password.h
mpc_headers += charConv.h
mpc_headers += status.h
mpc_headers += util.h
mpc_headers += command.h
mpc_headers += mpc.h
mpc_headers += options.h

mpc_SOURCES  = libmpdclient.c 
mpc_SOURCES += main.c
mpc_SOURCES += list.c 
mpc_SOURCES += password.c 
mpc_SOURCES += charConv.c
mpc_SOURCES += status.c
mpc_SOURCES += util.c
mpc_SOURCES += command.c
mpc_SOURCES += options.c
mpc_SOURCES += $(mpc_headers)

--- NEW FILE: charConv.h ---
/* the Music Player Daemon (MPD)
 * (c)2003-2004 by Warren Dukes (warren.dukes at gmail.com)
 * This project's homepage is: http://www.musicpd.org
 *
 * 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
 */

#ifndef CHAR_CONV_H
#define CHAR_CONV_H

char * toUtf8(char * from);

char * fromUtf8(char * to);

void setLocaleCharset();

int setCharSetConversion(char * to, char * from);

char * convStrDup(char * string);

void closeCharSetConversion();

#endif

--- NEW FILE: status.c ---
/* 
 * (c)2003-2004 by Warren Dukes (warren.dukes at gmail.com)
 *                 Daniel Brown (danb at cs.utexas.edu)
 * This project's homepage is: http://www.musicpd.org
 *
 * 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
 */


#include "libmpdclient.h"
#include "charConv.h"
#include "util.h"
#include "mpc.h"

#include <assert.h>
#include <stdio.h>
#include <string.h>

void print_status (mpd_Connection *conn)
{
	mpd_Status * status;
	mpd_InfoEntity * entity;

	mpd_sendCommandListOkBegin(conn);
	printErrorAndExit(conn);
	mpd_sendStatusCommand(conn);
	printErrorAndExit(conn);
	mpd_sendCurrentSongCommand(conn);
	printErrorAndExit(conn);
	mpd_sendCommandListEnd(conn);
	printErrorAndExit(conn);

	status = mpd_getStatus(conn);
	printErrorAndExit(conn);

	if(status->state == MPD_STATUS_STATE_PLAY || 
			status->state == MPD_STATUS_STATE_PAUSE) 
	{
		float perc;

		mpd_nextListOkCommand(conn);
		printErrorAndExit(conn);
			
		while((entity = mpd_getNextInfoEntity(conn))) {
			mpd_Song * song = entity->info.song;
			
			if(entity->type!=MPD_INFO_ENTITY_TYPE_SONG) {
				mpd_freeInfoEntity(entity);
				continue;
			}

			pretty_print_song(song);
			printf("\n");

			mpd_freeInfoEntity(entity);

			break;
		}

		printErrorAndExit(conn);

		mpd_finishCommand(conn);
		printErrorAndExit(conn);

		if(status->state==MPD_STATUS_STATE_PLAY) {
			printf("[playing]");
		}
		else printf("[paused] ");

		perc = status->elapsedTime<status->totalTime ?
				100.0*status->elapsedTime/status->totalTime :
				100.0;

		printf(" #%i/%i %3i:%02i (%.0f%c)\n",
				status->song+1,
				status->playlistLength,
				status->elapsedTime/60,
				status->elapsedTime%60,
				perc,'%');
	}

	if(status->updatingDb) {
		printf("Updating DB (#%i) ...\n",status->updatingDb);
	}

	if(status->volume!=MPD_STATUS_NO_VOLUME) {
		printf("volume:%3i%c   ",status->volume,'%');
	}
	else {
		printf("volume: n/a   ");
	}

	printf("repeat: ");
	if(status->repeat) printf("on    ");
	else printf("off   ");

	printf("random: ");
	if(status->random) printf("on \n");
	else printf("off\n");

	mpd_freeStatus(status);
}





More information about the dslinux-commit mailing list