/*
    TiMidity++ -- MIDI to WAVE converter and player
    Copyright (C) 1999-2018 Masanao Izumo <iz@onicos.co.jp>
    Copyright (C) 1995 Tuukka Toivonen <tt@cgs.fi>

    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
*/

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */
#ifdef __POCC__
#include <sys/types.h>
#endif //for off_t
#include <stdio.h>
#ifdef STDC_HEADERS
#include <stdlib.h>
#include <ctype.h>
#include <stddef.h>
#endif
#ifndef NO_STRING_H
#include <string.h>
#else
#include <strings.h>
#endif
#ifdef __W32__
#include <windows.h>
#include <io.h>
#include <shlobj.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif /* HAVE_UNISTD_H */
#include <time.h>
#ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
#endif /* HAVE_SYS_TIME_H */
#include <fcntl.h> /* for open */

#ifdef BORLANDC_EXCEPTION
#include <excpt.h>
#endif /* BORLANDC_EXCEPTION */
#include <signal.h>

#if defined(__FreeBSD__) && !defined(__alpha__)
#include <floatingpoint.h> /* For FP exceptions */
#endif
#if defined(__NetBSD__) || defined(__OpenBSD__)
#include <ieeefp.h> /* For FP exceptions */
#endif

#include "interface.h"
#include "timidity.h"
#include "tmdy_getopt.h"
#include "common.h"
#include "instrum.h"
#include "playmidi.h"
#include "readmidi.h"
#include "output.h"
#include "controls.h"
#include "tables.h"
#include "miditrace.h"
#include "reverb.h"
#ifdef SUPPORT_SOUNDSPEC
#include "soundspec.h"
#endif /* SUPPORT_SOUNDSPEC */
#include "resample.h"
#include "recache.h"
#include "arc.h"
#include "strtab.h"
#include "wrd.h"
#define DEFINE_GLOBALS
#include "mid.defs"
#include "aq.h"
#include "mix.h"
#include "unimod.h"
#include "quantity.h"
#include "rtsyn.h"

#ifdef AU_SPEEX
#include "speex_a.h"
#endif

#ifdef AU_FLAC
#include "flac_a.h"
#endif

#ifdef __BORLANDC__
#undef inline
#define inline
#endif

#ifdef IA_W32GUI
#include "w32g.h"
#include "w32g_utl.h"
#endif

#ifdef WINDRV
/* supress std outputs */
#define fputs(a, b)
#endif

#ifndef __GNUC__
#define __attribute__(x) /* ignore */
#endif

/* option enums */
enum {
	TIM_OPT_FIRST = 256,
	/* first entry */
	TIM_OPT_VOLUME = TIM_OPT_FIRST,
	TIM_OPT_DRUM_POWER,
	TIM_OPT_VOLUME_COMP,
	TIM_OPT_ANTI_ALIAS,
	TIM_OPT_BUFFER_FRAGS,
	TIM_OPT_CONTROL_RATIO,
	TIM_OPT_CONFIG_FILE,
	TIM_OPT_DRUM_CHANNEL,
	TIM_OPT_IFACE_PATH,
	TIM_OPT_EXT,
	TIM_OPT_MOD_WHEEL,
	TIM_OPT_PORTAMENTO,
	TIM_OPT_VIBRATO,
	TIM_OPT_CH_PRESS,
	TIM_OPT_MOD_ENV,
	TIM_OPT_TRACE_TEXT,
	TIM_OPT_OVERLAP,
	TIM_OPT_TEMPER_CTRL,
	TIM_OPT_DEFAULT_MID,
	TIM_OPT_SYSTEM_MID,
	TIM_OPT_DEFAULT_BANK,
	TIM_OPT_FORCE_BANK,
	TIM_OPT_DEFAULT_PGM,
	TIM_OPT_FORCE_PGM,
	TIM_OPT_DELAY,
	TIM_OPT_CHORUS,
	TIM_OPT_REVERB,
	TIM_OPT_VOICE_LPF,
	TIM_OPT_NS,
	TIM_OPT_RESAMPLE,
	TIM_OPT_EVIL,
	TIM_OPT_FAST_PAN,
	TIM_OPT_FAST_DECAY,
	TIM_OPT_SEGMENT,
	TIM_OPT_SPECTROGRAM,
	TIM_OPT_KEYSIG,
	TIM_OPT_HELP,
	TIM_OPT_INTERFACE,
	TIM_OPT_VERBOSE,
	TIM_OPT_QUIET,
	TIM_OPT_TRACE,
	TIM_OPT_LOOP,
	TIM_OPT_RANDOM,
	TIM_OPT_SORT,
	TIM_OPT_BACKGROUND,
	TIM_OPT_RT_PRIO,
	TIM_OPT_SEQ_PORTS,
	TIM_OPT_RTSYN_LATENCY,
	TIM_OPT_REALTIME_LOAD,
	TIM_OPT_ADJUST_KEY,
	TIM_OPT_VOICE_QUEUE,
	TIM_OPT_PATCH_PATH,
	TIM_OPT_PCM_FILE,
	TIM_OPT_DECAY_TIME,
	TIM_OPT_INTERPOLATION,
	TIM_OPT_OUTPUT_MODE,
	TIM_OPT_OUTPUT_STEREO,
	TIM_OPT_OUTPUT_SIGNED,
	TIM_OPT_OUTPUT_BITWIDTH,
	TIM_OPT_OUTPUT_FORMAT,
	TIM_OPT_OUTPUT_SWAB,
	TIM_OPT_FLAC_VERIFY,
	TIM_OPT_FLAC_PADDING,
	TIM_OPT_FLAC_COMPLEVEL,
	TIM_OPT_FLAC_OGGFLAC,
	TIM_OPT_SPEEX_QUALITY,
	TIM_OPT_SPEEX_VBR,
	TIM_OPT_SPEEX_ABR,
	TIM_OPT_SPEEX_VAD,
	TIM_OPT_SPEEX_DTX,
	TIM_OPT_SPEEX_COMPLEXITY,
	TIM_OPT_SPEEX_NFRAMES,
	TIM_OPT_OUTPUT_FILE,
	TIM_OPT_PATCH_FILE,
	TIM_OPT_POLYPHONY,
	TIM_OPT_POLY_REDUCE,
	TIM_OPT_MUTE,
	TIM_OPT_TEMPER_MUTE,
	TIM_OPT_PRESERVE_SILENCE,
	TIM_OPT_AUDIO_BUFFER,
	TIM_OPT_CACHE_SIZE,
	TIM_OPT_SAMPLE_FREQ,
	TIM_OPT_ADJUST_TEMPO,
	TIM_OPT_CHARSET,
	TIM_OPT_UNLOAD_INST,
	TIM_OPT_VOLUME_CURVE,
	TIM_OPT_VERSION,
	TIM_OPT_WRD,
	TIM_OPT_RCPCV_DLL,
	TIM_OPT_CONFIG_STR,
	TIM_OPT_FREQ_TABLE,
	TIM_OPT_PURE_INT,
	TIM_OPT_MODULE,
	/* last entry */
	TIM_OPT_LAST = TIM_OPT_MODULE
};

#ifdef IA_WINSYN
const char *optcommands =
#else
static const char *optcommands =
#endif
		"4A:aB:b:C:c:D:d:E:eFfG:g:H:hI:i:jK:k:L:M:m:N:"
		"O:o:P:p:Q:q:R:S:s:T:t:UV:vW:"
#ifdef __W32__
		"w:"
#endif
		"x:Z:";		/* Only JlnruXYyz are remain... */
#ifdef IA_WINSYN
const struct option longopts[] = {
#else
static const struct option longopts[] = {
#endif
	{ "volume",                 required_argument, NULL, TIM_OPT_VOLUME },
	{ "drum-power",             required_argument, NULL, TIM_OPT_DRUM_POWER },
	{ "no-volume-compensation", no_argument,       NULL, TIM_OPT_DRUM_POWER },
	{ "volume-compensation",    optional_argument, NULL, TIM_OPT_VOLUME_COMP },
	{ "no-anti-alias",          no_argument,       NULL, TIM_OPT_ANTI_ALIAS },
	{ "anti-alias",             optional_argument, NULL, TIM_OPT_ANTI_ALIAS },
	{ "buffer-fragments",       required_argument, NULL, TIM_OPT_BUFFER_FRAGS },
	{ "control-ratio",          required_argument, NULL, TIM_OPT_CONTROL_RATIO },
	{ "config-file",            required_argument, NULL, TIM_OPT_CONFIG_FILE },
	{ "drum-channel",           required_argument, NULL, TIM_OPT_DRUM_CHANNEL },
	{ "interface-path",         required_argument, NULL, TIM_OPT_IFACE_PATH },
	{ "ext",                    required_argument, NULL, TIM_OPT_EXT },
	{ "no-mod-wheel",           no_argument,       NULL, TIM_OPT_MOD_WHEEL },
	{ "mod-wheel",              optional_argument, NULL, TIM_OPT_MOD_WHEEL },
	{ "no-portamento",          no_argument,       NULL, TIM_OPT_PORTAMENTO },
	{ "portamento",             optional_argument, NULL, TIM_OPT_PORTAMENTO },
	{ "no-vibrato",             no_argument,       NULL, TIM_OPT_VIBRATO },
	{ "vibrato",                optional_argument, NULL, TIM_OPT_VIBRATO },
	{ "no-ch-pressure",         no_argument,       NULL, TIM_OPT_CH_PRESS },
	{ "ch-pressure",            optional_argument, NULL, TIM_OPT_CH_PRESS },
	{ "no-mod-envelope",        no_argument,       NULL, TIM_OPT_MOD_ENV },
	{ "mod-envelope",           optional_argument, NULL, TIM_OPT_MOD_ENV },
	{ "no-trace-text-meta",     no_argument,       NULL, TIM_OPT_TRACE_TEXT },
	{ "trace-text-meta",        optional_argument, NULL, TIM_OPT_TRACE_TEXT },
	{ "no-overlap-voice",       no_argument,       NULL, TIM_OPT_OVERLAP },
	{ "overlap-voice",          optional_argument, NULL, TIM_OPT_OVERLAP },
	{ "no-temper-control",      no_argument,       NULL, TIM_OPT_TEMPER_CTRL },
	{ "temper-control",         optional_argument, NULL, TIM_OPT_TEMPER_CTRL },
	{ "default-mid",            required_argument, NULL, TIM_OPT_DEFAULT_MID },
	{ "system-mid",             required_argument, NULL, TIM_OPT_SYSTEM_MID },
	{ "default-bank",           required_argument, NULL, TIM_OPT_DEFAULT_BANK },
	{ "force-bank",             required_argument, NULL, TIM_OPT_FORCE_BANK },
	{ "default-program",        required_argument, NULL, TIM_OPT_DEFAULT_PGM },
	{ "force-program",          required_argument, NULL, TIM_OPT_FORCE_PGM },
	{ "delay",                  required_argument, NULL, TIM_OPT_DELAY },
	{ "chorus",                 required_argument, NULL, TIM_OPT_CHORUS },
	{ "reverb",                 required_argument, NULL, TIM_OPT_REVERB },
	{ "voice-lpf",              required_argument, NULL, TIM_OPT_VOICE_LPF },
	{ "noise-shaping",          required_argument, NULL, TIM_OPT_NS },
#ifndef FIXED_RESAMPLATION
	{ "resample",               required_argument, NULL, TIM_OPT_RESAMPLE },
#endif
	{ "evil",                   required_argument, NULL, TIM_OPT_EVIL },
	{ "no-fast-panning",        no_argument,       NULL, TIM_OPT_FAST_PAN },
	{ "fast-panning",           optional_argument, NULL, TIM_OPT_FAST_PAN },
	{ "no-fast-decay",          no_argument,       NULL, TIM_OPT_FAST_DECAY },
	{ "fast-decay",             optional_argument, NULL, TIM_OPT_FAST_DECAY },
	{ "segment",                required_argument, NULL, TIM_OPT_SEGMENT },
	{ "spectrogram",            required_argument, NULL, TIM_OPT_SPECTROGRAM },
	{ "force-keysig",           required_argument, NULL, TIM_OPT_KEYSIG },
	{ "help",                   optional_argument, NULL, TIM_OPT_HELP },
	{ "interface",              required_argument, NULL, TIM_OPT_INTERFACE },
	{ "verbose",                optional_argument, NULL, TIM_OPT_VERBOSE },
	{ "quiet",                  optional_argument, NULL, TIM_OPT_QUIET },
	{ "no-trace",               no_argument,       NULL, TIM_OPT_TRACE },
	{ "trace",                  optional_argument, NULL, TIM_OPT_TRACE },
	{ "no-loop",                no_argument,       NULL, TIM_OPT_LOOP },
	{ "loop",                   optional_argument, NULL, TIM_OPT_LOOP },
	{ "no-random",              no_argument,       NULL, TIM_OPT_RANDOM },
	{ "random",                 optional_argument, NULL, TIM_OPT_RANDOM },
	{ "no-sort",                no_argument,       NULL, TIM_OPT_SORT },
	{ "sort",                   optional_argument, NULL, TIM_OPT_SORT },
#ifdef IA_ALSASEQ
	{ "no-background",          no_argument,       NULL, TIM_OPT_BACKGROUND },
	{ "background",             optional_argument, NULL, TIM_OPT_BACKGROUND },
	{ "realtime-priority",      required_argument, NULL, TIM_OPT_RT_PRIO },
	{ "sequencer-ports",        required_argument, NULL, TIM_OPT_SEQ_PORTS },
#endif
#if defined(IA_WINSYN) || defined(IA_PORTMIDISYN) || defined(IA_NPSYN) || defined(IA_W32G_SYN) || defined(IA_W32GUI)
	{ "rtsyn-latency",          required_argument, NULL, TIM_OPT_RTSYN_LATENCY },
#endif
	{ "no-realtime-load",       no_argument,       NULL, TIM_OPT_REALTIME_LOAD },
	{ "realtime-load",          optional_argument, NULL, TIM_OPT_REALTIME_LOAD },
	{ "adjust-key",             required_argument, NULL, TIM_OPT_ADJUST_KEY },
	{ "voice-queue",            required_argument, NULL, TIM_OPT_VOICE_QUEUE },
	{ "patch-path",             required_argument, NULL, TIM_OPT_PATCH_PATH },
	{ "pcm-file",               required_argument, NULL, TIM_OPT_PCM_FILE },
	{ "decay-time",             required_argument, NULL, TIM_OPT_DECAY_TIME },
	{ "interpolation",          required_argument, NULL, TIM_OPT_INTERPOLATION },
	{ "output-mode",            required_argument, NULL, TIM_OPT_OUTPUT_MODE },
	{ "output-stereo",          no_argument,       NULL, TIM_OPT_OUTPUT_STEREO },
	{ "output-mono",            no_argument,       NULL, TIM_OPT_OUTPUT_STEREO },
	{ "output-signed",          no_argument,       NULL, TIM_OPT_OUTPUT_SIGNED },
	{ "output-unsigned",        no_argument,       NULL, TIM_OPT_OUTPUT_SIGNED },
	{ "output-16bit",           no_argument,       NULL, TIM_OPT_OUTPUT_BITWIDTH },
	{ "output-24bit",           no_argument,       NULL, TIM_OPT_OUTPUT_BITWIDTH },
	{ "output-8bit",            no_argument,       NULL, TIM_OPT_OUTPUT_BITWIDTH },
	{ "output-linear",          no_argument,       NULL, TIM_OPT_OUTPUT_FORMAT },
	{ "output-ulaw",            no_argument,       NULL, TIM_OPT_OUTPUT_FORMAT },
	{ "output-alaw",            no_argument,       NULL, TIM_OPT_OUTPUT_FORMAT },
	{ "no-output-swab",         no_argument,       NULL, TIM_OPT_OUTPUT_SWAB },
	{ "output-swab",            optional_argument, NULL, TIM_OPT_OUTPUT_SWAB },
#ifdef AU_FLAC
	{ "flac-verify",            no_argument,       NULL, TIM_OPT_FLAC_VERIFY },
	{ "flac-padding",           required_argument, NULL, TIM_OPT_FLAC_PADDING },
	{ "flac-complevel",         required_argument, NULL, TIM_OPT_FLAC_COMPLEVEL },
#ifdef AU_OGGFLAC
	{ "oggflac",                no_argument,       NULL, TIM_OPT_FLAC_OGGFLAC },
#endif /* AU_OGGFLAC */
#endif /* AU_FLAC */
#ifdef AU_SPEEX
	{ "speex-quality",          required_argument, NULL, TIM_OPT_SPEEX_QUALITY },
	{ "speex-vbr",              no_argument,       NULL, TIM_OPT_SPEEX_VBR },
	{ "speex-abr",              required_argument, NULL, TIM_OPT_SPEEX_ABR },
	{ "speex-vad",              no_argument,       NULL, TIM_OPT_SPEEX_VAD },
	{ "speex-dtx",              no_argument,       NULL, TIM_OPT_SPEEX_DTX },
	{ "speex-complexity",       required_argument, NULL, TIM_OPT_SPEEX_COMPLEXITY },
	{ "speex-nframes",          required_argument, NULL, TIM_OPT_SPEEX_NFRAMES },
#endif /* AU_SPEEX */
	{ "output-file",            required_argument, NULL, TIM_OPT_OUTPUT_FILE },
	{ "patch-file",             required_argument, NULL, TIM_OPT_PATCH_FILE },
	{ "polyphony",              required_argument, NULL, TIM_OPT_POLYPHONY },
	{ "no-polyphony-reduction", no_argument,       NULL, TIM_OPT_POLY_REDUCE },
	{ "polyphony-reduction",    optional_argument, NULL, TIM_OPT_POLY_REDUCE },
	{ "mute",                   required_argument, NULL, TIM_OPT_MUTE },
	{ "temper-mute",            required_argument, NULL, TIM_OPT_TEMPER_MUTE },
	{ "preserve-silence",       no_argument,       NULL, TIM_OPT_PRESERVE_SILENCE },
	{ "audio-buffer",           required_argument, NULL, TIM_OPT_AUDIO_BUFFER },
	{ "cache-size",             required_argument, NULL, TIM_OPT_CACHE_SIZE },
	{ "sampling-freq",          required_argument, NULL, TIM_OPT_SAMPLE_FREQ },
	{ "adjust-tempo",           required_argument, NULL, TIM_OPT_ADJUST_TEMPO },
	{ "output-charset",         required_argument, NULL, TIM_OPT_CHARSET },
	{ "no-unload-instruments",  no_argument,       NULL, TIM_OPT_UNLOAD_INST },
	{ "unload-instruments",     optional_argument, NULL, TIM_OPT_UNLOAD_INST },
	{ "volume-curve",           required_argument, NULL, TIM_OPT_VOLUME_CURVE },
	{ "version",                no_argument,       NULL, TIM_OPT_VERSION },
	{ "wrd",                    required_argument, NULL, TIM_OPT_WRD },
#ifdef __W32__
	{ "rcpcv-dll",              required_argument, NULL, TIM_OPT_RCPCV_DLL },
#endif
	{ "config-string",          required_argument, NULL, TIM_OPT_CONFIG_STR },
	{ "freq-table",             required_argument, NULL, TIM_OPT_FREQ_TABLE },
	{ "pure-intonation",        optional_argument, NULL, TIM_OPT_PURE_INT },
	{ "module",                 required_argument, NULL, TIM_OPT_MODULE },
	{ NULL,                     no_argument,       NULL, '\0'     }
};
#define INTERACTIVE_INTERFACE_IDS "kmqagrwAWNP"

/* main interfaces (To be used another main) */
#if defined(main) || defined(ANOTHER_MAIN) || defined ( IA_W32GUI ) || defined ( IA_W32G_SYN )
#define MAIN_INTERFACE
#else
#define MAIN_INTERFACE static
#endif /* main */

MAIN_INTERFACE void timidity_start_initialize(struct timiditycontext_t *c);
MAIN_INTERFACE int timidity_pre_load_configuration(struct timiditycontext_t *c);
MAIN_INTERFACE int timidity_post_load_configuration(struct timiditycontext_t *c);
MAIN_INTERFACE void timidity_init_player(struct timiditycontext_t *c);
MAIN_INTERFACE int timidity_play_main(struct timiditycontext_t *c, int nfiles, char **files);
void timidity_init_aq_buff(struct timiditycontext_t *c);

int set_extension_modes(struct timiditycontext_t *c, char *);
int set_ctl(struct timiditycontext_t *c, char *);
int set_play_mode(struct timiditycontext_t *c, char *);
MAIN_INTERFACE int set_tim_opt_short(struct timiditycontext_t *c, int, char *);
MAIN_INTERFACE int set_tim_opt_long(struct timiditycontext_t *c, int, char *, int);
static inline int parse_opt_A(struct timiditycontext_t *c, const char *);
static inline int parse_opt_drum_power(struct timiditycontext_t *c, const char *);
static inline int parse_opt_volume_comp(struct timiditycontext_t *c, const char *);
static inline int parse_opt_a(struct timiditycontext_t *c, const char *);
static inline int parse_opt_B(struct timiditycontext_t *c, const char *);
static inline int parse_opt_C(struct timiditycontext_t *c, const char *);
static inline int parse_opt_c(struct timiditycontext_t *c, char *);
static inline int parse_opt_D(struct timiditycontext_t *c, const char *);
static inline int parse_opt_d(struct timiditycontext_t *c, const char *);
static inline int parse_opt_E(struct timiditycontext_t *c, char *);
static inline int parse_opt_mod_wheel(struct timiditycontext_t *c, const char *);
static inline int parse_opt_portamento(struct timiditycontext_t *c, const char *);
static inline int parse_opt_vibrato(struct timiditycontext_t *c, const char *);
static inline int parse_opt_ch_pressure(struct timiditycontext_t *c, const char *);
static inline int parse_opt_mod_env(struct timiditycontext_t *c, const char *);
static inline int parse_opt_trace_text(struct timiditycontext_t *c, const char *);
static inline int parse_opt_overlap_voice(struct timiditycontext_t *c, const char *);
static inline int parse_opt_temper_control(struct timiditycontext_t *c, const char *);
static inline int parse_opt_default_mid(struct timiditycontext_t *c, char *);
static inline int parse_opt_system_mid(struct timiditycontext_t *c, char *);
static inline int parse_opt_default_bank(struct timiditycontext_t *c, const char *);
static inline int parse_opt_force_bank(struct timiditycontext_t *c, const char *);
static inline int parse_opt_default_program(struct timiditycontext_t *c, const char *);
static inline int parse_opt_force_program(struct timiditycontext_t *c, const char *);
static inline int set_default_program(struct timiditycontext_t *c, int);
static inline int parse_opt_delay(struct timiditycontext_t *c, const char *);
static inline int parse_opt_chorus(struct timiditycontext_t *c, const char *);
static inline int parse_opt_reverb(struct timiditycontext_t *, const char *);
static int parse_opt_reverb_freeverb(struct timiditycontext_t *c, const char *arg, char type);
static inline int parse_opt_voice_lpf(struct timiditycontext_t *c ,const char *);
static inline int parse_opt_noise_shaping(struct timiditycontext_t *c, const char *);
static inline int parse_opt_resample(struct timiditycontext_t *c, const char *);
static inline int parse_opt_e(struct timiditycontext_t *c, const char *);
static inline int parse_opt_F(struct timiditycontext_t *c, const char *);
static inline int parse_opt_f(struct timiditycontext_t *c, const char *);
static inline int parse_opt_G(struct timiditycontext_t *c, const char *);
static inline int parse_opt_G1(struct timiditycontext_t *c, const char *);
static int parse_segment(struct timiditycontext_t *c, TimeSegment *, const char *);
static int parse_segment2(struct timiditycontext_t *c, TimeSegment *, const char *);
static int parse_time(struct timiditycontext_t *c, FLOAT_T *, const char *);
static int parse_time2(struct timiditycontext_t *c, Measure *, const char *);
static inline int parse_opt_g(struct timiditycontext_t *c, const char *);
static inline int parse_opt_H(struct timiditycontext_t *c, const char *);
__attribute__((noreturn))
static inline int parse_opt_h(struct timiditycontext_t *c, const char *);
#ifdef IA_DYNAMIC
static inline void list_dyna_interface(FILE *, char *, char *);
ControlMode *dynamic_interface_module(int);
#endif
static inline int parse_opt_i(struct timiditycontext_t *c, const char *);
static inline int parse_opt_verbose(const char *);
static inline int parse_opt_quiet(const char *);
static inline int parse_opt_trace(const char *);
static inline int parse_opt_loop(const char *);
static inline int parse_opt_random(const char *);
static inline int parse_opt_sort(const char *);
#ifdef IA_ALSASEQ
static inline int parse_opt_background(const char *);
static inline int parse_opt_rt_prio(struct timiditycontext_t *c, const char *);
static inline int parse_opt_seq_ports(struct timiditycontext_t *c, const char *);
#endif
#if defined(IA_WINSYN) || defined(IA_PORTMIDISYN) || defined(IA_NPSYN) || defined(IA_W32G_SYN) || defined(IA_W32GUI)
static inline int parse_opt_rtsyn_latency(const char *);
#endif
static inline int parse_opt_j(struct timiditycontext_t *c, const char *);
static inline int parse_opt_K(struct timiditycontext_t *c, const char *);
static inline int parse_opt_k(struct timiditycontext_t *c, const char *);
static inline int parse_opt_L(struct timiditycontext_t *c, char *);
static inline int parse_opt_M(struct timiditycontext_t *c, const char *);
static inline int parse_opt_m(struct timiditycontext_t *c, const char *);
static inline int parse_opt_N(struct timiditycontext_t *c, const char *);
static inline int parse_opt_O(struct timiditycontext_t *c, const char *);
static inline int parse_opt_output_stereo(struct timiditycontext_t *c, const char *);
static inline int parse_opt_output_signed(struct timiditycontext_t *c, const char *);
static inline int parse_opt_output_bitwidth(struct timiditycontext_t *c, const char *);
static inline int parse_opt_output_format(struct timiditycontext_t *c, const char *);
static inline int parse_opt_output_swab(struct timiditycontext_t *c, const char *);
#if defined(AU_PORTAUDIO) || defined(AU_W32)
static inline int parse_opt_output_device(const char *);
#endif
#ifdef AU_FLAC
static inline int parse_opt_flac_verify(const char *);
static inline int parse_opt_flac_padding(const char *);
static inline int parse_opt_flac_complevel(const char *);
#ifdef AU_OGGFLAC
static inline int parse_opt_flac_oggflac(const char *);
#endif /* AU_OGGFLAC */
#endif /* AU_FLAC */
#ifdef AU_SPEEX
static inline int parse_opt_speex_quality(const char *);
static inline int parse_opt_speex_vbr(const char *);
static inline int parse_opt_speex_abr(const char *);
static inline int parse_opt_speex_vad(const char *);
static inline int parse_opt_speex_dtx(const char *);
static inline int parse_opt_speex_complexity(const char *);
static inline int parse_opt_speex_nframes(const char *);
#endif /* AU_SPEEX */
static inline int parse_opt_o(struct timiditycontext_t *c, char *);
static inline int parse_opt_P(struct timiditycontext_t *c, const char *);
static inline int parse_opt_p(struct timiditycontext_t *c, const char *);
static inline int parse_opt_p1(struct timiditycontext_t *c, const char *);
static inline int parse_opt_Q(struct timiditycontext_t *c, const char *);
static inline int parse_opt_Q1(struct timiditycontext_t *c, const char *);
static inline int parse_opt_preserve_silence(struct timiditycontext_t *c, const char *);
static inline int parse_opt_q(struct timiditycontext_t *c, const char *);
static inline int parse_opt_R(struct timiditycontext_t *c, const char *);
static inline int parse_opt_S(struct timiditycontext_t *c, const char *);
static inline int parse_opt_s(struct timiditycontext_t *c, const char *);
static inline int parse_opt_T(struct timiditycontext_t *c, const char *);
static inline int parse_opt_t(struct timiditycontext_t *c, const char *);
static inline int parse_opt_U(struct timiditycontext_t *c, const char *);
static inline int parse_opt_volume_curve(struct timiditycontext_t *c, char *);
__attribute__((noreturn))
static inline int parse_opt_v(const char *);
static inline int parse_opt_W(struct timiditycontext_t *c, char *);
#ifdef __W32__
static inline int parse_opt_w(struct timiditycontext_t *c, const char *);
#endif
static inline int parse_opt_x(struct timiditycontext_t *c, char *);
static inline void expand_escape_string(char *);
static inline int parse_opt_Z(struct timiditycontext_t *c, char *);
static inline int parse_opt_Z1(struct timiditycontext_t *c, const char *);
static inline int parse_opt_default_module(struct timiditycontext_t *c, const char *);
__attribute__((noreturn))
static inline int parse_opt_fail(struct timiditycontext_t *c, const char *);
static inline int set_value(struct timiditycontext_t *c, int *, int, int, int, char *);
static inline int set_val_i32(struct timiditycontext_t *c, int32 *, int32, int32, int32, char *);
static int parse_val_float_t(struct timiditycontext_t *c, FLOAT_T *, const char *, FLOAT_T, FLOAT_T,
		const char *, int);
static inline int set_val_float_t(struct timiditycontext_t *c, FLOAT_T *, FLOAT_T, FLOAT_T, FLOAT_T,
		const char *, int);
static inline int set_channel_flag(struct timiditycontext_t *c, ChannelBitMask *, int32, char *);
static inline int y_or_n_p(const char *);
static inline int set_flag(int32 *, int32, const char *);
static inline FILE *open_pager(void);
static inline void close_pager(FILE *);
#if !defined(ANOTHER_MAIN) && defined(__W32__)
static void interesting_message(void);
#endif

extern struct URL_module URL_module_file;
#ifndef __MACOS__
extern struct URL_module URL_module_dir;
#endif /* __MACOS__ */
#ifdef SUPPORT_SOCKET
extern struct URL_module URL_module_http;
extern struct URL_module URL_module_ftp;
extern struct URL_module URL_module_news;
extern struct URL_module URL_module_newsgroup;
#endif /* SUPPORT_SOCKET */
#ifdef HAVE_POPEN
extern struct URL_module URL_module_pipe;
#endif /* HAVE_POPEN */

MAIN_INTERFACE struct URL_module *url_module_list[] =
{
    &URL_module_file,
#ifndef __MACOS__
    &URL_module_dir,
#endif /* __MACOS__ */
#ifdef SUPPORT_SOCKET
    &URL_module_http,
    &URL_module_ftp,
    &URL_module_news,
    &URL_module_newsgroup,
#endif /* SUPPORT_SOCKET */
#if !defined(__MACOS__) && defined(HAVE_POPEN)
    &URL_module_pipe,
#endif
#if defined(main) || defined(ANOTHER_MAIN)
    /* You can put some other modules */
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
#endif /* main */
    NULL
};

#ifdef IA_DYNAMIC
#include "dlutils.h"
#ifndef SHARED_LIB_PATH
#define SHARED_LIB_PATH PKGLIBDIR
#endif /* SHARED_LIB_PATH */
static char *dynamic_lib_root = NULL;
#endif /* IA_DYNAMIC */

#ifndef MAXPATHLEN
#define MAXPATHLEN 1024
#endif /* MAXPATHLEN */

#ifdef __W32__
CRITICAL_SECTION critSect;

#if 0
#pragma argsused
static BOOL WINAPI handler(DWORD dw)
{
#if defined(IA_WINSYN) || defined(IA_PORTMIDISYN)
	if (ctl->id_character == 'W' || ctl->id_character == 'P')
		rtsyn_midiports_close();
#endif
#if 0
#if defined(IA_NPSYN)
	if (ctl->id_character == 'N')
		return FALSE;	/* why FALSE need?  It must close by intr++; */
#endif
#endif
	printf ("***BREAK" NLS);
	fflush(stdout);
	c->intr++;
	return TRUE;
}
#endif
#endif

#ifndef atof
extern double atof(const char *);
#endif

/*! copy bank and, if necessary, map appropriately */
static void copybank(struct timiditycontext_t *c, ToneBank *to, ToneBank *from, int mapid, int bankmapfrom, int bankno)
{
	ToneBankElement *toelm, *fromelm;
	int i;

	if (from == NULL)
		return;
	for(i = 0; i < 128; i++)
	{
		toelm = &to->tone[i];
		fromelm = &from->tone[i];
		if (fromelm->name == NULL)
		    continue;
		copy_tone_bank_element(c, toelm, fromelm);
		toelm->instrument = NULL;
		if (mapid != INST_NO_MAP)
		    set_instrument_map(c, mapid, bankmapfrom, i, bankno, i);
	}
}

/*! copy the whole mapped bank. returns 0 if no error. */
static int copymap(struct timiditycontext_t *c, int mapto, int mapfrom, int isdrum)
{
	ToneBank **tb = isdrum ? c->drumset : c->tonebank;
	int i, bankfrom, bankto;

	for(i = 0; i < 128; i++)
	{
		bankfrom = find_instrument_map_bank(c, isdrum, mapfrom, i);
		if (bankfrom <= 0) /* not mapped */
			continue;
		bankto = alloc_instrument_map_bank(c, isdrum, mapto, i);
		if (bankto == -1) /* failed */
			return 1;
		copybank(c, tb[bankto], tb[bankfrom], mapto, i, bankto);
	}
	return 0;
}

static float *config_parse_tune(struct timiditycontext_t *c, const char *cp, int *num)
{
	const char *p;
	float *tune_list;
	int i;

	/* count num */
	*num = 1, p = cp;
	while ((p = strchr(p, ',')) != NULL)
		(*num)++, p++;
	/* alloc */
	tune_list = (float *) safe_malloc(c, (*num) * sizeof(float));
	/* regist */
	for (i = 0, p = cp; i < *num; i++, p++) {
		tune_list[i] = atof(p);
		if (! (p = strchr(p, ',')))
			break;
	}
	return tune_list;
}

static int16 *config_parse_int16(struct timiditycontext_t *c, const char *cp, int *num)
{
	const char *p;
	int16 *list;
	int i;

	/* count num */
	*num = 1, p = cp;
	while ((p = strchr(p, ',')) != NULL)
		(*num)++, p++;
	/* alloc */
	list = (int16 *) safe_malloc(c, (*num) * sizeof(int16));
	/* regist */
	for (i = 0, p = cp; i < *num; i++, p++) {
		list[i] = atoi(p);
		if (! (p = strchr(p, ',')))
			break;
	}
	return list;
}

static int **config_parse_envelope(struct timiditycontext_t *c, const char *cp, int *num)
{
	const char *p, *px;
	int **env_list;
	int i, j;

	/* count num */
	*num = 1, p = cp;
	while ((p = strchr(p, ',')) != NULL)
		(*num)++, p++;
	/* alloc */
	env_list = (int **) safe_malloc(c, (*num) * sizeof(int *));
	for (i = 0; i < *num; i++)
		env_list[i] = (int *) safe_malloc(c, 6 * sizeof(int));
	/* init */
	for (i = 0; i < *num; i++)
		for (j = 0; j < 6; j++)
			env_list[i][j] = -1;
	/* regist */
	for (i = 0, p = cp; i < *num; i++, p++) {
		px = strchr(p, ',');
		for (j = 0; j < 6; j++, p++) {
			if (*p == ':')
				continue;
			env_list[i][j] = atoi(p);
			if (! (p = strchr(p, ':')))
				break;
			if (px && p > px)
				break;
		}
		if (! (p = px))
			break;
	}
	return env_list;
}

static Quantity **config_parse_modulation(struct timiditycontext_t *c, const char *name, int line, const char *cp, int *num, int mod_type)
{
	const char *p, *px, *err;
	char buf[128], *delim;
	Quantity **mod_list;
	int i, j;
	static const char * qtypestr[] = {"tremolo", "vibrato"};
	static const uint16 qtypes[] = {
		QUANTITY_UNIT_TYPE(TREMOLO_SWEEP), QUANTITY_UNIT_TYPE(TREMOLO_RATE), QUANTITY_UNIT_TYPE(DIRECT_INT),
		QUANTITY_UNIT_TYPE(VIBRATO_SWEEP), QUANTITY_UNIT_TYPE(VIBRATO_RATE), QUANTITY_UNIT_TYPE(DIRECT_INT)
	};

	/* count num */
	*num = 1, p = cp;
	while ((p = strchr(p, ',')) != NULL)
		(*num)++, p++;
	/* alloc */
	mod_list = (Quantity **) safe_malloc(c, (*num) * sizeof(Quantity *));
	for (i = 0; i < *num; i++)
		mod_list[i] = (Quantity *) safe_malloc(c, 3 * sizeof(Quantity));
	/* init */
	for (i = 0; i < *num; i++)
		for (j = 0; j < 3; j++)
			INIT_QUANTITY(mod_list[i][j]);
	buf[sizeof buf - 1] = '\0';
	/* regist */
	for (i = 0, p = cp; i < *num; i++, p++) {
		px = strchr(p, ',');
		for (j = 0; j < 3; j++, p++) {
			if (*p == ':')
				continue;
			if ((delim = strpbrk(strncpy(buf, p, sizeof buf - 1), ":,")) != NULL)
				*delim = '\0';
			if (*buf != '\0' && (err = string_to_quantity(c, buf, &mod_list[i][j], qtypes[mod_type * 3 + j])) != NULL) {
				ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL, "%s: line %d: %s: parameter %d of item %d: %s (%s)",
						name, line, qtypestr[mod_type], j+1, i+1, err, buf);
				free_ptr_list(mod_list, *num);
				mod_list = NULL;
				*num = 0;
				return NULL;
			}
			if (! (p = strchr(p, ':')))
				break;
			if (px && p > px)
				break;
		}
		if (! (p = px))
			break;
	}
	return mod_list;
}

static int set_gus_patchconf_opts(struct timiditycontext_t *c, char *name,
		int line, char *opts, ToneBankElement *tone)
{
	char *cp;
	int k;

	if (! (cp = strchr(opts, '='))) {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
				"%s: line %d: bad patch option %s", name, line, opts);
		return 1;
	}
	*cp++ = 0;
	if (! strcmp(opts, "amp")) {
		k = atoi(cp);
		if ((k < 0 || k > MAX_AMPLIFICATION) || (*cp < '0' || *cp > '9')) {
			ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
					"%s: line %d: amplification must be between 0 and %d",
					name, line, MAX_AMPLIFICATION);
			return 1;
		}
		tone->amp = k;
	} else if (! strcmp(opts, "note")) {
		k = atoi(cp);
		if ((k < 0 || k > 127) || (*cp < '0' || *cp > '9')) {
			ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
					"%s: line %d: note must be between 0 and 127",
					name, line);
			return 1;
		}
		tone->note = k;
		tone->scltune = config_parse_int16(c, "100", &tone->scltunenum);
	} else if (! strcmp(opts, "pan")) {
		if (! strcmp(cp, "center"))
			k = 64;
		else if (! strcmp(cp, "left"))
			k = 0;
		else if (! strcmp(cp, "right"))
			k = 127;
		else {
			k = ((atoi(cp) + 100) * 100) / 157;
			if ((k < 0 || k > 127)
					|| (k == 0 && *cp != '-' && (*cp < '0' || *cp > '9'))) {
				ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
						"%s: line %d: panning must be left, right, "
						"center, or between -100 and 100",
						name, line);
				return 1;
			}
		}
		tone->pan = k;
	} else if (! strcmp(opts, "tune"))
		tone->tune = config_parse_tune(c, cp, &tone->tunenum);
	else if (! strcmp(opts, "rate"))
		tone->envrate = config_parse_envelope(c, cp, &tone->envratenum);
	else if (! strcmp(opts, "offset"))
		tone->envofs = config_parse_envelope(c, cp, &tone->envofsnum);
	else if (! strcmp(opts, "keep")) {
		if (! strcmp(cp, "env"))
			tone->strip_envelope = 0;
		else if (! strcmp(cp, "loop"))
			tone->strip_loop = 0;
		else {
			ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
					"%s: line %d: keep must be env or loop", name, line);
			return 1;
		}
	} else if (! strcmp(opts, "strip")) {
		if (! strcmp(cp, "env"))
			tone->strip_envelope = 1;
		else if (! strcmp(cp, "loop"))
			tone->strip_loop = 1;
		else if (! strcmp(cp, "tail"))
			tone->strip_tail = 1;
		else {
			ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
					"%s: line %d: strip must be env, loop, or tail",
					name, line);
			return 1;
		}
	} else if (! strcmp(opts, "tremolo")) {
		if ((tone->trem = config_parse_modulation(c, name,
				line, cp, &tone->tremnum, 0)) == NULL)
			return 1;
	} else if (! strcmp(opts, "vibrato")) {
		if ((tone->vib = config_parse_modulation(c, name,
				line, cp, &tone->vibnum, 1)) == NULL)
			return 1;
	} else if (! strcmp(opts, "sclnote"))
		tone->sclnote = config_parse_int16(c, cp, &tone->sclnotenum);
	else if (! strcmp(opts, "scltune"))
		tone->scltune = config_parse_int16(c, cp, &tone->scltunenum);
	else if (! strcmp(opts, "comm")) {
		char *p;

		if (tone->comment)
			free(tone->comment);
		p = tone->comment = safe_strdup(c, cp);
		while (*p) {
			if (*p == ',')
				*p = ' ';
			p++;
		}
	} else if (! strcmp(opts, "modrate"))
		tone->modenvrate = config_parse_envelope(c, cp, &tone->modenvratenum);
	else if (! strcmp(opts, "modoffset"))
		tone->modenvofs = config_parse_envelope(c, cp, &tone->modenvofsnum);
	else if (! strcmp(opts, "envkeyf"))
		tone->envkeyf = config_parse_envelope(c, cp, &tone->envkeyfnum);
	else if (! strcmp(opts, "envvelf"))
		tone->envvelf = config_parse_envelope(c, cp, &tone->envvelfnum);
	else if (! strcmp(opts, "modkeyf"))
		tone->modenvkeyf = config_parse_envelope(c, cp, &tone->modenvkeyfnum);
	else if (! strcmp(opts, "modvelf"))
		tone->modenvvelf = config_parse_envelope(c, cp, &tone->modenvvelfnum);
	else if (! strcmp(opts, "trempitch"))
		tone->trempitch = config_parse_int16(c, cp, &tone->trempitchnum);
	else if (! strcmp(opts, "tremfc"))
		tone->tremfc = config_parse_int16(c, cp, &tone->tremfcnum);
	else if (! strcmp(opts, "modpitch"))
		tone->modpitch = config_parse_int16(c, cp, &tone->modpitchnum);
	else if (! strcmp(opts, "modfc"))
		tone->modfc = config_parse_int16(c, cp, &tone->modfcnum);
	else if (! strcmp(opts, "fc"))
		tone->fc = config_parse_int16(c, cp, &tone->fcnum);
	else if (! strcmp(opts, "q"))
		tone->reso = config_parse_int16(c, cp, &tone->resonum);
	else if (! strcmp(opts, "fckeyf"))		/* filter key-follow */
		tone->key_to_fc = atoi(cp);
	else if (! strcmp(opts, "fcvelf"))		/* filter velocity-follow */
		tone->vel_to_fc = atoi(cp);
	else if (! strcmp(opts, "qvelf"))		/* resonance velocity-follow */
		tone->vel_to_resonance = atoi(cp);
	else {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
				"%s: line %d: bad patch option %s",
				name, line, opts);
		return 1;
	}
	return 0;
}

static void reinit_tone_bank_element(ToneBankElement *tone)
{
	free_tone_bank_element(tone);
	tone->note = tone->pan = -1;
	tone->strip_loop = tone->strip_envelope = tone->strip_tail = -1;
	tone->amp = -1;
	tone->rnddelay = 0;
	tone->loop_timeout = 0;
	tone->legato = tone->damper_mode = tone->key_to_fc = tone->vel_to_fc = 0;
	tone->reverb_send = tone->chorus_send = tone->delay_send = -1;
	tone->tva_level = -1;
	tone->play_note = -1;
}

#define SET_GUS_PATCHCONF_COMMENT
static int set_gus_patchconf(struct timiditycontext_t *c, char *name, int line,
			     ToneBankElement *tone, char *pat, char **opts)
{
    int j;
#ifdef SET_GUS_PATCHCONF_COMMENT
		char *old_name = NULL;

		if(tone != NULL && tone->name != NULL)
			old_name = safe_strdup(c, tone->name);
#endif
    reinit_tone_bank_element(tone);

    if(strcmp(pat, "%font") == 0) /* Font extention */
    {
	/* %font filename bank prog [note-to-use]
	 * %font filename 128 bank key
	 */

	if(opts[0] == NULL || opts[1] == NULL || opts[2] == NULL ||
	   (atoi(opts[1]) == 128 && opts[3] == NULL))
	{
	    ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
		      "%s: line %d: Syntax error", name, line);
#ifdef SET_GUS_PATCHCONF_COMMENT
        if(old_name != NULL)
            free(old_name);
#endif
	    return 1;
	}
	tone->name = safe_strdup(c, opts[0]);
	tone->instype = 1;
	if(atoi(opts[1]) == 128) /* drum */
	{
	    tone->font_bank = 128;
	    tone->font_preset = atoi(opts[2]);
	    tone->font_keynote = atoi(opts[3]);
	    opts += 4;
	}
	else
	{
	    tone->font_bank = atoi(opts[1]);
	    tone->font_preset = atoi(opts[2]);

	    if(opts[3] && isdigit(opts[3][0]))
	    {
		tone->font_keynote = atoi(opts[3]);
		opts += 4;
	    }
	    else
	    {
		tone->font_keynote = -1;
		opts += 3;
	    }
	}
    }
    else if(strcmp(pat, "%sample") == 0) /* Sample extention */
    {
	/* %sample filename */

	if(opts[0] == NULL)
	{
	    ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
		      "%s: line %d: Syntax error", name, line);
	    return 1;
	}
	tone->name = safe_strdup(c, opts[0]);
	tone->instype = 2;
	opts++;
    }
    else
    {
	tone->instype = 0;
	tone->name = safe_strdup(c, pat);
	if ((c->pathlist == &c->defaultpathlist) && (!tone->comment))
	{ /* fill in comment with just the filename if the "dir" syntax has not been used, the full path can be overwhelming long and already present in tone->name */
	    const char *forward = strrchr (pat, '/');
	    const char *backward = strrchr (pat, '\\');
	    const char *afterslash = 0;
	    if (forward && forward[1])
	    {
		afterslash = forward + 1;
	    }
	    if (backward && backward[1])
	    {
		if ((!afterslash) || (afterslash < (backward + 1)))
		{
		    afterslash = backward + 1;
		}
	    }
	    tone->comment = safe_strdup(c, afterslash ? afterslash : pat);
	}
    }

    for(j = 0; opts[j] != NULL; j++)
    {
	int err;
	if((err = set_gus_patchconf_opts(c, name, line, opts[j], tone)) != 0)
    {
#ifdef SET_GUS_PATCHCONF_COMMENT
        if(old_name != NULL)
            free(old_name);
#endif
            return err;
    }
	    return err;
    }
#ifdef SET_GUS_PATCHCONF_COMMENT
		if(tone->comment == NULL ||
			(old_name != NULL && strcmp(old_name,tone->comment) == 0))
		{
			if(tone->comment != NULL )
				free(tone->comment);
			tone->comment = safe_strdup(c, tone->name);
		}
		if(old_name != NULL)
			free(old_name);
#else
    if(tone->comment == NULL)
	tone->comment = safe_strdup(c, tone->name);
#endif
    return 0;
}

static int set_patchconf(struct timiditycontext_t *c, char *name, int line, ToneBank *bank, char *w[], int dr, int mapid, int bankmapfrom, int bankno)
{
    int i;

    i = atoi(w[0]);
    if(!dr)
	i -= c->progbase;
    if(i < 0 || i > 127)
    {
	if(dr)
	    ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
		      "%s: line %d: Drum number must be between "
		      "0 and 127",
		      name, line);
	else
	    ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
		      "%s: line %d: Program must be between "
		      "%d and %d",
		      name, line, c->progbase, 127 + c->progbase);
	return 1;
    }
    if(!bank)
    {
	ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
		  "%s: line %d: Must specify tone bank or drum set "
		  "before assignment", name, line);
	return 1;
    }

    if(set_gus_patchconf(c, name, line, &bank->tone[i], w[1], w + 2))
	return 1;
    if (mapid != INST_NO_MAP)
	set_instrument_map(c, mapid, bankmapfrom, i, bankno, i);
    return 0;
}

typedef struct {
	const char *name;
	int mapid, isdrum;
} MapNameEntry;

static int mapnamecompare(const void *name, const void *entry)
{
	return strcmp((const char *)name, ((const MapNameEntry *)entry)->name);
}

static int mapname2id(char *name, int *isdrum)
{
	static const MapNameEntry data[] = {
		/* sorted in alphabetical order */
		{"gm2",         GM2_TONE_MAP, 0},
		{"gm2drum",     GM2_DRUM_MAP, 1},
		{"sc55",        SC_55_TONE_MAP, 0},
		{"sc55drum",    SC_55_DRUM_MAP, 1},
		{"sc88",        SC_88_TONE_MAP, 0},
		{"sc8850",      SC_8850_TONE_MAP, 0},
		{"sc8850drum",  SC_8850_DRUM_MAP, 1},
		{"sc88drum",    SC_88_DRUM_MAP, 1},
		{"sc88pro",     SC_88PRO_TONE_MAP, 0},
		{"sc88prodrum", SC_88PRO_DRUM_MAP, 1},
		{"xg",          XG_NORMAL_MAP, 0},
		{"xgdrum",      XG_DRUM_MAP, 1},
		{"xgsfx126",    XG_SFX126_MAP, 1},
		{"xgsfx64",     XG_SFX64_MAP, 0}
	};
	const MapNameEntry *found;

	found = (MapNameEntry *)bsearch(name, data, sizeof data / sizeof data[0], sizeof data[0], mapnamecompare);
	if (found != NULL)
	{
		*isdrum = found->isdrum;
		return found->mapid;
	}
	return -1;
}

/* string[0] should not be '#' */
static int strip_trailing_comment(char *string, int next_token_index)
{
    if (string[next_token_index - 1] == '#'	/* strip \1 in /^\S+(#*[ \t].*)/ */
	&& (string[next_token_index] == ' ' || string[next_token_index] == '\t'))
    {
	string[next_token_index] = '\0';	/* new c-string terminator */
	while(string[--next_token_index - 1] == '#')
	    ;
    }
    return next_token_index;
}

static char *expand_variables(struct timiditycontext_t *c, char *string, MBlockList *varbuf, const char *basedir)
{
	char *p, *expstr;
	const char *copystr;
	int limlen, copylen, explen, varlen, braced;

	if ((p = strchr(string, '$')) == NULL)
		return string;
	varlen = strlen(basedir);
	explen = limlen = 0;
	expstr = NULL;
	copystr = string;
	copylen = p - string;
	string = p;
	for(;;)
	{
		if (explen + copylen + 1 > limlen)
		{
			limlen += copylen + 128;
			expstr = memcpy(new_segment(c, varbuf, limlen), expstr, explen);
		}
		memcpy(&expstr[explen], copystr, copylen);
		explen += copylen;
		if (*string == '\0')
			break;
		else if (*string == '$')
		{
			braced = *++string == '{';
			if (braced)
			{
				if ((p = strchr(string + 1, '}')) == NULL)
					p = string;	/* no closing brace */
				else
					string++;
			}
			else
				for(p = string; isalnum(*p) || *p == '_'; p++) ;
			if (p == string)	/* empty */
			{
				copystr = "${";
				copylen = 1 + braced;
			}
			else
			{
				if (p - string == 7 && memcmp(string, "basedir", 7) == 0)
				{
					copystr = basedir;
					copylen = varlen;
				}
				else	/* undefined variable */
					copylen = 0;
				string = p + braced;
			}
		}
		else	/* search next */
		{
			p = strchr(string, '$');
			if (p == NULL)
				copylen = strlen(string);
			else
				copylen = p - string;
			copystr = string;
			string += copylen;
		}
	}
	expstr[explen] = '\0';
	return expstr;
}

#define MAXWORDS 130
#define CHECKERRLIMIT \
  if(++errcnt >= 10) { \
    ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL, \
      "Too many errors... Give up read %s", name); \
    reuse_mblock(c, &varbuf); \
    close_file(c, tf); return 1; }

#define READ_CONFIG_SUCCESS        0
#define READ_CONFIG_ERROR          1
#define READ_CONFIG_RECURSION      2 /* Too much recursion */
#define READ_CONFIG_FILE_NOT_FOUND 3 /* Returned only w. allow_missing_file */
#define rcf_count c->read_config_file_rcf_count
MAIN_INTERFACE int read_config_file(struct timiditycontext_t *c, char *name, int self, int allow_missing_file)
{
    struct timidity_file *tf;
    char buf[1024], *tmp, *w[MAXWORDS + 1], *cp;
    ToneBank *bank = NULL;
    int i, j, k, line = 0, words, errcnt = 0;
    int dr = 0, bankno = 0, mapid = INST_NO_MAP, origbankno = 0x7FFFFFFF;
    int extension_flag, param_parse_err;
    MBlockList varbuf;
    char *basedir, *sep;

    if(rcf_count > 50)
    {
	ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
		  "Probable source loop in configuration files");
	return READ_CONFIG_RECURSION;
    }

    if(self)
    {
	tf = open_with_mem(c, name, (int32)strlen(name), OF_VERBOSE);
	name = "(configuration)";
    }
    else
	tf = open_file(c, name, 1, allow_missing_file ? OF_NORMAL : OF_VERBOSE);
    if(tf == NULL)
	return allow_missing_file ? READ_CONFIG_FILE_NOT_FOUND :
	                            READ_CONFIG_ERROR;

    init_mblock(&varbuf);
    if (!self)
    {
	basedir = strdup_mblock(c, &varbuf, c->current_filename);
	if (is_url_prefix(basedir))
	    sep = strrchr(basedir, '/');
	else
	    sep = pathsep_strrchr(basedir);
    }
    else
	sep = NULL;
    if (sep == NULL)
    {
	#ifndef __MACOS__
	basedir = ".";
	#else
	basedir = "";
	#endif
    }
    else
    {
	if ((cp = strchr(sep, '#')) != NULL)
	    sep = cp + 1;	/* inclusive of '#' */
	*sep = '\0';
    }

    errno = 0;
    while(tf_gets(c, buf, sizeof(buf), tf))
    {
	line++;
	if(strncmp(buf, "#extension", 10) == 0) {
	    extension_flag = 1;
	    i = 10;
	}
	else
	{
	    extension_flag = 0;
	    i = 0;
	}

	while(isspace(buf[i]))			/* skip /^\s*(?#)/ */
	    i++;
	if (buf[i] == '#' || buf[i] == '\0')	/* /^#|^$/ */
	    continue;
	tmp = expand_variables(c, buf, &varbuf, basedir);
	j = strcspn(tmp + i, " \t\r\n\240");
	if (j == 0)
		j = strlen(tmp + i);
	j = strip_trailing_comment(tmp + i, j);
	tmp[i + j] = '\0';			/* terminate the first token */
	w[0] = tmp + i;
	i += j + 1;
	words = param_parse_err = 0;
	while(words < MAXWORDS - 1)		/* -1 : next arg */
	{
	    char *terminator;

	    while(isspace(tmp[i]))		/* skip /^\s*(?#)/ */
		i++;
	    if (tmp[i] == '\0'
		    || tmp[i] == '#')		/* /\s#/ */
		break;
	    if ((tmp[i] == '"' || tmp[i] == '\'')
		    && (terminator = strchr(tmp + i + 1, tmp[i])) != NULL)
	    {
		if (!isspace(terminator[1]) && terminator[1] != '\0')
		{
		    ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			"%s: line %d: there must be at least one whitespace between "
			"string terminator (%c) and the next parameter", name, line, tmp[i]);
		    CHECKERRLIMIT;
		    param_parse_err = 1;
		    break;
		}
		w[++words] = tmp + i + 1;
		i = terminator - tmp + 1;
		*terminator = '\0';
	    }
	    else	/* not terminated */
	    {
		j = strcspn(tmp + i, " \t\r\n\240");
		if (j > 0)
		    j = strip_trailing_comment(tmp + i, j);
		w[++words] = tmp + i;
		i += j;
		if (tmp[i] != '\0')		/* unless at the end-of-string (i.e. EOF) */
		    tmp[i++] = '\0';		/* terminate the token */
	    }
	}
	if (param_parse_err)
	    continue;
	w[++words] = NULL;

	/*
	 * #extension [something...]
	 */

	/* #extension comm program comment */
	if(strcmp(w[0], "comm") == 0)
	{
	    char *p;

	    if(words != 3)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: syntax error", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    if(!bank)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: Must specify tone bank or drum "
			  "set before assignment", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    i = atoi(w[1]);
	    if(i < 0 || i > 127)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: extension comm must be "
			  "between 0 and 127", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    if(bank->tone[i].comment)
		free(bank->tone[i].comment);
	    p = bank->tone[i].comment = safe_strdup(c, w[2]);
	    while(*p)
	    {
		if(*p == ',') *p = ' ';
		p++;
	    }
	}
	/* #extension timeout program sec */
	else if(strcmp(w[0], "timeout") == 0)
	{
	    if(words != 3)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: syntax error", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    if(!bank)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: Must specify tone bank or drum set "
			  "before assignment", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    i = atoi(w[1]);
	    if(i < 0 || i > 127)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: extension timeout "
			  "must be between 0 and 127", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    bank->tone[i].loop_timeout = atoi(w[2]);
	}
	/* #extension copydrumset drumset */
	else if(strcmp(w[0], "copydrumset") == 0)
	{
	    if(words < 2)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: No copydrumset number given",
			  name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    i = atoi(w[1]);
	    if(i < 0 || i > 127)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: extension copydrumset "
			  "must be between 0 and 127", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    if(!bank)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: Must specify tone bank or "
			  "drum set before assignment", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    copybank(c, bank, c->drumset[i], mapid, origbankno, bankno);
	}
	/* #extension copybank bank */
	else if(strcmp(w[0], "copybank") == 0)
	{
	    if(words < 2)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: No copybank number given",
			  name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    i = atoi(w[1]);
	    if(i < 0 || i > 127)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: extension copybank "
			  "must be between 0 and 127", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    if(!bank)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: Must specify tone bank or "
			  "drum set before assignment", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    copybank(c, bank, c->tonebank[i], mapid, origbankno, bankno);
	}
	/* #extension copymap tomapid frommapid */
	else if(strcmp(w[0], "copymap") == 0)
	{
	    int mapto, mapfrom;
	    int toisdrum, fromisdrum;

	    if(words != 3)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: syntax error", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    if ((mapto = mapname2id(w[1], &toisdrum)) == -1)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: Invalid map name: %s", name, line, w[1]);
		CHECKERRLIMIT;
		continue;
	    }
	    if ((mapfrom = mapname2id(w[2], &fromisdrum)) == -1)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: Invalid map name: %s", name, line, w[2]);
		CHECKERRLIMIT;
		continue;
	    }
	    if (toisdrum != fromisdrum)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: Map type should be matched", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    if (copymap(c, mapto, mapfrom, toisdrum))
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: No free %s available to map",
			  name, line, toisdrum ? "drum set" : "tone bank");
		CHECKERRLIMIT;
		continue;
	    }
	}
	/* #extension HTTPproxy hostname:port */
	else if(strcmp(w[0], "HTTPproxy") == 0)
	{
#ifdef SUPPORT_SOCKET
            char r_bracket, l_bracket;
#endif

	    if(words < 2)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: No proxy name given",
			  name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    /* If network is not supported, this extension is ignored. */
#ifdef SUPPORT_SOCKET
	    url_http_proxy_host = safe_strdup(c, w[1]);
	    if((cp = strrchr(url_http_proxy_host, ':')) == NULL)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: Syntax error", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    *cp++ = '\0';
	    if((url_http_proxy_port = atoi(cp)) <= 0)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: Port number must be "
			  "positive number", name, line);
		CHECKERRLIMIT;
		continue;
	    }

            l_bracket = url_http_proxy_host[0];
            r_bracket = url_http_proxy_host[strlen(url_http_proxy_host) - 1];

            if (l_bracket == '[' || r_bracket == ']')
            {
                if (l_bracket != '[' || r_bracket != ']')
                {
                    ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
                              "%s: line %d: Malformed IPv6 address",
                              name, line);
                    CHECKERRLIMIT;
                    continue;
                }
                url_http_proxy_host++;
                url_http_proxy_host[strlen(url_http_proxy_host) - 1] = '\0';
            }
#endif
	}
	/* #extension FTPproxy hostname:port */
	else if(strcmp(w[0], "FTPproxy") == 0)
	{
#ifdef SUPPORT_SOCKET
            char l_bracket, r_bracket;
#endif

	    if(words < 2)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: No proxy name given",
			  name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    /* If network is not supported, this extension is ignored. */
#ifdef SUPPORT_SOCKET
	    url_ftp_proxy_host = safe_strdup(c, w[1]);
	    if((cp = strrchr(url_ftp_proxy_host, ':')) == NULL)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: Syntax error", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    *cp++ = '\0';
	    if((url_ftp_proxy_port = atoi(cp)) <= 0)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: Port number "
			  "must be positive number", name, line);
		CHECKERRLIMIT;
		continue;
	    }

            l_bracket = url_ftp_proxy_host[0];
            r_bracket = url_ftp_proxy_host[strlen(url_ftp_proxy_host) - 1];

            if (l_bracket == '[' || r_bracket == ']')
            {
                if (l_bracket != '[' || r_bracket != ']')
                {
                    ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
                              "%s: line %d: Malformed IPv6 address",
                              name, line);
                    CHECKERRLIMIT;
                    continue;
                }
                url_ftp_proxy_host++;
                url_ftp_proxy_host[strlen(url_ftp_proxy_host) - 1] = '\0';
            }
#endif
	}
	/* #extension mailaddr somebody@someware.domain.com */
	else if(strcmp(w[0], "mailaddr") == 0)
	{
	    if(words < 2)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: No mail address given",
			  name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    if(strchr(w[1], '@') == NULL) {
		ctl->cmsg(c, CMSG_WARNING, VERB_NOISY,
			  "%s: line %d: Warning: Mail address %s is not valid",
			  name, line);
	    }

	    /* If network is not supported, this extension is ignored. */
#ifdef SUPPORT_SOCKET
	    user_mailaddr = safe_strdup(c, w[1]);
#endif /* SUPPORT_SOCKET */
	}
	/* #extension opt [-]{option}[optarg] */
	else if (strcmp(w[0], "opt") == 0) {
		int ch, longind, err;
		char *p, *cmd, *arg;

		if (words != 2 && words != 3) {
			ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
					"%s: line %d: Syntax error", name, line);
			CHECKERRLIMIT;
			continue;
		}
		if (*w[1] == '-') {
			int optind_save = optind;
			optind = 0;
#if defined(__CYGWIN__)
			optreset = 1;
#endif
			ch = getopt_long(words, w, optcommands, longopts, &longind);
			err = set_tim_opt_long(c, ch, optarg, longind);
			optind = optind_save;
		} else {
			/* backward compatibility */
			if ((p = strchr(optcommands, ch = *(cmd = w[1]))) == NULL)
				err = 1;
			else {
				if (*(p + 1) == ':')
					arg = (words == 2) ? cmd + 1 : w[2];
				else
					arg = "";
				err = set_tim_opt_short(c, ch, arg);
			}
		}
		if (err) {
			/* error */
			ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
					"%s: line %d: Invalid command line option",
					name, line);
			errcnt += err - 1;
			CHECKERRLIMIT;
			continue;
		}
	}
	/* #extension undef program */
	else if(strcmp(w[0], "undef") == 0)
	{
	    if(words < 2)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: No undef number given",
			  name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    i = atoi(w[1]);
	    if(i < 0 || i > 127)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: extension undef "
			  "must be between 0 and 127", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    if(!bank)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: Must specify tone bank or "
			  "drum set before assignment", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    free_tone_bank_element(&bank->tone[i]);
	}
	/* #extension altassign numbers... */
	else if(strcmp(w[0], "altassign") == 0)
	{
	    ToneBank *bk;

	    if(!bank)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: Must specify tone bank or drum set "
			  "before altassign", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    if(words < 2)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: No alternate assignment", name, line);
		CHECKERRLIMIT;
		continue;
	    }

	    if(!dr) {
		ctl->cmsg(c, CMSG_WARNING, VERB_NORMAL,
			  "%s: line %d: Warning: Not a drumset altassign"
			  " (ignored)",
			  name, line);
		continue;
	    }

	    bk = c->drumset[bankno];
	    bk->alt = add_altassign_string(c, bk->alt, w + 1, words - 1);
	}	/* #extension legato [program] [0 or 1] */
	else if(strcmp(w[0], "legato") == 0)
	{
	    if(words != 3)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: syntax error", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    if(!bank)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: Must specify tone bank or drum set "
			  "before assignment", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    i = atoi(w[1]);
	    if(i < 0 || i > 127)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: extension legato "
			  "must be between 0 and 127", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    bank->tone[i].legato = atoi(w[2]);
	}	/* #extension damper [program] [0 or 1] */
	else if(strcmp(w[0], "damper") == 0)
	{
	    if(words != 3)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: syntax error", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    if(!bank)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: Must specify tone bank or drum set "
			  "before assignment", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    i = atoi(w[1]);
	    if(i < 0 || i > 127)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: extension damper "
			  "must be between 0 and 127", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    bank->tone[i].damper_mode = atoi(w[2]);
	}	/* #extension rnddelay [program] [0 or 1] */
	else if(strcmp(w[0], "rnddelay") == 0)
	{
	    if(words != 3)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: syntax error", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    if(!bank)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: Must specify tone bank or drum set "
			  "before assignment", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    i = atoi(w[1]);
	    if(i < 0 || i > 127)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: extension rnddelay "
			  "must be between 0 and 127", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    bank->tone[i].rnddelay = atoi(w[2]);
	}	/* #extension level program tva_level */
	else if(strcmp(w[0], "level") == 0)
	{
	    if(words != 3)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL, "%s: line %d: syntax error", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    if(!bank)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: Must specify tone bank or drum set "
			  "before assignment", name, line);
		CHECKERRLIMIT;
		continue;
	    }
		i = atoi(w[2]);
		if(i < 0 || i > 127)
		{
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: extension level "
			  "must be between 0 and 127", name, line);
		CHECKERRLIMIT;
		continue;
		}
		cp = w[1];
		do {
			if (string_to_7bit_range(cp, &j, &k))
			{
				while (j <= k)
					bank->tone[j++].tva_level = i;
			}
			cp = strchr(cp, ',');
		} while(cp++ != NULL);
	}	/* #extension reverbsend */
	else if(strcmp(w[0], "reverbsend") == 0)
	{
	    if(words != 3)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL, "%s: line %d: syntax error", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    if(!bank)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: Must specify tone bank or drum set "
			  "before assignment", name, line);
		CHECKERRLIMIT;
		continue;
	    }
		i = atoi(w[2]);
		if(i < 0 || i > 127)
		{
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: extension reverbsend "
			  "must be between 0 and 127", name, line);
		CHECKERRLIMIT;
		continue;
		}
		cp = w[1];
		do {
			if (string_to_7bit_range(cp, &j, &k))
			{
				while (j <= k)
					bank->tone[j++].reverb_send = i;
			}
			cp = strchr(cp, ',');
		} while(cp++ != NULL);
	}	/* #extension chorussend */
	else if(strcmp(w[0], "chorussend") == 0)
	{
	    if(words != 3)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL, "%s: line %d: syntax error", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    if(!bank)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: Must specify tone bank or drum set "
			  "before assignment", name, line);
		CHECKERRLIMIT;
		continue;
	    }
		i = atoi(w[2]);
		if(i < 0 || i > 127)
		{
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: extension chorussend "
			  "must be between 0 and 127", name, line);
		CHECKERRLIMIT;
		continue;
		}
		cp = w[1];
		do {
			if (string_to_7bit_range(cp, &j, &k))
			{
				while (j <= k)
					bank->tone[j++].chorus_send = i;
			}
			cp = strchr(cp, ',');
		} while(cp++ != NULL);
	}	/* #extension delaysend */
	else if(strcmp(w[0], "delaysend") == 0)
	{
	    if(words != 3)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL, "%s: line %d: syntax error", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    if(!bank)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: Must specify tone bank or drum set "
			  "before assignment", name, line);
		CHECKERRLIMIT;
		continue;
	    }
		i = atoi(w[2]);
		if(i < 0 || i > 127)
		{
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: extension delaysend "
			  "must be between 0 and 127", name, line);
		CHECKERRLIMIT;
		continue;
		}
		cp = w[1];
		do {
			if (string_to_7bit_range(cp, &j, &k))
			{
				while (j <= k)
					bank->tone[j++].delay_send = i;
			}
			cp = strchr(cp, ',');
		} while(cp++ != NULL);
	}	/* #extension playnote */
	else if(strcmp(w[0], "playnote") == 0)
	{
	    if(words != 3)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL, "%s: line %d: syntax error", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    if(!bank)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: Must specify tone bank or drum set "
			  "before assignment", name, line);
		CHECKERRLIMIT;
		continue;
	    }
		i = atoi(w[2]);
		if(i < 0 || i > 127)
		{
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: extension playnote"
			  "must be between 0 and 127", name, line);
		CHECKERRLIMIT;
		continue;
		}
		cp = w[1];
		do {
			if (string_to_7bit_range(cp, &j, &k))
			{
				while (j <= k)
					bank->tone[j++].play_note = i;
			}
			cp = strchr(cp, ',');
		} while(cp++ != NULL);
	}
	else if(!strcmp(w[0], "soundfont"))
	{
	    int order, cutoff, isremove, reso, amp;
	    char *sf_file;

	    if(words < 2)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: No soundfont file given",
			  name, line);
		CHECKERRLIMIT;
		continue;
	    }

	    sf_file = w[1];
	    order = cutoff = reso = amp = -1;
	    isremove = 0;
	    for(j = 2; j < words; j++)
	    {
		if(strcmp(w[j], "remove") == 0)
		{
		    isremove = 1;
		    break;
		}
		if(!(cp = strchr(w[j], '=')))
		{
		    ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			      "%s: line %d: bad patch option %s",
			      name, line, w[j]);
		    CHECKERRLIMIT;
		    break;
		}
		*cp++=0;
		k = atoi(cp);
		if(!strcmp(w[j], "order"))
		{
		    if(k < 0 || (*cp < '0' || *cp > '9'))
		    {
			ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
				  "%s: line %d: order must be a digit",
				  name, line);
			CHECKERRLIMIT;
			break;
		    }
		    order = k;
		}
		else if(!strcmp(w[j], "cutoff"))
		{
		    if(k < 0 || (*cp < '0' || *cp > '9'))
		    {
			ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
				  "%s: line %d: cutoff must be a digit",
				  name, line);
			CHECKERRLIMIT;
			break;
		    }
		    cutoff = k;
		}
		else if(!strcmp(w[j], "reso"))
		{
		    if(k < 0 || (*cp < '0' || *cp > '9'))
		    {
			ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
				  "%s: line %d: reso must be a digit",
				  name, line);
			CHECKERRLIMIT;
			break;
		    }
		    reso = k;
		}
		else if(!strcmp(w[j], "amp"))
		{
		    amp = k;
		}
	    }
	    if(isremove)
		remove_soundfont(c, sf_file);
	    else
		add_soundfont(c, sf_file, order, cutoff, reso, amp);
	}
	else if(!strcmp(w[0], "font"))
	{
	    int bank, preset, keynote;
	    if(words < 2)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: no font command", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    if(!strcmp(w[1], "exclude"))
	    {
		if(words < 3)
		{
		    ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			      "%s: line %d: No bank/preset/key is given",
			      name, line);
		    CHECKERRLIMIT;
		    continue;
		}
		bank = atoi(w[2]);
		if(words >= 4)
		    preset = atoi(w[3]) - c->progbase;
		else
		    preset = -1;
		if(words >= 5)
		    keynote = atoi(w[4]);
		else
		    keynote = -1;
		if(exclude_soundfont(c, bank, preset, keynote))
		{
		    ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			      "%s: line %d: No soundfont is given",
			      name, line);
		    CHECKERRLIMIT;
		}
	    }
	    else if(!strcmp(w[1], "order"))
	    {
		int order;
		if(words < 4)
		{
		    ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			      "%s: line %d: No order/bank is given",
			      name, line);
		    CHECKERRLIMIT;
		    continue;
		}
		order = atoi(w[2]);
		bank = atoi(w[3]);
		if(words >= 5)
		    preset = atoi(w[4]) - c->progbase;
		else
		    preset = -1;
		if(words >= 6)
		    keynote = atoi(w[5]);
		else
		    keynote = -1;
		if(order_soundfont(c, bank, preset, keynote, order))
		{
		    ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			      "%s: line %d: No soundfont is given",
			      name, line);
		    CHECKERRLIMIT;
		}
	    }
	}
	else if(!strcmp(w[0], "progbase"))
	{
	    if(words < 2 || *w[1] < '0' || *w[1] > '9')
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: syntax error", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    c->progbase = atoi(w[1]);
	}
	else if(!strcmp(w[0], "map")) /* map <name> set1 elem1 set2 elem2 */
	{
	    int arg[5], isdrum;

	    if(words != 6)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: syntax error", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    if((arg[0] = mapname2id(w[1], &isdrum)) == -1)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: Invalid map name: %s", name, line, w[1]);
		CHECKERRLIMIT;
		continue;
	    }
	    for(i = 2; i < 6; i++)
		arg[i - 1] = atoi(w[i]);
	    if(isdrum)
	    {
		arg[1] -= c->progbase;
		arg[3] -= c->progbase;
	    }
	    else
	    {
		arg[2] -= c->progbase;
		arg[4] -= c->progbase;
	    }

	    for(i = 1; i < 5; i++)
		if(arg[i] < 0 || arg[i] > 127)
		    break;
	    if(i != 5)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: Invalid parameter", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    set_instrument_map(c, arg[0], arg[1], arg[2], arg[3], arg[4]);
	}

	/*
	 * Standard configurations
	 */
	else if(!strcmp(w[0], "dir"))
	{
	    if(words < 2)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: No directory given", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    for(i = 1; i < words; i++)
		add_to_pathlist(c, w[i]);
	}
	else if(!strcmp(w[0], "source") || !strcmp(w[0], "trysource"))
	{
	    if(words < 2)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: No file name given", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    for(i = 1; i < words; i++)
	    {
		int status;
		rcf_count++;
		status = read_config_file(c, w[i], 0, !strcmp(w[0], "trysource"));
		rcf_count--;
		switch (status) {
		case READ_CONFIG_SUCCESS:
		    break;
		case READ_CONFIG_ERROR:
		    CHECKERRLIMIT;
		    continue;
		case READ_CONFIG_RECURSION:
		    reuse_mblock(c, &varbuf);
		    close_file(c, tf);
		    return READ_CONFIG_RECURSION;
		case READ_CONFIG_FILE_NOT_FOUND:
		    break;
		}
	    }
	}
	else if(!strcmp(w[0], "default"))
	{
	    if(words != 2)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: Must specify exactly one patch name",
			  name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    strncpy(c->def_instr_name, w[1], 255);
	    c->def_instr_name[255] = '\0';
	    c->default_instrument_name = c->def_instr_name;
	}
	/* drumset [mapid] num */
	else if(!strcmp(w[0], "drumset"))
	{
	    int newmapid, isdrum, newbankno;

	    if(words < 2)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: No drum set number given", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    if (words != 2 && !isdigit(*w[1]))
	    {
		if ((newmapid = mapname2id(w[1], &isdrum)) == -1 || !isdrum)
		{
		    ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: Invalid drum set map name: %s", name, line, w[1]);
		    CHECKERRLIMIT;
		    continue;
		}
		words--;
		memmove(&w[1], &w[2], sizeof w[0] * words);
	    }
	    else
		newmapid = INST_NO_MAP;
	    i = atoi(w[1]) - c->progbase;
	    if(i < 0 || i > 127)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: Drum set must be between %d and %d",
			  name, line,
			  c->progbase, c->progbase + 127);
		CHECKERRLIMIT;
		continue;
	    }

	    newbankno = i;
	    i = alloc_instrument_map_bank(c, 1, newmapid, i);
	    if (i == -1)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: No free drum set available to map",
			  name, line);
		CHECKERRLIMIT;
		continue;
	    }

	    if(words == 2)
	    {
		bank = c->drumset[i];
		bankno = i;
		mapid = newmapid;
		origbankno = newbankno;
		dr = 1;
	    }
	    else
	    {
		if(words < 4 || *w[2] < '0' || *w[2] > '9')
		{
		    ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			      "%s: line %d: syntax error", name, line);
		    CHECKERRLIMIT;
		    continue;
		}
		if (set_patchconf(c, name, line, c->drumset[i], &w[2], 1, newmapid, newbankno, i))
		{
		    CHECKERRLIMIT;
		    continue;
		}
	    }
	}
	/* bank [mapid] num */
	else if(!strcmp(w[0], "bank"))
	{
	    int newmapid, isdrum, newbankno;

	    if(words < 2)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: No bank number given", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    if (words != 2 && !isdigit(*w[1]))
	    {
		if ((newmapid = mapname2id(w[1], &isdrum)) == -1 || isdrum)
		{
		    ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: Invalid bank map name: %s", name, line, w[1]);
		    CHECKERRLIMIT;
		    continue;
		}
		words--;
		memmove(&w[1], &w[2], sizeof w[0] * words);
	    }
	    else
		newmapid = INST_NO_MAP;
	    i = atoi(w[1]);
	    if(i < 0 || i > 127)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: Tone bank must be between 0 and 127",
			  name, line);
		CHECKERRLIMIT;
		continue;
	    }

	    newbankno = i;
	    i = alloc_instrument_map_bank(c, 0, newmapid, i);
	    if (i == -1)
	    {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: No free tone bank available to map",
			  name, line);
		CHECKERRLIMIT;
		continue;
	    }

	    if(words == 2)
	    {
		bank = c->tonebank[i];
		bankno = i;
		mapid = newmapid;
		origbankno = newbankno;
		dr = 0;
	    }
	    else
	    {
		if(words < 4 || *w[2] < '0' || *w[2] > '9')
		{
		    ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			      "%s: line %d: syntax error", name, line);
		    CHECKERRLIMIT;
		    continue;
		}
		if (set_patchconf(c, name, line, c->tonebank[i], &w[2], 0, newmapid, newbankno, i))
		{
		    CHECKERRLIMIT;
		    continue;
		}
	    }
	}
	else
	{
	    if(words < 2 || *w[0] < '0' || *w[0] > '9')
	    {
		if(extension_flag)
		    continue;
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "%s: line %d: syntax error", name, line);
		CHECKERRLIMIT;
		continue;
	    }
	    if (set_patchconf(c, name, line, bank, w, dr, mapid, origbankno, bankno))
	    {
		CHECKERRLIMIT;
		continue;
	    }
	}
    }
    if(errno)
    {
	ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
		  "Can't read %s: %s", name, strerror(errno));
	errcnt++;
    }
    reuse_mblock(c, &varbuf);
    close_file(c, tf);
    return (errcnt == 0) ? READ_CONFIG_SUCCESS : READ_CONFIG_ERROR;
}
#undef rcf_count

#ifdef SUPPORT_SOCKET

#if defined(__W32__) && !defined(MAIL_NAME)
#define MAIL_NAME "anonymous"
#endif /* __W32__ */

#ifdef MAIL_NAME
#define get_username() MAIL_NAME
#else /* MAIL_NAME */
#include <pwd.h>
static char *get_username(void)
{
    char *p;
    struct passwd *pass;

    /* USER
     * LOGIN
     * LOGNAME
     * getpwnam()
     */

    if((p = getenv("USER")) != NULL)
        return p;
    if((p = getenv("LOGIN")) != NULL)
        return p;
    if((p = getenv("LOGNAME")) != NULL)
        return p;

    pass = getpwuid(getuid());
    if(pass == NULL)
        return "nobody";
    return pass->pw_name;
}
#endif /* MAIL_NAME */

static void init_mail_addr(struct timiditycontext_t *c)
{
    char addr[BUFSIZ];

    sprintf(addr, "%s%s", get_username(), MAIL_DOMAIN);
    user_mailaddr = safe_strdup(c, addr);
}
#endif /* SUPPORT_SOCKET */

static int read_user_config_file(struct timiditycontext_t *c)
{
    char *home;
    char path[BUFSIZ];
    int status;

    home = getenv("HOME");
#ifdef __W32__
/* HOME or home */
    if(home == NULL)
	home = getenv("home");
#endif
    if(home == NULL)
    {
	ctl->cmsg(c, CMSG_INFO, VERB_NOISY,
		  "Warning: HOME environment is not defined.");
	return 0;
    }

#ifdef __W32__
/* timidity.cfg or _timidity.cfg or .timidity.cfg*/
    sprintf(path, "%s" PATH_STRING "timidity.cfg", home);
    status = read_config_file(c, path, 0, 1);
    if (status != READ_CONFIG_FILE_NOT_FOUND)
        return status;

    sprintf(path, "%s" PATH_STRING "_timidity.cfg", home);
    status = read_config_file(c, path, 0, 1);
    if (status != READ_CONFIG_FILE_NOT_FOUND)
        return status;
#endif

    sprintf(path, "%s" PATH_STRING ".timidity.cfg", home);
    status = read_config_file(c, path, 0, 1);
    if (status != READ_CONFIG_FILE_NOT_FOUND)
        return status;

    return 0;
}

MAIN_INTERFACE void tmdy_free_config(struct timiditycontext_t *c)
{
	free_tone_bank(c);
	free_instrument_map(c);
	clean_up_pathlist(c);
}

int set_extension_modes(struct timiditycontext_t *c, char *flag)
{
	return parse_opt_E(c, flag);
}

int set_ctl(struct timiditycontext_t *c, char *cp)
{
	return parse_opt_i(c, cp);
}

int set_play_mode(struct timiditycontext_t *c, char *cp)
{
	return parse_opt_O(c, cp);
}

int set_wrd(struct timiditycontext_t *c, char *w)
{
	return parse_opt_W(c, w);
}

#ifdef __W32__
int opt_evil_mode = 0;
#ifdef SMFCONV
int opt_rcpcv_dll = 0;
#endif	/* SMFCONV */
#endif	/* __W32__ */
#ifdef SUPPORT_SOUNDSPEC
static double spectrogram_update_sec = 0.0;
#endif /* SUPPORT_SOUNDSPEC */

MAIN_INTERFACE int set_tim_opt_short(struct timiditycontext_t *c, int ch, char *optarg)
{
	int err = 0;

	switch (ch) {
	case '4':
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
				"-4 option is obsoleted.  Please use -N");
		return 1;
	case 'A':
		if (*optarg != ',' && *optarg != 'a')
			err += parse_opt_A(c, optarg);
		if (strchr(optarg, ','))
			err += parse_opt_drum_power(c, strchr(optarg, ',') + 1);
		if (strchr(optarg, 'a'))
			c->opt_amp_compensation = 1;
		return err;
	case 'a':
		c->antialiasing_allowed = 1;
		break;
	case 'B':
		return parse_opt_B(c, optarg);
	case 'C':
		return parse_opt_C(c, optarg);
	case 'c':
		return parse_opt_c(c, optarg);
	case 'D':
		return parse_opt_D(c, optarg);
	case 'd':
		return parse_opt_d(c, optarg);
	case 'E':
		return parse_opt_E(c, optarg);
	case 'e':
		return parse_opt_e(c, optarg);
	case 'F':
		c->adjust_panning_immediately = (c->adjust_panning_immediately) ? 0 : 1;
		break;
	case 'f':
		c->fast_decay = (c->fast_decay) ? 0 : 1;
		break;
	case 'G':
		return parse_opt_G(c, optarg);
	case 'g':
		return parse_opt_g(c, optarg);
	case 'H':
		return parse_opt_H(c, optarg);
	case 'h':
		return parse_opt_h(c, optarg);
	case 'I':
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
				"-I option is obsoleted.  Please use -Ei");
		return 1;
	case 'i':
		return parse_opt_i(c, optarg);
	case 'j':
		c->opt_realtime_playing = (c->opt_realtime_playing) ? 0 : 1;
		break;
	case 'K':
		return parse_opt_K(c, optarg);
	case 'k':
		return parse_opt_k(c, optarg);
	case 'L':
		return parse_opt_L(c, optarg);
	case 'M':
		return parse_opt_M(c, optarg);
	case 'm':
		return parse_opt_m(c, optarg);
	case 'N':
		return parse_opt_N(c, optarg);
	case 'O':
		return parse_opt_O(c, optarg);
	case 'o':
		return parse_opt_o(c, optarg);
	case 'P':
		return parse_opt_P(c, optarg);
	case 'p':
		if (*optarg != 'a')
			err += parse_opt_p(c, optarg);
		if (strchr(optarg, 'a'))
			c->auto_reduce_polyphony = (c->auto_reduce_polyphony) ? 0 : 1;
		return err;
	case 'Q':
		return parse_opt_Q(c, optarg);
	case 'q':
		return parse_opt_q(c, optarg);
	case 'R':
		return parse_opt_R(c, optarg);
	case 'S':
		return parse_opt_S(c, optarg);
	case 's':
		return parse_opt_s(c, optarg);
	case 'T':
		return parse_opt_T(c, optarg);
	case 't':
		return parse_opt_t(c, optarg);
	case 'U':
		c->free_instruments_afterwards = 1;
		break;
	case 'V':
		return parse_opt_volume_curve(c, optarg);
	case 'v':
		return parse_opt_v(optarg);
	case 'W':
		return parse_opt_W(c, optarg);
#ifdef __W32__
	case 'w':
		return parse_opt_w(c, optarg);
#endif
	case 'x':
		return parse_opt_x(c, optarg);
	case 'Z':
		if (strncmp(optarg, "pure", 4))
			return parse_opt_Z(c, optarg);
		else
			return parse_opt_Z1(c, optarg + 4);
	default:
		return 1;
	}
	return 0;
}

#ifdef __W32__
MAIN_INTERFACE int set_tim_opt_short_cfg(struct timiditycontext_t *c, int ch, char *optarg)
{
	switch (ch) {
	case 'c':
		return parse_opt_c(c, optarg);
	}
	return 0;
}
#endif

/* -------- getopt_long -------- */
MAIN_INTERFACE int set_tim_opt_long(struct timiditycontext_t *c, int ch, char *optarg, int index)
{
	const struct option *the_option = &(longopts[index]);
	char *arg;

	if (ch == '?')	/* getopt_long failed parsing */
		parse_opt_fail(c, optarg);
	else if (ch < TIM_OPT_FIRST)
		return set_tim_opt_short(c, ch, optarg);
	if (! strncmp(the_option->name, "no-", 3))
		arg = "no";		/* `reverse' switch */
	else
		arg = optarg;
	switch (ch) {
	case TIM_OPT_VOLUME:
		return parse_opt_A(c, arg);
	case TIM_OPT_DRUM_POWER:
		return parse_opt_drum_power(c, arg);
	case TIM_OPT_VOLUME_COMP:
		return parse_opt_volume_comp(c, arg);
	case TIM_OPT_ANTI_ALIAS:
		return parse_opt_a(c, arg);
	case TIM_OPT_BUFFER_FRAGS:
		return parse_opt_B(c, arg);
	case TIM_OPT_CONTROL_RATIO:
		return parse_opt_C(c, arg);
	case TIM_OPT_CONFIG_FILE:
		return parse_opt_c(c, arg);
	case TIM_OPT_DRUM_CHANNEL:
		return parse_opt_D(c, arg);
	case TIM_OPT_IFACE_PATH:
		return parse_opt_d(c, arg);
	case TIM_OPT_EXT:
		return parse_opt_E(c, arg);
	case TIM_OPT_MOD_WHEEL:
		return parse_opt_mod_wheel(c, arg);
	case TIM_OPT_PORTAMENTO:
		return parse_opt_portamento(c, arg);
	case TIM_OPT_VIBRATO:
		return parse_opt_vibrato(c, arg);
	case TIM_OPT_CH_PRESS:
		return parse_opt_ch_pressure(c, arg);
	case TIM_OPT_MOD_ENV:
		return parse_opt_mod_env(c, arg);
	case TIM_OPT_TRACE_TEXT:
		return parse_opt_trace_text(c, arg);
	case TIM_OPT_OVERLAP:
		return parse_opt_overlap_voice(c, arg);
	case TIM_OPT_TEMPER_CTRL:
		return parse_opt_temper_control(c, arg);
	case TIM_OPT_DEFAULT_MID:
		return parse_opt_default_mid(c, arg);
	case TIM_OPT_SYSTEM_MID:
		return parse_opt_system_mid(c, arg);
	case TIM_OPT_DEFAULT_BANK:
		return parse_opt_default_bank(c, arg);
	case TIM_OPT_FORCE_BANK:
		return parse_opt_force_bank(c, arg);
	case TIM_OPT_DEFAULT_PGM:
		return parse_opt_default_program(c, arg);
	case TIM_OPT_FORCE_PGM:
		return parse_opt_force_program(c, arg);
	case TIM_OPT_DELAY:
		return parse_opt_delay(c, arg);
	case TIM_OPT_CHORUS:
		return parse_opt_chorus(c, arg);
	case TIM_OPT_REVERB:
		return parse_opt_reverb(c, arg);
	case TIM_OPT_VOICE_LPF:
		return parse_opt_voice_lpf(c, arg);
	case TIM_OPT_NS:
		return parse_opt_noise_shaping(c, arg);
#ifndef FIXED_RESAMPLATION
	case TIM_OPT_RESAMPLE:
		return parse_opt_resample(c, arg);
#endif
	case TIM_OPT_EVIL:
		return parse_opt_e(c, arg);
	case TIM_OPT_FAST_PAN:
		return parse_opt_F(c, arg);
	case TIM_OPT_FAST_DECAY:
		return parse_opt_f(c, arg);
	case TIM_OPT_SEGMENT:
		return parse_opt_G(c, arg);
	case TIM_OPT_SPECTROGRAM:
		return parse_opt_g(c, arg);
	case TIM_OPT_KEYSIG:
		return parse_opt_H(c, arg);
	case TIM_OPT_HELP:
		return parse_opt_h(c, arg);
	case TIM_OPT_INTERFACE:
		return parse_opt_i(c, arg);
	case TIM_OPT_VERBOSE:
		return parse_opt_verbose(arg);
	case TIM_OPT_QUIET:
		return parse_opt_quiet(arg);
	case TIM_OPT_TRACE:
		return parse_opt_trace(arg);
	case TIM_OPT_LOOP:
		return parse_opt_loop(arg);
	case TIM_OPT_RANDOM:
		return parse_opt_random(arg);
	case TIM_OPT_SORT:
		return parse_opt_sort(arg);
#ifdef IA_ALSASEQ
	case TIM_OPT_BACKGROUND:
		return parse_opt_background(arg);
	case TIM_OPT_RT_PRIO:
		return parse_opt_rt_prio(c, arg);
	case TIM_OPT_SEQ_PORTS:
		return parse_opt_seq_ports(c, arg);
#endif
#if defined(IA_WINSYN) || defined(IA_PORTMIDISYN) || defined(IA_NPSYN) || defined(IA_W32G_SYN) || defined(IA_W32GUI)
	case TIM_OPT_RTSYN_LATENCY:
		return parse_opt_rtsyn_latency(arg);
#endif
	case TIM_OPT_REALTIME_LOAD:
		return parse_opt_j(c, arg);
	case TIM_OPT_ADJUST_KEY:
		return parse_opt_K(c, arg);
	case TIM_OPT_VOICE_QUEUE:
		return parse_opt_k(c, arg);
	case TIM_OPT_PATCH_PATH:
		return parse_opt_L(c, arg);
	case TIM_OPT_PCM_FILE:
		return parse_opt_M(c, arg);
	case TIM_OPT_DECAY_TIME:
		return parse_opt_m(c, arg);
	case TIM_OPT_INTERPOLATION:
		return parse_opt_N(c, arg);
	case TIM_OPT_OUTPUT_MODE:
		return parse_opt_O(c, arg);
	case TIM_OPT_OUTPUT_STEREO:
		if (! strcmp(the_option->name, "output-mono"))
			/* --output-mono == --output-stereo=no */
			arg = "no";
		return parse_opt_output_stereo(c, arg);
	case TIM_OPT_OUTPUT_SIGNED:
		if (! strcmp(the_option->name, "output-unsigned"))
			/* --output-unsigned == --output-signed=no */
			arg = "no";
		return parse_opt_output_signed(c, arg);
	case TIM_OPT_OUTPUT_BITWIDTH:
		if (! strcmp(the_option->name, "output-16bit"))
			arg = "16bit";
		else if (! strcmp(the_option->name, "output-24bit"))
			arg = "24bit";
		else if (! strcmp(the_option->name, "output-8bit"))
			arg = "8bit";
		return parse_opt_output_bitwidth(c, arg);
	case TIM_OPT_OUTPUT_FORMAT:
		if (! strcmp(the_option->name, "output-linear"))
			arg = "linear";
		else if (! strcmp(the_option->name, "output-ulaw"))
			arg = "ulaw";
		else if (! strcmp(the_option->name, "output-alaw"))
			arg = "alaw";
		return parse_opt_output_format(c, arg);
	case TIM_OPT_OUTPUT_SWAB:
		return parse_opt_output_swab(c, arg);
#ifdef AU_FLAC
	case TIM_OPT_FLAC_VERIFY:
		return parse_opt_flac_verify(arg);
	case TIM_OPT_FLAC_PADDING:
		return parse_opt_flac_padding(arg);
	case TIM_OPT_FLAC_COMPLEVEL:
		return parse_opt_flac_complevel(arg);
#ifdef AU_OGGFLAC
	case TIM_OPT_FLAC_OGGFLAC:
		return parse_opt_flac_oggflac(arg);
#endif /* AU_OGGFLAC */
#endif /* AU_FLAC */
#ifdef AU_SPEEX
	case TIM_OPT_SPEEX_QUALITY:
		return parse_opt_speex_quality(arg);
	case TIM_OPT_SPEEX_VBR:
		return parse_opt_speex_vbr(arg);
	case TIM_OPT_SPEEX_ABR:
		return parse_opt_speex_abr(arg);
	case TIM_OPT_SPEEX_VAD:
		return parse_opt_speex_vad(arg);
	case TIM_OPT_SPEEX_DTX:
		return parse_opt_speex_dtx(arg);
	case TIM_OPT_SPEEX_COMPLEXITY:
		return parse_opt_speex_complexity(arg);
	case TIM_OPT_SPEEX_NFRAMES:
		return parse_opt_speex_nframes(arg);
#endif /* AU_SPEEX */
	case TIM_OPT_OUTPUT_FILE:
		return parse_opt_o(c, arg);
	case TIM_OPT_PATCH_FILE:
		return parse_opt_P(c, arg);
	case TIM_OPT_POLYPHONY:
		return parse_opt_p(c, arg);
	case TIM_OPT_POLY_REDUCE:
		return parse_opt_p1(c, arg);
	case TIM_OPT_MUTE:
		return parse_opt_Q(c, arg);
	case TIM_OPT_TEMPER_MUTE:
		return parse_opt_Q1(c, arg);
	case TIM_OPT_PRESERVE_SILENCE:
		return parse_opt_preserve_silence(c, arg);
	case TIM_OPT_AUDIO_BUFFER:
		return parse_opt_q(c, arg);
	case TIM_OPT_CACHE_SIZE:
		return parse_opt_S(c, arg);
	case TIM_OPT_SAMPLE_FREQ:
		return parse_opt_s(c, arg);
	case TIM_OPT_ADJUST_TEMPO:
		return parse_opt_T(c, arg);
	case TIM_OPT_CHARSET:
		return parse_opt_t(c, arg);
	case TIM_OPT_UNLOAD_INST:
		return parse_opt_U(c, arg);
	case TIM_OPT_VOLUME_CURVE:
		return parse_opt_volume_curve(c, arg);
	case TIM_OPT_VERSION:
		return parse_opt_v(arg);
	case TIM_OPT_WRD:
		return parse_opt_W(c, arg);
#ifdef __W32__
	case TIM_OPT_RCPCV_DLL:
		return parse_opt_w(c, arg);
#endif
	case TIM_OPT_CONFIG_STR:
		return parse_opt_x(c, arg);
	case TIM_OPT_FREQ_TABLE:
		return parse_opt_Z(c, arg);
	case TIM_OPT_PURE_INT:
		return parse_opt_Z1(c, arg);
	case TIM_OPT_MODULE:
		return parse_opt_default_module(c, arg);
	default:
		ctl->cmsg(c, CMSG_FATAL, VERB_NORMAL,
				"[BUG] Inconceivable case branch %d", ch);
		abort();
	}
}

#ifdef __W32__
MAIN_INTERFACE int set_tim_opt_long_cfg(struct timiditycontext_t *c, int ch, char *optarg, int index)
{
	const struct option *the_option = &(longopts[index]);
	char *arg;

	if (ch == '?')	/* getopt_long failed parsing */
		parse_opt_fail(c, optarg);
	else if (ch < TIM_OPT_FIRST)
		return set_tim_opt_short_cfg(c, ch, optarg);
	if (! strncmp(the_option->name, "no-", 3))
		arg = "no";		/* `reverse' switch */
	else
		arg = optarg;
	switch (ch) {
	case TIM_OPT_CONFIG_FILE:
		return parse_opt_c(c, arg);
	}
	return 1;
}
#endif

static inline int parse_opt_A(struct timiditycontext_t *c, const char *arg)
{
	/* amplify volume by n percent */
	return set_val_i32(c, &c->amplification, atoi(arg), 0, MAX_AMPLIFICATION,
			"Amplification");
}

static inline int parse_opt_drum_power(struct timiditycontext_t *c, const char *arg)
{
	/* --drum-power */
	return set_val_i32(c, &c->opt_drum_power, atoi(arg), 0, MAX_AMPLIFICATION,
			"Drum power");
}

static inline int parse_opt_volume_comp(struct timiditycontext_t *c, const char *arg)
{
	/* --[no-]volume-compensation */
	c->opt_amp_compensation = y_or_n_p(arg);
	return 0;
}

static inline int parse_opt_a(struct timiditycontext_t *c, const char *arg)
{
	c->antialiasing_allowed = y_or_n_p(arg);
	return 0;
}

static inline int parse_opt_B(struct timiditycontext_t *c, const char *arg)
{
	/* --buffer-fragments */
	const char *p;

	/* num */
	if (*arg != ',') {
		if (set_value(c, &c->opt_buffer_fragments, atoi(arg), 0, 1000,
				"Buffer Fragments (num)"))
			return 1;
	}
	/* bits */
	if ((p = strchr(arg, ',')) != NULL) {
		if (set_value(c, &c->audio_buffer_bits, atoi(++p), 1, AUDIO_BUFFER_BITS,
				"Buffer Fragments (bit)"))
			return 1;
	}
	return 0;
}

static inline int parse_opt_C(struct timiditycontext_t *c, const char *arg)
{
	if (set_val_i32(c, &c->control_ratio, atoi(arg), 0, MAX_CONTROL_RATIO,
			"Control ratio"))
		return 1;
	c->opt_control_ratio = c->control_ratio;
	return 0;
}

static inline int parse_opt_c(struct timiditycontext_t *c, char *arg)
{
#ifdef __W32__
	if (c->got_a_configuration == 1)
		return 0;
#endif
	if (read_config_file(c, arg, 0, 0))
		return 1;
	c->got_a_configuration = 1;
	return 0;
}

static inline int parse_opt_D(struct timiditycontext_t *c, const char *arg)
{
	return set_channel_flag(c, &c->default_drumchannels, atoi(arg), "Drum channel");
}

static inline int parse_opt_d(struct timiditycontext_t *c, const char *arg)
{
	/* dynamic lib root */
#ifdef IA_DYNAMIC
	if (dynamic_lib_root)
		free(dynamic_lib_root);
	dynamic_lib_root = safe_strdup(c, arg);
	return 0;
#else
	ctl->cmsg(c, CMSG_WARNING, VERB_NOISY, "-d option is not supported");
	return 1;
#endif	/* IA_DYNAMIC */
}

static inline int parse_opt_E(struct timiditycontext_t *c, char *arg)
{
	/* undocumented option --ext */
	int err = 0;

	while (*arg) {
		switch (*arg) {
		case 'w':
			c->opt_modulation_wheel = 1;
			break;
		case 'W':
			c->opt_modulation_wheel = 0;
			break;
		case 'p':
			c->opt_portamento = 1;
			break;
		case 'P':
			c->opt_portamento = 0;
			break;
		case 'v':
			c->opt_nrpn_vibrato = 1;
			break;
		case 'V':
			c->opt_nrpn_vibrato = 0;
			break;
		case 's':
			c->opt_channel_pressure = 1;
			break;
		case 'S':
			c->opt_channel_pressure = 0;
			break;
		case 'e':
			c->opt_modulation_envelope = 1;
			break;
		case 'E':
			c->opt_modulation_envelope = 0;
			break;
		case 't':
			c->opt_trace_text_meta_event = 1;
			break;
		case 'T':
			c->opt_trace_text_meta_event = 0;
			break;
		case 'o':
			c->opt_overlap_voice_allow = 1;
			break;
		case 'O':
			c->opt_overlap_voice_allow = 0;
			break;
		case 'z':
			c->opt_temper_control = 1;
			break;
		case 'Z':
			c->opt_temper_control = 0;
			break;
		case 'm':
			if (parse_opt_default_mid(c, arg + 1))
				err++;
			arg += 2;
			break;
		case 'M':
			if (parse_opt_system_mid(c, arg + 1))
				err++;
			arg += 2;
			break;
		case 'b':
			if (parse_opt_default_bank(c, arg + 1))
				err++;
			while (isdigit(*(arg + 1)))
				arg++;
			break;
		case 'B':
			if (parse_opt_force_bank(c, arg + 1))
				err++;
			while (isdigit(*(arg + 1)))
				arg++;
			break;
		case 'i':
			if (parse_opt_default_program(c, arg + 1))
				err++;
			while (isdigit(*(arg + 1)) || *(arg + 1) == '/')
				arg++;
			break;
		case 'I':
			if (parse_opt_force_program(c, arg + 1))
				err++;
			while (isdigit(*(arg + 1)) || *(arg + 1) == '/')
				arg++;
			break;
		case 'F':
			if (strncmp(arg + 1, "delay=", 6) == 0) {
				if (parse_opt_delay(c, arg + 7))
					err++;
			} else if (strncmp(arg + 1, "chorus=", 7) == 0) {
				if (parse_opt_chorus(c, arg + 8))
					err++;
			} else if (strncmp(arg + 1, "reverb=", 7) == 0) {
				if (parse_opt_reverb(c, arg + 8))
					err++;
			} else if (strncmp(arg + 1, "ns=", 3) == 0) {
				if (parse_opt_noise_shaping(c, arg + 4))
					err++;
#ifndef FIXED_RESAMPLATION
			} else if (strncmp(arg + 1, "resamp=", 7) == 0) {
				if (parse_opt_resample(c, arg + 8))
					err++;
#endif
			}
			if (err) {
				ctl->cmsg(c, CMSG_ERROR,
						VERB_NORMAL, "-E%s: unsupported effect", arg);
				return err;
			}
			return err;
		default:
			ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
					"-E: Illegal mode `%c'", *arg);
			err++;
			break;
		}
		arg++;
	}
	return err;
}

static inline int parse_opt_mod_wheel(struct timiditycontext_t *c, const char *arg)
{
	/* --[no-]mod-wheel */
	c->opt_modulation_wheel = y_or_n_p(arg);
	return 0;
}

static inline int parse_opt_portamento(struct timiditycontext_t *c, const char *arg)
{
	/* --[no-]portamento */
	c->opt_portamento = y_or_n_p(arg);
	return 0;
}

static inline int parse_opt_vibrato(struct timiditycontext_t *c, const char *arg)
{
	/* --[no-]vibrato */
	c->opt_nrpn_vibrato = y_or_n_p(arg);
	return 0;
}

static inline int parse_opt_ch_pressure(struct timiditycontext_t *c, const char *arg)
{
	/* --[no-]ch-pressure */
	c->opt_channel_pressure = y_or_n_p(arg);
	return 0;
}

static inline int parse_opt_mod_env(struct timiditycontext_t *c, const char *arg)
{
	/* --[no-]mod-envelope */
	c->opt_modulation_envelope = y_or_n_p(arg);
	return 0;
}

static inline int parse_opt_trace_text(struct timiditycontext_t *c, const char *arg)
{
	/* --[no-]trace-text-meta */
	c->opt_trace_text_meta_event = y_or_n_p(arg);
	return 0;
}

static inline int parse_opt_overlap_voice(struct timiditycontext_t *c, const char *arg)
{
	/* --[no-]overlap-voice */
	c->opt_overlap_voice_allow = y_or_n_p(arg);
	return 0;
}

static inline int parse_opt_temper_control(struct timiditycontext_t *c, const char *arg)
{
	/* --[no-]temper-control */
	c->opt_temper_control = y_or_n_p(arg);
	return 0;
}

static inline int parse_opt_default_mid(struct timiditycontext_t *c, char *arg)
{
	/* --default-mid */
	int val = str2mID(arg);

	if (! val) {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL, "Manufacture ID: Illegal value");
		return 1;
	}
	c->opt_default_mid = val;
	return 0;
}

static inline int parse_opt_system_mid(struct timiditycontext_t *c, char *arg)
{
	/* --system-mid */
	int val = str2mID(arg);

	if (! val) {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL, "Manufacture ID: Illegal value");
		return 1;
	}
	c->opt_system_mid = val;
	return 0;
}

static inline int parse_opt_default_bank(struct timiditycontext_t *c, const char *arg)
{
	/* --default-bank */
	if (set_value(c, &c->default_tonebank, atoi(arg), 0, 0x7f, "Bank number"))
		return 1;
	c->special_tonebank = -1;
	return 0;
}

static inline int parse_opt_force_bank(struct timiditycontext_t *c, const char *arg)
{
	/* --force-bank */
	if (set_value(c, &c->special_tonebank, atoi(arg), 0, 0x7f, "Bank number"))
		return 1;
	return 0;
}

static inline int parse_opt_default_program(struct timiditycontext_t *c, const char *arg)
{
	/* --default-program */
	int prog, i;
	const char *p;

	if (set_value(c, &prog, atoi(arg), 0, 0x7f, "Program number"))
		return 1;
	if ((p = strchr(arg, '/')) != NULL) {
		if (set_value(c, &i, atoi(++p), 1, MAX_CHANNELS, "Program channel"))
			return 1;
		c->default_program[i - 1] = prog;
	} else
		for (i = 0; i < MAX_CHANNELS; i++)
			c->default_program[i] = prog;
	return 0;
}

static inline int parse_opt_force_program(struct timiditycontext_t *c, const char *arg)
{
	/* --force-program */
	const char *p;
	int i;

	if (set_value(c, &c->def_prog, atoi(arg), 0, 0x7f, "Program number"))
		return 1;
	if (ctl->opened)
		set_default_program(c, c->def_prog);
	if ((p = strchr(arg, '/')) != NULL) {
		if (set_value(c, &i, atoi(++p), 1, MAX_CHANNELS, "Program channel"))
			return 1;
		c->default_program[i - 1] = SPECIAL_PROGRAM;
	} else
		for (i = 0; i < MAX_CHANNELS; i++)
			c->default_program[i] = SPECIAL_PROGRAM;
	return 0;
}

static inline int set_default_program(struct timiditycontext_t *c, int prog)
{
	int bank;
	Instrument *ip;

	bank = (c->special_tonebank >= 0) ? c->special_tonebank : c->default_tonebank;
	if ((ip = play_midi_load_instrument(c, 0, bank, prog)) == NULL)
		return 1;
	c->default_instrument = ip;
	return 0;
}

static inline int parse_opt_delay(struct timiditycontext_t *c, const char *arg)
{
	/* --delay */
	const char *p;

	switch (*arg) {
	case '0':
	case 'd':	/* disable */
		c->effect_lr_mode = -1;
		return 0;
	case 'l':	/* left */
		c->effect_lr_mode = 0;
		break;
	case 'r':	/* right */
		c->effect_lr_mode = 1;
		break;
	case 'b':	/* both */
		c->effect_lr_mode = 2;
		break;
	}
	if ((p = strchr(arg, ',')) != NULL)
		if ((c->effect_lr_delay_msec = atoi(++p)) < 0) {
			c->effect_lr_delay_msec = 0;
			c->effect_lr_mode = -1;
			ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL, "Invalid delay parameter.");
			return 1;
		}
	return 0;
}

static inline int parse_opt_chorus(struct timiditycontext_t *c, const char *arg)
{
	/* --chorus */
	const char *p;

	switch (*arg) {
	case '0':
	case 'd':	/* disable */
		c->opt_chorus_control = 0;
		c->opt_surround_chorus = 0;
		break;
	case '1':
	case 'n':	/* normal */
	case '2':
	case 's':	/* surround */
		c->opt_surround_chorus = (*arg == '2' || *arg == 's') ? 1 : 0;
		if ((p = strchr(arg, ',')) != NULL) {
			if (set_value(c, &c->opt_chorus_control, atoi(++p), 0, 0x7f,
					"Chorus level"))
				return 1;
			c->opt_chorus_control = -c->opt_chorus_control;
		} else
			c->opt_chorus_control = 1;
		break;
	default:
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL, "Invalid chorus parameter.");
		return 1;
	}
	return 0;
}

static inline int parse_opt_reverb(struct timiditycontext_t *c, const char *arg)
{
	/* --reverb */
	const char *p;

	/* option       action                  opt_reverb_control
	 * reverb=0     no reverb                 0
	 * reverb=1     old reverb                1
	 * reverb=1,n   set reverb level to n   (-1 to -127)
	 * reverb=2     "global" old reverb       2
	 * reverb=2,n   set reverb level to n   (-1 to -127) - 128
	 * reverb=3     new reverb                3
	 * reverb=3,n   set reverb level to n   (-1 to -127) - 256
	 * reverb=4     "global" new reverb       4
	 * reverb=4,n   set reverb level to n   (-1 to -127) - 384
	 *
	 * I think "global" was meant to apply a single global reverb,
	 * without applying any reverb to the channels.  The do_effects()
	 * function in effects.c looks like a good way to do this.
	 *
	 * This is NOT the "correct" way to implement global reverb, we should
	 * really make a new variable just for that.  But if opt_reverb_control
	 * is already used in a similar fashion, rather than creating a new
	 * variable for setting the channel reverb levels, then I guess
	 * maybe this isn't so bad....  It would be nice to create new
	 * variables for both global reverb and channel reverb level settings
	 * in the future, but this will do for now.
	 */

	switch (*arg) {
	case '0':
	case 'd':	/* disable */
		c->opt_reverb_control = 0;
		break;
	case '1':
	case 'n':	/* normal */
		if ((p = strchr(arg, ',')) != NULL) {
			if (set_value(c, &c->opt_reverb_control, atoi(++p), 1, 0x7f,
					"Reverb level"))
				return 1;
			c->opt_reverb_control = - c->opt_reverb_control;
		} else
			c->opt_reverb_control = 1;
		break;
	case '2':
	case 'g':	/* global */
		if ((p = strchr(arg, ',')) != NULL) {
			if (set_value(c, &c->opt_reverb_control, atoi(++p), 1, 0x7f,
					"Reverb level"))
				return 1;
			c->opt_reverb_control = - c->opt_reverb_control - 128;
		} else
			c->opt_reverb_control = 2;
		break;
	case '3':
	case 'f':	/* freeverb */
		return parse_opt_reverb_freeverb(c, arg, 'f');
	case '4':
	case 'G':	/* global freeverb */
		return parse_opt_reverb_freeverb(c, arg, 'G');
	default:
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL, "Invalid reverb parameter.");
		return 1;
	}
	return 0;
}

static int parse_opt_reverb_freeverb(struct timiditycontext_t *c, const char *arg, char type)
{
	const char *p;

	if ((p = strchr(arg, ',')) != NULL)
		p++;
	else
		p = "";
	/* reverb level */
	if (*p && *p != ',') {
		if (set_value(c, &c->opt_reverb_control, atoi(p), 1, 0x7f,
				"Reverb level"))
			return 1;
		if (type == 'f')
			c->opt_reverb_control = - c->opt_reverb_control - 256;
		else
			c->opt_reverb_control = - c->opt_reverb_control - 384;
	} else
		c->opt_reverb_control = (type == 'f') ? 3 : 4;
	if ((p = strchr(p, ',')) == NULL)
		return 0;
	p++;
	/* ranges 0..10 below determined just to reject an extreme value */
	/* scaleroom */
	if (*p && *p != ',') {
		if (parse_val_float_t(c, &c->freeverb_scaleroom, p, 0, 10,
				"Freeverb scaleroom", 1))
			return 1;
	}
	if ((p = strchr(p, ',')) == NULL)
		return 0;
	p++;
	/* offsetroom */
	if (*p && *p != ',') {
		if (parse_val_float_t(c, &c->freeverb_offsetroom, p, 0, 10,
				"Freeverb offsetroom", 1))
			return 1;
	}
	if ((p = strchr(p, ',')) == NULL)
		return 0;
	p++;
	/* predelay factor */
	if (*p && *p != ',') {
		int value;

		if (set_val_i32(c, &value, atoi(p), 0, 1000,
				"Freeverb predelay factor"))
			return 1;
		c->reverb_predelay_factor = value / 100.0;
	}
	return 0;
}

static inline int parse_opt_voice_lpf(struct timiditycontext_t *c, const char *arg)
{
	/* --voice-lpf */
	switch (*arg) {
	case '0':
	case 'd':	/* disable */
		c->opt_lpf_def = 0;
		break;
	case '1':
	case 'c':	/* chamberlin */
		c->opt_lpf_def = 1;
		break;
	case '2':
	case 'm':	/* moog */
		c->opt_lpf_def = 2;
		break;
	default:
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL, "Invalid voice LPF type %s", arg);
		return 1;
	}
	return 0;
}

/* Noise Shaping filter from
 * Kunihiko IMAI <imai@leo.ec.t.kanazawa-u.ac.jp>
 */
static inline int parse_opt_noise_shaping(struct timiditycontext_t *c, const char *arg)
{
	/* --noise-shaping */
	if (set_value(c, &c->noise_sharp_type, atoi(arg), 0, 4, "Noise shaping type"))
		return 1;
	return 0;
}

static inline int parse_opt_resample(struct timiditycontext_t *c, const char *arg)
{
	/* --resample */
	switch (*arg) {
	case '0':
	case 'd':	/* disable */
		set_current_resampler(c, RESAMPLE_NONE);
		break;
	case '1':
	case 'l':	/* linear */
		set_current_resampler(c, RESAMPLE_LINEAR);
		break;
	case '2':
	case 'c':	/* cspline */
		set_current_resampler(c, RESAMPLE_CSPLINE);
		break;
	case '3':
	case 'L':	/* lagrange */
		set_current_resampler(c, RESAMPLE_LAGRANGE);
		break;
	case '4':
	case 'n':	/* newton */
		set_current_resampler(c, RESAMPLE_NEWTON);
		break;
	case '5':
	case 'g':	/* guass */
		set_current_resampler(c, RESAMPLE_GAUSS);
		break;
	default:
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL, "Invalid resample type %s", arg);
		return 1;
	}
	return 0;
}

static inline int parse_opt_e(struct timiditycontext_t *c, const char *arg)
{
	/* evil */
#ifdef __W32__
	opt_evil_mode = 1;
	return 0;
#else
	ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL, "-e option is not supported");
	return 1;
#endif /* __W32__ */
}

static inline int parse_opt_F(struct timiditycontext_t *c, const char *arg)
{
	c->adjust_panning_immediately = y_or_n_p(arg);
	return 0;
}

static inline int parse_opt_f(struct timiditycontext_t *c, const char *arg)
{
	c->fast_decay = y_or_n_p(arg);
	return 0;
}

static inline int parse_opt_G(struct timiditycontext_t *c, const char *arg)
{
	/* play just sub-segment(s) (seconds) */
	TimeSegment *sp;
	const char *p = arg;
	int prev_end;

	if (strchr(arg, 'm'))
		return parse_opt_G1(c, arg);
	if (c->time_segments == NULL) {
		c->time_segments = (TimeSegment *) safe_malloc(c, sizeof(TimeSegment));
		c->time_segments->type = 0;
		if (parse_segment(c, c->time_segments, p)) {
			free_time_segments(c);
			return 1;
		}
		c->time_segments->prev = c->time_segments->next = NULL, sp = c->time_segments;
	} else {
		for (sp = c->time_segments; sp->next != NULL; sp = sp->next)
			;
		sp->next = (TimeSegment *) safe_malloc(c, sizeof(TimeSegment));
		sp->next->type = 0;
		if (parse_segment(c, sp->next, p)) {
			free_time_segments(c);
			return 1;
		}
		sp->next->prev = sp, sp->next->next = NULL, sp = sp->next;
	}
	while ((p = strchr(p, ',')) != NULL) {
		sp->next = (TimeSegment *) safe_malloc(c, sizeof(TimeSegment));
		sp->next->type = 0;
		if (parse_segment(c, sp->next, ++p)) {
			free_time_segments(c);
			return 1;
		}
		sp->next->prev = sp, sp->next->next = NULL, sp = sp->next;
	}
	prev_end = -1;
	for (sp = c->time_segments; sp != NULL; sp = sp->next) {
		if (sp->type != 0)
			continue;
		if (sp->begin.s <= prev_end) {
			ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL, "Segments must be ordered");
			free_time_segments(c);
			return 1;
		} else if (sp->end.s != -1 && sp->begin.s >= sp->end.s) {
			ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL, "Segment time must be ordered");
			free_time_segments(c);
			return 1;
		}
		prev_end = sp->end.s;
	}
	return 0;
}

static inline int parse_opt_G1(struct timiditycontext_t *c, const char *arg)
{
	/* play just sub-segment(s) (measure) */
	TimeSegment *sp;
	const char *p = arg;
	int prev_end_meas, prev_end_beat;

	if (c->time_segments == NULL) {
		c->time_segments = (TimeSegment *) safe_malloc(c, sizeof(TimeSegment));
		c->time_segments->type = 1;
		if (parse_segment2(c, c->time_segments, p)) {
			free_time_segments(c);
			return 1;
		}
		c->time_segments->prev = c->time_segments->next = NULL, sp = c->time_segments;
	} else {
		for (sp = c->time_segments; sp->next != NULL; sp = sp->next)
			;
		sp->next = (TimeSegment *) safe_malloc(c, sizeof(TimeSegment));
		sp->next->type = 1;
		if (parse_segment2(c, sp->next, p)) {
			free_time_segments(c);
			return 1;
		}
		sp->next->prev = sp, sp->next->next = NULL, sp = sp->next;
	}
	while ((p = strchr(p, ',')) != NULL) {
		sp->next = (TimeSegment *) safe_malloc(c, sizeof(TimeSegment));
		sp->next->type = 1;
		if (parse_segment2(c, sp->next, ++p)) {
			free_time_segments(c);
			return 1;
		}
		sp->next->prev = sp, sp->next->next = NULL, sp = sp->next;
	}
	prev_end_meas = prev_end_beat = -1;
	for (sp = c->time_segments; sp != NULL; sp = sp->next) {
		if (sp->type != 1)
			continue;
		if (sp->begin.m.meas * 16 + sp->begin.m.beat
				<= prev_end_meas * 16 + prev_end_beat) {
			ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL, "Segments must be ordered");
			free_time_segments(c);
			return 1;
		} else if (sp->end.m.meas != -1 && sp->end.m.beat != -1
				&& sp->begin.m.meas * 16 + sp->begin.m.beat
				>= sp->end.m.meas * 16 + sp->end.m.beat) {
			ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL, "Segment time must be ordered");
			free_time_segments(c);
			return 1;
		}
		prev_end_meas = sp->end.m.meas, prev_end_beat = sp->end.m.beat;
	}
	return 0;
}

static int parse_segment(struct timiditycontext_t *c, TimeSegment *seg, const char *p)
{
	const char *q;

	if (*p == '-')
		seg->begin.s = 0;
	else if (parse_time(c, &seg->begin.s, p))
		return 1;
	p = ((q = strchr(p, '-')) == NULL) ? p + strlen(p) : q + 1;
	if (*p == ',' || *p == '\0')
		seg->end.s = -1;
	else if (parse_time(c, &seg->end.s, p))
		return 1;
	return 0;
}

static int parse_segment2(struct timiditycontext_t *c, TimeSegment *seg, const char *p)
{
	const char *q;

	if (*p == '-')
		seg->begin.m.meas = seg->begin.m.beat = 1;
	else if (parse_time2(c, &seg->begin.m, p))
		return 1;
	p = ((q = strchr(p, '-')) == NULL) ? p + strlen(p) : q + 1;
	if (*p == ',' || *p == 'm')
		seg->end.m.meas = seg->end.m.beat = -1;
	else if (parse_time2(c, &seg->end.m, p))
		return 1;
	return 0;
}

static int parse_time(struct timiditycontext_t *c, FLOAT_T *param, const char *p)
{
	const char *p1, *p2, *p3;
	int min;
	FLOAT_T sec;

	p1 = ((p1 = strchr(p, ':')) == NULL) ? p + strlen(p) : p1;
	p2 = ((p2 = strchr(p, '-')) == NULL) ? p + strlen(p) : p2;
	p3 = ((p3 = strchr(p, ',')) == NULL) ? p + strlen(p) : p3;
	if ((p1 < p2 && p2 <= p3) || (p1 < p3 && p3 <= p2)) {
		if (set_value(c, &min, atoi(p), 0, 59, "Segment time (min part)"))
			return 1;
		if (parse_val_float_t(c, &sec, p1 + 1, 0, 59.999,
				"Segment time (sec+frac part)", 3))
			return 1;
		*param = min * 60 + sec;
	} else if (parse_val_float_t(c, param, p, 0, 3599.999, "Segment time", 3))
		return 1;
	return 0;
}

static int parse_time2(struct timiditycontext_t *c, Measure *param, const char *p)
{
	const char *p1, *p2, *p3;

	if (set_value(c, &param->meas, atoi(p), 0, 999, "Segment time (measure)"))
		return 1;
	p1 = ((p1 = strchr(p, '.')) == NULL) ? p + strlen(p) : p1;
	p2 = ((p2 = strchr(p, '-')) == NULL) ? p + strlen(p) : p2;
	p3 = ((p3 = strchr(p, ',')) == NULL) ? p + strlen(p) : p3;
	if ((p1 < p2 && p2 <= p3) || (p1 < p3 && p3 <= p2)) {
		if (set_value(c, &param->beat, atoi(p1 + 1), 1, 15,
				"Segment time (beat)"))
			return 1;
	} else
		param->beat = 1;
	return 0;
}

static inline int parse_opt_g(struct timiditycontext_t *c, const char *arg)
{
#ifdef SUPPORT_SOUNDSPEC
	spectrogram_update_sec = atof(arg);
	if (spectrogram_update_sec <= 0) {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
				"Invalid -g argument: `%s'", arg);
		return 1;
	}
	view_soundspec_flag = 1;
	return 0;
#else
	ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL, "-g option is not supported");
	return 1;
#endif	/* SUPPORT_SOUNDSPEC */
}

static inline int parse_opt_H(struct timiditycontext_t *c, const char *arg)
{
	/* force keysig (number of sharp/flat) */
	int keysig;

	if (set_value(c, &keysig, atoi(arg), -7, 7,
			"Force keysig (number of sHarp(+)/flat(-))"))
		return 1;
	c->opt_force_keysig = keysig;
	return 0;
}

__attribute__((noreturn))
#ifndef __BORLANDC__
static inline int parse_opt_h(struct timiditycontext_t *c, const char *arg)
#else
static int parse_opt_h(struct timiditycontext_t *c, const char *arg)
#endif
{
	static char *help_list[] = {
"TiMidity++ %s (C) 1999-2018 Masanao Izumo <iz@onicos.co.jp>",
"The original version (C) 1995 Tuukka Toivonen <tt@cgs.fi>",
"TiMidity is free software and comes with ABSOLUTELY NO WARRANTY.",
"",
#ifdef __W32__
"Win32 version by Davide Moretti <dave@rimini.com>",
"              and Daisuke Aoki <dai@y7.net>",
"",
#endif /* __W32__ */
"Usage:",
"  %s [options] filename [...]",
"",
#ifndef __W32__		/*does not work in Windows */
"  Use \"-\" as filename to read a MIDI file from stdin",
"",
#endif
"Options:",
"  -A n,m     --volume=n, --drum-power=m",
"               Amplify volume by n percent (may cause clipping),",
"                 and amplify drum power by m percent",
"     (a)     --[no-]volume-compensation",
"               Toggle amplify compensation (disabled by default)",
"  -a         --[no-]anti-alias",
"               Enable the anti-aliasing filter",
"  -B n,m     --buffer-fragments=n,m",
"               Set number of buffer fragments(n), and buffer size(2^m)",
"  -C n       --control-ratio=n",
"               Set ratio of sampling and control frequencies",
"  -c file    --config-file=file",
"               Read extra configuration file",
"  -D n       --drum-channel=n",
"               Play drums on channel n",
#ifdef IA_DYNAMIC
"  -d path    --interface-path=path",
"               Set dynamic interface module directory",
#endif /* IA_DYNAMIC */
"  -E mode    --ext=mode",
"               TiMidity sequencer extensional modes:",
"                 mode = w/W : Enable/Disable Modulation wheel",
"                        p/P : Enable/Disable Portamento",
"                        v/V : Enable/Disable NRPN Vibrato",
"                        s/S : Enable/Disable Channel pressure",
"                        e/E : Enable/Disable Modulation Envelope",
"                        t/T : Enable/Disable Trace Text Meta Event at playing",
"                        o/O : Enable/Disable Overlapped voice",
"                        z/Z : Enable/Disable Temperament control",
"                        m<HH>: Define default Manufacture ID <HH> in two hex",
"                        M<HH>: Define system Manufacture ID <HH> in two hex",
"                        b<n>: Use tone bank <n> as the default",
"                        B<n>: Always use tone bank <n>",
"                        i<n/m>: Use program <n> on channel <m> as the default",
"                        I<n/m>: Always use program <n> on channel <m>",
"                        F<args>: For effect.  See below for effect options",
"                   default: -E "
#ifdef MODULATION_WHEEL_ALLOW
"w"
#else
"W"
#endif /* MODULATION_WHEEL_ALLOW */
#ifdef PORTAMENTO_ALLOW
"p"
#else
"P"
#endif /* PORTAMENTO_ALLOW */
#ifdef NRPN_VIBRATO_ALLOW
"v"
#else
"V"
#endif /* NRPN_VIBRATO_ALLOW */
#ifdef GM_CHANNEL_PRESSURE_ALLOW
"s"
#else
"S"
#endif /* GM_CHANNEL_PRESSURE_ALLOW */
#ifdef MODULATION_ENVELOPE_ALLOW
"e"
#else
"E"
#endif /* MODULATION_ENVELOPE_ALLOW */
#ifdef ALWAYS_TRACE_TEXT_META_EVENT
"t"
#else
"T"
#endif /* ALWAYS_TRACE_TEXT_META_EVENT */
#ifdef OVERLAP_VOICE_ALLOW
"o"
#else
"O"
#endif /* OVERLAP_VOICE_ALLOW */
#ifdef TEMPER_CONTROL_ALLOW
"z"
#else
"Z"
#endif /* TEMPER_CONTROL_ALLOW */
,
#ifdef __W32__
"  -e         --evil",
"               Increase thread priority (evil) - be careful!",
#endif
"  -F         --[no-]fast-panning",
"               Disable/Enable fast panning (toggle on/off, default is on)",
"  -f         --[no-]fast-decay",
"               "
#ifdef FAST_DECAY
"Disable "
#else
"Enable "
#endif
"fast decay mode (toggle)",
"  -G <begin>-<end>[,<begin2>-<end2>,...](m)",
"  --segment=<begin>-<end>[,<begin2>-<end2>,...](m)",
"               Play just sub-segment(s), comma separated segments",
"                 Each segment is dash separated of two time values of:",
"                 <begin>-<end> - defaulted to 0-infinity",
"                 Playing from <begin> to <end>",
"                 Time format: [<minutes>:]<seconds>[.<milliseconds>]",
"                 'm' stands for using measure and beat instead of secs",
"                 Time format: <measure>[.<beat>] (one-origin)",
#ifdef SUPPORT_SOUNDSPEC
"  -g sec     --spectrogram=sec",
"               Open Sound-Spectrogram Window",
#endif /* SUPPORT_SOUNDSPEC */
"  -H n       --force-keysig=n",
"               Force keysig number of sHarp(+)/flat(-) (-7..7)",
"  -h         --help",
"               Display this help message",
"  -i mode    --interface=mode",
"               Select user interface (see below for list)",
#ifdef IA_ALSASEQ
"             --realtime-priority=n (for alsaseq only)",
"               Set the realtime priority (0-100)",
"             --sequencer-ports=n (for alsaseq only)",
"               Set the number of opened sequencer ports (default is 4)",
#endif
#if defined(IA_WINSYN) || defined(IA_PORTMIDISYN) || defined(IA_NPSYN) || defined(IA_W32G_SYN)
"             --rtsyn-latency=sec (for rtsyn only)",
"               Set the realtime latency (sec)",
"                 (default is 0.2 sec, minimum is 0.04 sec)",
#endif
"  -j         --[no-]realtime-load",
"               Realtime load instrument (toggle on/off)",
"  -K n       --adjust-key=n",
"               Adjust key by n half tone (-24..24)",
"  -k msec    --voice-queue=msec",
"               Specify audio queue time limit to reduce voice",
"  -L path    --patch-path=path",
"               Append dir to search path",
"  -M name    --pcm-file=name",
"               Specify PCM filename (*.wav or *.aiff) to be played or:",
"                 \"auto\" : Play *.mid.wav or *.mid.aiff",
"                 \"none\" : Disable this feature (default)",
"  -m msec    --decay-time=msec",
"               Minimum time for a full volume sustained note to decay,",
"                 0 disables",
"  -N n       --interpolation=n",
"               Set the interpolation parameter (depends on -EFresamp option)",
"                 Linear interpolation is used if audio queue < 99%%",
"                 cspline, lagrange:",
"                   Toggle 4-point interpolation (default on)",
"                 newton:",
"                   n'th order Newton polynomial interpolation, n=1-57 odd",
"                 gauss:",
"                   n+1 point Gauss-like interpolation, n=1-34 (default 25)",
"  -O mode    --output-mode=mode",
"               Select output mode and format (see below for list)",
#ifdef AU_FLAC
"             --flac-verify (for Ogg FLAC only)",
"               Verify a correct encoding",
"             --flac-padding=n (for Ogg FLAC only)",
"               Write a PADDING block of length n",
"             --flac-complevel=n (for Ogg FLAC only)",
"               Set compression level n:[0..8]",
#ifdef AU_OGGFLAC
"             --oggflac (for Ogg FLAC only)",
"               Output OggFLAC stream (experimental)",
#endif /* AU_OGGFLAC */
#endif /* AU_FLAC */
#ifdef AU_SPEEX
"             --speex-quality=n (for Ogg Speex only)",
"               Encoding quality n:[0..10]",
"             --speex-vbr (for Ogg Speex only)",
"               Enable variable bit-rate (VBR)",
"             --speex-abr=n (for Ogg Speex only)",
"               Enable average bit-rate (ABR) at rate bps",
"             --speex-vad (for Ogg Speex only)",
"               Enable voice activity detection (VAD)",
"             --speex-dtx (for Ogg Speex only)",
"               Enable file-based discontinuous transmission (DTX)",
"             --speex-complexity=n (for Ogg Speex only)",
"               Set encoding complexity n:[0-10]",
"             --speex-nframes=n (for Ogg Speex only)",
"               Number of frames per Ogg packet n:[0-10]",
#endif
"  -o file    --output-file=file",
"               Output to another file (or device/server) (Use \"-\" for stdout)",
#if defined(AU_PORTAUDIO) || defined(AU_WIN32)
"               Set the output device no. (-1 shows available device no. list)",
#endif
"  -P file    --patch-file=file",
"               Use patch file for all programs",
"  -p n       --polyphony=n",
"               Allow n-voice polyphony.  Optional auto polyphony reduction",
"     (a)     --[no-]polyphony-reduction",
"               Toggle automatic polyphony reduction.  Enabled by default",
"  -Q n[,...] --mute=n[,...]",
"               Ignore channel n (0: ignore all, -n: resume channel n)",
"     (t)     --temper-mute=n[,...]",
"               Quiet temperament type n (0..3: preset, 4..7: user-defined)",
"             --preserve-silence",
"               Do not drop initial silence.  Default: drop initial silence",
"  -q sec/n   --audio-buffer=sec/n",
"               Specify audio buffer in seconds",
"                 sec: Maxmum buffer, n: Filled to start (default is 5.0/100%%)",
"                 (size of 100%% equals device buffer size)",
"  -R msec      Pseudo reveb effect (set every instrument's release to msec)",
"                 if n=0, n is set to 800",
"  -S n       --cache-size=n",
"               Cache size (0 means no cache)",
"  -s freq    --sampling-freq=freq",
"               Set sampling frequency to freq (Hz or kHz)",
"  -T n       --adjust-tempo=n",
"               Adjust tempo to n%%,",
"                 120=play MOD files with an NTSC Amiga's timing",
"  -t code    --output-charset=code",
"               Output text language code:",
"                 code=auto  : Auto conversion by `LANG' environment variable",
"                              (UNIX only)",
"                      ascii : Convert unreadable characters to '.' (0x2e)",
"                      nocnv : No conversion",
"                      1251  : Convert from windows-1251 to koi8-r",
#ifdef JAPANESE
"                      euc   : EUC-japan",
"                      jis   : JIS",
"                      sjis  : shift JIS",
#endif /* JAPANESE */
"  -U         --[no-]unload-instruments",
"               Unload instruments from memory between MIDI files",
"  -V power   --volume-curve=power",
"               Define the velocity/volume/expression curve",
"                 amp = vol^power (auto: 0, linear: 1, ideal: ~1.661, GS: ~2)",
"  -v         --version",
"               Display TiMidity version information",
"  -W mode    --wrd=mode",
"               Select WRD interface (see below for list)",
#ifdef __W32__
"  -w mode    --rcpcv-dll=mode",
"               Windows extensional modes:",
"                 mode=r/R : Enable/Disable rcpcv.dll",
#endif /* __W32__ */
"  -x str     --config-string=str",
"               Read configuration str from command line argument",
"  -Z file    --freq-table=file",
"               Load frequency table (Use \"pure\" for pure intonation)",
"  pure<n>(m) --pure-intonation=n(m)",
"               Initial keysig number <n> of sharp(+)/flat(-) (-7..7)",
"                 'm' stands for minor mode",
"  --module=n",
"               Simulate behavior of specific synthesizer module by n",
"                 n=0       : TiMidity++ Default (default)",
"                   1-15    : GS family",
"                   16-31   : XG family",
"                   32-111  : SoundBlaster and other systhesizer modules",
"                   112-127 : TiMidity++ specification purposes",
		NULL
	};
	void show_ao_device_info(FILE *fp);
	FILE *fp;
	char version[32], *help_args[3];
	int i, j;
	char *h;
	ControlMode *cmp, **cmpp;
#ifdef IA_DYNAMIC
	char mark[128];
#endif
	PlayMode *pmp, **pmpp;
	const WRDTracer *wlp, **wlpp;

	fp = open_pager();
	strcpy(version, (strcmp(timidity_version, "current")) ? "version " : "");
	strcat(version, timidity_version);
	help_args[0] = version;
	help_args[1] = c->program_name;
	help_args[2] = NULL;
	for (i = 0, j = 0; (h = help_list[i]) != NULL; i++) {
		if (strchr(h, '%')) {
			if (*(strchr(h, '%') + 1) != '%')
				fprintf(fp, h, help_args[j++]);
			else
				fprintf(fp, "%s", h);
		} else
			fputs(h, fp);
		fputs(NLS, fp);
	}
	fputs(NLS, fp);
	fputs("Effect options (-EF, --ext=F option):" NLS
"  -EFdelay=d   Disable delay effect (default)" NLS
"  -EFdelay=l   Enable Left delay" NLS
"    [,msec]      `msec' is optional to specify left-right delay time" NLS
"  -EFdelay=r   Enable Right delay" NLS
"    [,msec]      `msec' is optional to specify left-right delay time" NLS
"  -EFdelay=b   Enable rotate Both left and right" NLS
"    [,msec]      `msec' is optional to specify left-right delay time" NLS
"  -EFchorus=d  Disable MIDI chorus effect control" NLS
"  -EFchorus=n  Enable Normal MIDI chorus effect control" NLS
"    [,level]     `level' is optional to specify chorus level [0..127]" NLS
"                 (default)" NLS
"  -EFchorus=s  Surround sound, chorus detuned to a lesser degree" NLS
"    [,level]     `level' is optional to specify chorus level [0..127]" NLS
"  -EFreverb=d  Disable MIDI reverb effect control" NLS
"  -EFreverb=n  Enable Normal MIDI reverb effect control" NLS
"    [,level]     `level' is optional to specify reverb level [1..127]" NLS
"  -EFreverb=g  Global reverb effect" NLS
"    [,level]     `level' is optional to specify reverb level [1..127]" NLS
"  -EFreverb=f  Enable Freeverb MIDI reverb effect control (default)" NLS
"    [,level]     `level' is optional to specify reverb level [1..127]" NLS
"  -EFreverb=G  Global Freeverb effect" NLS
"    [,level]     `level' is optional to specify reverb level [1..127]" NLS
"  -EFvlpf=d    Disable voice LPF" NLS
"  -EFvlpf=c    Enable Chamberlin resonant LPF (12dB/oct) (default)" NLS
"  -EFvlpf=m    Enable Moog resonant lowpass VCF (24dB/oct)" NLS
"  -EFns=n      Enable the n th degree (type) noise shaping filter" NLS
"                 n:[0..4] (for 8-bit linear encoding, default is 4)" NLS
"                 n:[0..4] (for 16-bit linear encoding, default is 4)" NLS, fp);
#ifndef FIXED_RESAMPLATION
#ifdef HAVE_STRINGIZE
#define tim_str_internal(x) #x
#define tim_str(x) tim_str_internal(x)
#else
#define tim_str(x) "x"
#endif
	fputs("  -EFresamp=d  Disable resamplation", fp);
	if (! strcmp(tim_str(DEFAULT_RESAMPLATION), "resample_none"))
		fputs(" (default)", fp);
	fputs(NLS, fp);
	fputs("  -EFresamp=l  Enable Linear resample algorithm", fp);
	if (! strcmp(tim_str(DEFAULT_RESAMPLATION), "resample_linear"))
		fputs(" (default)", fp);
	fputs(NLS, fp);
	fputs("  -EFresamp=c  Enable C-spline resample algorithm", fp);
	if (! strcmp(tim_str(DEFAULT_RESAMPLATION), "resample_cspline"))
		fputs(" (default)", fp);
	fputs(NLS, fp);
	fputs("  -EFresamp=L  Enable Lagrange resample algorithm", fp);
	if (! strcmp(tim_str(DEFAULT_RESAMPLATION), "resample_lagrange"))
		fputs(" (default)", fp);
	fputs(NLS, fp);
	fputs("  -EFresamp=n  Enable Newton resample algorithm", fp);
	if (! strcmp(tim_str(DEFAULT_RESAMPLATION), "resample_newton"))
		fputs(" (default)", fp);
	fputs(NLS, fp);
	fputs("  -EFresamp=g  Enable Gauss-like resample algorithm", fp);
	if (! strcmp(tim_str(DEFAULT_RESAMPLATION), "resample_gauss"))
		fputs(" (default)", fp);
	fputs(NLS
"                 -EFresamp affects the behavior of -N option" NLS, fp);
#endif
	fputs(NLS, fp);
	fputs("Alternative TiMidity sequencer extensional mode long options:" NLS
"  --[no-]mod-wheel" NLS
"  --[no-]portamento" NLS
"  --[no-]vibrato" NLS
"  --[no-]ch-pressure" NLS
"  --[no-]mod-envelope" NLS
"  --[no-]trace-text-meta" NLS
"  --[no-]overlap-voice" NLS
"  --[no-]temper-control" NLS
"  --default-mid=<HH>" NLS
"  --system-mid=<HH>" NLS
"  --default-bank=n" NLS
"  --force-bank=n" NLS
"  --default-program=n/m" NLS
"  --force-program=n/m" NLS
"  --delay=(d|l|r|b)[,msec]" NLS
"  --chorus=(d|n|s)[,level]" NLS
"  --reverb=(d|n|g|f|G)[,level]" NLS
"  --voice-lpf=(d|c|m)" NLS
"  --noise-shaping=n" NLS, fp);
#ifndef FIXED_RESAMPLATION
	fputs("  --resample=(d|l|c|L|n|g)" NLS, fp);
#endif
	fputs(NLS, fp);
	fputs("Available interfaces (-i, --interface option):" NLS, fp);
	for (cmpp = ctl_list; (cmp = *cmpp) != NULL; cmpp++)
		fprintf(fp, "  -i%c          %s" NLS,
				cmp->id_character, cmp->id_name);
#ifdef IA_DYNAMIC
	fprintf(fp, "Supported dynamic load interfaces (%s):" NLS,
			dynamic_lib_root);
	memset(mark, 0, sizeof(mark));
	for (cmpp = ctl_list; (cmp = *cmpp) != NULL; cmpp++)
		mark[(int) cmp->id_character] = 1;
	list_dyna_interface(fp, dynamic_lib_root, mark);
#endif	/* IA_DYNAMIC */
	fputs(NLS, fp);
	fputs("Interface options (append to -i? option):" NLS
"  `v'          more verbose (cumulative)" NLS
"  `q'          quieter (cumulative)" NLS
"  `t'          trace playing" NLS
"  `l'          loop playing (some interface ignore this option)" NLS
"  `r'          randomize file list arguments before playing" NLS
"  `s'          sorting file list arguments before playing" NLS, fp);
#ifdef IA_ALSASEQ
	fputs("  `D'          daemonize TiMidity++ in background "
			"(for alsaseq only)" NLS, fp);
#endif
	fputs(NLS, fp);
	fputs("Alternative interface long options:" NLS
"  --verbose=n" NLS
"  --quiet=n" NLS
"  --[no-]trace" NLS
"  --[no-]loop" NLS
"  --[no-]random" NLS
"  --[no-]sort" NLS, fp);
#ifdef IA_ALSASEQ
	fputs("  --[no-]background" NLS, fp);
#endif
	fputs(NLS, fp);
	fputs("Available output modes (-O, --output-mode option):" NLS, fp);
	for (pmpp = play_mode_list; (pmp = *pmpp) != NULL; pmpp++)
		fprintf(fp, "  -O%c          %s" NLS,
				pmp->id_character, pmp->id_name);
	fputs(NLS, fp);
	fputs("Output format options (append to -O? option):" NLS
"  `S'          stereo" NLS
"  `M'          monophonic" NLS
"  `s'          signed output" NLS
"  `u'          unsigned output" NLS
"  `1'          16-bit sample width" NLS
"  `2'          24-bit sample width" NLS
"  `8'          8-bit sample width" NLS
"  `l'          linear encoding" NLS
"  `U'          U-Law encoding" NLS
"  `A'          A-Law encoding" NLS
"  `x'          byte-swapped output" NLS, fp);
	fputs(NLS, fp);
	fputs("Alternative output format long options:" NLS
"  --output-stereo" NLS
"  --output-mono" NLS
"  --output-signed" NLS
"  --output-unsigned" NLS
"  --output-16bit" NLS
"  --output-24bit" NLS
"  --output-8bit" NLS
"  --output-linear" NLS
"  --output-ulaw" NLS
"  --output-alaw" NLS
"  --[no-]output-swab" NLS, fp);
	fputs(NLS, fp);
	fputs("Available WRD interfaces (-W, --wrd option):" NLS, fp);
	for (wlpp = wrdt_list; (wlp = *wlpp) != NULL; wlpp++)
		fprintf(fp, "  -W%c          %s" NLS, wlp->id, wlp->name);
	fputs(NLS, fp);
	close_pager(fp);
	exit(EXIT_SUCCESS);
}

#ifdef IA_DYNAMIC
static inline void list_dyna_interface(FILE *fp, char *path, char *mark)
{
    URL dir;
    char fname[NAME_MAX];
    int cwd, dummy;
	if ((dir = url_dir_open(path)) == NULL)
		return;
	cwd = open(".", 0);
	if(chdir(path) != 0)
		return;
	while (url_gets(dir, fname, sizeof(fname)) != NULL)
		if (strncmp(fname, "if_", 3) == 0) {
			void* handle = NULL;
			char path[NAME_MAX];
			snprintf(path, NAME_MAX, ".%c%s", PATH_SEP, fname);
			if((handle = dl_load_file(path))) {
				ControlMode *(* loader)(void) = NULL;
				char c;
				for (c = 'A'; c <= 'z'; c++) {
					char buf[20]; /* enough */
					if(mark[(int)c]) continue;
					sprintf(buf, "interface_%c_loader", c);
					if((loader = dl_find_symbol(handle, buf))) {
						fprintf(fp, "  -i%c          %s" NLS, c, loader()->id_name);
						mark[(int)c] = 1;
						break;
					}
				}
				dl_free(handle);
			}
		}
	dummy = fchdir(cwd);
	dummy += close(cwd);
	url_close(dir);
}

static ControlMode *dynamic_interface_module(int id_char)
{
	URL url;
	char fname[BUFSIZ];
	ControlMode *ctl = NULL;
	int cwd, dummy;
	void *handle;
	ControlMode *(* inferface_loader)(void);

	if ((url = url_dir_open(dynamic_lib_root)) == NULL)
		return NULL;
	cwd = open(".", 0);
	if(chdir(dynamic_lib_root) != 0)
		return NULL;
	while (url_gets(url, fname, sizeof(fname)) != NULL) {
		if (strncmp(fname, "if_", 3) == 0) {
			char path[NAME_MAX], buff[20];
			snprintf(path, NAME_MAX-1, ".%c%s", PATH_SEP, fname);
			if((handle = dl_load_file(path)) == NULL)
				continue;
			sprintf(buff, "interface_%c_loader", id_char);
			if((inferface_loader = dl_find_symbol(handle, buff)) == NULL) {
				dl_free(handle);
				continue;
			}
			ctl = inferface_loader();
			if(ctl->id_character == id_char)
				break;
		}
	}
	dummy = fchdir(cwd);
	dummy += close(cwd);
	url_close(url);
	return ctl;
}
#endif	/* IA_DYNAMIC */

static inline int parse_opt_i(struct timiditycontext_t *c, const char *arg)
{
	/* interface mode */
	ControlMode *cmp, **cmpp;
	int found = 0;

	for (cmpp = ctl_list; (cmp = *cmpp) != NULL; cmpp++) {
		if (cmp->id_character == *arg) {
			found = 1;
			ctl = cmp;
#if defined(IA_W32GUI) || defined(IA_W32G_SYN)
			cmp->verbosity = 1;
			cmp->trace_playing = 0;
			cmp->flags = 0;
#endif	/* IA_W32GUI */
			break;
		}
	}
#ifdef IA_DYNAMIC
	if (! found) {
		cmp = dynamic_interface_module(*arg);
		if(cmp) {
			ctl = cmp;
			found = 1;
		}
	}
#endif	/* IA_DYNAMIC */
	if (! found) {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
				"Interface `%c' is not compiled in.", *arg);
		return 1;
	}
	while (*(++arg))
		switch (*arg) {
		case 'v':
			cmp->verbosity++;
			break;
		case 'q':
			cmp->verbosity--;
			break;
		case 't':	/* toggle */
			cmp->trace_playing = (cmp->trace_playing) ? 0 : 1;
			break;
		case 'l':
			cmp->flags ^= CTLF_LIST_LOOP;
			break;
		case 'r':
			cmp->flags ^= CTLF_LIST_RANDOM;
			break;
		case 's':
			cmp->flags ^= CTLF_LIST_SORT;
			break;
		case 'a':
			cmp->flags ^= CTLF_AUTOSTART;
			break;
		case 'x':
			cmp->flags ^= CTLF_AUTOEXIT;
			break;
		case 'd':
			cmp->flags ^= CTLF_DRAG_START;
			break;
		case 'u':
			cmp->flags ^= CTLF_AUTOUNIQ;
			break;
		case 'R':
			cmp->flags ^= CTLF_AUTOREFINE;
			break;
		case 'C':
			cmp->flags ^= CTLF_NOT_CONTINUE;
			break;
#ifdef IA_ALSASEQ
		case 'D':
			cmp->flags ^= CTLF_DAEMONIZE;
			break;
#endif
		default:
			ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
					"Unknown interface option `%c'", *arg);
			return 1;
		}
	return 0;
}

static inline int parse_opt_verbose(const char *arg)
{
	/* --verbose */
	ctl->verbosity += (arg) ? atoi(arg) : 1;
	return 0;
}

static inline int parse_opt_quiet(const char *arg)
{
	/* --quiet */
	ctl->verbosity -= (arg) ? atoi(arg) : 1;
	return 0;
}

static inline int parse_opt_trace(const char *arg)
{
	/* --[no-]trace */
	ctl->trace_playing = y_or_n_p(arg);
	return 0;
}

static inline int parse_opt_loop(const char *arg)
{
	/* --[no-]loop */
	return set_flag(&(ctl->flags), CTLF_LIST_LOOP, arg);
}

static inline int parse_opt_random(const char *arg)
{
	/* --[no-]random */
	return set_flag(&(ctl->flags), CTLF_LIST_RANDOM, arg);
}

static inline int parse_opt_sort(const char *arg)
{
	/* --[no-]sort */
	return set_flag(&(ctl->flags), CTLF_LIST_SORT, arg);
}

#ifdef IA_ALSASEQ
static inline int parse_opt_background(const char *arg)
{
	/* --[no-]background */
	return set_flag(&(ctl->flags), CTLF_DAEMONIZE, arg);
}

static inline int parse_opt_rt_prio(struct timiditycontext_t *c, const char *arg)
{
	/* --realtime-priority */
	if (set_value(c, &opt_realtime_priority, atoi(arg), 0, 100,
			"Realtime priority"))
		return 1;
	return 0;
}

static inline int parse_opt_seq_ports(struct timiditycontext_t *c, const char *arg)
{
	/* --sequencer-ports */
	if (set_value(c, &opt_sequencer_ports, atoi(arg), 1, 16,
			"Number of sequencer ports"))
		return 1;
	return 0;
}
#endif

#if defined(IA_W32GUI)
static inline int parse_opt_rtsyn_latency(const char *arg)
{
	return 0;
}
#endif
#if defined(IA_WINSYN) || defined(IA_PORTMIDISYN) ||defined(IA_NPSYN) || defined(IA_W32G_SYN)
static inline int parse_opt_rtsyn_latency(const char *arg)
{
	double latency;

	if (sscanf(arg, "%lf", &latency) == EOF)
		latency = RTSYN_LATENCY;
	rtsyn_set_latency(latency);
	return 0;
}
#endif

static inline int parse_opt_j(struct timiditycontext_t *c, const char *arg)
{
	c->opt_realtime_playing = y_or_n_p(arg);
	return 0;
}

static inline int parse_opt_K(struct timiditycontext_t *c, const char *arg)
{
	/* key adjust */
	if (set_value(c, &c->key_adjust, atoi(arg), -24, 24, "Key adjust"))
		return 1;
	return 0;
}

static inline int parse_opt_k(struct timiditycontext_t *c, const char *arg)
{
	c->reduce_voice_threshold = atoi(arg);
	return 0;
}

static inline int parse_opt_L(struct timiditycontext_t *c, char *arg)
{
	add_to_pathlist(c, arg);
	c->try_config_again = 1;
	return 0;
}

static inline int parse_opt_M(struct timiditycontext_t *c, const char *arg)
{
	if (c->pcm_alternate_file)
		free(c->pcm_alternate_file);
	c->pcm_alternate_file = safe_strdup(c, arg);
	return 0;
}

static inline int parse_opt_m(struct timiditycontext_t *c, const char *arg)
{
	c->min_sustain_time = atoi(arg);
	if (c->min_sustain_time < 0)
		c->min_sustain_time = 0;
	return 0;
}

static inline int parse_opt_N(struct timiditycontext_t *c, const char *arg)
{
	int val;

	switch (get_current_resampler(c)) {
	case RESAMPLE_CSPLINE:
	case RESAMPLE_LAGRANGE:
		c->no_4point_interpolation = y_or_n_p(arg);
		break;
	case RESAMPLE_NEWTON:
	case RESAMPLE_GAUSS:
		if (! (val = atoi(arg)))
			/* set to linear interpolation for compatibility */
			set_current_resampler(c, RESAMPLE_LINEAR);
		else if (set_resampler_parm(c, val)) {
			ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL, "Invalid -N value");
			return 1;
		}
		break;
	}
	return 0;
}

static inline int parse_opt_O(struct timiditycontext_t *c, const char *arg)
{
	/* output mode */
	PlayMode *pmp, **pmpp;
	int found = 0;

	for (pmpp = play_mode_list; (pmp = *pmpp) != NULL; pmpp++)
		if (pmp->id_character == *arg) {
			found = 1;
			play_mode = pmp;
			break;
		}
	if (! found) {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
				"Playmode `%c' is not compiled in.", *arg);
		return 1;
	}
	while (*(++arg))
		switch (*arg) {
		case 'S':	/* stereo */
			pmp->encoding &= ~PE_MONO;
			break;
		case 'M':
			pmp->encoding |= PE_MONO;
			break;
		case 's':
			pmp->encoding |= PE_SIGNED;
			pmp->encoding &= ~(PE_ULAW | PE_ALAW);
			break;
		case 'u':
			pmp->encoding &= ~PE_SIGNED;
			pmp->encoding &= ~(PE_ULAW | PE_ALAW);
			break;
		case '1':	/* 1 for 16-bit */
			pmp->encoding |= PE_16BIT;
			pmp->encoding &= ~(PE_24BIT | PE_ULAW | PE_ALAW);
			break;
		case '2':	/* 2 for 24-bit */
			pmp->encoding |= PE_24BIT;
			pmp->encoding &= ~(PE_16BIT | PE_ULAW | PE_ALAW);
			break;
		case '8':
			pmp->encoding &= ~(PE_16BIT | PE_24BIT);
			break;
		case 'l':	/* linear */
			pmp->encoding &= ~(PE_ULAW | PE_ALAW);
			break;
		case 'U':	/* uLaw */
			pmp->encoding |= PE_ULAW;
			pmp->encoding &= ~(PE_SIGNED
					| PE_16BIT | PE_24BIT | PE_ALAW | PE_BYTESWAP);
			break;
		case 'A':	/* aLaw */
			pmp->encoding |= PE_ALAW;
			pmp->encoding &= ~(PE_SIGNED
					| PE_16BIT | PE_24BIT | PE_ULAW | PE_BYTESWAP);
			break;
		case 'x':
			pmp->encoding ^= PE_BYTESWAP;	/* toggle */
			pmp->encoding &= ~(PE_ULAW | PE_ALAW);
			break;
		default:
			ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
					"Unknown format modifier `%c'", *arg);
			return 1;
		}
	return 0;
}

static inline int parse_opt_output_stereo(struct timiditycontext_t *c, const char *arg)
{
	/* --output-stereo, --output-mono */
	if (y_or_n_p(arg))
		/* I first thought --mono should be the syntax sugar to
		 * --stereo=no, but the source said stereo should be !PE_MONO,
		 * not mono should be !PE_STEREO.  Perhaps I took a wrong
		 * choice? -- mput
		 */
		play_mode->encoding &= ~PE_MONO;
	else
		play_mode->encoding |= PE_MONO;
	return 0;
}

static inline int parse_opt_output_signed(struct timiditycontext_t *c, const char *arg)
{
	/* --output-singed, --output-unsigned */
	if (set_flag(&(play_mode->encoding), PE_SIGNED, arg))
		return 1;
	play_mode->encoding &= ~(PE_ULAW | PE_ALAW);
	return 0;
}

static inline int parse_opt_output_bitwidth(struct timiditycontext_t *c, const char *arg)
{
	/* --output-16bit, --output-24bit, --output-8bit */
	switch (*arg) {
	case '1':	/* 16bit */
		play_mode->encoding |= PE_16BIT;
		play_mode->encoding &= ~(PE_24BIT | PE_ULAW | PE_ALAW);
		return 0;
	case '2':	/* 24bit */
		play_mode->encoding |= PE_24BIT;
		play_mode->encoding &= ~(PE_16BIT | PE_ULAW | PE_ALAW);
		return 0;
	case '8':	/* 8bit */
		play_mode->encoding &= ~(PE_16BIT | PE_24BIT);
		return 0;
	default:
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL, "Invalid output bitwidth %s", arg);
		return 1;
	}
}

static inline int parse_opt_output_format(struct timiditycontext_t *c, const char *arg)
{
	/* --output-linear, --output-ulaw, --output-alaw */
	switch (*arg) {
	case 'l':	/* linear */
		play_mode->encoding &= ~(PE_ULAW | PE_ALAW);
		return 0;
	case 'u':	/* uLaw */
		play_mode->encoding |= PE_ULAW;
		play_mode->encoding &=
				~(PE_SIGNED | PE_16BIT | PE_24BIT | PE_ALAW | PE_BYTESWAP);
		return 0;
	case 'a':	/* aLaw */
		play_mode->encoding |= PE_ALAW;
		play_mode->encoding &=
				~(PE_SIGNED | PE_16BIT | PE_24BIT | PE_ULAW | PE_BYTESWAP);
		return 0;
	default:
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL, "Invalid output format %s", arg);
		return 1;
	}
}

static inline int parse_opt_output_swab(struct timiditycontext_t *c, const char *arg)
{
	/* --[no-]output-swab */
	if (set_flag(&(play_mode->encoding), PE_BYTESWAP, arg))
		return 1;
	play_mode->encoding &= ~(PE_ULAW | PE_ALAW);
	return 0;
}

#ifdef AU_FLAC
static inline int parse_opt_flac_verify(const char *arg)
{
	flac_set_option_verify(1);
	return 0;
}

static inline int parse_opt_flac_padding(const char *arg)
{
	flac_set_option_padding(atoi(arg));
	return 0;
}

static inline int parse_opt_flac_complevel(const char *arg)
{
	flac_set_compression_level(atoi(arg));
	return 0;
}

#ifdef AU_OGGFLAC
extern void flac_set_option_oggflac(int);

static inline int parse_opt_flac_oggflac(const char *arg)
{
	flac_set_option_oggflac(1);
	return 0;
}
#endif /* AU_OGGFLAC */
#endif /* AU_FLAC */

#ifdef AU_SPEEX

static inline int parse_opt_speex_quality(const char *arg)
{
	speex_set_option_quality(atoi(arg));
	return 0;
}

static inline int parse_opt_speex_vbr(const char *arg)
{
	speex_set_option_vbr(1);
	return 0;
}

static inline int parse_opt_speex_abr(const char *arg)
{
	speex_set_option_abr(atoi(arg));
	return 0;
}

static inline int parse_opt_speex_vad(const char *arg)
{
	speex_set_option_vad(1);
	return 0;
}

static inline int parse_opt_speex_dtx(const char *arg)
{
	speex_set_option_dtx(1);
	return 0;
}

static inline int parse_opt_speex_complexity(const char *arg)
{
	speex_set_option_complexity(atoi(arg));
	return 0;
}

static inline int parse_opt_speex_nframes(const char *arg)
{
	speex_set_option_nframes(atoi(arg));
	return 0;
}
#endif /* AU_SPEEX */

static inline int parse_opt_o(struct timiditycontext_t *c, char *arg)
{
	if (c->opt_output_name)
		free(c->opt_output_name);
	c->opt_output_name = safe_strdup(c, url_expand_home_dir(c, arg));
	return 0;
}

static inline int parse_opt_P(struct timiditycontext_t *c, const char *arg)
{
	/* set overriding instrument */
	strncpy(c->def_instr_name, arg, sizeof(c->def_instr_name) - 1);
	c->def_instr_name[sizeof(c->def_instr_name) - 1] = '\0';
	return 0;
}

static inline int parse_opt_p(struct timiditycontext_t *c, const char *arg)
{
	if (set_value(c, &c->voices, atoi(arg), 1,
			MAX_SAFE_MALLOC_SIZE / sizeof(Voice), "Polyphony"))
		return 1;
	c->max_voices = c->voices;
	return 0;
}

static inline int parse_opt_p1(struct timiditycontext_t *c, const char *arg)
{
	/* --[no-]polyphony-reduction */
	c->auto_reduce_polyphony = y_or_n_p(arg);
	return 0;
}

static inline int parse_opt_Q(struct timiditycontext_t *c, const char *arg)
{
	const char *p = arg;

	if (strchr(arg, 't'))
		/* backward compatibility */
		return parse_opt_Q1(c, arg);
	if (set_channel_flag(c, &c->quietchannels, atoi(arg), "Quiet channel"))
		return 1;
	while ((p = strchr(p, ',')) != NULL)
		if (set_channel_flag(c, &c->quietchannels, atoi(++p), "Quiet channel"))
			return 1;
	return 0;
}

static inline int parse_opt_Q1(struct timiditycontext_t *c, const char *arg)
{
	/* --temper-mute */
	int prog;
	const char *p = arg;

	if (set_value(c, &prog, atoi(arg), 0, 7, "Temperament program number"))
		return 1;
	c->temper_type_mute |= 1 << prog;
	while ((p = strchr(p, ',')) != NULL) {
		if (set_value(c, &prog, atoi(++p), 0, 7, "Temperament program number"))
			return 1;
		c->temper_type_mute |= 1 << prog;
	}
	return 0;
}

static inline int parse_opt_preserve_silence(struct timiditycontext_t *c, const char *arg)
{
	c->opt_preserve_silence = 1;
	return 0;
}

static inline int parse_opt_q(struct timiditycontext_t *c, const char *arg)
{
	char *max_buff = safe_strdup(c, arg);
	char *fill_buff = strchr(max_buff, '/');

	if (fill_buff != max_buff) {
		if (c->opt_aq_max_buff)
			free(c->opt_aq_max_buff);
		c->opt_aq_max_buff = max_buff;
	}
	if (fill_buff) {
		*fill_buff = '\0';
		if (c->opt_aq_fill_buff)
			free(c->opt_aq_fill_buff);
		c->opt_aq_fill_buff = ++fill_buff;
		c->opt_aq_fill_buff_free_not_needed = 1;
	}
	return 0;
}

static inline int parse_opt_R(struct timiditycontext_t *c, const char *arg)
{
	/* I think pseudo reverb can now be retired... Computers are
	 * enough fast to do a full reverb, don't they?
	 */
	if (atoi(arg) == -1)	/* reset */
		c->modify_release = 0;
	else {
		if (set_val_i32(c, &c->modify_release, atoi(arg), 0, MAX_MREL,
				"Modify Release"))
			return 1;
		if (c->modify_release == 0)
			c->modify_release = DEFAULT_MREL;
	}
	return 0;
}

static inline int parse_opt_S(struct timiditycontext_t *c, const char *arg)
{
	int suffix = arg[strlen(arg) - 1];
	int32 figure;

	switch (suffix) {
	case 'M':
	case 'm':
		figure = 1 << 20;
		break;
	case 'K':
	case 'k':
		figure = 1 << 10;
		break;
	default:
		figure = 1;
		break;
	}
	c->allocate_cache_size = atof(arg) * figure;
	return 0;
}

static inline int parse_opt_s(struct timiditycontext_t *c, const char *arg)
{
	/* sampling rate */
	int32 freq;

	if ((freq = atoi(arg)) < 100)
		freq = atof(arg) * 1000 + 0.5;
	return set_val_i32(c, &c->opt_output_rate, freq,
			MIN_OUTPUT_RATE, MAX_OUTPUT_RATE, "Resampling frequency");
}

static inline int parse_opt_T(struct timiditycontext_t *c, const char *arg)
{
	/* tempo adjust */
	int adjust;

	if (set_value(c, &adjust, atoi(arg), 10, 400, "Tempo adjust"))
		return 1;
	c->tempo_adjust = 100.0 / adjust;
	return 0;
}

static inline int parse_opt_t(struct timiditycontext_t *c, const char *arg)
{
	if (c->output_text_code)
		free(c->output_text_code);
	c->output_text_code = safe_strdup(c, arg);
	return 0;
}

static inline int parse_opt_U(struct timiditycontext_t *c, const char *arg)
{
	c->free_instruments_afterwards = y_or_n_p(arg);
	return 0;
}

static inline int parse_opt_volume_curve(struct timiditycontext_t *c, char *arg)
{
	if (atof(arg) < 0) {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
				"Volume curve power must be >= 0", *arg);
		return 1;
	}
	if (atof(arg) != 0) {
		init_user_vol_table(c, atof(arg));
		c->opt_user_volume_curve = 1;
	}
	return 0;
}

__attribute__((noreturn))
static inline int parse_opt_v(const char *arg)
{
	const char *version_list[] = {
#if defined(__BORLANDC__) || defined(__MRC__) || defined(__WATCOMC__) ||  defined(__DMC__)
		"TiMidity++ ",
				"",
				NULL, NLS,
		NLS,
#else
		"TiMidity++ ",
				(strcmp(timidity_version, "current")) ? "version " : "",
				timidity_version, NLS,
		NLS,
#endif
		"Copyright (C) 1999-2018 Masanao Izumo <iz@onicos.co.jp>", NLS,
		"Copyright (C) 1995 Tuukka Toivonen <tt@cgs.fi>", NLS,
		NLS,
#ifdef __W32__
		"Win32 version by Davide Moretti <dmoretti@iper.net>", NLS,
		"              and Daisuke Aoki <dai@y7.net>", NLS,
		NLS,
#endif	/* __W32__ */
		"This program is distributed in the hope that it will be useful,", NLS,
		"but WITHOUT ANY WARRANTY; without even the implied warranty of", NLS,
		"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the", NLS,
		"GNU General Public License for more details.", NLS,
	};
	FILE *fp = open_pager();
	int i;

#if defined(__BORLANDC__) || defined(__MRC__)
	if (strcmp(timidity_version, "current"))
		version_list[1] = "version ";
	version_list[2] = timidity_version;
#endif
	for (i = 0; i < sizeof(version_list) / sizeof(char *); i++)
		fputs(version_list[i], fp);
	close_pager(fp);
	exit(EXIT_SUCCESS);
}

static inline int parse_opt_W(struct timiditycontext_t *c, char *arg)
{
	const WRDTracer *wlp, **wlpp;

	if (*arg == 'R') {	/* for WRD reader options */
		put_string_table(c, &c->wrd_read_opts, arg + 1, strlen(arg + 1));
		return 0;
	}
	for (wlpp = wrdt_list; (wlp = *wlpp) != NULL; wlpp++)
		if (wlp->id == *arg) {
			wrdt = wlp;
			if (c->wrdt_open_opts)
				free(c->wrdt_open_opts);
			c->wrdt_open_opts = safe_strdup(c, arg + 1);
			return 0;
		}
	ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			"WRD Tracer `%c' is not compiled in.", *arg);
	return 1;
}

#ifdef __W32__
static inline int parse_opt_w(struct timiditycontext_t *c, const char *arg)
{
	switch (*arg) {
#ifdef SMFCONV
	case 'r':
		opt_rcpcv_dll = 1;
		return 0:
	case 'R':
		opt_rcpcv_dll = 0;
		return 0;
#else
	case 'r':
	case 'R':
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
				"-w%c option is not supported", *arg);
		return 1;
#endif	/* SMFCONV */
	default:
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL, "-w: Illegal mode `%c'", *arg);
		return 1;
	}
}
#endif	/* __W32__ */

static inline int parse_opt_x(struct timiditycontext_t *c, char *arg)
{
	StringTableNode *st;

	if ((st = put_string_table(c, &c->opt_config_string,
			arg, strlen(arg))) != NULL)
		expand_escape_string(st->string);
	return 0;
}

static inline void expand_escape_string(char *s)
{
	char *t = s;

	if (s == NULL)
		return;
	for (t = s; *s; s++)
		if (*s == '\\') {
			switch (*++s) {
			case 'a':
				*t++ = '\a';
				break;
			case 'b':
				*t++ = '\b';
				break;
			case 't':
				*t++ = '\t';
				break;
			case 'n':
				*t++ = '\n';
				break;
			case 'f':
				*t++ = '\f';
				break;
			case 'v':
				*t++ = '\v';
				break;
			case 'r':
				*t++ = '\r';
				break;
			case '\\':
				*t++ = '\\';
				break;
			default:
				if (! (*t++ = *s))
					return;
				break;
			}
		} else
			*t++ = *s;
	*t = *s;
}

static inline int parse_opt_Z(struct timiditycontext_t *c, char *arg)
{
	/* load frequency table */
	return load_table(c, arg);
}

static inline int parse_opt_Z1(struct timiditycontext_t *c, const char *arg)
{
	/* --pure-intonation */
	int keysig;

	c->opt_pure_intonation = 1;
	if (*arg) {
		if (set_value(c, &keysig, atoi(arg), -7, 7,
				"Initial keysig (number of #(+)/b(-)[m(minor)])"))
			return 1;
		c->opt_init_keysig = keysig;
		if (strchr(arg, 'm'))
			c->opt_init_keysig += 16;
	}
	return 0;
}

static inline int parse_opt_default_module(struct timiditycontext_t *c, const char *arg)
{
	c->opt_default_module = atoi(arg);
	if (c->opt_default_module < 0)
		c->opt_default_module = 0;
	return 0;
}

__attribute__((noreturn))
static inline int parse_opt_fail(struct timiditycontext_t *c, const char *arg)
{
	/* getopt_long failed to recognize any options */
	ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			"Could not understand option : try --help");
	exit(EXIT_FAILURE);
}

static inline int set_value(struct timiditycontext_t *c, int *param, int i, int low, int high, char *name)
{
	int32 val;

	if (set_val_i32(c, &val, i, low, high, name))
		return 1;
	*param = val;
	return 0;
}

static inline int set_val_i32(struct timiditycontext_t *c, int32 *param,
		int32 i, int32 low, int32 high, char *name)
{
	if (i < low || i > high) {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
				"%s must be between %d and %d", name, low, high);
		return 1;
	}
	*param = i;
	return 0;
}

static int parse_val_float_t(struct timiditycontext_t *c, FLOAT_T *param,
		const char *arg, FLOAT_T low, FLOAT_T high, const char *name, int f)
{
	FLOAT_T value;
	char *errp;

	value = strtod(arg, &errp);
	if (arg == errp) {
		/* only when nothing was parsed */
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL, "Invalid %s", name);
		return 1;
	}
	return set_val_float_t(c, param, value, low, high, name, f);
}

static inline int set_val_float_t(struct timiditycontext_t *c, FLOAT_T *param,
		FLOAT_T i, FLOAT_T low, FLOAT_T high, const char *name, int f)
{
	if (i < low || i > high) {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
				"%s must be between %.*f and %.*f", name, f, low, f, high);
		return 1;
	}
	*param = i;
	return 0;
}

static inline int set_channel_flag(struct timiditycontext_t *c, ChannelBitMask *flags, int32 i, char *name)
{
	if (i == 0) {
		FILL_CHANNELMASK(*flags);
		return 0;
	} else if (abs(i) > MAX_CHANNELS) {
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
				"%s must be between (-)1 and (-)%d, or 0",
						name, MAX_CHANNELS);
		return 1;
	}
	if (i > 0)
		SET_CHANNELMASK(*flags, i - 1);
	else
		UNSET_CHANNELMASK(*flags, -i - 1);
	return 0;
}

static inline int y_or_n_p(const char *arg)
{
	if (arg) {
		switch (arg[0]) {
		case 'y':
		case 'Y':
		case 't':
		case 'T':
			return 1;
		case 'n':
		case 'N':
		case 'f':
		case 'F':
		default:
			return 0;
		}
	} else
		return 1;
}

static inline int set_flag(int32 *fields, int32 bitmask, const char *arg)
{
	if (y_or_n_p(arg))
		*fields |= bitmask;
	else
		*fields &= ~bitmask;
	return 0;
}

static inline FILE *open_pager(void)
{
#if ! defined(__MACOS__) && defined(HAVE_POPEN) && defined(HAVE_ISATTY) \
		&& ! defined(IA_W32GUI) && ! defined(IA_W32G_SYN)
	char *pager;

	if (isatty(1) && (pager = getenv("PAGER")) != NULL)
		return popen(pager, "w");
#endif
	return stdout;
}

static inline void close_pager(FILE *fp)
{
#if ! defined(__MACOS__) && defined(HAVE_POPEN) && defined(HAVE_ISATTY) \
		&& ! defined(IA_W32GUI) && ! defined(IA_W32G_SYN)
	if (fp != stdout)
		pclose(fp);
#endif
}

#if !defined(ANOTHER_MAIN) && defined(__W32__)
static void interesting_message(void)
{
	printf(
"TiMidity++ %s%s -- MIDI to WAVE converter and player" NLS
"Copyright (C) 1999-2018 Masanao Izumo <iz@onicos.co.jp>" NLS
"Copyright (C) 1995 Tuukka Toivonen <tt@cgs.fi>" NLS
			NLS
#ifdef __W32__
"Win32 version by Davide Moretti <dmoretti@iper.net>" NLS
"              and Daisuke Aoki <dai@y7.net>" NLS
			NLS
#endif /* __W32__ */
"This program is free software; you can redistribute it and/or modify" NLS
"it under the terms of the GNU General Public License as published by" NLS
"the Free Software Foundation; either version 2 of the License, or" NLS
"(at your option) any later version." NLS
			NLS
"This program is distributed in the hope that it will be useful," NLS
"but WITHOUT ANY WARRANTY; without even the implied warranty of" NLS
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the" NLS
"GNU General Public License for more details." NLS
			NLS
"You should have received a copy of the GNU General Public License" NLS
"along with this program; if not, write to the Free Software" NLS
"Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA" NLS
			NLS, (strcmp(timidity_version, "current")) ? "version " : "",
			timidity_version);
}
#endif

/* -------- functions for getopt_long ends here --------- */

#ifdef HAVE_SIGNAL
static void sigterm_exit(int sig)
{
    char s[4];
#if defined(__MINGW32__) && !defined(HAVE_SSIZE_T)
    int dummy;
#else
    ssize_t dummy;
#endif

    /* NOTE: Here, fprintf is dangerous because it is not re-enterance
     * function.  It is possible coredump if the signal is called in printf's.
     */

    dummy = write(2, "Terminated sig=0x", 17);
    s[0] = "0123456789abcdef"[(sig >> 4) & 0xf];
    s[1] = "0123456789abcdef"[sig & 0xf];
    s[2] = '\n';
    dummy += write(2, s, 3);

    safe_exit(1);
}
#endif /* HAVE_SIGNAL */

static void timidity_arc_error_handler(struct timiditycontext_t *c, char *error_message)
{
    if(c->open_file_noise_mode)
	ctl->cmsg(c, CMSG_WARNING, VERB_NORMAL, "%s", error_message);
}

static PlayMode null_play_mode = {
    0,                          /* rate */
    0,                          /* encoding */
    0,                          /* flag */
    -1,                         /* fd */
    {0,0,0,0,0},                /* extra_param */
    "Null output device",       /* id_name */
    '\0',                       /* id_character */
    NULL,                       /* open_output */
    NULL,                       /* close_output */
    NULL,                       /* output_data */
    NULL,                       /* acntl */
    NULL                        /* detect */
};

#define is_not_first c->timidity_start_initialize_initialized
MAIN_INTERFACE void timidity_start_initialize(struct timiditycontext_t *c)
{
    int i;
    static const int drums[] = DEFAULT_DRUMCHANNELS;
#if defined(__FreeBSD__) && !defined(__alpha__)
    fp_except_t fpexp;
#elif defined(__NetBSD__) || defined(__OpenBSD__)
    fp_except fpexp;
#endif

#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
    fpexp = fpgetmask();
    fpsetmask(fpexp & ~(FP_X_INV|FP_X_DZ));
#endif

    if(!c->output_text_code)
	c->output_text_code = safe_strdup(c, OUTPUT_TEXT_CODE);
    if(!c->opt_aq_max_buff)
	c->opt_aq_max_buff = safe_strdup(c, "5.0");
    if(!c->opt_aq_fill_buff)
	c->opt_aq_fill_buff = safe_strdup(c, "100%");

    /* Check the byte order */
    i = 1;
#ifdef LITTLE_ENDIAN
    if(*(char *)&i != 1)
#else
    if(*(char *)&i == 1)
#endif
    {
	fprintf(stderr, "Byte order is miss configured.\n");
	exit(1);
    }

    for(i = 0; i < MAX_CHANNELS; i++)
    {
	memset(&(c->channel[i]), 0, sizeof(Channel));
    }

    CLEAR_CHANNELMASK(c->quietchannels);
    CLEAR_CHANNELMASK(c->default_drumchannels);

    for(i = 0; drums[i] > 0; i++)
	SET_CHANNELMASK(c->default_drumchannels, drums[i] - 1);
#if MAX_CHANNELS > 16
    for(i = 16; i < MAX_CHANNELS; i++)
	if(IS_SET_CHANNELMASK(c->default_drumchannels, i & 0xF))
	    SET_CHANNELMASK(c->default_drumchannels, i);
#endif

    if(c->program_name == NULL)
	c->program_name = "TiMidity";
    c->uudecode_unquote_html = 1;
    for(i = 0; i < MAX_CHANNELS; i++)
    {
	c->default_program[i] = DEFAULT_PROGRAM;
	memset(c->channel[i].drums, 0, sizeof(c->channel[i].drums));
    }
    c->arc_error_handler = timidity_arc_error_handler;

    if(play_mode == NULL) play_mode = &null_play_mode;

    if(!is_not_first) /* initialize once time */
    {
	c->got_a_configuration = 0;

#ifdef SUPPORT_SOCKET
	init_mail_addr(c);
	if(url_user_agent == NULL)
	{
	    url_user_agent =
		(char *)safe_malloc(c, 10 + strlen(timidity_version));
	    strcpy(url_user_agent, "TiMidity-");
	    strcat(url_user_agent, timidity_version);
	}
#endif /* SUPPORT_SOCKET */

	for(i = 0; url_module_list[i]; i++)
	    url_add_module(c, url_module_list[i]);
	init_string_table(&c->opt_config_string);
	init_freq_table(c);
	init_freq_table_tuning(c);
	init_freq_table_pytha(c);
	init_freq_table_meantone(c);
	init_freq_table_pureint(c);
	init_freq_table_user(c);
	init_bend_fine(c);
	init_bend_coarse(c);
	init_tables(c);
	init_gm2_pan_table(c);
	init_attack_vol_table(c);
	init_sb_vol_table(c);
	init_modenv_vol_table(c);
	init_def_vol_table(c);
	init_gs_vol_table(c);
	init_perceived_vol_table(c);
	init_gm2_vol_table(c);
#ifdef SUPPORT_SOCKET
	url_news_connection_cache(c, URL_NEWS_CONN_CACHE);
#endif /* SUPPORT_SOCKET */
	for(i = 0; i < NSPECIAL_PATCH; i++)
	    c->special_patch[i] = NULL;
	init_midi_trace(c);
	int_rand(-1);	/* initialize random seed */
	int_rand(42);	/* the 1st number generated is not very random */
	ML_RegisterAllLoaders ();
    }

    is_not_first = 1;
}

MAIN_INTERFACE int timidity_pre_load_configuration(struct timiditycontext_t *c)
{
#if defined(__W32__)
    /* Windows */
    int check;
    int len = 8192;

#if defined ( IA_W32GUI ) || defined ( IA_W32G_SYN )
    char local[1024];
    if(!ConfigFile[0]) {
      GetWindowsDirectory(ConfigFile, 1023 - 13);
      strcat(ConfigFile, "\\TIMIDITY.CFG");
    }
    strncpy(local, ConfigFile, sizeof(local) - 1);
    if((check = open(local, 0)) >= 0)
    {
	close(check);
	if(!read_config_file(c, local, 0, 0)) {
	    c->got_a_configuration = 1;
		return 0;
	}
    }
#endif

    /* First, try read configuration file which is in the
     * TiMidity directory.
     */
    while (1)
    {
	uint16_t *wpath = calloc (len, 2);
	if (!wpath)
	    break; /* calloc() failed, give up */
	if(GetModuleFileNameW(NULL, wpath, len))
	{
	    char *path, *strp;
	    if (wpath[len-2])
	    { /* buffer probably not big enough, since we filled it up until the termination marker (Windows XP will even fill that character) */
		len += 8192;
		free (wpath);
		continue;
	    }
	    path = c->utf16_to_utf8 (c, wpath + (wcsncmp (wpath, L"\\\\?\\", 4) ? 0 : 4)); /* skip \\?\ if that is present */
	    if (!path)
	    { /* utf16_to_utf8 failed, give up */
		free (wpath);
		break;
	    }
	    if((strp = strrchr(path, '\\')))
	    { /* the very last \ has been located */
		char *path2;
		*(++strp)='\0';
		path2 = malloc (strlen (path) + 12 + 1);
		if (path2)
		{
		    sprintf (path2, "%sTIMIDITY.CFG", path);
		    if((check = open(path2, 0)) >= 0)
		    {
			close(check);
			if(!read_config_file(c, path2, 0, 0))
			{
			    c->got_a_configuration = 1;
			    free (path2);
			    free (path);
			    free (wpath);
			    return 0;
			}
		    }
		    free (path2);
		}
	    }
	    free (path);
	}
	free (wpath);
    }

#if !defined ( IA_W32GUI ) && !defined ( IA_W32G_SYN )
    /* Next, try read system configuration file.
     * Default is C:\WINDOWS\TIMIDITY.CFG
     */
    do {
	DWORD length;
	uint16_t *wpath;
	char *path, *filepath;
	if (!(length = GetWindowsDirectoryW (NULL, 0)))
	{
	    break;
	}
	if (!(wpath = calloc (length, sizeof (uint16_t))))
	{
	    break;
	}
	if (GetWindowsDirectoryW (wpath, length) != (length-1))
	{
	    free (wpath);
	    break;
	}
	path = c->utf16_to_utf8 (c, wpath);
	free (wpath); wpath = 0;
	if (!path)
	{
	    break;
	}
	length = strlen (path) + 13 + 1;
	filepath = malloc (length);
	if (!filepath)
	{
	    free (path);
	    break;
	}
	snprintf (filepath, length, "%s\\TIMIDITY.CFG", path);
	free (path);
	if ((check = open(filepath, 0)) >= 0)
	{
	    close (check);
	    if (!read_config_file(c, filepath, 0, 0)) // C:\WINDOWS\timidity.cfg
	    {
		free (filepath);
		c->got_a_configuration = 1;
		break;
	    }
	}
	free (filepath);
    } while (0);
#endif

#else
    /* UNIX */
    if(!read_config_file(c, CONFIG_FILE, 0, 0))
		c->got_a_configuration = 1;
#endif

    /* Try read configuration file which is in the
     * $HOME (or %HOME% for DOS) directory.
     * Please setup each user preference in $HOME/.timidity.cfg
     * (or %HOME%/timidity.cfg for DOS)
     */
    if(read_user_config_file(c)) {
	ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
		  "Error: Syntax error in ~/.timidity.cfg");
	return 1;
    }

    return 0;
}

MAIN_INTERFACE int timidity_post_load_configuration(struct timiditycontext_t *c)
{
    int i, cmderr = 0;

#ifdef IA_ALSASEQ
    /* If we're going to fork for daemon mode, we need to fork now, as
       certain output libraries (pulseaudio) become unhappy if initialized
       before forking and then being used from the child. */
    if (ctl->id_character == 'A' && (ctl->flags & CTLF_DAEMONIZE))
    {
	int pid = fork();
	FILE *pidf;
	switch (pid)
	{
	    case 0:		// child is the daemon
		break;
	    case -1:		// error status return
		exit(7);
	    default:		// no error, doing well
		if ((pidf = fopen( "/var/run/timidity.pid", "w" )) != NULL )
		{
		    fprintf( pidf, "%d\n", pid );
		    fclose( pidf );
		}
		exit(0);
	}
    }
#endif

    if(play_mode == &null_play_mode)
    {
	char *output_id;

	output_id = getenv("TIMIDITY_OUTPUT_ID");
#ifdef TIMIDITY_OUTPUT_ID
	if(output_id == NULL)
	    output_id = TIMIDITY_OUTPUT_ID;
#endif /* TIMIDITY_OUTPUT_ID */
	if(output_id != NULL)
	{
	    for(i = 0; play_mode_list[i]; i++)
		if(play_mode_list[i]->id_character == *output_id)
		{
		    if (! play_mode_list[i]->detect ||
			play_mode_list[i]->detect()) {
			play_mode = play_mode_list[i];
			break;
		    }
		}
	}
    }

    if (play_mode == &null_play_mode) {
	/* try to detect the first available device */
	for(i = 0; play_mode_list[i]; i++) {
	    /* check only the devices with detect callback */
	    if (play_mode_list[i]->detect) {
		if (play_mode_list[i]->detect()) {
		    play_mode = play_mode_list[i];
		    break;
		}
	    }
	}
    }

    if (play_mode == &null_play_mode) {
	fprintf(stderr, "Couldn't open output device" NLS);
	exit(1);
    }
    else {
        /* apply changes made for null play mode to actual play mode */
        if(null_play_mode.encoding != 0) {
            play_mode->encoding = apply_encoding(play_mode->encoding, null_play_mode.encoding);
        }
        if(null_play_mode.rate != 0) {
            play_mode->rate = null_play_mode.rate;
        }
    }

    if(!c->got_a_configuration)
    {
	if(c->try_config_again && !read_config_file(c, CONFIG_FILE, 0, 0))
	    c->got_a_configuration = 1;
    }

    if(c->opt_config_string.nstring > 0)
    {
	char **config_string_list;

	config_string_list = make_string_array(c, &c->opt_config_string);
	if(config_string_list != NULL)
	{
	    for(i = 0; config_string_list[i]; i++)
	    {
		if(!read_config_file(c, config_string_list[i], 1, 0))
		    c->got_a_configuration = 1;
		else
		    cmderr++;
	    }
	    free(config_string_list[0]);
	    free(config_string_list);
	}
    }

    if(!c->got_a_configuration)
	cmderr++;
    return cmderr;
}

MAIN_INTERFACE void timidity_init_player(struct timiditycontext_t *c)
{
    initialize_resampler_coeffs(c);

    /* Allocate voice[] */
    c->voice = (Voice *) safe_realloc(c, c->voice, c->max_voices * sizeof(Voice));
	memset(c->voice, 0, c->max_voices * sizeof(Voice));

    /* Set play mode parameters */
    if(c->opt_output_rate != 0)
	play_mode->rate = c->opt_output_rate;
    else if(play_mode->rate == 0)
	play_mode->rate = DEFAULT_RATE;

    /* save defaults */
    COPY_CHANNELMASK(c->drumchannels, c->default_drumchannels);
    COPY_CHANNELMASK(c->drumchannel_mask, c->default_drumchannel_mask);

    if(c->opt_buffer_fragments != -1)
    {
	if(play_mode->flag & PF_BUFF_FRAGM_OPT)
	    play_mode->extra_param[0] = c->opt_buffer_fragments;
	else
	    ctl->cmsg(c, CMSG_WARNING, VERB_NORMAL,
		      "%s: -B option is ignored", play_mode->id_name);
    }

#ifdef SUPPORT_SOUNDSPEC
    if(view_soundspec_flag)
    {
	open_soundspec();
	soundspec_setinterval(spectrogram_update_sec);
    }
#endif /* SOUNDSPEC */
}

void timidity_init_aq_buff(struct timiditycontext_t *c)
{
    double time1, /* max buffer */
	   time2, /* init filled */
	   base;  /* buffer of device driver */

    if(!IS_STREAM_TRACE)
	return; /* Ignore */

    time1 = atof(c->opt_aq_max_buff);
    time2 = atof(c->opt_aq_fill_buff);
    base  = (double)aq_get_dev_queuesize(c) / play_mode->rate;
    if(strchr(c->opt_aq_max_buff, '%'))
    {
	time1 = base * (time1 - 100) / 100.0;
	if(time1 < 0)
	    time1 = 0;
    }
    if(strchr(c->opt_aq_fill_buff, '%'))
	time2 = base * time2 / 100.0;
    aq_set_soft_queue(c, time1, time2);
}

MAIN_INTERFACE int timidity_play_main(struct timiditycontext_t *c, int nfiles, char **files)
{
    int need_stdin = 0, need_stdout = 0;
    int i;
    int output_fail = 0;
    int retval;

    if(nfiles == 0 && !strchr(INTERACTIVE_INTERFACE_IDS, ctl->id_character))
	return 0;

    if(c->opt_output_name)
    {
	play_mode->name = c->opt_output_name;
    if(!strcmp(c->opt_output_name, "-")){
	    need_stdout = 1;
#ifdef __W32__
    	setmode( fileno(stdout), O_BINARY );
#endif
    }
    }

    for(i = 0; i < nfiles; i++)
	if (!strcmp(files[i], "-")){
	    need_stdin = 1;
#ifdef __W32__
    	setmode( fileno(stdin), O_BINARY );
#endif
	}

    if(ctl->open(need_stdin, need_stdout))
    {
	fprintf(stderr, "Couldn't open %s (`%c')" NLS,
		ctl->id_name, ctl->id_character);
	play_mode->close_output();
	return 3;
    }

    if(wrdt->open(c->wrdt_open_opts))
    {
	fprintf(stderr, "Couldn't open WRD Tracer: %s (`%c')" NLS,
		wrdt->name, wrdt->id);
	play_mode->close_output();
	ctl->close();
	return 1;
    }

#ifdef BORLANDC_EXCEPTION
    __try
    {
#endif /* BORLANDC_EXCEPTION */
#ifdef __W32__

#ifdef HAVE_SIGNAL
	signal(SIGTERM, sigterm_exit);
#endif
#if 0
	SetConsoleCtrlHandler(handler, TRUE);
#endif

	ctl->cmsg(c, CMSG_INFO, VERB_DEBUG_SILLY,
		  "Initialize for Critical Section");
	InitializeCriticalSection(&critSect);
	if(opt_evil_mode)
	    if(!SetThreadPriority(GetCurrentThread(),
				  THREAD_PRIORITY_ABOVE_NORMAL))
		ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
			  "Error raising process priority");

#else
	/* UNIX */
#ifdef HAVE_SIGNAL
	signal(SIGINT, sigterm_exit);
	signal(SIGTERM, sigterm_exit);
#ifdef SIGPIPE
	signal(SIGPIPE, sigterm_exit);    /* Handle broken pipe */
#endif /* SIGPIPE */
#endif /* HAVE_SIGNAL */

#endif

	/* Open output device */
	ctl->cmsg(c, CMSG_INFO, VERB_DEBUG_SILLY,
		  "Open output: %c, %s",
		  play_mode->id_character,
		  play_mode->id_name);

	if (play_mode->flag & PF_PCM_STREAM) {
	    play_mode->extra_param[1] = aq_calc_fragsize(c);
	    ctl->cmsg(c, CMSG_INFO, VERB_DEBUG_SILLY,
		      "requesting fragment size: %d",
		      play_mode->extra_param[1]);
	}
#if !defined ( IA_W32GUI ) && !defined ( IA_W32G_SYN )
	if(play_mode->open_output() < 0)
	{
	    ctl->cmsg(c, CMSG_FATAL, VERB_NORMAL,
		      "Couldn't open %s (`%c')",
		      play_mode->id_name, play_mode->id_character);
	    output_fail = 1;
	    ctl->close();
	    return 2;
	}
#endif /* IA_W32GUI */
	if(!c->control_ratio)
	{
	    c->control_ratio = play_mode->rate / CONTROLS_PER_SECOND;
	    if(c->control_ratio < 1)
		c->control_ratio = 1;
	    else if (c->control_ratio > MAX_CONTROL_RATIO)
		c->control_ratio = MAX_CONTROL_RATIO;
	}

	init_load_soundfont(c);
	if(!output_fail)
	{
	    aq_setup(c);
	    timidity_init_aq_buff(c);
	}
	if(c->allocate_cache_size > 0)
	    resamp_cache_reset(c);

	if (c->def_prog >= 0)
		set_default_program(c, c->def_prog);
	if (*c->def_instr_name)
		set_default_instrument(c, c->def_instr_name);

	if(ctl->flags & CTLF_LIST_RANDOM)
	    randomize_string_list(files, nfiles);
	else if(ctl->flags & CTLF_LIST_SORT)
	    sort_pathname(files, nfiles);

	/* Return only when quitting */
	ctl->cmsg(c, CMSG_INFO, VERB_DEBUG_SILLY,
		  "pass_playing_list() nfiles=%d", nfiles);

	retval=ctl->pass_playing_list(nfiles, files);

	if(c->intr)
	    aq_flush(c, 1);

#ifdef XP_UNIX
	return 0;
#endif /* XP_UNIX */

	play_mode->close_output();
	ctl->close();
	wrdt->close();
#ifdef __W32__
	DeleteCriticalSection (&critSect);
#endif

#ifdef BORLANDC_EXCEPTION
    } __except(1) {
	fprintf(stderr, "\nError!!!\nUnexpected Exception Occured!\n");
	if(play_mode->fd != -1)
	{
		play_mode->purge_output();
		play_mode->close_output();
	}
	ctl->close();
	wrdt->close();
	DeleteCriticalSection (&critSect);
	exit(EXIT_FAILURE);
    }
#endif /* BORLANDC_EXCEPTION */

#ifdef SUPPORT_SOUNDSPEC
    if(view_soundspec_flag)
	close_soundspec();
#endif /* SUPPORT_SOUNDSPEC */

    free_archive_files(c);
#ifdef SUPPORT_SOCKET
    url_news_connection_cache(URL_NEWS_CLOSE_CACHE);
#endif /* SUPPORT_SOCKET */

    return retval;
}

#ifdef IA_W32GUI
int w32gSecondTiMidity(int opt, int argc, char **argv);
int w32gSecondTiMidityExit(void);
int w32gLoadDefaultPlaylist(void);
int w32gSaveDefaultPlaylist(void);
extern int volatile save_playlist_once_before_exit_flag;
#endif /* IA_W32GUI */

#if !defined(ANOTHER_MAIN) && defined(__W32__) && !defined(WINDRV)
typedef BOOL (WINAPI *SetDllDirectoryAProc)(LPCSTR lpPathName);

/*! Remove the current directory for the search path of LoadLibrary. Returns 0 if failed. */
static int w32_reset_dll_directory(void)
{
	HMODULE module;
	SetDllDirectoryAProc setDllDirectory;
	if ((module = GetModuleHandle(TEXT("Kernel32.dll"))) == NULL)
		return 0;
	if ((setDllDirectory = (SetDllDirectoryAProc)GetProcAddress(module, TEXT("SetDllDirectoryA"))) == NULL)
		return 0;
	/* Microsoft Security Advisory 2389418 */
	return (*setDllDirectory)("") != 0;
}
#endif

#if defined ( IA_W32GUI ) || defined ( IA_W32G_SYN )
static int CoInitializeOK = 0;
#endif

#if !defined(ANOTHER_MAIN)// || defined(__W32__)
#ifdef __W32__ /* Windows */
#if defined(IA_W32GUI) && !defined(__CYGWIN32__) && !defined(__MINGW32__) \
		|| defined(IA_W32G_SYN) /* _MSC_VER, _BORLANDC_, __WATCOMC__ */
int win_main(int argc, char **argv)
#else /* Cygwin, MinGW or console */
int __cdecl main(int argc, char **argv)
#endif
#else /* UNIX */
int main(int argc, char **argv)
#endif
{
	int c, err, i;
	int nfiles;
	char **files;
	char *files_nbuf = NULL;
	int main_ret;
	int longind;
#if defined(DANGEROUS_RENICE) && !defined(__W32__) && !defined(main)
	/*
	 * THIS CODES MUST EXECUTE BEGINNING OF MAIN FOR SECURITY.
	 * DON'T PUT ANY CODES ABOVE.
	 */
#include <sys/resource.h>
	int uid;
#ifdef sun
	extern int setpriority(int which, id_t who, int prio);
	extern int setreuid(int ruid, int euid);
#endif

	uid = getuid();
	if (setpriority(PRIO_PROCESS, 0, DANGEROUS_RENICE) < 0) {
		perror("setpriority");
		fprintf(stderr, "Couldn't set priority to %d.", DANGEROUS_RENICE);
	}
	setreuid(uid, uid);
#endif
#if defined(REDIRECT_STDOUT)
	memcpy(stdout, fopen(REDIRECT_STDOUT, "a+"), sizeof(FILE));
	printf("TiMidity++ start\n");
	fflush(stdout);
#endif
#if defined(__W32__) && !defined(WINDRV)
	(void)w32_reset_dll_directory();
#endif
#ifdef main
{
	static int maincnt = 0;

	if (maincnt++ > 0) {
		do {
			argc--, argv++;
		} while (argv[0][0] == '-');
		ctl->pass_playing_list(argc, argv);
		return 0;
	}
}
#endif
#ifdef IA_DYNAMIC
{
	dynamic_lib_root = safe_strdup(c, SHARED_LIB_PATH);
	dl_init(argc, argv);
}
#endif /* IA_DYNAMIC */
	if ((program_name = pathsep_strrchr(argv[0])))
		program_name++;
	else
		program_name = argv[0];
	if (strncmp(program_name, "timidity", 8) == 0)
		;
	else if (strncmp(program_name, "kmidi", 5) == 0)
		set_ctl(c, "q");
	else if (strncmp(program_name, "tkmidi", 6) == 0)
		set_ctl(c, "k");
	else if (strncmp(program_name, "gtkmidi", 6) == 0)
		set_ctl(c, "g");
	else if (strncmp(program_name, "xmmidi", 6) == 0)
		set_ctl(c, "m");
	else if (strncmp(program_name, "xawmidi", 7) == 0)
		set_ctl(c, "a");
	else if (strncmp(program_name, "xskinmidi", 9) == 0)
		set_ctl(c, "i");
	if (argc == 1 && !strchr(INTERACTIVE_INTERFACE_IDS, ctl->id_character)) {
		interesting_message();
		return 0;
	}
	timidity_start_initialize(c);
#if defined (IA_W32GUI) || defined (IA_W32G_SYN)
	if (CoInitialize(NULL) == S_OK)
		CoInitializeOK = 1;
	w32g_initialize();
#ifdef IA_W32GUI
	/* Secondary TiMidity Execute */
	/*	FirstLoadIniFile(); */
	if (w32gSecondTiMidity(SecondMode,argc,argv) == FALSE)
		return 0;
#endif
	for (c = 1; c < argc; c++)
		if (is_directory(argv[c])) {
			char *p;

			p = (char *) safe_malloc(c, strlen(argv[c]) + 2);
			strcpy(p, argv[c]);
			directory_form(p);
			argv[c] = p;
		}
#endif /* IA_W32GUI || IA_W32G_SYN */
#if defined(IA_WINSYN) || defined(IA_PORTMIDISYN) || defined(IA_NPSYN) || defined(IA_W32G_SYN)
	opt_sf_close_each_file = 0;
#endif
	optind = longind = 0;
#if defined(__CYGWIN__)
	optreset = 1;
#endif
#ifdef __W32__
	while ((c = getopt_long(argc, argv, optcommands, longopts, &longind)) > 0)
		if ((err = set_tim_opt_long_cfg(c, optarg, longind)) != 0)
			break;
#endif
	if (c->got_a_configuration != 1){
		if ((err = timidity_pre_load_configuration()) != 0)
			return err;
	}
	optind = longind = 0;
#if defined(__CYGWIN__)
	optreset = 1;
#endif
	while ((c = getopt_long(argc, argv, optcommands, longopts, &longind)) > 0)
		if ((err = set_tim_opt_long(c, optarg, longind)) != 0)
			break;
	err += timidity_post_load_configuration();
	/* If there were problems, give up now */
	if (err || (optind >= argc
			&& !strchr(INTERACTIVE_INTERFACE_IDS, ctl->id_character))) {
		if (!c->got_a_configuration) {
#ifdef __W32__
			char config1[1024], config2[1024];

			memset(config1, 0, sizeof(config1));
			memset(config2, 0, sizeof(config2));
#if defined(IA_W32GUI) || defined(IA_W32G_SYN)
{
			strncpy(config1, ConfigFile, sizeof(config1) - 1);
}
#else /* !IA_W32GUI && !IA_W32G_SYN */
			GetWindowsDirectory(config1, 1023 - 13);
			strcat(config1, "\\TIMIDITY.CFG");
#endif
			if (GetModuleFileName(NULL, config2, 1023)) {
				char *strp;

				config2[1023] = '\0';
				if (strp = strrchr(config2, '\\')) {
					*(++strp) = '\0';
					strncat(config2, "TIMIDITY.CFG",
							sizeof(config2) - strlen(config2) - 1);
				}
			}
			ctl->cmsg(c, CMSG_FATAL, VERB_NORMAL,
					"%s: Can't read any configuration file.\n"
					"Please check %s or %s", program_name, config1, config2);
#else
			ctl->cmsg(c, CMSG_FATAL, VERB_NORMAL,
					"%s: Can't read any configuration file.\n"
					"Please check " CONFIG_FILE, program_name);
#endif /* __W32__ */
		} else
			ctl->cmsg(c, CMSG_ERROR, VERB_NORMAL,
					"Try %s -h for help", program_name);
/* Try to continue if it is Windows version */
#if !defined(IA_W32GUI) && !defined(IA_W32G_SYN)
		return 1; /* problems with command line */
#endif
	}
	timidity_init_player(c);
	nfiles = argc - optind;
	files  = argv + optind;
	if (nfiles > 0
			&& ctl->id_character != 'r' && ctl->id_character != 'A'
			&& ctl->id_character != 'W' && ctl->id_character != 'N'
			&& ctl->id_character != 'P')
		files = expand_file_archives(files, &nfiles);
	if (nfiles > 0)
		files_nbuf = files[0];
#if !defined(IA_W32GUI) && !defined(IA_W32G_SYN)
	if (dumb_error_count)
		sleep(1);
#endif
#ifdef IA_W32GUI
	w32gLoadDefaultPlaylist();
	main_ret = timidity_play_main(c, nfiles, files);
	if (save_playlist_once_before_exit_flag) {
		save_playlist_once_before_exit_flag = 0;
		w32gSaveDefaultPlaylist();
	}
	w32gSecondTiMidityExit();
	if (CoInitializeOK)
		CoUninitialize();
	w32g_free_playlist();
	w32g_uninitialize();
	w32g_free_doc();
#else
#ifdef IA_NPSYN
	timeBeginPeriod(1);
#endif
	main_ret = timidity_play_main(c, nfiles, files);
#ifdef IA_NPSYN
	timeEndPeriod(1);
#endif
#ifdef IA_W32G_SYN
	if (CoInitializeOK)
		CoUninitialize();
	w32g_uninitialize();
#endif /* IA_W32G_SYN */
#endif /* IA_W32GUI */
#ifdef SUPPORT_SOCKET
	if (url_user_agent)
		free(url_user_agent);
	if (url_http_proxy_host)
		free(url_http_proxy_host);
	if (url_ftp_proxy_host)
		free(url_ftp_proxy_host);
	if (user_mailaddr)
		free(user_mailaddr);
#endif
#ifdef IA_DYNAMIC
	if (dynamic_lib_root)
		free(dynamic_lib_root);
#endif
	if (pcm_alternate_file)
		free(pcm_alternate_file);
	if (c->opt_output_name)
		free(c->opt_output_name);
	if (c->opt_aq_max_buff)
		free(c->opt_aq_max_buff);
	if (c->opt_aq_fill_buff && !c->opt_aq_fill_buff_free_not_needed)
		free(c->opt_aq_fill_buff);
	if (output_text_code)
		free(output_text_code);
	if (c->wrdt_open_opts)
		free(c->wrdt_open_opts);
	if (nfiles > 0
			&& ctl->id_character != 'r' && ctl->id_character != 'A'
			&& ctl->id_character != 'W' && ctl->id_character != 'N'
			&& ctl->id_character != 'P') {
		free(files_nbuf);
		free(files);
	}
	free_soft_queue(c);
	free_instruments(c, 0);
	free_soundfonts(c);
	free_cache_data(c);
	free_wrd(c);
	free_readmidi(c);
	free_global_mblock(c);
	tmdy_free_config(c);
	free_reverb_buffer(c);
	free_effect_buffers(c);
	free(voice);
	free_gauss_table(c);
	for (i = 0; i < MAX_CHANNELS; i++)
		free_drum_effect(c, i);
	return main_ret;
}
#endif /* !ANOTHER_MAIN || __W32__ */

