#line 2 "sfz2pat.c"

#line 4 "sfz2pat.c"

#define  YY_INT_ALIGNED short int

/* A lexical scanner generated by flex */

#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 5
#define YY_FLEX_SUBMINOR_VERSION 31
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif

/* First, we deal with  platform-specific or compiler-specific issues. */

/* begin standard C headers. */
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>

/* end standard C headers. */

/* flex integer type definitions */

#ifndef FLEXINT_H
#define FLEXINT_H

/* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */

#if defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L
#include <inttypes.h>
typedef int8_t flex_int8_t;
typedef uint8_t flex_uint8_t;
typedef int16_t flex_int16_t;
typedef uint16_t flex_uint16_t;
typedef int32_t flex_int32_t;
typedef uint32_t flex_uint32_t;
#else
typedef signed char flex_int8_t;
typedef short int flex_int16_t;
typedef int flex_int32_t;
typedef unsigned char flex_uint8_t; 
typedef unsigned short int flex_uint16_t;
typedef unsigned int flex_uint32_t;
#endif /* ! C99 */

/* Limits of integral types. */
#ifndef INT8_MIN
#define INT8_MIN               (-128)
#endif
#ifndef INT16_MIN
#define INT16_MIN              (-32767-1)
#endif
#ifndef INT32_MIN
#define INT32_MIN              (-2147483647-1)
#endif
#ifndef INT8_MAX
#define INT8_MAX               (127)
#endif
#ifndef INT16_MAX
#define INT16_MAX              (32767)
#endif
#ifndef INT32_MAX
#define INT32_MAX              (2147483647)
#endif
#ifndef UINT8_MAX
#define UINT8_MAX              (255U)
#endif
#ifndef UINT16_MAX
#define UINT16_MAX             (65535U)
#endif
#ifndef UINT32_MAX
#define UINT32_MAX             (4294967295U)
#endif

#endif /* ! FLEXINT_H */

#ifdef __cplusplus

/* The "const" storage-class-modifier is valid. */
#define YY_USE_CONST

#else	/* ! __cplusplus */

#if __STDC__

#define YY_USE_CONST

#endif	/* __STDC__ */
#endif	/* ! __cplusplus */

#ifdef YY_USE_CONST
#define yyconst const
#else
#define yyconst
#endif

/* Returned upon end-of-file. */
#define YY_NULL 0

/* Promotes a possibly negative, possibly signed char to an unsigned
 * integer for use as an array index.  If the signed char is negative,
 * we want to instead treat it as an 8-bit unsigned char, hence the
 * double cast.
 */
#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c)

/* Enter a start condition.  This macro really ought to take a parameter,
 * but we do it the disgusting crufty way forced on us by the ()-less
 * definition of BEGIN.
 */
#define BEGIN (yy_start) = 1 + 2 *

/* Translate the current start state into a value that can be later handed
 * to BEGIN to return to the state.  The YYSTATE alias is for lex
 * compatibility.
 */
#define YY_START (((yy_start) - 1) / 2)
#define YYSTATE YY_START

/* Action number for EOF rule of a given start state. */
#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)

/* Special action meaning "start processing a new file". */
#define YY_NEW_FILE sfzrestart(sfzin  )

#define YY_END_OF_BUFFER_CHAR 0

/* Size of default input buffer. */
#ifndef YY_BUF_SIZE
#define YY_BUF_SIZE 16384
#endif

#ifndef YY_TYPEDEF_YY_BUFFER_STATE
#define YY_TYPEDEF_YY_BUFFER_STATE
typedef struct yy_buffer_state *YY_BUFFER_STATE;
#endif

extern int sfzleng;

extern FILE *sfzin, *sfzout;

#define EOB_ACT_CONTINUE_SCAN 0
#define EOB_ACT_END_OF_FILE 1
#define EOB_ACT_LAST_MATCH 2

    #define YY_LESS_LINENO(n)
    
/* Return all but the first "n" matched characters back to the input stream. */
#define yyless(n) \
	do \
		{ \
		/* Undo effects of setting up sfztext. */ \
        int yyless_macro_arg = (n); \
        YY_LESS_LINENO(yyless_macro_arg);\
		*yy_cp = (yy_hold_char); \
		YY_RESTORE_YY_MORE_OFFSET \
		(yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
		YY_DO_BEFORE_ACTION; /* set up sfztext again */ \
		} \
	while ( 0 )

#define unput(c) yyunput( c, (yytext_ptr)  )

/* The following is because we cannot portably get our hands on size_t
 * (without autoconf's help, which isn't available because we want
 * flex-generated scanners to compile on their own).
 */

#ifndef YY_TYPEDEF_YY_SIZE_T
#define YY_TYPEDEF_YY_SIZE_T
typedef unsigned int yy_size_t;
#endif

#ifndef YY_STRUCT_YY_BUFFER_STATE
#define YY_STRUCT_YY_BUFFER_STATE
struct yy_buffer_state
	{
	FILE *yy_input_file;

	char *yy_ch_buf;		/* input buffer */
	char *yy_buf_pos;		/* current position in input buffer */

	/* Size of input buffer in bytes, not including room for EOB
	 * characters.
	 */
	yy_size_t yy_buf_size;

	/* Number of characters read into yy_ch_buf, not including EOB
	 * characters.
	 */
	int yy_n_chars;

	/* Whether we "own" the buffer - i.e., we know we created it,
	 * and can realloc() it to grow it, and should free() it to
	 * delete it.
	 */
	int yy_is_our_buffer;

	/* Whether this is an "interactive" input source; if so, and
	 * if we're using stdio for input, then we want to use getc()
	 * instead of fread(), to make sure we stop fetching input after
	 * each newline.
	 */
	int yy_is_interactive;

	/* Whether we're considered to be at the beginning of a line.
	 * If so, '^' rules will be active on the next match, otherwise
	 * not.
	 */
	int yy_at_bol;

    int yy_bs_lineno; /**< The line count. */
    int yy_bs_column; /**< The column count. */
    
	/* Whether to try to fill the input buffer when we reach the
	 * end of it.
	 */
	int yy_fill_buffer;

	int yy_buffer_status;

#define YY_BUFFER_NEW 0
#define YY_BUFFER_NORMAL 1
	/* When an EOF's been seen but there's still some text to process
	 * then we mark the buffer as YY_EOF_PENDING, to indicate that we
	 * shouldn't try reading from the input source any more.  We might
	 * still have a bunch of tokens to match, though, because of
	 * possible backing-up.
	 *
	 * When we actually see the EOF, we change the status to "new"
	 * (via sfzrestart()), so that the user can continue scanning by
	 * just pointing sfzin at a new input file.
	 */
#define YY_BUFFER_EOF_PENDING 2

	};
#endif /* !YY_STRUCT_YY_BUFFER_STATE */

/* Stack of input buffers. */
static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */
static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */
static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */

/* We provide macros for accessing buffer states in case in the
 * future we want to put the buffer states in a more general
 * "scanner state".
 *
 * Returns the top of the stack, or NULL.
 */
#define YY_CURRENT_BUFFER ( (yy_buffer_stack) \
                          ? (yy_buffer_stack)[(yy_buffer_stack_top)] \
                          : NULL)

/* Same as previous macro, but useful when we know that the buffer stack is not
 * NULL or when we need an lvalue. For internal use only.
 */
#define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)]

/* yy_hold_char holds the character lost when sfztext is formed. */
static char yy_hold_char;
static int yy_n_chars;		/* number of characters read into yy_ch_buf */
int sfzleng;

/* Points to current character in buffer. */
static char *yy_c_buf_p = (char *) 0;
static int yy_init = 1;		/* whether we need to initialize */
static int yy_start = 0;	/* start state number */

/* Flag which is used to allow sfzwrap()'s to do buffer switches
 * instead of setting up a fresh sfzin.  A bit of a hack ...
 */
static int yy_did_buffer_switch_on_eof;

void sfzrestart (FILE *input_file  );
void sfz_switch_to_buffer (YY_BUFFER_STATE new_buffer  );
YY_BUFFER_STATE sfz_create_buffer (FILE *file,int size  );
void sfz_delete_buffer (YY_BUFFER_STATE b  );
void sfz_flush_buffer (YY_BUFFER_STATE b  );
void sfzpush_buffer_state (YY_BUFFER_STATE new_buffer  );
void sfzpop_buffer_state (void );

static void sfzensure_buffer_stack (void );
static void sfz_load_buffer_state (void );
static void sfz_init_buffer (YY_BUFFER_STATE b,FILE *file  );

#define YY_FLUSH_BUFFER sfz_flush_buffer(YY_CURRENT_BUFFER )

YY_BUFFER_STATE sfz_scan_buffer (char *base,yy_size_t size  );
YY_BUFFER_STATE sfz_scan_string (yyconst char *yy_str  );
YY_BUFFER_STATE sfz_scan_bytes (yyconst char *bytes,int len  );

void *sfzalloc (yy_size_t  );
void *sfzrealloc (void *,yy_size_t  );
void sfzfree (void *  );

#define yy_new_buffer sfz_create_buffer

#define yy_set_interactive(is_interactive) \
	{ \
	if ( ! YY_CURRENT_BUFFER ){ \
        sfzensure_buffer_stack (); \
		YY_CURRENT_BUFFER_LVALUE =    \
            sfz_create_buffer(sfzin,YY_BUF_SIZE ); \
	} \
	YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
	}

#define yy_set_bol(at_bol) \
	{ \
	if ( ! YY_CURRENT_BUFFER ){\
        sfzensure_buffer_stack (); \
		YY_CURRENT_BUFFER_LVALUE =    \
            sfz_create_buffer(sfzin,YY_BUF_SIZE ); \
	} \
	YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
	}

#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)

/* Begin user sect3 */

#define sfzwrap(n) 1
#define YY_SKIP_YYWRAP

typedef unsigned char YY_CHAR;

FILE *sfzin = (FILE *) 0, *sfzout = (FILE *) 0;

typedef int yy_state_type;

extern int sfzlineno;

int sfzlineno = 1;

extern char *sfztext;
#define yytext_ptr sfztext

static yy_state_type yy_get_previous_state (void );
static yy_state_type yy_try_NUL_trans (yy_state_type current_state  );
static int yy_get_next_buffer (void );
static void yy_fatal_error (yyconst char msg[]  );

/* Done after the current pattern has been matched and before the
 * corresponding action - sets up sfztext.
 */
#define YY_DO_BEFORE_ACTION \
	(yytext_ptr) = yy_bp; \
	sfzleng = (size_t) (yy_cp - yy_bp); \
	(yy_hold_char) = *yy_cp; \
	*yy_cp = '\0'; \
	(yy_c_buf_p) = yy_cp;

#define YY_NUM_RULES 45
#define YY_END_OF_BUFFER 46
/* This struct is not used in this scanner,
   but its presence is necessary. */
struct yy_trans_info
	{
	flex_int32_t yy_verify;
	flex_int32_t yy_nxt;
	};
static yyconst flex_int16_t yy_accept[337] =
    {   0,
        0,    0,    0,    0,   46,   44,   42,   43,   44,   44,
       44,   44,   44,   44,   44,   44,   44,   44,   44,   44,
       44,   42,    1,    0,    0,    0,    0,    0,    0,    0,
        0,    0,    0,    0,    0,    0,    0,    0,    1,    0,
        0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
        0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
        0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
        0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
        0,    0,    0,    0,    0,    0,    0,    0,   38,    0,
        0,    0,    0,   22,    0,    0,    0,    0,    0,    0,

        0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
        0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
        0,   23,    0,    0,    0,    0,    0,    0,    0,    0,
        0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
        2,    0,    0,    0,    7,   19,    0,    0,    5,   20,
        0,    0,    0,    0,    0,    6,    0,    0,    0,    0,
        0,    0,    0,    0,    0,   31,    0,    0,    0,    3,
        0,    0,    0,    0,   24,   17,    0,    0,   25,    0,
        0,    0,   18,    8,   37,    0,    4,    0,    4,   41,
        0,    0,   41,    0,    0,    0,    0,    0,    0,   32,

        0,    0,   15,    0,    0,   17,    0,    0,    0,   18,
        0,    4,    0,    4,    0,    4,   41,    0,   41,    0,
       41,   33,    0,    0,   35,    0,    0,    0,    0,    0,
        0,   15,    0,    0,   17,   40,    0,    0,   18,    0,
        4,    0,    4,    0,    4,   41,    0,   41,    0,   41,
        0,    0,   34,   27,    0,    0,    0,   36,   29,    0,
        0,    0,    0,    0,   15,    0,    0,    0,    0,    0,
        4,    0,    0,    4,   41,    0,    0,   41,    0,    0,
       28,    0,    0,   30,    0,    0,    0,    0,   16,    0,
        0,   39,    0,    0,    0,    0,    0,    0,    0,   16,

        0,    0,    0,    4,   41,    0,   12,    0,    0,   16,
        0,    0,    0,    9,   11,    0,   14,    0,    0,   10,
       14,    0,    0,   14,    0,   21,    0,    0,    0,    0,
       26,    0,    0,    0,   13,    0
    } ;

static yyconst flex_int32_t yy_ec[256] =
    {   0,
        1,    1,    1,    1,    1,    1,    1,    1,    2,    3,
        1,    1,    4,    1,    1,    1,    1,    1,    1,    1,
        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
        1,    2,    1,    5,    6,    1,    1,    1,    1,    1,
        1,    1,    7,    1,    8,    9,   10,   11,   12,   11,
       11,   11,   11,   11,   11,   11,   11,    1,    1,   13,
       14,   15,    1,    1,   16,   16,   16,   16,   16,   16,
       16,    1,    1,    1,    1,    1,    1,    1,    1,    1,
        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
        1,    1,    1,    1,   17,    1,   18,   19,   20,   21,

       22,   23,   24,   25,   26,    1,   27,   28,   29,   30,
       31,   32,    1,   33,   34,   35,   36,   37,   38,    1,
       39,    1,    1,    1,    1,    1,    1,    1,    1,    1,
        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,

        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
        1,    1,    1,    1,    1
    } ;

static yyconst flex_int32_t yy_meta[40] =
    {   0,
        1,    1,    2,    1,    1,    1,    1,    1,    1,    1,
        3,    3,    1,    1,    1,    3,    1,    3,    3,    3,
        3,    3,    3,    3,    1,    1,    1,    1,    1,    1,
        1,    1,    1,    1,    1,    1,    1,    1,    1
    } ;

static yyconst flex_int16_t yy_base[356] =
    {   0,
        0,    2,   11,    0,  581,  582,  578,  582,  569,    1,
      549,  547,  543,  549,  552,  542,  549,  545,    9,  537,
      538,  566,    0,  534,  544,  533,  543,  532,    4,  523,
       22,  538,  525,  530,  522,  540,  530,  527,    0,  523,
      529,    0,  538,  515,  528,  531,  526,  533,  524,  513,
      526,  521,   27,  522,  509,  507,   29,  515,  502,  501,
      510,  502,  510,    4,  501,  493,  501,  502,    7,  490,
      511,  497,  498,  506,  502,  498,  494,  501,  489,  493,
       33,  486,  493,  487,  483,  483,  495,  495,   51,  497,
      496,  488,  494,   55,   62,  493,   49,  485,  491,  465,

      468,  485,  479,  478,  461,  471,  463,  469,  481,  472,
      471,  477,  461,  460,  456,   64,   68,  474,   73,   78,
      475,  582,   76,  456,  454,  449,  469,   80,  468,  467,
      453,  465,  476,  447,  454,  440,  452,   82,  440,  458,
      582,  456,  449,  447,   84,   86,   93,   91,   95,   97,
      105,  447,  446,  448,  103,  107,  109,  111,  443,    4,
      123,  450,  424,  448,  422,  118,  125,  446,  127,  582,
      428,  430,  134,  445,  582,  138,  140,  444,  582,  441,
      432,  420,  144,  129,  146,  413,  157,  442,  158,  166,
      167,  441,  175,  153,  435,  162,  434,  170,  435,  582,

      165,  174,  178,  417,  423,  180,  183,  430,  408,  185,
      422,  197,   14,  198,    2,  206,  210,  195,  216,   21,
      222,  205,  226,  211,  217,  235,  228,  406,  414,  417,
      416,  238,  423,  418,  240,  244,  407,  420,  246,  411,
      257,   51,  423,  204,  260,  268,  258,  422,  274,  280,
      279,  418,  582,  262,  288,  293,  417,  582,  269,  302,
      393,  394,  402,  397,  281,  291,  389,  389,  304,  387,
      315,   19,  313,  321,  325,   63,  323,  331,  331,  402,
      582,  336,  399,  582,  390,  371,  384,  377,  340,  371,
      359,  326,  354,  341,  348,  364,  347,  342,  350,  343,

      347,  327,  323,  351,  353,  293,  582,  280,  275,  352,
      354,  289,  264,  582,  582,  273,  358,  254,  257,  582,
      360,  232,  362,  364,  229,  368,  375,  218,  380,  224,
      582,  212,  179,  124,  582,  582,  394,  397,  140,  129,
      123,  107,  400,  403,  406,  409,  412,  415,   79,   74,
      418,  421,   55,   29,   17
    } ;

static yyconst flex_int16_t yy_def[356] =
    {   0,
      337,  337,  337,    3,  336,  336,  336,  336,  336,  336,
      336,  336,  336,  336,  336,  336,  336,  336,  336,  336,
      336,  336,  338,  336,  336,  336,  336,  336,  336,  336,
      336,  336,  336,  336,  336,  336,  336,  336,  338,  336,
      336,  336,  336,  336,  336,  336,  336,  336,  336,  336,
      336,  336,  336,  336,  336,  336,  336,  336,  336,  336,
      336,  336,  336,  336,  336,  336,  336,  336,  339,  336,
      336,  336,  336,  336,  336,  336,  336,  336,  336,  336,
      336,  336,  336,  336,  336,  336,  336,  336,  336,  336,
      336,  336,  336,  336,  336,  336,  336,  336,  336,  336,

      336,  336,  336,  336,  336,  336,  336,  336,  336,  336,
      336,  336,  336,  336,  336,  336,  340,  336,  336,  336,
      336,  336,  341,  336,  336,  336,  336,  336,  336,  336,
      336,  336,  336,  336,  336,  336,  336,  342,  336,  336,
      336,  336,  336,  336,  336,  336,  336,  336,  336,  336,
      336,  336,  336,  336,  336,  336,  336,  336,  336,  343,
      344,  336,  336,  336,  336,  336,  336,  336,  336,  336,
      336,  336,  336,  336,  336,  336,  336,  336,  336,  336,
      336,  336,  336,  336,  336,  336,  343,  345,  346,  344,
      344,  347,  348,  349,  336,  350,  336,  336,  336,  336,

      336,  336,  336,  336,  336,  336,  336,  336,  336,  336,
      336,  343,  345,  346,  351,  346,  344,  347,  348,  352,
      348,  336,  336,  353,  336,  336,  354,  336,  336,  336,
      336,  336,  336,  336,  336,  336,  336,  336,  336,  336,
      343,  345,  345,  351,  346,  344,  347,  347,  352,  348,
      336,  336,  336,  336,  336,  336,  336,  336,  336,  336,
      336,  336,  336,  336,  336,  336,  336,  336,  336,  336,
      343,  345,  351,  346,  344,  347,  352,  348,  336,  336,
      336,  336,  336,  336,  336,  336,  336,  336,  336,  336,
      336,  336,  336,  351,  352,  336,  336,  336,  336,  336,

      336,  336,  336,  351,  352,  336,  336,  336,  336,  336,
      336,  336,  336,  336,  336,  336,  336,  336,  336,  336,
      336,  336,  355,  336,  336,  336,  336,  336,  336,  336,
      336,  336,  336,  336,  336,    0,  336,  336,  336,  336,
      336,  336,  336,  336,  336,  336,  336,  336,  336,  336,
      336,  336,  336,  336,  336
    } ;

static yyconst flex_int16_t yy_nxt[622] =
    {   0,
      336,    7,    8,    7,    8,  188,  243,  188,  189,    9,
      244,    9,    7,    8,   89,   89,   62,   94,   94,  327,
        9,   63,  213,   10,   24,  248,   34,  213,   11,  249,
       45,  260,   12,   25,   13,   14,   46,   15,   16,   35,
       47,   17,   18,   74,   19,   20,   36,   21,   49,   79,
      107,  242,   50,   80,   51,  243,   81,  255,   52,  213,
       75,   89,   89,  108,   82,   94,   94,  120,  272,  121,
      124,  218,  122,  122,  145,  145,  226,  125,  146,  146,
      120,  223,  126,  149,  149,  121,  150,  150,  122,  122,
      156,  156,  166,  166,  145,  145,  146,  146,  173,  248,

      174,  176,  176,  175,  175,  149,  149,  150,  150,  167,
      177,  173,  178,  183,  183,  179,  179,  156,  156,  184,
      184,  185,  185,  177,  191,  151,  192,  193,  166,  166,
      198,  147,  199,  202,  202,  200,  200,  203,  203,  184,
      184,  174,   95,  198,  175,  175,  206,  178,  176,  176,
      179,  179,  210,  335,  183,  183,  185,  185,  188,  215,
      188,  215,  187,  222,  222,  212,  216,  192,  191,  192,
      192,  193,  225,  225,  217,  217,  220,  199,  220,  190,
      200,  200,  228,  221,  203,  203,  232,  229,  203,  203,
      235,  235,  230,  236,  236,  239,  239,  231,  188,  215,

      188,  215,  187,  218,  334,  212,  216,  215,  243,  215,
      187,  192,  244,  192,  216,  222,  222,  220,  217,  220,
      190,  254,  254,  220,  221,  220,  190,  225,  225,  333,
      221,  251,  247,  252,  241,  331,  253,  253,  259,  259,
      256,  273,  257,  245,  251,  258,  258,  246,  265,  265,
      235,  235,  332,  256,  236,  236,  239,  239,  188,  250,
      188,  215,  328,  215,  187,  212,  218,  325,  216,  192,
      323,  192,  254,  254,  271,  276,  217,  274,  248,  259,
      259,  220,  249,  220,  190,  275,  252,  322,  221,  253,
      253,  265,  265,  279,  320,  280,  319,  278,  281,  281,

      257,  289,  289,  258,  258,  318,  279,  282,  316,  283,
      315,  277,  284,  284,  292,  292,  188,  243,  188,  314,
      282,  244,  215,  212,  215,  187,  192,  248,  192,  216,
      294,  249,  220,  217,  220,  190,  292,  292,  280,  221,
      295,  281,  281,  283,  313,  243,  284,  284,  300,  244,
      289,  289,  248,  310,  310,  243,  249,  248,  312,  244,
      311,  249,  310,  310,  317,  317,  321,  309,  317,  317,
      324,  324,  326,  326,  324,  324,  308,  304,  326,  326,
      329,  307,  330,  306,  305,  331,  331,  330,  303,  302,
      331,  331,  301,  329,    6,    6,    6,   39,  299,   39,

      187,  298,  187,  190,  297,  190,  188,  296,  188,  214,
      284,  214,  192,  281,  192,  219,  293,  219,  215,  291,
      215,  220,  290,  220,  288,  287,  286,  285,  258,  253,
      218,  213,  270,  269,  268,  267,  266,  264,  263,  262,
      261,  240,  238,  237,  234,  233,  200,  227,  224,  218,
      213,  211,  209,  208,  207,  179,  175,  205,  204,  201,
      197,  196,  195,  194,  186,  182,  181,  180,  172,  171,
      170,  169,  168,  165,  164,  163,  162,  161,  160,  159,
      158,  157,  155,  154,  153,  152,  122,  148,  144,  143,
      142,  141,  140,  139,  138,  137,  136,  135,  134,  133,

      132,  131,  130,  129,  128,  127,  123,  119,  118,  117,
      116,  115,  114,  113,  112,  111,  110,  109,  106,  105,
      104,  103,  102,  101,  100,   99,   98,   97,   96,   93,
       92,   91,   90,   88,   87,   86,   85,   84,   83,   78,
       77,   76,   73,   72,   71,   70,   69,   68,   67,   66,
       65,   64,   61,   60,   59,   58,   57,   56,   55,   54,
       53,   48,   44,   43,   42,   41,   40,   22,   38,   37,
       33,   32,   31,   30,   29,   28,   27,   26,   23,   22,
      336,    5,  336,  336,  336,  336,  336,  336,  336,  336,
      336,  336,  336,  336,  336,  336,  336,  336,  336,  336,

      336,  336,  336,  336,  336,  336,  336,  336,  336,  336,
      336,  336,  336,  336,  336,  336,  336,  336,  336,  336,
      336
    } ;

static yyconst flex_int16_t yy_chk[622] =
    {   0,
        0,    1,    1,    2,    2,  160,  215,  160,  160,    1,
      215,    2,    3,    3,   64,   64,   42,   69,   69,  355,
        3,   42,  213,    3,   10,  220,   19,  272,    3,  220,
       29,  354,    3,   10,    3,    3,   29,    3,    3,   19,
       29,    3,    3,   53,    3,    3,   19,    3,   31,   57,
       81,  213,   31,   57,   31,  272,   57,  353,   31,  242,
       53,   89,   89,   81,   57,   94,   94,   95,  242,   95,
       97,  276,   95,   95,  116,  116,  350,   97,  117,  117,
       95,  349,   97,  119,  119,  120,  123,  123,  120,  120,
      128,  128,  138,  138,  145,  145,  146,  146,  147,  276,

      147,  148,  148,  147,  147,  149,  149,  150,  150,  342,
      151,  147,  151,  155,  155,  151,  151,  156,  156,  157,
      157,  158,  158,  151,  161,  341,  161,  161,  166,  166,
      167,  340,  167,  169,  169,  167,  167,  169,  169,  184,
      184,  173,  339,  167,  173,  173,  176,  177,  176,  176,
      177,  177,  183,  334,  183,  183,  185,  185,  187,  189,
      187,  189,  189,  194,  194,  187,  189,  190,  191,  190,
      191,  191,  196,  196,  190,  191,  193,  198,  193,  193,
      198,  198,  201,  193,  202,  202,  203,  201,  203,  203,
      206,  206,  201,  207,  207,  210,  210,  201,  212,  214,

      212,  214,  214,  218,  333,  212,  214,  216,  244,  216,
      216,  217,  244,  217,  216,  222,  222,  219,  217,  219,
      219,  224,  224,  221,  219,  221,  221,  225,  225,  332,
      221,  223,  218,  223,  212,  330,  223,  223,  227,  227,
      226,  244,  226,  216,  223,  226,  226,  217,  232,  232,
      235,  235,  328,  226,  236,  236,  239,  239,  241,  221,
      241,  245,  325,  245,  245,  241,  247,  322,  245,  246,
      319,  246,  254,  254,  241,  247,  246,  245,  249,  259,
      259,  250,  249,  250,  250,  246,  251,  318,  250,  251,
      251,  265,  265,  255,  316,  255,  313,  250,  255,  255,

      256,  266,  266,  256,  256,  312,  255,  260,  309,  260,
      308,  249,  260,  260,  269,  269,  271,  273,  271,  306,
      260,  273,  274,  271,  274,  274,  275,  277,  275,  274,
      273,  277,  278,  275,  278,  278,  292,  292,  279,  278,
      277,  279,  279,  282,  303,  294,  282,  282,  289,  294,
      289,  289,  295,  300,  300,  304,  295,  305,  302,  304,
      301,  305,  310,  310,  311,  311,  317,  299,  317,  317,
      321,  321,  323,  323,  324,  324,  298,  294,  326,  326,
      327,  297,  327,  296,  295,  327,  327,  329,  293,  291,
      329,  329,  290,  327,  337,  337,  337,  338,  288,  338,

      343,  287,  343,  344,  286,  344,  345,  285,  345,  346,
      283,  346,  347,  280,  347,  348,  270,  348,  351,  268,
      351,  352,  267,  352,  264,  263,  262,  261,  257,  252,
      248,  243,  240,  238,  237,  234,  233,  231,  230,  229,
      228,  211,  209,  208,  205,  204,  199,  197,  195,  192,
      188,  186,  182,  181,  180,  178,  174,  172,  171,  168,
      165,  164,  163,  162,  159,  154,  153,  152,  144,  143,
      142,  140,  139,  137,  136,  135,  134,  133,  132,  131,
      130,  129,  127,  126,  125,  124,  121,  118,  115,  114,
      113,  112,  111,  110,  109,  108,  107,  106,  105,  104,

      103,  102,  101,  100,   99,   98,   96,   93,   92,   91,
       90,   88,   87,   86,   85,   84,   83,   82,   80,   79,
       78,   77,   76,   75,   74,   73,   72,   71,   70,   68,
       67,   66,   65,   63,   62,   61,   60,   59,   58,   56,
       55,   54,   52,   51,   50,   49,   48,   47,   46,   45,
       44,   43,   41,   40,   38,   37,   36,   35,   34,   33,
       32,   30,   28,   27,   26,   25,   24,   22,   21,   20,
       18,   17,   16,   15,   14,   13,   12,   11,    9,    7,
        5,  336,  336,  336,  336,  336,  336,  336,  336,  336,
      336,  336,  336,  336,  336,  336,  336,  336,  336,  336,

      336,  336,  336,  336,  336,  336,  336,  336,  336,  336,
      336,  336,  336,  336,  336,  336,  336,  336,  336,  336,
      336
    } ;

static yy_state_type yy_last_accepting_state;
static char *yy_last_accepting_cpos;

extern int sfz_flex_debug;
int sfz_flex_debug = 0;

/* The intent behind this definition is that it'll catch
 * any uses of REJECT which flex missed.
 */
#define REJECT reject_used_but_not_detected
#define yymore() yymore_used_but_not_detected
#define YY_MORE_ADJ 0
#define YY_RESTORE_YY_MORE_OFFSET
char *sfztext;
#line 1 "./sfz2pat.l"
#line 2 "./sfz2pat.l"
/*
 * SFZ file reader, Greg Lee, 10/04.
 * Adapted from Cfg file reader, Greg Lee, 8/93.
 * Adapted from Adagio for KMidi 12/99.
 *	$Id: cfg.l,v 1.8 2000/08/08 17:32:37 faure Exp $
 */
/*
 Also adapted from:

    Wav2pat -- simple WAVE to GUS patch converter
    Copyright (C) 1995 Tuukka Toivonen <toivonen@clinet.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., 675 Mass Ave, Cambridge, MA 02139, USA.

    This is a little tool to convert RIFF WAVEs to GUS-compatible
    patches. A WAVE is read from stdin, and a GUS patch is written to
    stdout.

*/
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "gtim.h"
#ifdef HAVE_OGG
#include <vorbis/codec.h>
#include <vorbis/vorbisfile.h>
#endif
#include "common.h"
#include "instrum.h"
#include "playmidi.h"
#include "readmidi.h"
#include "output.h"
#include "controls.h"
#include "tables.h"

#define YY_ALWAYS_INTERACTIVE 0
#define YY_NEVER_INTERACTIVE 1

#define YY_INPUT(buf,result,max_size) \
	 result = fread( buf, 1, max_size, sfzin );

static char *sfzname = 0;

static int rcf_count=1;

#define MAX_INCLUDE_DEPTH 40
static YY_BUFFER_STATE include_stack[MAX_INCLUDE_DEPTH];
static int include_stack_ptr = 0;
static char *this_fname[MAX_INCLUDE_DEPTH] = { NULL };
static int this_line[MAX_INCLUDE_DEPTH] = { 0 };

static int read_sample(char *name);
#ifndef LOADER
static void make_pat(void);
#endif
static void point_regions_to_groups(void);
static void leave_region(void);
static int enter_region(void);
static void leave_group(void);
static int enter_group(void);

#ifndef LOADER
typedef union {
      unsigned char c[4];
      unsigned long l;
} long_end;
typedef union {
      unsigned char c[2];
      unsigned short s;
} short_end;

typedef struct linfo {
	unsigned char velmin;
	unsigned char velmax;
	unsigned char left_samples;
	unsigned char right_samples;
} linfo;

#pragma pack (1)

struct pat_header
  {
    char            magic[12];
    char            version[10];
    char            description[60];
    unsigned char   instruments;
    unsigned char   pat_voices;
    unsigned char   pat_channels;
    unsigned short  nr_waveforms;
    unsigned short  master_volume;
    unsigned long   data_size;
    char	    sf2magic[7];
    char	    unused1[29];
    short	    instrument_number;
    char	    instrument_name[16];
    int		    instrument_size;
    unsigned char   layer_count;
    unsigned char   velocity_count;
    struct linfo    sf2layer[9];
    char	    unused2[40-37];
    char	    layer_duplicate;
    char	    layer_number;
    int		    layer_size;
    unsigned char   num_samples;
    struct linfo    sf2layer2[10];
  };

#pragma pack (1)

struct sample_header
  {
    char            name[7];
    unsigned char   fractions;
    long            len;
    long            loop_start;
    long            loop_end;
    unsigned short  base_freq;
    long            low_note;
    long            high_note;
    long            base_note;
    short           detune;
    unsigned char   panning;

    unsigned char   envelope_rate[6];
    unsigned char   envelope_offset[6];

    unsigned char   tremolo_sweep;
    unsigned char   tremolo_rate;
    unsigned char   tremolo_depth;

    unsigned char   vibrato_sweep;
    unsigned char   vibrato_rate;
    unsigned char   vibrato_depth;

    char            modes;

    short           scale_frequency;
    unsigned short  scale_factor;
    unsigned short  volume; /* Is this really here?? */

    unsigned char   volume_envelope_delay;
    unsigned char   exclusive_class;
    unsigned char   vibrato_delay;

    unsigned char   mod_envelope_rate[6];
    unsigned char   mod_envelope_offset[6];
    unsigned char   mod_envelope_delay;
    unsigned char   chorus_effect;
    unsigned char   reverb_effect;
    short	    resonance;
    short	    cutoff_frequency;
    unsigned char   modEnvToPitch;
    unsigned char   modEnvToFilterFc;
    unsigned char   modLfoToFilterFc;
    unsigned char   keynumToModEnvHold;
    unsigned char   keynumToModEnvDecay;
    unsigned char   keynumToVolEnvHold;
    unsigned char   keynumToVolEnvDecay;
    unsigned char   true_panning;

    short	    lfo_rate;
    unsigned char   lfo_depth;
    char	    aps_parameter;
  };
#endif

#define TRUE	1
#define FALSE	0

#define REGION_IN_GROUP 0
#define REGION_IS_BUSY  1

#define FIRST_SFZ_PARM 11
#define KEY	11
#define HIKEY	12
#define LOKEY	13
#define PITCH_KEYCENTER 14
#define OFFSET	15
#define END	16
#define LOOP_START  17
#define LOOP_END    18
#define HIVEL	19
#define LOVEL	20
#define GROUP	21
#define OFF_BY	22
#define TRIGGER	23
  #define VAL_TRIGGER_ATTACK	0
  #define VAL_TRIGGER_FIRST	1
  #define VAL_TRIGGER_RELEASE	2
  #define VAL_TRIGGER_LEGATO	3
#define LOOP_MODE	24
  #define VAL_LOOP_SUSTAIN	1
#define SW_HIKEY	25
#define SW_LOKEY	26
#define SW_UP		27
#define SW_DOWN		28
#define SW_LAST		29
#define MAX_SFZ_PARM	30

#define AMPEG_RELEASE	1
#define VOLUME		2
#define AMP_RANDOM	3
#define HIRAND		4
#define LORAND		5
#define MAX_FLOAT_PARM	6

#define MAX_SFZ_REGION 2048
#define MAX_SFZ_GROUP 128


static int m;

static int am_in_group = FALSE;
static int am_in_region = FALSE;
static int am_in_group_scope = FALSE;

static int32 default_parm[MAX_SFZ_PARM] = {
		0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* key */	60,
/* hikey */	60,
/* lokey */	60,
/* pitch_keycenter */	60,
/* offset */	0,
/* end */	0,
/* loop_start */	0,
/* loop_end */	0,
/* hivel */	127,
/* lovel */	9,
/* group */	0,
/* off_by */	0,
/* trigger */	0,
/* loop_mode */	0,
/* sw_hikey */	127,
/* sw_lokey */	0,
/* sw_up */	-1,
/* sw_down */	-1,
/* sw_last */	-1
};
static double default_flt_parm[MAX_FLOAT_PARM] = {
		    0,
/* ampeg_release */ 0,
/* volume */	    0,
/* amp_random */    0,
/* hirand */        1,
/* lorand */        0
};

static int32 group_parm[MAX_SFZ_PARM];
static int32 region_parm[MAX_SFZ_PARM];
static double group_flt_parm[MAX_FLOAT_PARM];
static double region_flt_parm[MAX_FLOAT_PARM];
static int32 region[MAX_SFZ_REGION][MAX_SFZ_PARM];
static double region_flt[MAX_SFZ_REGION][MAX_FLOAT_PARM];
static int32 current_region = 0;
static int32 current_group = 0;

static unsigned char *region_left_sample[MAX_SFZ_REGION] = { NULL };
static unsigned char *region_right_sample[MAX_SFZ_REGION] = { NULL };
static int32 region_datasize[MAX_SFZ_REGION];
static int32 region_channels[MAX_SFZ_REGION];
static int32 region_modes[MAX_SFZ_REGION];
static int32 region_samplerate[MAX_SFZ_REGION];
static int32 region_samplesize[MAX_SFZ_REGION];

#ifdef LOADER
#define SFZERR ctl->cmsg (CMSG_ERROR, VERB_NORMAL,
#define SFZNOTE ctl->cmsg (CMSG_INFO, VERB_VERBOSE,
#define SFZDBG ctl->cmsg (CMSG_INFO, VERB_DEBUG,
#define SFZNL
#else
static int32 verbosity=0;
#define SFZERR fprintf(stderr,
#define SFZNOTE if (verbosity) fprintf(stderr,
#define SFZDBG if (verbosity) fprintf(stderr,
#define SFZNL  if (verbosity) fprintf(stderr,"\n");
#endif

#define GROUP_IS_FREE -1

static int32
    group_link[MAX_SFZ_GROUP],
    sample_left_datasize[MAX_SFZ_GROUP],
    sample_right_datasize[MAX_SFZ_GROUP],
    sample_channels[MAX_SFZ_GROUP],
    sample_modes[MAX_SFZ_GROUP],
    sample_samplerate[MAX_SFZ_GROUP],
    sample_samplesize[MAX_SFZ_GROUP];

static unsigned char
    *sample_left_buf[MAX_SFZ_GROUP] = { NULL},
    *sample_right_buf[MAX_SFZ_GROUP] = { NULL};

static int ipn_val(char *text);


#line 1009 "sfz2pat.c"

#define INITIAL 0
#define K 1

/* Special case for "unistd.h", since it is non-ANSI. We include it way
 * down here because we want the user's section 1 to have been scanned first.
 * The user has a chance to override it with an option.
 */
#include <unistd.h>

#ifndef YY_EXTRA_TYPE
#define YY_EXTRA_TYPE void *
#endif

/* Macros after this point can all be overridden by user definitions in
 * section 1.
 */

#ifndef YY_SKIP_YYWRAP
#ifdef __cplusplus
extern "C" int sfzwrap (void );
#else
extern int sfzwrap (void );
#endif
#endif

#ifndef yytext_ptr
static void yy_flex_strncpy (char *,yyconst char *,int );
#endif

#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (yyconst char * );
#endif

#ifndef YY_NO_INPUT

#ifdef __cplusplus
static int yyinput (void );
#else
static int input (void );
#endif

#endif

/* Amount of stuff to slurp up with each read. */
#ifndef YY_READ_BUF_SIZE
#define YY_READ_BUF_SIZE 8192
#endif

/* Copy whatever the last rule matched to the standard output. */
#ifndef ECHO
/* This used to be an fputs(), but since the string might contain NUL's,
 * we now use fwrite().
 */
#define ECHO (void) fwrite( sfztext, sfzleng, 1, sfzout )
#endif

/* Gets input and stuffs it into "buf".  number of characters read, or YY_NULL,
 * is returned in "result".
 */
#ifndef YY_INPUT
#define YY_INPUT(buf,result,max_size) \
	if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
		{ \
		int c = '*'; \
		size_t n; \
		for ( n = 0; n < max_size && \
			     (c = getc( sfzin )) != EOF && c != '\n'; ++n ) \
			buf[n] = (char) c; \
		if ( c == '\n' ) \
			buf[n++] = (char) c; \
		if ( c == EOF && ferror( sfzin ) ) \
			YY_FATAL_ERROR( "input in flex scanner failed" ); \
		result = n; \
		} \
	else \
		{ \
		errno=0; \
		while ( (result = fread(buf, 1, max_size, sfzin))==0 && ferror(sfzin)) \
			{ \
			if( errno != EINTR) \
				{ \
				YY_FATAL_ERROR( "input in flex scanner failed" ); \
				break; \
				} \
			errno=0; \
			clearerr(sfzin); \
			} \
		}\
\

#endif

/* No semi-colon after return; correct usage is to write "yyterminate();" -
 * we don't want an extra ';' after the "return" because that will cause
 * some compilers to complain about unreachable statements.
 */
#ifndef yyterminate
#define yyterminate() return YY_NULL
#endif

/* Number of entries by which start-condition stack grows. */
#ifndef YY_START_STACK_INCR
#define YY_START_STACK_INCR 25
#endif

/* Report a fatal error. */
#ifndef YY_FATAL_ERROR
#define YY_FATAL_ERROR(msg) yy_fatal_error( msg )
#endif

/* end tables serialization structures and prototypes */

/* Default declaration of generated scanner - a define so the user can
 * easily add parameters.
 */
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1

extern int sfzlex (void);

#define YY_DECL int sfzlex (void)
#endif /* !YY_DECL */

/* Code executed at the beginning of each rule, after sfztext and sfzleng
 * have been set up.
 */
#ifndef YY_USER_ACTION
#define YY_USER_ACTION
#endif

/* Code executed at the end of each rule. */
#ifndef YY_BREAK
#define YY_BREAK break;
#endif

#define YY_RULE_SETUP \
	YY_USER_ACTION

/** The main scanner function which does all the work.
 */
YY_DECL
{
	register yy_state_type yy_current_state;
	register char *yy_cp, *yy_bp;
	register int yy_act;
    
#line 324 "./sfz2pat.l"


#line 1160 "sfz2pat.c"

	if ( (yy_init) )
		{
		(yy_init) = 0;

#ifdef YY_USER_INIT
		YY_USER_INIT;
#endif

		if ( ! (yy_start) )
			(yy_start) = 1;	/* first start state */

		if ( ! sfzin )
			sfzin = stdin;

		if ( ! sfzout )
			sfzout = stdout;

		if ( ! YY_CURRENT_BUFFER ) {
			sfzensure_buffer_stack ();
			YY_CURRENT_BUFFER_LVALUE =
				sfz_create_buffer(sfzin,YY_BUF_SIZE );
		}

		sfz_load_buffer_state( );
		}

	while ( 1 )		/* loops until end-of-file is reached */
		{
		yy_cp = (yy_c_buf_p);

		/* Support of sfztext. */
		*yy_cp = (yy_hold_char);

		/* yy_bp points to the position in yy_ch_buf of the start of
		 * the current run.
		 */
		yy_bp = yy_cp;

		yy_current_state = (yy_start);
yy_match:
		do
			{
			register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)];
			if ( yy_accept[yy_current_state] )
				{
				(yy_last_accepting_state) = yy_current_state;
				(yy_last_accepting_cpos) = yy_cp;
				}
			while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
				{
				yy_current_state = (int) yy_def[yy_current_state];
				if ( yy_current_state >= 337 )
					yy_c = yy_meta[(unsigned int) yy_c];
				}
			yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
			++yy_cp;
			}
		while ( yy_base[yy_current_state] != 582 );

yy_find_action:
		yy_act = yy_accept[yy_current_state];
		if ( yy_act == 0 )
			{ /* have to back up */
			yy_cp = (yy_last_accepting_cpos);
			yy_current_state = (yy_last_accepting_state);
			yy_act = yy_accept[yy_current_state];
			}

		YY_DO_BEFORE_ACTION;

do_action:	/* This label is used only to access EOF actions. */

		switch ( yy_act )
	{ /* beginning of action switch */
			case 0: /* must back up */
			/* undo the effects of YY_DO_BEFORE_ACTION */
			*yy_cp = (yy_hold_char);
			yy_cp = (yy_last_accepting_cpos);
			yy_current_state = (yy_last_accepting_state);
			goto yy_find_action;

case 1:
YY_RULE_SETUP
#line 326 "./sfz2pat.l"
;
	YY_BREAK
case 2:
YY_RULE_SETUP
#line 328 "./sfz2pat.l"
{
	int i;
	leave_region();
	leave_group();
	if (!enter_group()) {
		SFZERR
		"Can't start group\n");
		return 1;
	}
	am_in_group_scope = TRUE;
	for (i = FIRST_SFZ_PARM; i < MAX_SFZ_PARM; i++) group_parm[i] = default_parm[i];
	for (i = 0; i < MAX_FLOAT_PARM; i++) group_flt_parm[i] = default_flt_parm[i];
	group_parm[REGION_IN_GROUP] = current_group;
	BEGIN(0);
}
	YY_BREAK
case 3:
YY_RULE_SETUP
#line 343 "./sfz2pat.l"
{
	int i;
	if (!am_in_group) {
		SFZERR
		"Can't start region outside group.\n");
		return 1;
	}
	leave_region();
	if (!enter_region()) {
		SFZERR
		"Can't start region\n");
		return 1;
	}
	am_in_group_scope = FALSE;
	for (i = 0; i < MAX_SFZ_PARM; i++) region_parm[i] = group_parm[i];
	for (i = 0; i < MAX_FLOAT_PARM; i++) region_flt_parm[i] = group_flt_parm[i];
	BEGIN(0);
}
	YY_BREAK
case 4:
YY_RULE_SETUP
#line 361 "./sfz2pat.l"
{
	int i = 7, j;
	unsigned namelen;
	if (sfztext[i] == '"') {
		i++;
		for (j = i; j < sfzleng && sfztext[j] != '"'; j++) ;
	}
	else j = sfzleng;
	namelen = (unsigned)(j - i + 1);
	sfzname = strncpy( (char *)malloc(namelen), sfztext+i, (unsigned)(j-i) );
	sfzname[j-i] = '\0';
	for (i = 0; i < (int)namelen; i++) if (sfzname[i] == '\\') sfzname[i] = '/';
	SFZDBG
	"Sample name is \"%s\"", sfzname);
	SFZNL
	if (read_sample(sfzname)) {
#ifndef LOADER
		fprintf(stderr, "\n");
#endif
		return 0;
	}
	BEGIN(0);
}
	YY_BREAK
case 5:
YY_RULE_SETUP
#line 384 "./sfz2pat.l"
{
	m = atoi(sfztext+6);
	if (am_in_group_scope) group_parm[HIVEL] = m;
	else region_parm[HIVEL] = m;
	BEGIN(0);
}
	YY_BREAK
case 6:
YY_RULE_SETUP
#line 390 "./sfz2pat.l"
{
	m = atoi(sfztext+6);
	if (am_in_group_scope) group_parm[LOVEL] = m;
	else region_parm[LOVEL] = m;
	BEGIN(0);
}
	YY_BREAK
case 7:
YY_RULE_SETUP
#line 396 "./sfz2pat.l"
{
	m = atoi(sfztext+6);
	if (am_in_group_scope) group_parm[GROUP] = m;
	else region_parm[GROUP] = m;
	BEGIN(0);
}
	YY_BREAK
case 8:
YY_RULE_SETUP
#line 402 "./sfz2pat.l"
{
	m = atoi(sfztext+7);
	if (am_in_group_scope) group_parm[OFF_BY] = m;
	else region_parm[OFF_BY] = m;
	BEGIN(0);
}
	YY_BREAK
case 9:
YY_RULE_SETUP
#line 408 "./sfz2pat.l"
{
	if (am_in_group_scope) group_parm[TRIGGER] = VAL_TRIGGER_ATTACK;
	else region_parm[TRIGGER] = VAL_TRIGGER_ATTACK;
	BEGIN(0);
}
	YY_BREAK
case 10:
YY_RULE_SETUP
#line 413 "./sfz2pat.l"
{
	if (am_in_group_scope) group_parm[TRIGGER] = VAL_TRIGGER_RELEASE;
	else region_parm[TRIGGER] = VAL_TRIGGER_RELEASE;
	BEGIN(0);
}
	YY_BREAK
case 11:
YY_RULE_SETUP
#line 418 "./sfz2pat.l"
{
	if (am_in_group_scope) group_parm[TRIGGER] = VAL_TRIGGER_LEGATO;
	else region_parm[TRIGGER] = VAL_TRIGGER_LEGATO;
	BEGIN(0);
}
	YY_BREAK
case 12:
YY_RULE_SETUP
#line 423 "./sfz2pat.l"
{
	if (am_in_group_scope) group_parm[TRIGGER] = VAL_TRIGGER_FIRST;
	else region_parm[TRIGGER] = VAL_TRIGGER_FIRST;
	BEGIN(0);
}
	YY_BREAK
case 13:
YY_RULE_SETUP
#line 428 "./sfz2pat.l"
{
	if (am_in_group_scope) group_parm[LOOP_MODE] = VAL_LOOP_SUSTAIN;
	else region_parm[LOOP_MODE] = VAL_LOOP_SUSTAIN;
	BEGIN(0);
}
	YY_BREAK
case 14:
YY_RULE_SETUP
#line 433 "./sfz2pat.l"
{
	double d;
	d = atof(sfztext+14);
	if (am_in_group_scope) group_flt_parm[AMPEG_RELEASE] = d;
	else region_flt_parm[AMPEG_RELEASE] = d;
	BEGIN(0);
}
	YY_BREAK
case 15:
YY_RULE_SETUP
#line 440 "./sfz2pat.l"
{
	double d;
	d = atof(sfztext+7);
	if (am_in_group_scope) group_flt_parm[VOLUME] = d;
	else region_flt_parm[VOLUME] = d;
	BEGIN(0);
}
	YY_BREAK
case 16:
YY_RULE_SETUP
#line 447 "./sfz2pat.l"
{
	double d;
	d = atof(sfztext+11);
	if (am_in_group_scope) group_flt_parm[AMP_RANDOM] = d;
	else region_flt_parm[AMP_RANDOM] = d;
	BEGIN(0);
}
	YY_BREAK
case 17:
YY_RULE_SETUP
#line 454 "./sfz2pat.l"
{
	double d;
	d = atof(sfztext+7);
	if (am_in_group_scope) group_flt_parm[HIRAND] = d;
	else region_flt_parm[HIRAND] = d;
	BEGIN(0);
}
	YY_BREAK
case 18:
YY_RULE_SETUP
#line 461 "./sfz2pat.l"
{
	double d;
	d = atof(sfztext+7);
	if (am_in_group_scope) group_flt_parm[LORAND] = d;
	else region_flt_parm[LORAND] = d;
	BEGIN(0);
}
	YY_BREAK
case 19:
YY_RULE_SETUP
#line 468 "./sfz2pat.l"
{
	m = atoi(sfztext+6);
	if (am_in_group_scope) group_parm[HIKEY] = m;
	else region_parm[HIKEY] = m;
	BEGIN(0);
}
	YY_BREAK
case 20:
YY_RULE_SETUP
#line 474 "./sfz2pat.l"
{
	m = atoi(sfztext+6);
	if (am_in_group_scope) group_parm[LOKEY] = m;
	else region_parm[LOKEY] = m;
	BEGIN(0);
}
	YY_BREAK
case 21:
YY_RULE_SETUP
#line 480 "./sfz2pat.l"
{
	m = atoi(sfztext+16);
	if (am_in_group_scope) group_parm[PITCH_KEYCENTER] = m;
	else region_parm[PITCH_KEYCENTER] = m;
	BEGIN(0);
}
	YY_BREAK
case 22:
YY_RULE_SETUP
#line 486 "./sfz2pat.l"
{
	m = atoi(sfztext+4);
	if (am_in_group_scope) group_parm[KEY] =
		group_parm[HIKEY] = 
		group_parm[LOKEY] = 
		group_parm[PITCH_KEYCENTER] = m;
	else region_parm[KEY] =
		region_parm[HIKEY] = 
		region_parm[LOKEY] = 
		region_parm[PITCH_KEYCENTER] = m;
	BEGIN(0);
}
	YY_BREAK
case 23:
YY_RULE_SETUP
#line 498 "./sfz2pat.l"
{
	m = ipn_val(sfztext);
	if (am_in_group_scope) group_parm[KEY] =
		group_parm[HIKEY] = 
		group_parm[LOKEY] = 
		group_parm[PITCH_KEYCENTER] = m;
	else region_parm[KEY] =
		region_parm[HIKEY] = 
		region_parm[LOKEY] = 
		region_parm[PITCH_KEYCENTER] = m;
	BEGIN(0);
/*
C4 is middle C = midi note 60

-1 00 01 02 03 04 05 06 07 08 09 10 11
0  12 13 14 15 16 17 18 19 20 21 22 23
1  24 25 26 27 28 29 30 31 32 33 34 35
2  36 37 38 39 40 41 42 43 44 45 46 47
3  48 49 50 51 52 53 54 55 56 57 58 59
4  60 61 62 63 64 65 66 67 68 69 70 71
   C  C# D  D# E  F  F# G  G# A  A# B
5  72 73 74 75 76 77 78 79 80 81 82 83
6  84 85 86 87 88 89 90 91 92 93 94 95
7  96 97 98 99 00 01 02 03 04 05 06 07
8  08 09 10 11 12 13 14 15 16 17 18 19
9  20 21 22 23 24 25 26 27
*/
}
	YY_BREAK
case 24:
YY_RULE_SETUP
#line 526 "./sfz2pat.l"
{
	m = ipn_val(sfztext);
	if (am_in_group_scope) group_parm[HIKEY] = m;
	else region_parm[HIKEY] = m;
	BEGIN(0);
}
	YY_BREAK
case 25:
YY_RULE_SETUP
#line 532 "./sfz2pat.l"
{
	m = ipn_val(sfztext);
	if (am_in_group_scope) group_parm[LOKEY] = m;
	else region_parm[LOKEY] = m;
	BEGIN(0);
}
	YY_BREAK
case 26:
YY_RULE_SETUP
#line 538 "./sfz2pat.l"
{
	m = ipn_val(sfztext);
	if (am_in_group_scope) group_parm[PITCH_KEYCENTER] = m;
	else region_parm[PITCH_KEYCENTER] = m;
	BEGIN(0);
}
	YY_BREAK
case 27:
YY_RULE_SETUP
#line 544 "./sfz2pat.l"
{
	m = atoi(sfztext+9);
	if (am_in_group_scope) group_parm[SW_HIKEY] = m;
	else region_parm[SW_HIKEY] = m;
	BEGIN(0);
}
	YY_BREAK
case 28:
YY_RULE_SETUP
#line 550 "./sfz2pat.l"
{
	m = ipn_val(sfztext);
	if (am_in_group_scope) group_parm[SW_HIKEY] = m;
	else region_parm[SW_HIKEY] = m;
	BEGIN(0);
}
	YY_BREAK
case 29:
YY_RULE_SETUP
#line 556 "./sfz2pat.l"
{
	m = atoi(sfztext+9);
	if (am_in_group_scope) group_parm[SW_LOKEY] = m;
	else region_parm[SW_LOKEY] = m;
	BEGIN(0);
}
	YY_BREAK
case 30:
YY_RULE_SETUP
#line 562 "./sfz2pat.l"
{
	m = ipn_val(sfztext);
	if (am_in_group_scope) group_parm[SW_LOKEY] = m;
	else region_parm[SW_LOKEY] = m;
	BEGIN(0);
}
	YY_BREAK
case 31:
YY_RULE_SETUP
#line 568 "./sfz2pat.l"
{
	m = atoi(sfztext+6);
	if (am_in_group_scope) group_parm[SW_UP] = m;
	else region_parm[SW_UP] = m;
	BEGIN(0);
}
	YY_BREAK
case 32:
YY_RULE_SETUP
#line 574 "./sfz2pat.l"
{
	m = ipn_val(sfztext);
	if (am_in_group_scope) group_parm[SW_UP] = m;
	else region_parm[SW_UP] = m;
	BEGIN(0);
}
	YY_BREAK
case 33:
YY_RULE_SETUP
#line 580 "./sfz2pat.l"
{
	m = atoi(sfztext+8);
	if (am_in_group_scope) group_parm[SW_DOWN] = m;
	else region_parm[SW_DOWN] = m;
	BEGIN(0);
}
	YY_BREAK
case 34:
YY_RULE_SETUP
#line 586 "./sfz2pat.l"
{
	m = ipn_val(sfztext);
	if (am_in_group_scope) group_parm[SW_DOWN] = m;
	else region_parm[SW_DOWN] = m;
	BEGIN(0);
}
	YY_BREAK
case 35:
YY_RULE_SETUP
#line 592 "./sfz2pat.l"
{
	m = atoi(sfztext+8);
	if (am_in_group_scope) group_parm[SW_LAST] = m;
	else region_parm[SW_LAST] = m;
	BEGIN(0);
}
	YY_BREAK
case 36:
YY_RULE_SETUP
#line 598 "./sfz2pat.l"
{
	m = ipn_val(sfztext);
	if (am_in_group_scope) group_parm[SW_LAST] = m;
	else region_parm[SW_LAST] = m;
	BEGIN(0);
}
	YY_BREAK
case 37:
YY_RULE_SETUP
#line 605 "./sfz2pat.l"
{
	m = atoi(sfztext+7);
	if (am_in_group_scope) group_parm[OFFSET] = m;
	else region_parm[OFFSET] = m;
	BEGIN(0);
}
	YY_BREAK
case 38:
YY_RULE_SETUP
#line 612 "./sfz2pat.l"
{
	m = atoi(sfztext+4);
	if (am_in_group_scope) group_parm[END] = m;
	else region_parm[END] = m;
	BEGIN(0);
}
	YY_BREAK
case 39:
YY_RULE_SETUP
#line 619 "./sfz2pat.l"
{
	m = atoi(sfztext+11);
	if (am_in_group_scope) group_parm[LOOP_START] = m;
	else region_parm[LOOP_START] = m;
	BEGIN(0);
}
	YY_BREAK
case 40:
YY_RULE_SETUP
#line 626 "./sfz2pat.l"
{
	m = atoi(sfztext+9);
	if (am_in_group_scope) group_parm[LOOP_END] = m;
	else region_parm[LOOP_END] = m;
	BEGIN(0);
}
	YY_BREAK
case 41:
YY_RULE_SETUP
#line 633 "./sfz2pat.l"
{
	char *fname;
	int i = 0;
	FILE *save_yyin;

	while (isspace(sfztext[i])) i++;
	i += 6;
	while (isspace(sfztext[i])) i++;


        if ( include_stack_ptr >= MAX_INCLUDE_DEPTH ) {
		SFZERR
		 "Probable source loop in configuration files\n");
		return (-1);
        }
        include_stack[include_stack_ptr++] =
                YY_CURRENT_BUFFER;

	fname = strcpy( (char *)malloc(strlen(sfztext+i)+1), sfztext+i );
	if (this_fname[include_stack_ptr]) free(this_fname[include_stack_ptr]);
	this_fname[include_stack_ptr] = strdup(fname);

	save_yyin = sfzin;
	sfzin = NULL;

#ifdef LOADER
	sfzin = open_file (fname, 1, OF_NORMAL, 0);
#else
	sfzin = fopen(fname, "r");
#endif
	if (sfzin == NULL) {
		SFZERR
		 "Source file %s not found\n", fname);
		include_stack_ptr--;
	}

	if (sfzin == NULL) sfzin = save_yyin;
	else {
	    rcf_count++;
            sfz_switch_to_buffer(sfz_create_buffer(sfzin,YY_BUF_SIZE ) );
	}
	BEGIN(0);
}  
	YY_BREAK
case YY_STATE_EOF(INITIAL):
case YY_STATE_EOF(K):
#line 678 "./sfz2pat.l"
{
        if ( --include_stack_ptr < 0 ) {
                yyterminate();
        }
        else {
		if (sfzin) fclose(sfzin);
                sfz_delete_buffer(YY_CURRENT_BUFFER );
		rcf_count--;
                sfz_switch_to_buffer(include_stack[include_stack_ptr] );
        }
	BEGIN(K);
}
	YY_BREAK
case 42:
YY_RULE_SETUP
#line 692 "./sfz2pat.l"
{
	BEGIN(K);
}
	YY_BREAK
case 43:
/* rule 43 can match eol */
YY_RULE_SETUP
#line 696 "./sfz2pat.l"
{
	this_line[include_stack_ptr]++;
	BEGIN(K);
}
	YY_BREAK
case 44:
YY_RULE_SETUP
#line 700 "./sfz2pat.l"
;
	YY_BREAK
case 45:
YY_RULE_SETUP
#line 702 "./sfz2pat.l"
ECHO;
	YY_BREAK
#line 1793 "sfz2pat.c"

	case YY_END_OF_BUFFER:
		{
		/* Amount of text matched not including the EOB char. */
		int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1;

		/* Undo the effects of YY_DO_BEFORE_ACTION. */
		*yy_cp = (yy_hold_char);
		YY_RESTORE_YY_MORE_OFFSET

		if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
			{
			/* We're scanning a new file or input source.  It's
			 * possible that this happened because the user
			 * just pointed sfzin at a new source and called
			 * sfzlex().  If so, then we have to assure
			 * consistency between YY_CURRENT_BUFFER and our
			 * globals.  Here is the right place to do so, because
			 * this is the first action (other than possibly a
			 * back-up) that will match for the new input source.
			 */
			(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
			YY_CURRENT_BUFFER_LVALUE->yy_input_file = sfzin;
			YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
			}

		/* Note that here we test for yy_c_buf_p "<=" to the position
		 * of the first EOB in the buffer, since yy_c_buf_p will
		 * already have been incremented past the NUL character
		 * (since all states make transitions on EOB to the
		 * end-of-buffer state).  Contrast this with the test
		 * in input().
		 */
		if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
			{ /* This was really a NUL. */
			yy_state_type yy_next_state;

			(yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text;

			yy_current_state = yy_get_previous_state(  );

			/* Okay, we're now positioned to make the NUL
			 * transition.  We couldn't have
			 * yy_get_previous_state() go ahead and do it
			 * for us because it doesn't know how to deal
			 * with the possibility of jamming (and we don't
			 * want to build jamming into it because then it
			 * will run more slowly).
			 */

			yy_next_state = yy_try_NUL_trans( yy_current_state );

			yy_bp = (yytext_ptr) + YY_MORE_ADJ;

			if ( yy_next_state )
				{
				/* Consume the NUL. */
				yy_cp = ++(yy_c_buf_p);
				yy_current_state = yy_next_state;
				goto yy_match;
				}

			else
				{
				yy_cp = (yy_c_buf_p);
				goto yy_find_action;
				}
			}

		else switch ( yy_get_next_buffer(  ) )
			{
			case EOB_ACT_END_OF_FILE:
				{
				(yy_did_buffer_switch_on_eof) = 0;

				if ( sfzwrap( ) )
					{
					/* Note: because we've taken care in
					 * yy_get_next_buffer() to have set up
					 * sfztext, we can now set up
					 * yy_c_buf_p so that if some total
					 * hoser (like flex itself) wants to
					 * call the scanner after we return the
					 * YY_NULL, it'll still work - another
					 * YY_NULL will get returned.
					 */
					(yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ;

					yy_act = YY_STATE_EOF(YY_START);
					goto do_action;
					}

				else
					{
					if ( ! (yy_did_buffer_switch_on_eof) )
						YY_NEW_FILE;
					}
				break;
				}

			case EOB_ACT_CONTINUE_SCAN:
				(yy_c_buf_p) =
					(yytext_ptr) + yy_amount_of_matched_text;

				yy_current_state = yy_get_previous_state(  );

				yy_cp = (yy_c_buf_p);
				yy_bp = (yytext_ptr) + YY_MORE_ADJ;
				goto yy_match;

			case EOB_ACT_LAST_MATCH:
				(yy_c_buf_p) =
				&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)];

				yy_current_state = yy_get_previous_state(  );

				yy_cp = (yy_c_buf_p);
				yy_bp = (yytext_ptr) + YY_MORE_ADJ;
				goto yy_find_action;
			}
		break;
		}

	default:
		YY_FATAL_ERROR(
			"fatal flex scanner internal error--no action found" );
	} /* end of action switch */
		} /* end of scanning one token */
} /* end of sfzlex */

/* yy_get_next_buffer - try to read in a new buffer
 *
 * Returns a code representing an action:
 *	EOB_ACT_LAST_MATCH -
 *	EOB_ACT_CONTINUE_SCAN - continue scanning from current position
 *	EOB_ACT_END_OF_FILE - end of file
 */
static int yy_get_next_buffer (void)
{
    	register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
	register char *source = (yytext_ptr);
	register int number_to_move, i;
	int ret_val;

	if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] )
		YY_FATAL_ERROR(
		"fatal flex scanner internal error--end of buffer missed" );

	if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
		{ /* Don't try to fill the buffer, so this is an EOF. */
		if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 )
			{
			/* We matched a single character, the EOB, so
			 * treat this as a final EOF.
			 */
			return EOB_ACT_END_OF_FILE;
			}

		else
			{
			/* We matched some text prior to the EOB, first
			 * process it.
			 */
			return EOB_ACT_LAST_MATCH;
			}
		}

	/* Try to read more data. */

	/* First move last chars to start of buffer. */
	number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr)) - 1;

	for ( i = 0; i < number_to_move; ++i )
		*(dest++) = *(source++);

	if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
		/* don't do the read, it's not guaranteed to return an EOF,
		 * just force an EOF
		 */
		YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0;

	else
		{
			size_t num_to_read =
			YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;

		while ( num_to_read <= 0 )
			{ /* Not enough room in the buffer - grow it. */

			/* just a shorter name for the current buffer */
			YY_BUFFER_STATE b = YY_CURRENT_BUFFER;

			int yy_c_buf_p_offset =
				(int) ((yy_c_buf_p) - b->yy_ch_buf);

			if ( b->yy_is_our_buffer )
				{
				int new_size = b->yy_buf_size * 2;

				if ( new_size <= 0 )
					b->yy_buf_size += b->yy_buf_size / 8;
				else
					b->yy_buf_size *= 2;

				b->yy_ch_buf = (char *)
					/* Include room in for 2 EOB chars. */
					sfzrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2  );
				}
			else
				/* Can't grow it, we don't own it. */
				b->yy_ch_buf = 0;

			if ( ! b->yy_ch_buf )
				YY_FATAL_ERROR(
				"fatal error - scanner input buffer overflow" );

			(yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset];

			num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size -
						number_to_move - 1;

			}

		if ( num_to_read > YY_READ_BUF_SIZE )
			num_to_read = YY_READ_BUF_SIZE;

		/* Read in more data. */
		YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
			(yy_n_chars), num_to_read );

		YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
		}

	if ( (yy_n_chars) == 0 )
		{
		if ( number_to_move == YY_MORE_ADJ )
			{
			ret_val = EOB_ACT_END_OF_FILE;
			sfzrestart(sfzin  );
			}

		else
			{
			ret_val = EOB_ACT_LAST_MATCH;
			YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
				YY_BUFFER_EOF_PENDING;
			}
		}

	else
		ret_val = EOB_ACT_CONTINUE_SCAN;

	(yy_n_chars) += number_to_move;
	YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR;
	YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR;

	(yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];

	return ret_val;
}

/* yy_get_previous_state - get the state just before the EOB char was reached */

    static yy_state_type yy_get_previous_state (void)
{
	register yy_state_type yy_current_state;
	register char *yy_cp;
    
	yy_current_state = (yy_start);

	for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp )
		{
		register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
		if ( yy_accept[yy_current_state] )
			{
			(yy_last_accepting_state) = yy_current_state;
			(yy_last_accepting_cpos) = yy_cp;
			}
		while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
			{
			yy_current_state = (int) yy_def[yy_current_state];
			if ( yy_current_state >= 337 )
				yy_c = yy_meta[(unsigned int) yy_c];
			}
		yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
		}

	return yy_current_state;
}

/* yy_try_NUL_trans - try to make a transition on the NUL character
 *
 * synopsis
 *	next_state = yy_try_NUL_trans( current_state );
 */
    static yy_state_type yy_try_NUL_trans  (yy_state_type yy_current_state )
{
	register int yy_is_jam;
    	register char *yy_cp = (yy_c_buf_p);

	register YY_CHAR yy_c = 1;
	if ( yy_accept[yy_current_state] )
		{
		(yy_last_accepting_state) = yy_current_state;
		(yy_last_accepting_cpos) = yy_cp;
		}
	while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
		{
		yy_current_state = (int) yy_def[yy_current_state];
		if ( yy_current_state >= 337 )
			yy_c = yy_meta[(unsigned int) yy_c];
		}
	yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
	yy_is_jam = (yy_current_state == 336);

	return yy_is_jam ? 0 : yy_current_state;
}

#ifndef YY_NO_INPUT
#ifdef __cplusplus
    static int yyinput (void)
#else
    static int input  (void)
#endif

{
	int c;
    
	*(yy_c_buf_p) = (yy_hold_char);

	if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR )
		{
		/* yy_c_buf_p now points to the character we want to return.
		 * If this occurs *before* the EOB characters, then it's a
		 * valid NUL; if not, then we've hit the end of the buffer.
		 */
		if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
			/* This was really a NUL. */
			*(yy_c_buf_p) = '\0';

		else
			{ /* need more input */
			int offset = (yy_c_buf_p) - (yytext_ptr);
			++(yy_c_buf_p);

			switch ( yy_get_next_buffer(  ) )
				{
				case EOB_ACT_LAST_MATCH:
					/* This happens because yy_g_n_b()
					 * sees that we've accumulated a
					 * token and flags that we need to
					 * try matching the token before
					 * proceeding.  But for input(),
					 * there's no matching to consider.
					 * So convert the EOB_ACT_LAST_MATCH
					 * to EOB_ACT_END_OF_FILE.
					 */

					/* Reset buffer status. */
					sfzrestart(sfzin );

					/*FALLTHROUGH*/

				case EOB_ACT_END_OF_FILE:
					{
					if ( sfzwrap( ) )
						return EOF;

					if ( ! (yy_did_buffer_switch_on_eof) )
						YY_NEW_FILE;
#ifdef __cplusplus
					return yyinput();
#else
					return input();
#endif
					}

				case EOB_ACT_CONTINUE_SCAN:
					(yy_c_buf_p) = (yytext_ptr) + offset;
					break;
				}
			}
		}

	c = *(unsigned char *) (yy_c_buf_p);	/* cast for 8-bit char's */
	*(yy_c_buf_p) = '\0';	/* preserve sfztext */
	(yy_hold_char) = *++(yy_c_buf_p);

	return c;
}
#endif	/* ifndef YY_NO_INPUT */

/** Immediately switch to a different input stream.
 * @param input_file A readable stream.
 * 
 * @note This function does not reset the start condition to @c INITIAL .
 */
    void sfzrestart  (FILE * input_file )
{
    
	if ( ! YY_CURRENT_BUFFER ){
        sfzensure_buffer_stack ();
		YY_CURRENT_BUFFER_LVALUE =
            sfz_create_buffer(sfzin,YY_BUF_SIZE );
	}

	sfz_init_buffer(YY_CURRENT_BUFFER,input_file );
	sfz_load_buffer_state( );
}

/** Switch to a different input buffer.
 * @param new_buffer The new input buffer.
 * 
 */
    void sfz_switch_to_buffer  (YY_BUFFER_STATE  new_buffer )
{
    
	/* TODO. We should be able to replace this entire function body
	 * with
	 *		sfzpop_buffer_state();
	 *		sfzpush_buffer_state(new_buffer);
     */
	sfzensure_buffer_stack ();
	if ( YY_CURRENT_BUFFER == new_buffer )
		return;

	if ( YY_CURRENT_BUFFER )
		{
		/* Flush out information for old buffer. */
		*(yy_c_buf_p) = (yy_hold_char);
		YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
		YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
		}

	YY_CURRENT_BUFFER_LVALUE = new_buffer;
	sfz_load_buffer_state( );

	/* We don't actually know whether we did this switch during
	 * EOF (sfzwrap()) processing, but the only time this flag
	 * is looked at is after sfzwrap() is called, so it's safe
	 * to go ahead and always set it.
	 */
	(yy_did_buffer_switch_on_eof) = 1;
}

static void sfz_load_buffer_state  (void)
{
    	(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
	(yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
	sfzin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
	(yy_hold_char) = *(yy_c_buf_p);
}

/** Allocate and initialize an input buffer state.
 * @param file A readable stream.
 * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE.
 * 
 * @return the allocated buffer state.
 */
    YY_BUFFER_STATE sfz_create_buffer  (FILE * file, int  size )
{
	YY_BUFFER_STATE b;
    
	b = (YY_BUFFER_STATE) sfzalloc(sizeof( struct yy_buffer_state )  );
	if ( ! b )
		YY_FATAL_ERROR( "out of dynamic memory in sfz_create_buffer()" );

	b->yy_buf_size = size;

	/* yy_ch_buf has to be 2 characters longer than the size given because
	 * we need to put in 2 end-of-buffer characters.
	 */
	b->yy_ch_buf = (char *) sfzalloc(b->yy_buf_size + 2  );
	if ( ! b->yy_ch_buf )
		YY_FATAL_ERROR( "out of dynamic memory in sfz_create_buffer()" );

	b->yy_is_our_buffer = 1;

	sfz_init_buffer(b,file );

	return b;
}

/** Destroy the buffer.
 * @param b a buffer created with sfz_create_buffer()
 * 
 */
    void sfz_delete_buffer (YY_BUFFER_STATE  b )
{
    
	if ( ! b )
		return;

	if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
		YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;

	if ( b->yy_is_our_buffer )
		sfzfree((void *) b->yy_ch_buf  );

	sfzfree((void *) b  );
}

#ifndef __cplusplus
extern int isatty (int );
#endif /* __cplusplus */
    
/* Initializes or reinitializes a buffer.
 * This function is sometimes called more than once on the same buffer,
 * such as during a sfzrestart() or at EOF.
 */
    static void sfz_init_buffer  (YY_BUFFER_STATE  b, FILE * file )

{
	int oerrno = errno;
    
	sfz_flush_buffer(b );

	b->yy_input_file = file;
	b->yy_fill_buffer = 1;

    /* If b is the current buffer, then sfz_init_buffer was _probably_
     * called from sfzrestart() or through yy_get_next_buffer.
     * In that case, we don't want to reset the lineno or column.
     */
    if (b != YY_CURRENT_BUFFER){
        b->yy_bs_lineno = 1;
        b->yy_bs_column = 0;
    }

        b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0;
    
	errno = oerrno;
}

/** Discard all buffered characters. On the next scan, YY_INPUT will be called.
 * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER.
 * 
 */
    void sfz_flush_buffer (YY_BUFFER_STATE  b )
{
    	if ( ! b )
		return;

	b->yy_n_chars = 0;

	/* We always need two end-of-buffer characters.  The first causes
	 * a transition to the end-of-buffer state.  The second causes
	 * a jam in that state.
	 */
	b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
	b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;

	b->yy_buf_pos = &b->yy_ch_buf[0];

	b->yy_at_bol = 1;
	b->yy_buffer_status = YY_BUFFER_NEW;

	if ( b == YY_CURRENT_BUFFER )
		sfz_load_buffer_state( );
}

/** Pushes the new state onto the stack. The new state becomes
 *  the current state. This function will allocate the stack
 *  if necessary.
 *  @param new_buffer The new state.
 *  
 */
void sfzpush_buffer_state (YY_BUFFER_STATE new_buffer )
{
    	if (new_buffer == NULL)
		return;

	sfzensure_buffer_stack();

	/* This block is copied from sfz_switch_to_buffer. */
	if ( YY_CURRENT_BUFFER )
		{
		/* Flush out information for old buffer. */
		*(yy_c_buf_p) = (yy_hold_char);
		YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
		YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
		}

	/* Only push if top exists. Otherwise, replace top. */
	if (YY_CURRENT_BUFFER)
		(yy_buffer_stack_top)++;
	YY_CURRENT_BUFFER_LVALUE = new_buffer;

	/* copied from sfz_switch_to_buffer. */
	sfz_load_buffer_state( );
	(yy_did_buffer_switch_on_eof) = 1;
}

/** Removes and deletes the top of the stack, if present.
 *  The next element becomes the new top.
 *  
 */
void sfzpop_buffer_state (void)
{
    	if (!YY_CURRENT_BUFFER)
		return;

	sfz_delete_buffer(YY_CURRENT_BUFFER );
	YY_CURRENT_BUFFER_LVALUE = NULL;
	if ((yy_buffer_stack_top) > 0)
		--(yy_buffer_stack_top);

	if (YY_CURRENT_BUFFER) {
		sfz_load_buffer_state( );
		(yy_did_buffer_switch_on_eof) = 1;
	}
}

/* Allocates the stack if it does not exist.
 *  Guarantees space for at least one push.
 */
static void sfzensure_buffer_stack (void)
{
	int num_to_alloc;
    
	if (!(yy_buffer_stack)) {

		/* First allocation is just for 2 elements, since we don't know if this
		 * scanner will even need a stack. We use 2 instead of 1 to avoid an
		 * immediate realloc on the next call.
         */
		num_to_alloc = 1;
		(yy_buffer_stack) = (struct yy_buffer_state**)sfzalloc
								(num_to_alloc * sizeof(struct yy_buffer_state*)
								);
		
		memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*));
				
		(yy_buffer_stack_max) = num_to_alloc;
		(yy_buffer_stack_top) = 0;
		return;
	}

	if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){

		/* Increase the buffer to prepare for a possible push. */
		int grow_size = 8 /* arbitrary grow size */;

		num_to_alloc = (yy_buffer_stack_max) + grow_size;
		(yy_buffer_stack) = (struct yy_buffer_state**)sfzrealloc
								((yy_buffer_stack),
								num_to_alloc * sizeof(struct yy_buffer_state*)
								);

		/* zero only the new slots.*/
		memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*));
		(yy_buffer_stack_max) = num_to_alloc;
	}
}

/** Setup the input buffer state to scan directly from a user-specified character buffer.
 * @param base the character buffer
 * @param size the size in bytes of the character buffer
 * 
 * @return the newly allocated buffer state object. 
 */
YY_BUFFER_STATE sfz_scan_buffer  (char * base, yy_size_t  size )
{
	YY_BUFFER_STATE b;
    
	if ( size < 2 ||
	     base[size-2] != YY_END_OF_BUFFER_CHAR ||
	     base[size-1] != YY_END_OF_BUFFER_CHAR )
		/* They forgot to leave room for the EOB's. */
		return 0;

	b = (YY_BUFFER_STATE) sfzalloc(sizeof( struct yy_buffer_state )  );
	if ( ! b )
		YY_FATAL_ERROR( "out of dynamic memory in sfz_scan_buffer()" );

	b->yy_buf_size = size - 2;	/* "- 2" to take care of EOB's */
	b->yy_buf_pos = b->yy_ch_buf = base;
	b->yy_is_our_buffer = 0;
	b->yy_input_file = 0;
	b->yy_n_chars = b->yy_buf_size;
	b->yy_is_interactive = 0;
	b->yy_at_bol = 1;
	b->yy_fill_buffer = 0;
	b->yy_buffer_status = YY_BUFFER_NEW;

	sfz_switch_to_buffer(b  );

	return b;
}

/** Setup the input buffer state to scan a string. The next call to sfzlex() will
 * scan from a @e copy of @a str.
 * @param str a NUL-terminated string to scan
 * 
 * @return the newly allocated buffer state object.
 * @note If you want to scan bytes that may contain NUL values, then use
 *       sfz_scan_bytes() instead.
 */
YY_BUFFER_STATE sfz_scan_string (yyconst char * str )
{
    
	return sfz_scan_bytes(str,strlen(str) );
}

/** Setup the input buffer state to scan the given bytes. The next call to sfzlex() will
 * scan from a @e copy of @a bytes.
 * @param bytes the byte buffer to scan
 * @param len the number of bytes in the buffer pointed to by @a bytes.
 * 
 * @return the newly allocated buffer state object.
 */
YY_BUFFER_STATE sfz_scan_bytes  (yyconst char * bytes, int  len )
{
	YY_BUFFER_STATE b;
	char *buf;
	yy_size_t n;
	int i;
    
	/* Get memory for full buffer, including space for trailing EOB's. */
	n = len + 2;
	buf = (char *) sfzalloc(n  );
	if ( ! buf )
		YY_FATAL_ERROR( "out of dynamic memory in sfz_scan_bytes()" );

	for ( i = 0; i < len; ++i )
		buf[i] = bytes[i];

	buf[len] = buf[len+1] = YY_END_OF_BUFFER_CHAR;

	b = sfz_scan_buffer(buf,n );
	if ( ! b )
		YY_FATAL_ERROR( "bad buffer in sfz_scan_bytes()" );

	/* It's okay to grow etc. this buffer, and we should throw it
	 * away when we're done.
	 */
	b->yy_is_our_buffer = 1;

	return b;
}

#ifndef YY_EXIT_FAILURE
#define YY_EXIT_FAILURE 2
#endif

static void yy_fatal_error (yyconst char* msg )
{
    	(void) fprintf( stderr, "%s\n", msg );
	exit( YY_EXIT_FAILURE );
}

/* Redefine yyless() so it works in section 3 code. */

#undef yyless
#define yyless(n) \
	do \
		{ \
		/* Undo effects of setting up sfztext. */ \
        int yyless_macro_arg = (n); \
        YY_LESS_LINENO(yyless_macro_arg);\
		sfztext[sfzleng] = (yy_hold_char); \
		(yy_c_buf_p) = sfztext + yyless_macro_arg; \
		(yy_hold_char) = *(yy_c_buf_p); \
		*(yy_c_buf_p) = '\0'; \
		sfzleng = yyless_macro_arg; \
		} \
	while ( 0 )

/* Accessor  methods (get/set functions) to struct members. */

/** Get the current line number.
 * 
 */
int sfzget_lineno  (void)
{
        
    return sfzlineno;
}

/** Get the input stream.
 * 
 */
FILE *sfzget_in  (void)
{
        return sfzin;
}

/** Get the output stream.
 * 
 */
FILE *sfzget_out  (void)
{
        return sfzout;
}

/** Get the length of the current token.
 * 
 */
int sfzget_leng  (void)
{
        return sfzleng;
}

/** Get the current token.
 * 
 */

char *sfzget_text  (void)
{
        return sfztext;
}

/** Set the current line number.
 * @param line_number
 * 
 */
void sfzset_lineno (int  line_number )
{
    
    sfzlineno = line_number;
}

/** Set the input stream. This does not discard the current
 * input buffer.
 * @param in_str A readable stream.
 * 
 * @see sfz_switch_to_buffer
 */
void sfzset_in (FILE *  in_str )
{
        sfzin = in_str ;
}

void sfzset_out (FILE *  out_str )
{
        sfzout = out_str ;
}

int sfzget_debug  (void)
{
        return sfz_flex_debug;
}

void sfzset_debug (int  bdebug )
{
        sfz_flex_debug = bdebug ;
}

/* sfzlex_destroy is for both reentrant and non-reentrant scanners. */
int sfzlex_destroy  (void)
{
    
    /* Pop the buffer stack, destroying each element. */
	while(YY_CURRENT_BUFFER){
		sfz_delete_buffer(YY_CURRENT_BUFFER  );
		YY_CURRENT_BUFFER_LVALUE = NULL;
		sfzpop_buffer_state();
	}

	/* Destroy the stack itself. */
	sfzfree((yy_buffer_stack) );
	(yy_buffer_stack) = NULL;

    return 0;
}

/*
 * Internal utility routines.
 */

#ifndef yytext_ptr
static void yy_flex_strncpy (char* s1, yyconst char * s2, int n )
{
	register int i;
    	for ( i = 0; i < n; ++i )
		s1[i] = s2[i];
}
#endif

#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (yyconst char * s )
{
	register int n;
    	for ( n = 0; s[n]; ++n )
		;

	return n;
}
#endif

void *sfzalloc (yy_size_t  size )
{
	return (void *) malloc( size );
}

void *sfzrealloc  (void * ptr, yy_size_t  size )
{
	/* The cast to (char *) in the following accommodates both
	 * implementations that use char* generic pointers, and those
	 * that use void* generic pointers.  It works with the latter
	 * because both ANSI C and C++ allow castless assignment from
	 * any pointer type to void*, and deal with argument conversions
	 * as though doing an assignment.
	 */
	return (void *) realloc( (char *) ptr, size );
}

void sfzfree (void * ptr )
{
	free( (char *) ptr );	/* see sfzrealloc() for (char *) cast */
}

#define YYTABLES_NAME "yytables"

#undef YY_NEW_FILE
#undef YY_FLUSH_BUFFER
#undef yy_set_bol
#undef yy_new_buffer
#undef yy_set_interactive
#undef yytext_ptr
#undef YY_DO_BEFORE_ACTION

#ifdef YY_DECL_IS_OURS
#undef YY_DECL_IS_OURS
#undef YY_DECL
#endif
#line 702 "./sfz2pat.l"



static int
ipn_val(char *text)
{
	int i, sharp = 0, octave;
	char keyletter;

	for (i = 0; text[i] != '='; i++);
	i++;
	keyletter = text[i++];

	if (text[i] == '#') sharp = 1;
	else if (text[i] == 'b') sharp = -1;
	else i--;
	i++;

	if (text[i] == '-') octave = 0;
	else octave = 12 *(text[i] - '0' + 1);
	switch(keyletter) {
		case 'c':
		case 'C': break;
		case 'd':
		case 'D': octave += 2; break;
		case 'e':
		case 'E': octave += 4; break;
		case 'f':
		case 'F': octave += 5; break;
		case 'g':
		case 'G': octave += 7; break;
		case 'a':
		case 'A': octave += 9; break;
		case 'b':
		case 'B': octave += 11; break;
	}
	return (octave + sharp);
}

static int sfz_is_ready = FALSE;
static int first_group = -1;
static int previous_group = -1;

static void
initialize_sfz(void)
{
	int i;
	first_group = previous_group = -1;
	am_in_group = am_in_region = am_in_group_scope = FALSE;
	if (sfz_is_ready) return;
	for (i = 0; i < MAX_SFZ_GROUP; i++) {
		group_link[i] = GROUP_IS_FREE;
		sample_left_buf[i] = NULL;
		sample_right_buf[i] = NULL;
	}
	for (i = 0; i < MAX_SFZ_REGION; i++) {
		region_left_sample[i] = NULL;
		region_right_sample[i] = NULL;
		region[i][REGION_IN_GROUP] = -1;
		region[i][REGION_IS_BUSY] = FALSE;
	}
	sfz_is_ready = TRUE;
}
#ifndef LOADER

static int big_endian = 1;

#if 0
static long longnum(unsigned char c1, unsigned char c2,
		unsigned char c3, unsigned char c4)
{
    long_end lswitch;
    if (big_endian) {
	lswitch.c[0] = c4;
	lswitch.c[1] = c3;
	lswitch.c[2] = c2;
	lswitch.c[3] = c1;
    } else {
	lswitch.c[0] = c1;
	lswitch.c[1] = c2;
	lswitch.c[2] = c3;
	lswitch.c[3] = c4;
    }
    return(lswitch.l);
}
#endif

static void numlong(long number, unsigned char* c)
{
    long_end lswitch;
    lswitch.l = number;
    if (big_endian) {
	c[3] = lswitch.c[0];
	c[2] = lswitch.c[1];
	c[1] = lswitch.c[2];
	c[0] = lswitch.c[3];
    } else {
	c[0] = lswitch.c[0];
	c[1] = lswitch.c[1];
	c[2] = lswitch.c[2];
	c[3] = lswitch.c[3];
    }
}

#if 0
static short shortnum(unsigned char c1, unsigned char c2)
{
    short_end sswitch;
    if (big_endian) {
	sswitch.c[0] = c2;
	sswitch.c[1] = c1;
    } else {
	sswitch.c[0] = c1;
	sswitch.c[1] = c2;
    }
    return(sswitch.s);
}
#endif

static void numshort(short number, unsigned char *c)
{
    short_end sswitch;
    sswitch.s = number;
    if (big_endian) {
	c[1] = sswitch.c[0];
	c[0] = sswitch.c[1];
    } else {
	c[0] = sswitch.c[0];
	c[1] = sswitch.c[1];
    }
}

static void byteorder()
{   long_end hexx;

    hexx.c[0] = 0x12;
    hexx.c[1] = 0x34;
    hexx.c[2] = 0x56;
    hexx.c[3] = 0x78;
    if (hexx.l == 0x78563412) big_endian = 0;
}


#define MAXSPV 14


static void fix_header_write(unsigned char *buf, struct pat_header *header)
{
	numshort(header->nr_waveforms, buf + 85);
	numshort(header->master_volume, buf + 87);
}

static void fix_sample_write(unsigned char *buf, struct sample_header *sample)
{
	numlong(sample->len, buf + 8);
	numlong(sample->loop_start, buf + 12);
	numlong(sample->loop_end, buf + 16);
	numshort(sample->base_freq, buf + 20);
	numlong(sample->low_note, buf + 22);
	numlong(sample->high_note, buf + 26);
	numlong(sample->base_note, buf + 30);
	numshort(sample->detune, buf + 34);
	buf[36] = sample->panning;
	memcpy(&buf[37], sample->envelope_rate, 6);
	memcpy(&buf[43], sample->envelope_offset, 6);
	buf[49] = sample->tremolo_sweep;
	buf[50] = sample->tremolo_rate;
	buf[51] = sample->tremolo_depth;
	buf[52] = sample->vibrato_sweep;
	buf[53] = sample->vibrato_rate;
	buf[54] = sample->vibrato_depth;
	buf[55] = sample->modes;
	numshort(sample->scale_frequency, buf + 56);
	numshort(sample->scale_factor, buf + 58);
	numshort(sample->volume, buf + 60);
	memcpy(&buf[65], sample->mod_envelope_rate, 6);
	memcpy(&buf[71], sample->mod_envelope_offset, 6);
	numshort(sample->resonance, buf + 79);
	numshort(sample->cutoff_frequency, buf + 81);
	numshort(sample->lfo_rate, buf + 92);
}

/* converts milliseconds to the even stranger floating point GUS format */
static int msec2gus(int t, int r)
{
   static int vexp[4] = { 1, 8, 64, 512 };
   int e, mantissa;

   if (r <= 0)
      return 0x3F;

   t = t * 32 / r;

   if (t <= 0)
      return 0x3F;

   for (e=3; e>=0; e--) {
      mantissa = (vexp[e] * 16 + t/2) / t;

      if ((mantissa > 0) && (mantissa < 64))
	 return ((e << 6) | mantissa);
   }

   return 0xC1;
}

static void nullify_extras ( struct sample_header *sample)
{	int i;

	sample->volume_envelope_delay = 0;
	sample->exclusive_class = 0;
	sample->vibrato_delay = 0;

	for (i = 0; i < 6; i++) sample->mod_envelope_rate[i] = 0;
	for (i = 0; i < 6; i++) sample->mod_envelope_offset[i] = 0;

	sample->mod_envelope_delay = 0;
	sample->chorus_effect = 0;
	sample->reverb_effect = 0;
	sample->resonance = 0;
	sample->cutoff_frequency = 0;
	sample->modEnvToPitch = 0;
	sample->modEnvToFilterFc = 0;
	sample->modLfoToFilterFc = 0;
	sample->keynumToModEnvHold = 0;
	sample->keynumToModEnvDecay = 0;
	sample->keynumToVolEnvHold = 0;
	sample->keynumToVolEnvDecay = 0;
	sample->true_panning = 0;
}

static void make_sample ( struct sample_header *sample, int r)
{
	uint32 volume = 255;
	uint32 sustain = 250;
	double attack = 0.1;
	double hold = 0.1;
	double decay = 0.1;
	double release = 0.1;
	//double delay = 0;

	if (region_flt[r][AMPEG_RELEASE] >0.0001)
		release = region_flt[r][AMPEG_RELEASE] * 1000;

	sample->envelope_rate[ATTACK] = msec2gus(attack, volume);
	sample->envelope_offset[ATTACK] = volume;

	sample->envelope_rate[HOLD] = msec2gus(hold, volume - 1);
	sample->envelope_offset[HOLD] = volume - 1;

	sample->envelope_rate[DECAY] = msec2gus(decay, volume - 1 - sustain);
	sample->envelope_offset[DECAY] = sustain;

	sample->envelope_rate[RELEASE] = msec2gus(release, 255);
	sample->envelope_offset[RELEASE] = 0;

	sample->envelope_rate[RELEASEB] = 63;
	sample->envelope_offset[RELEASEB] = 0;
	sample->envelope_rate[RELEASEC] = 63;
	sample->envelope_offset[RELEASEC] = 0;

	nullify_extras(sample);

	sample->modes |= MODES_ENVELOPE;

	if (region[r][LOOP_MODE] == VAL_LOOP_SUSTAIN) sample->modes |= (MODES_LOOPING|MODES_SUSTAIN);
}

#else

static void nullify_extras (Sample *sp)
{	int i;

	//sp->volume_envelope_delay = 0;
	//sp->vibrato_delay = 0;

	for (i = 0; i < 6; i++) sp->modulation_rate[i] = 0;
	for (i = 0; i < 6; i++) sp->modulation_offset[i] = 0;

	//sp->mod_envelope_delay = 0;
	sp->chorusdepth = 0;
	sp->reverberation = 0;
	sp->resonance = 0;
	sp->modEnvToPitch = 0;
	sp->modEnvToFilterFc = 0;
	sp->modLfoToFilterFc = 0;
	sp->keyToModEnvHold = 0;
	sp->keyToModEnvDecay = 0;
	sp->keyToVolEnvHold = 0;
	sp->keyToVolEnvDecay = 0;
	sp->lfo_sweep_increment =
			    sp->lfo_phase_increment = sp->lfo_depth = 0;
	sp->aps_parameter = 0;
	sp->vibrato_delay = 0;
}


/* convert from 8bit value to fractional offset (15.15) */
static uint32
to_offset (uint32 offset)
{
    if (offset > 255)
	return 255 << (7 + 15);
    return (uint32) offset << (7 + 15);
}

/* calculate ramp rate in fractional unit;
 * diff = 8bit, time = msec
 */
static uint32
calc_rate (uint32 diff, double msec)
{
    double  rate;

    if (!diff) return 10;
    diff <<= (7 + 15);
    if (msec * CONTROLS_PER_SECOND < (1000.0/255.0)) return (255 << (7 + 15));
    rate = ((double) diff * 1000.0) / (msec * CONTROLS_PER_SECOND);
    if (rate < 10.0)
	return 10;
    return (uint32) rate;
}


#define TO_VOLUME(decibel) pow(10.0, (double)(decibel)/20.0)
#define HOLD_EXCURSION 1
#define ENV_BOTTOM 0

static void make_sample(Sample *sp, ToneBank *b, int tn, int percussion, int r) {
    	int note_to_use = b->tone[tn].note;
	int amp = b->tone[tn].amp;
	int strip_loop = b->tone[tn].strip_loop;
	int strip_envelope = b->tone[tn].strip_envelope;
	int strip_tail = b->tone[tn].strip_tail;
	uint32 volume = 255;
	uint32 sustain = 250;
	double attack = 0.1;
	double hold = 0.1;
	double decay = 0.1;
	double release = 0.1;
	double delay = 0;
	double sfz_volume = region_flt[r][VOLUME];

	//if (note_to_use == -1 && percussion) note_to_use = tn;

	sp->sample_rate = region_samplerate[r];
	sp->low_freq = freq_table[region[r][LOKEY] ];
	sp->high_freq = freq_table[region[r][HIKEY] ];
	sp->root_freq = freq_table[region[r][PITCH_KEYCENTER] ];

	if (b->tone[tn].pan == -1) sp->panning = 64;
	else sp->panning = b->tone[tn].pan;

	if (b->tone[tn].tuning) {
	    double  tune_factor = (double) (b->tone[tn].tuning) / 1200.0;
	    tune_factor = pow (2.0, tune_factor);
	    sp->root_freq =
		(uint32) (tune_factor * (double) sp->root_freq);
	}

	sp->modes = region_modes[r];
	sp->tremolo_sweep_increment =
		sp->tremolo_phase_increment = sp->tremolo_depth = 0;
	sp->vibrato_sweep_increment =
		sp->vibrato_control_ratio = sp->vibrato_depth = 0;
	sp->freq_center = region[r][PITCH_KEYCENTER];
	sp->freq_scale = 1024;
	sp->attenuation = 0;

	sp->sw_hikey = (char)region[r][SW_HIKEY];
	sp->sw_lokey = (char)region[r][SW_LOKEY];
	sp->sw_up = (char)region[r][SW_UP];
	sp->sw_down = (char)region[r][SW_DOWN];
	sp->sw_last = (char)region[r][SW_LAST];

/* ?? */
	//if (!percussion) release = 400;
	//if (!percussion) decay = 400;
	if (percussion) {
		strip_envelope = 1;
	}
	else {
		release = 400;
		decay = 400;
	}

	if (region_flt[r][AMPEG_RELEASE] >0.0001)
		release = region_flt[r][AMPEG_RELEASE] * 1000;

/* ramp from 0 to <volume> in <attack> msecs */
	sp->envelope_offset[ATTACK] = to_offset (volume);
	sp->envelope_rate[ATTACK] = calc_rate (volume, attack);

/* ramp down HOLD_EXCURSION in <hold> msecs */
	sp->envelope_offset[HOLD] = to_offset (volume - HOLD_EXCURSION);
	sp->envelope_rate[HOLD] = calc_rate (HOLD_EXCURSION, hold);

/* ramp down by <sustain> in <decay> msecs */
	if (sustain <= ENV_BOTTOM) sustain = ENV_BOTTOM;
	if (sustain > volume - HOLD_EXCURSION) sustain = volume - HOLD_EXCURSION;

	sp->envelope_offset[DECAY] = to_offset (sustain);
	sp->envelope_rate[DECAY] = calc_rate (volume - HOLD_EXCURSION - sustain, decay);
	if (fast_decay) sp->envelope_rate[DECAY] *= 2;

/* ramp to ENV_BOTTOM in ?? msec */
	sp->envelope_offset[RELEASE] = to_offset (ENV_BOTTOM);
	sp->envelope_rate[RELEASE] = calc_rate (255, release);

	if (fast_decay) sp->envelope_rate[RELEASE] *= 2;

	sp->envelope_offset[RELEASEB] = to_offset (ENV_BOTTOM);
	sp->envelope_rate[RELEASEB] = to_offset (200);
	sp->envelope_offset[RELEASEC] = to_offset (ENV_BOTTOM);
	sp->envelope_rate[RELEASEC] = to_offset (200);

	sp->envelope_rate[DELAY] = (int32) ((delay * play_mode->rate) / 1000);

	sp->modes |= MODES_ENVELOPE;

	if (region[r][LOOP_MODE] == VAL_LOOP_SUSTAIN) sp->modes |= (MODES_LOOPING|MODES_SUSTAIN);

	nullify_extras(sp);

	if (region[r][GROUP] == region[r][OFF_BY])
		sp->exclusiveClass = region[r][OFF_BY];
	else sp->exclusiveClass = 0;

	if (region[r][TRIGGER] == VAL_TRIGGER_LEGATO) sp->trigger = TRIGGER_LEGATO;
	else sp->trigger = TRIGGER_NONE;


	if (b->tone[tn].cutoff != -1) sp->cutoff_freq = b->tone[tn].cutoff;
	else sp->cutoff_freq = 0;

	if (note_to_use != -1)
	    sp->note_to_use = (uint8) (note_to_use);
	else if (percussion) sp->note_to_use = region[r][PITCH_KEYCENTER];
	else sp->note_to_use = 0;

	if (b->tone[tn].sustain != -1 && sp->modes & MODES_LOOPING) {
	    if (b->tone[tn].sustain == 1) sp->modes |= MODES_SUSTAIN;
	    else sp->modes &= ~MODES_SUSTAIN;
	}

	/* Strip any loops and envelopes we're permitted to */
	if ((strip_loop == 1) &&
	    (sp->modes & (MODES_SUSTAIN | MODES_LOOPING |
			  MODES_PINGPONG | MODES_REVERSE))) {
	    ctl->cmsg (CMSG_INFO, VERB_DEBUG,
		       " - Removing loop and/or sustain");
	    sp->modes &=
		~(MODES_SUSTAIN | MODES_LOOPING | MODES_PINGPONG |
		  MODES_REVERSE);
	}

	if (strip_envelope == 1) {
	    if (sp->modes & MODES_ENVELOPE)
		ctl->cmsg (CMSG_INFO, VERB_DEBUG,
			   " - Removing envelope");
	    sp->modes &= ~MODES_ENVELOPE;
	}

	if (amp != -1)
	    sp->volume = (double) (amp) / 100.0;
	else if (sfz_volume > 0.1 || sfz_volume < -0.1)
		sp->volume = TO_VOLUME(sfz_volume);
	else sp->volume = 1.0;

	sp->amp_random = region_flt[r][AMP_RANDOM];
	sp->hirand = region_flt[r][HIRAND];
	sp->lorand = region_flt[r][LORAND];

	sp->data_length /= 2;	/* These are in bytes. Convert into samples. */

	if (sp->samplesize > 16) sp->data_length /= 2;

	/* The sample must be padded out by 1 extra sample, so that
	   round off errors in the offsets used in interpolation will not
	   cause a "pop" by reading random data beyond data_length */
	//sp->data[sp->data_length] = sp->data[sp->data_length - 1];

	/* Then fractional samples */
	sp->data_length <<= FRACTION_BITS;
	sp->loop_start <<= FRACTION_BITS;
	sp->loop_end <<= FRACTION_BITS;

	if (strip_tail == 1) {
	   ctl->cmsg (CMSG_INFO, VERB_DEBUG, " - Stripping tail");
	   sp->data_length = sp->loop_end;
	}

}

#endif

int read_sfz_file(const char *name)
{
	int retvalue = 0;
	include_stack_ptr = 0;
	rcf_count = 1;

#ifdef LOADER
	sfzin = open_file (name, 1, OF_NORMAL, 0);
#else
	sfzin = fopen(name, "r");
#endif
	if (!sfzin) return -1;

	if (this_fname[include_stack_ptr]) free(this_fname[include_stack_ptr]);
	this_fname[include_stack_ptr] = strdup(name);

	BEGIN(K);
	retvalue = sfzlex();
	fclose(sfzin);
	if (!retvalue) leave_region();
	return retvalue;
}

#ifndef LOADER
static char outfile[80];

int main(int argc, char **argv)
{
	int32 c, i;

	byteorder();

	for (i = FIRST_SFZ_PARM; i < MAX_SFZ_PARM; i++) group_parm[i] = default_parm[i];
	for (i = 0; i < MAX_SFZ_PARM; i++) region_parm[i] = group_parm[i];

	while ((c=getopt(argc, argv, "v"))>0)
	    switch(c) {
		case 'v': verbosity++; break;
		default: return 1;
	    }

	if (optind==argc-1) {

		strcpy(outfile, argv[optind]);
		if (!strcmp(outfile + strlen(outfile) - 4, ".sfz"))
			outfile[ strlen(outfile) - 4 ] = '\0';
		strcat(outfile, ".pat");
		initialize_sfz();
		if (read_sfz_file(argv[optind])) {
			perror("sfz2pat: I can't open your SFZ");
			return 3;
		}
		make_pat();
	}
	else if (optind!=argc) {
      		fprintf(stderr, 
	      		"Usage: sfz2pat [-r RootFreq | -n Note] [-u Note] [-v] [filename]\n");
      		return 1;
	}

	return 0;
}
#else

void
free_sfz_data(InstrumentLayer *lp)
{
	int g = lp->sfz_group, ng, i;

SFZDBG
"freeing sfz");
	while (g >= 0) {
	    if (sample_left_buf[g]) free(sample_left_buf[g]);
	    if (sample_right_buf[g]) free(sample_right_buf[g]);
	    sample_left_buf[g] = NULL;
	    sample_right_buf[g] = NULL;
	    for (i = 0; i < MAX_SFZ_REGION; i++) if (region[i][REGION_IN_GROUP] == g) {
		if (region_left_sample[i]) free(region_left_sample[i]);
		if (region_right_sample[i]) free(region_right_sample[i]);
		region_left_sample[i] = NULL;
		region_right_sample[i] = NULL;
		region[i][REGION_IS_BUSY] = FALSE;
		region[i][REGION_IN_GROUP] = -1;
	    }
	    ng = group_link[g];
	    group_link[g] = GROUP_IS_FREE;
	    g = ng;
	}
}

#define MAX_VLAYER 128

InstrumentLayer *
load_sfz_instrument (ToneBank *b, int bank, int tn, int percussion)
{
	int32 i, r, l_ix, r_ix, g;
        InstrumentLayer *lp = NULL, *lastlp, *headlp = NULL;
	Instrument *ip;
	Sample *sp = NULL;
	const char *name = b->tone[tn].name;
    	int note_to_use = b->tone[tn].note;
	int vlayer_count, hivel, lovel;
	int vlayer, vlayer_list[MAX_VLAYER][4];
	int vlayer_region_left[MAX_VLAYER][MAX_SFZ_REGION];
	int stereo_layer, stereo_channels = 1, right_samples;

SFZDBG
"load %s", name);
	initialize_sfz();
	if (read_sfz_file(name)) {
		SFZERR
		"Couldn't read %s SFZ file", name);
		return NULL;
	}
SFZDBG
"sfz read ok");

	if (note_to_use == -1 && percussion) note_to_use = tn;


	point_regions_to_groups();

SFZDBG
"pointed ok");
	vlayer_count = 0;
	for (vlayer = 0; vlayer < MAX_VLAYER; vlayer++)
		 vlayer_list[vlayer][0] =
		 vlayer_list[vlayer][1] =
		 vlayer_list[vlayer][2] =
		 vlayer_list[vlayer][3] = 0;

	g = first_group;

	while (g >= 0) {
	    for (i = 0; i < MAX_SFZ_REGION; i++) if (region[i][REGION_IN_GROUP] == g) {
		hivel = region[i][HIVEL];
		lovel = region[i][LOVEL];
		for (vlayer = 0; vlayer < vlayer_count; vlayer++)
			if (vlayer_list[vlayer][0] == lovel && vlayer_list[vlayer][1] == hivel) break;
		if (vlayer == vlayer_count) {
			vlayer_list[vlayer][0] = lovel;
			vlayer_list[vlayer][1] = hivel;
			if (vlayer_count < MAX_VLAYER - 1) vlayer_count++;
		}
SFZDBG
"counting layer %d", vlayer_count);
		vlayer_region_left[vlayer][vlayer_list[vlayer][2] ] = i;
		if (region_left_sample[i]) vlayer_list[vlayer][2]++;
		if (region_right_sample[i]) vlayer_list[vlayer][3]++;
	    }
SFZDBG
"link from %d to %d", g, group_link[g]);

	    g = group_link[g];
	}

SFZDBG
"counted %d layers", vlayer_count);

	lastlp = NULL;

  for (vlayer = 0; vlayer < vlayer_count; vlayer++) {

	if (fast_load && vlayer > 0) break;

	lp = (InstrumentLayer *) safe_malloc (sizeof (InstrumentLayer));
	lp->size = 0;
	lp->map_size = 0;
	lp->all_layers = NULL;
	lp->lo = vlayer_list[vlayer][0];
	lp->hi = vlayer_list[vlayer][1];
	ip = (Instrument *) safe_malloc (sizeof (Instrument));
	lp->instrument = ip;
	lp->purgelist = NULL;
	lp->next = NULL;
	lp->font_type = FONT_SFZ;
	lp->sfz_group = first_group;

	if (lastlp) lastlp->next = lp;
	else {
		headlp = lp;
	}

	lastlp = lp;

	ip->type = FONT_SFZ;
	ip->samples = vlayer_list[vlayer][2];
	ip->sample = (Sample *) safe_malloc (sizeof (Sample) * ip->samples);
	ip->left_samples = ip->samples;
	ip->left_sample = ip->sample;
	right_samples = vlayer_list[vlayer][3];
	ip->right_samples = right_samples;
	if (right_samples) {
	    ip->right_sample =
		(Sample *) safe_malloc (sizeof (Sample) * right_samples);
	    stereo_channels = 2;
	}
	else
	    ip->right_sample = 0;
	ip->contents = NULL;

	l_ix = r_ix = 0;

	if (!vlayer)
	ctl->cmsg (CMSG_LOAD, VERB_NOISY,
		   "%s%s[%d,%d] %s(%d layer%s)",
		   (percussion) ? "   " : "", name,
		   (percussion) ? note_to_use : tn, bank,
		   (right_samples) ? "(2) " : "", vlayer_count, (vlayer_count>1)? "s":"");

   for (stereo_layer = 0; stereo_layer < stereo_channels; stereo_layer++) {
    int     sample_count;
    sample_count = ip->left_samples;

    for (i = 0; i < sample_count; i++) {
	int32 region_start, region_end, region_bytes;
	int32 datasize, data_width, loop_start, loop_end;
	unsigned char *left_buf, *right_buf;

	r = vlayer_region_left[vlayer][i];
	datasize = region_datasize[r];
	left_buf = region_left_sample[r];
	right_buf = region_right_sample[r];
	data_width = region_samplesize[r]/8;
	if (data_width == 3) data_width = 4;
	if (stereo_layer && !right_buf) continue;

	region_start = region[r][OFFSET];
	region_end = region[r][END];
	if (region_end <= 0) region_end = datasize/data_width;

	if (!region[r][LOOP_START]) loop_start = 0;
	else loop_start = region[r][LOOP_START] - region_start;
	if (!region[r][LOOP_END]) loop_end = region_end - region_start;
	else loop_end = region[r][LOOP_END] - region_start;

	region_bytes = (region_end - region_start) * data_width;

	if (region_bytes / data_width > MAX_SAMPLE_SIZE) {
	    ctl->cmsg (CMSG_ERROR, VERB_NORMAL,
		       "Sample length of %d is too big for me to handle (max is %d).",
		       region_bytes/data_width, MAX_SAMPLE_SIZE);
	    region_bytes = data_width * MAX_SAMPLE_SIZE;
	    if (loop_end > MAX_SAMPLE_SIZE) loop_end = MAX_SAMPLE_SIZE;
	    if (loop_start > loop_end) loop_start = 0;
	}
//printf("region %d has %d bytes of %d total (%d samples of %d)\n", r, region_bytes, datasize, region_bytes/2, datasize/2);
//printf("\tregion_start %d, region_end %d\n", region_start, region_end);
//printf("\tloop_start %d, loop_end %d\n", loop_start, loop_end);
//printf("\tvolume %f -> %f, ampeg_release %f, loop_mode %d\n",
//	region_flt[r][VOLUME],
//	TO_VOLUME(region_flt[r][VOLUME]),
//	region_flt[r][AMPEG_RELEASE], region[r][LOOP_MODE]);


	if (!stereo_layer) {
		sp = &(ip->left_sample[l_ix++]);
		if (right_buf) sp->stereo_mode = LEFT_SAMPLE;
		else sp->stereo_mode = MONO_SAMPLE;
		if (data_width == 4)
		    sp->ldata = (samplel_t *)(left_buf + region_start * data_width);
		else sp->data = (sample_t *)(left_buf + region_start * data_width);
	}
	else {
		sp = &(ip->right_sample[r_ix++]);
		sp->stereo_mode = RIGHT_SAMPLE;
		if (data_width == 4)
		    sp->ldata = (samplel_t *)(right_buf + region_start * data_width);
		else sp->data = (sample_t *)(right_buf + region_start * data_width);
	}
	sp->data_length = region_bytes;
	headlp->size += sp->data_length;
	sp->loop_start = loop_start;
	sp->loop_end = loop_end;
	sp->samplesize = region_samplesize[r];
	make_sample(sp, b, tn, percussion, r);

    }		/* end of sample loop */

   }		/* end of stereo layer loop */
  }		/* end of vlayer loop */

    return headlp;
}

#endif

static
int read_sample(char *name)
{
	int32 samplerate=-1, datasize=-1, all_length, chunk_length, c, i;
      	int32 aiff_offset=-1, aiff_blocksize=-1, aiff_numsamples=-1, samplesize = 16;
	int32 left_datasize, right_datasize, data_width=2;
	int infd=STDIN_FILENO;
	unsigned char thing[4096], modes=0;
	unsigned char	*sample_buf = NULL, *left_buf, *right_buf;
	int stereo_channels = 1;

#ifdef LOADER
	if ((infd=open_file_raw (name, OF_NORMAL, 0))<0) {
#else
	if ((infd=open(name, O_RDONLY))<0) {
#endif
		SFZERR
      		"sfz2pat: I can't open your sample file %s", name);
      		return 3;
	}
	if (read(infd, thing, 12)<=0) {
		SFZERR
      		"sfz2pat: I can't read your WAVE");
      		return 3;
	}

	if (!memcmp(thing+4, "WAVE", 4)) {
		/* wave */
		all_length=LE_LONG(*((int32 *)(thing)));
		for (i = 0; i < 4; i++) thing[i] = thing[i+8];
		if (read(infd, thing+4, 4) != 4) {
			SFZERR
			"sfz2pat: I can't read your WAVE");
			return 3;
		}

	}
	else if (!memcmp(thing, "RIFF", 4)) {
		/* wave */
		all_length=LE_LONG(*((int32 *)(thing+4)));
		if (memcmp(thing+8, "WAVE", 4)) {
			SFZERR
			"File format not recognized");
			return 1;
		}
		if (read(infd, thing, 8) != 8) {
			SFZERR
			"sfz2pat: I can't read your WAVE");
			return 3;
		}
	}
	else if (!memcmp(thing, "FORM", 4)) {
	    /* aiff */
	    all_length=LE_LONG(*((int32 *)(thing+4)));
	    if (memcmp(thing+8, "AIFF", 4)) {
		SFZERR
		"File format not recognized");
		return 1;
	    }
		/* now look for SSND and COMM chunks */
	    while (datasize == -1 || aiff_offset == -1) {
		if (read(infd, thing, 8) != 8) {
			SFZERR
			"sfz2pat: I can't read your AIFF");
			return 3;
		}
      		chunk_length=BE_LONG(*((int32 *)(thing+4)));
		if (!chunk_length) break;
		SFZDBG
		"Chunk type %c%c%c%c", thing[0],thing[1],thing[2],thing[3]);
		SFZNL
		SFZDBG
		"Chunk length %d", chunk_length);
		SFZNL
		if (!memcmp(thing, "SSND", 4)) {
		    if (chunk_length < 8 || read(infd, thing, 8) != 8) {
			SFZERR
			"sfz2pat: I can't read your AIFF");
			return 3;
		    }
		    chunk_length -= 8;
      		    aiff_offset = BE_LONG(*((int32 *)thing));
      		    aiff_blocksize = BE_LONG(*((int32 *)(thing+4)));
		}
		else if (!memcmp(thing, "COMM", 4)) {
		    if (chunk_length < 18 || read(infd, thing, 18) != 18) {
			SFZERR
			"sfz2pat: I can't read your AIFF");
			return 3;
		    }
		    chunk_length -= 18;
	  	    stereo_channels = BE_SHORT(*((int16 *)thing));
      		    aiff_numsamples = BE_LONG(*((int32 *)(thing+2)));
	  	    samplesize = BE_SHORT(*((int16 *)(thing+6)));
		    if (samplesize == 8) data_width = 1;
		    else if (samplesize != 16) {
			SFZERR
			"Can't handle sample size %d in AIFF file", samplesize);
			return 1;
		    }
	  	    switch(samplesize) {
	    	    	case 8: data_width = 1; break;
	    	    	case 16: modes |= MODES_16BIT; break;
	  	    }
		    datasize = aiff_numsamples * data_width * stereo_channels;

		/* Is the frequency outside of what we can represent with Uint32? */
		    if ( (thing[8+0] & 0x80) || (thing[8+0] <= 0x3F) || (thing[8+0] > 0x40)
			|| (thing[8+0] == 0x40 && thing[8+1] > 0x1C) )
				samplerate = 0;
		    else samplerate = ((thing[8+2] << 23) | (thing[8+3] << 15) | (thing[8+4] << 7)
			| (thing[8+5] >> 1)) >> (29 - thing[8+1]);

		}
		else {
			SFZERR
		"Chunk type %c%c%c%c", thing[0],thing[1],thing[2],thing[3]);
			SFZERR
		"Unknown AIFF chunk");
	  	    if (chunk_length & 1) chunk_length++;

	  	    while (chunk_length>0) {
	      	        if ((c=read(infd, thing, (chunk_length>4096) ? 4096 : chunk_length)) <= 0) {
				SFZERR
		  	    "sfz2pat: Now your AIFF has run out of data");
		  	    return 3;
	      	        }
	      	        chunk_length -= c;
	  	    }
		}
	    }
	    SFZDBG
	    "AIFF: offset %d, blocksize %d, channels %d, samples %d",
		aiff_offset, aiff_blocksize, stereo_channels, aiff_numsamples);
	    SFZNL
	    SFZDBG
	    "AIFF: samplesize %d, samplerate %d, chunk left %d, datasize %d",
		samplesize, samplerate, chunk_length, datasize);
	    SFZNL
	  	    while (aiff_offset>0 && aiff_offset < chunk_length) {
	      	        if ((c=read(infd, thing, (aiff_offset>4096) ? 4096 : aiff_offset)) <= 0) {
				SFZERR
		  	    "sfz2pat: Now your AIFF has run out of data");
		  	    return 3;
	      	        }
	      	        aiff_offset -= c;
			chunk_length -= c;
	  	    }
	    if (datasize > chunk_length) {
		SFZERR
		"AIFF file is too short\n");
		return 1;
	    }
	}
	else if (!memcmp(thing, "OggS", 4)) {
		/* ogg */
#ifndef HAVE_OGG
		SFZERR
		"OGG format not implemented");
		return 1;
#else
	OggVorbis_File vf;
	int eof=0;
	int current_section, sample_point = 0;
	FILE *f;

	close (infd);
#ifdef LOADER
	f = fopen(current_filename, "r");
#else
	f = fopen(name, "r");
#endif
	if (ov_open(f, &vf, NULL, 0) < 0) {
		SFZERR
			"%s does not appear to be an Ogg bitstream.", name);
		return 1;;
	}
      {
	//char **ptr=ov_comment(&vf,-1)->user_comments;
	vorbis_info *vi=ov_info(&vf,-1);
	//while(*ptr){
	//  fprintf(stderr,"%s\n",*ptr);
	//  ++ptr;
	//}
	stereo_channels = vi->channels;
	samplerate = vi->rate;
	SFZDBG
    		"Bitstream is %d channel, %ldHz",vi->channels,vi->rate);
	SFZNL
	datasize = 2 * ov_pcm_total(&vf,-1);
	SFZDBG
    		"Decoded length: %d samples", datasize/2);
	SFZNL
	//fprintf(stderr,"Encoded by: %s\n\n",ov_comment(&vf,-1)->vendor);
      }

	sample_buf = (unsigned char *)malloc(datasize);
	samplesize = 16;
	modes |= MODES_16BIT;

  while(!eof){
	long ret = ov_read(&vf, sample_buf, datasize, 0, 2, 1, &current_section);
    if (ret == 0) {
      /* EOF */
      eof=1;
    } else if (ret < 0) {
      /* error in the stream.  Not a problem, just reporting it in
	 case we (the app) cares.  In this case, we don't. */
    } else {
      /* we don't bother dealing with sample rate changes, etc, but
	 you'll have to*/
      //fwrite(pcmout,1,ret,stdout);
	sample_point += ret;
	//SFZDBG
    	//	"read %d bytes of %d", sample_point, datasize);
	//SFZNL
    }
  }

  ov_clear(&vf);
    
  //fprintf(stderr,"Done.\n");

#endif
	}
	else if (!memcmp(thing, "CREA", 4)) {
		/* voc */
		SFZERR
		"VOC format not implemented");
		return 1;
	}

  if (datasize == -1) chunk_length=LE_LONG(*((int32 *)(thing+4)));

  while (datasize==-1) {
      /* This Microsoft file format is designed to be impossible to
	 parse correctly if one doesn't have the full specification.
	 If you have a wave with an INFO "chunk", you lose. Thank you
	 for playing. */

      if (!memcmp(thing, "fmt ", 4)) {
	  if (chunk_length > 4096) {
		SFZERR
		      "WAVEs with %d-byte format blocks make me throw up!\n",
		      chunk_length);
	      return 2;
	  }
	  if (read(infd, thing, chunk_length) != chunk_length) {
		SFZERR
	      "sfz2pat: Your WAVE is mangled");
	      return 3;
	  }
	  if (LE_SHORT(*((int16 *)(thing))) != 1) {
		SFZERR
	      "sfz2pat: I don't understand your WAVE. "
		      "It has a type %d format chunk!",
		      LE_SHORT(*((int16 *)(thing))));
	      return 2;
	  }
	  stereo_channels = LE_SHORT(*((int16 *)(thing + 2)));
	  if (stereo_channels < 1 || stereo_channels > 2) {
		SFZERR
	      "sfz2pat: This WAVE has %d channels! " 
		      "There can be at most two.", stereo_channels);
	      return 2;
	  }
	  samplerate = LE_LONG(*((int32 *)(thing + 4)));
	  samplesize = LE_SHORT(*((int16 *)(thing + 14)));
	  switch(samplesize) {
	    case 8: modes |= MODES_UNSIGNED; data_width = 1; break;
	    case 16: modes |= MODES_16BIT; break;
	    case 24: modes |= MODES_16BIT; data_width = 3; break;
	    default:
		SFZERR
	      "sfz2pat: Ack! Ppthbth! %d-bit samples!", samplesize);
	      return 2;
	  }
	    SFZNOTE
	    "%s is a %d-bit, %d channel, %d Hz WAVE", name,
		    (LE_SHORT(*((int16 *)(thing + 14)))),
		    stereo_channels,
		    samplerate);
	    SFZNL
      }
      else if (!memcmp(thing, "data", 4)) {
	  if (samplerate==-1) {
		SFZERR
	      "sfz2pat: Your WAVE has no format information before data!");
	      return 2;
	  }
	  SFZNOTE
	    "It has %d bytes of data and sample length %d", chunk_length, chunk_length/stereo_channels/data_width);
	  datasize=chunk_length;
	  SFZNL
      }
      else {
	  SFZNOTE
		    "Your WAVE has a %d-byte chunk called `%4.4s'\n",
		    chunk_length, thing);
	  SFZNL

	  /* It's cool to pad chunks with NULs to align them on
             half-word boundaries. */
	  if (chunk_length & 1) chunk_length++;

	  while (chunk_length>0) {
	      if ((c=read(infd, thing, (chunk_length>4096) ? 4096 : chunk_length)) <= 0) {
		SFZERR
		  "sfz2pat: Now your WAVE has run out of data");
		  return 3;
	      }
	      chunk_length -= c;
	  }
      }
      if (datasize != -1) break;
      if (read(infd, thing, 8)!=8) {
		SFZERR
		 "Your WAVE ran out before I got to the interesting bits");
	  return 3;
      }
      chunk_length=LE_LONG(*((int32 *)(thing+4)));
    }

	/* if it was an ogg, sample_buf has been filled */
    if (!sample_buf) {
	int offset_read = 0;
	if (data_width == 3) offset_read = 1;
	/* malloc 1 extra so following conversion from 24 to 32 bits doesn't go past end */
	sample_buf = (unsigned char *)malloc(datasize + offset_read);
	if ((c=read(infd, sample_buf + offset_read, datasize)) != datasize) {
		SFZERR
		"sfz2pat: I can't read the data");
		close(infd);
		return 3;
	}
	close(infd);
    }

#ifdef LOADER
	if (data_width == 3) {
		int32   data_len = datasize / 3, t = 0;
		unsigned char  *cp = sample_buf;
		int32 *tmpdta, *newdta;

		datasize = data_len * 4;
		tmpdta = newdta = malloc (datasize);
		while (data_len--) {
      			*tmpdta = LE_LONG(*((int32 *)(cp+t)));
			*tmpdta >>= 8;
			tmpdta++;
			t += 3;
		}
		cp = (unsigned char *) (sample_buf);
		sample_buf = (unsigned char *) newdta;
		free (cp);
		samplesize = 24;
		data_width = 4;
	}
#else
	if (data_width == 3) {
		int32   data_len = datasize / 3, t = 2;
		unsigned char  *cp = sample_buf;
		int16 *tmpdta, *newdta;
		datasize = data_len * 2;
		tmpdta = newdta = malloc (datasize);
		while (data_len--) {
      			*tmpdta++ = LE_SHORT(*((int16 *)(cp+t)));
			t += 3;
		}
		cp = (unsigned char *) (sample_buf);
		sample_buf = (unsigned char *) newdta;
		free (cp);
		samplesize = 16;
		data_width = 2;
	}
#endif

	if (stereo_channels == 2) {
		left_datasize = right_datasize = datasize/2;
	}
	else {
		left_datasize = datasize;
		right_datasize = 0;
	}

	if (data_width == 2) {
#ifdef LOADER
#ifdef LITTLE_ENDIAN
	if (aiff_numsamples > 0) {
		unsigned char onebyte;
		for (i = 0; i < datasize; i+= 2) {
			onebyte = sample_buf[i];
			sample_buf[i] = sample_buf[i+1];
			sample_buf[i+1] = onebyte;
		}
	}
#else
	    /* convert to machine byte order */
	{
	    int32   data_len = datasize / 2;
	    int16  *tmpdta = (int16 *) sample_buf, s;
	    while (data_len--) {
		s = LE_SHORT (*tmpdta);
		*tmpdta++ = s;
	    }
	}
#endif
#else
	if (big_endian || (!big_endian && aiff_numsamples > 0)) {
		unsigned char onebyte;
		for (i = 0; i < datasize; i+= 2) {
			onebyte = sample_buf[i];
			sample_buf[i] = sample_buf[i+1];
			sample_buf[i+1] = onebyte;
		}
	}
#endif
	}

	if (samplesize == 8) {	/* convert to 16-bit data */
		int32   data_len = datasize;
		unsigned char  *cp = sample_buf;
		uint16 *tmpdta, *newdta;
		tmpdta = newdta = malloc (datasize * 2);
		while (data_len--)
			*tmpdta++ = (uint16) (*cp++) << 8;
		cp = (unsigned char *) (sample_buf);
		sample_buf = (unsigned char *) newdta;
		free (cp);
		datasize *= 2;
		left_datasize *= 2;
		right_datasize *= 2;
		samplesize = 16;
		data_width = 2;
		modes |= MODES_16BIT;
	}

	if (modes & MODES_UNSIGNED) {	/* convert to signed data */
	    int32   data_len = datasize / 2;
	    int16  *tmpdta = (int16 *) sample_buf;
	    while (data_len--)
		*tmpdta++ ^= 0x8000;
	    modes &= ~MODES_UNSIGNED;
	}

	if (am_in_region) {
	    region_datasize[current_region] = left_datasize;
	    region_channels[current_region] = stereo_channels;
	    region_modes[current_region] = modes;
	    region_samplerate[current_region] = samplerate;
	    region_samplesize[current_region] = samplesize;
	}
	else {
	    sample_left_datasize[current_group] = left_datasize;
	    sample_right_datasize[current_group] = right_datasize;
	    sample_channels[current_group] = stereo_channels;
	    sample_modes[current_group] = modes;
	    sample_samplerate[current_group] = samplerate;
	    sample_samplesize[current_group] = samplesize;
	}

	if (stereo_channels == 1) {
		if (am_in_region) {
		    region_left_sample[current_region] = sample_buf;
		    region_right_sample[current_region] = NULL;
		}
		else {
		    sample_left_buf[current_group] = sample_buf;
		    sample_right_buf[current_group] = NULL;
		}
		return 0;
	}

	left_buf = (unsigned char *)malloc(datasize/2);
	right_buf = (unsigned char *)malloc(datasize/2);

	if (data_width == 2) {
		int32   data_len = datasize/4;
		int16  *tmpdta = (int16 *) sample_buf;
		int16  *ldta = (int16 *) left_buf;
		int16  *rdta = (int16 *) right_buf;

	    	while (data_len--) {
			*ldta++ = *tmpdta++;
			*rdta++ = *tmpdta++;
		}
	}
	else if (data_width == 4) {
		int32   data_len = datasize/8;
		int32  *tmpdta = (int32 *) sample_buf;
		int32  *ldta = (int32 *) left_buf;
		int32  *rdta = (int32 *) right_buf;

	    	while (data_len--) {
			*ldta++ = *tmpdta++;
			*rdta++ = *tmpdta++;
		}
	}

	if (am_in_region) {
	    region_left_sample[current_region] = left_buf;
	    region_right_sample[current_region] = right_buf;
	}
	else {
	    sample_left_buf[current_group] = left_buf;
	    sample_right_buf[current_group] = right_buf;
	}

	free(sample_buf);

	return 0;
}

static void
leave_region(void)
{
	int i;

	if (!am_in_region) return;
	for (i = 0; i < MAX_SFZ_PARM; i++)
		region[current_region][i] = region_parm[i];
	for (i = 0; i < MAX_FLOAT_PARM; i++)
		region_flt[current_region][i] = region_flt_parm[i];
	region[current_region][REGION_IS_BUSY] = TRUE;
	current_region = -1;
	am_in_region = FALSE;
}

static int
enter_region(void)
{
	int i;
	if (am_in_region) return FALSE;
	for (i = 0; i < MAX_SFZ_REGION; i++) if (!region[i][REGION_IS_BUSY]) break;
	if (i < MAX_SFZ_REGION) {
		current_region = i;
		am_in_region = TRUE;
		return TRUE;
	}
	return FALSE;
}

static void
leave_group(void)
{
	if (!am_in_group) return;
	previous_group = current_group;
	current_group = -1;
	am_in_group = FALSE;
}

static int
enter_group(void)
{
	int i;
	if (am_in_group) return TRUE;
	for (i = 0; i < MAX_SFZ_GROUP; i++) if (group_link[i] == GROUP_IS_FREE) break;
	if (i < MAX_SFZ_GROUP) {
		current_group = i;
		if (first_group == -1) {
			first_group = current_group;
		}
		else if (previous_group != -1) group_link[previous_group] = current_group;
		/* else error ? */
		group_link[current_group] = -2;
		am_in_group = TRUE;
		return TRUE;
	}
	return FALSE;
}


static void
point_regions_to_groups(void)
{	int i, g;

	g = first_group;

	while (g >= 0) {
	    for (i = 0; i < MAX_SFZ_REGION; i++) if (region[i][REGION_IN_GROUP] == g) {
		if (region_left_sample[i]) continue;
		//g = region[i][REGION_IN_GROUP];
		//while (!sample_left_buf[g] && g > 0) g--;
		region_left_sample[i] = sample_left_buf[g];
		region_right_sample[i] = sample_right_buf[g];
		region_samplerate[i] = sample_samplerate[g];
		region_samplesize[i] = sample_samplesize[g];
		region_datasize[i] = sample_left_datasize[g];
		region_modes[i] = sample_modes[g];
	    }
SFZDBG
"point: link %d to %d", g, group_link[g]);
	    g = group_link[g];
	}
}

#ifndef LOADER

#define MAX_VLAYER 19

static void
make_pat(void)
{
	int32 i, r, g;
	int stereofd;
	struct pat_header header;
	struct sample_header sample;
	unsigned char buf[1024];
	int vlayer_count, hivel, lovel;
	int     vlayer, vlayer_list[MAX_VLAYER][4];
	int vlayer_region_left[MAX_VLAYER][MAX_SFZ_REGION];
	int stereo_layer, stereo_channels = 0, left_sample_count = 0, right_sample_count = 0;
	int32 total_region_bytes = 0;

	point_regions_to_groups();

	vlayer_count = 0;
	for (vlayer = 0; vlayer < MAX_VLAYER; vlayer++)
		 vlayer_list[vlayer][0] =
		 vlayer_list[vlayer][1] =
		 vlayer_list[vlayer][2] =
		 vlayer_list[vlayer][3] = 0;

	g = first_group;

	while (g >= 0) {
	    for (i = 0; i < MAX_SFZ_REGION; i++) if (region[i][REGION_IN_GROUP] == g) {
		if (region_left_sample[i]) left_sample_count++;
		if (region_right_sample[i]) right_sample_count++;
		hivel = region[i][HIVEL];
		lovel = region[i][LOVEL];
		for (vlayer = 0; vlayer < vlayer_count; vlayer++)
			if (vlayer_list[vlayer][0] == lovel && vlayer_list[vlayer][1] == hivel) break;
		if (vlayer == vlayer_count) {
			vlayer_list[vlayer][0] = lovel;
			vlayer_list[vlayer][1] = hivel;
			if (vlayer_count < MAX_VLAYER - 1) vlayer_count++;
		}
		vlayer_region_left[vlayer][vlayer_list[vlayer][2] ] = i;
		if (region_left_sample[i]) vlayer_list[vlayer][2]++;
		if (region_right_sample[i]) vlayer_list[vlayer][3]++;
	    }

	    g = group_link[g];
	}
	if (left_sample_count) stereo_channels = 1;
	if (right_sample_count) stereo_channels = 2;

	memset((char *)&header, 0, sizeof(header));  /* patch header is 239, sample header is 96. sum = 335 */
	memcpy(header.magic, "GF1PATCH110", 12);
	memcpy(header.version, "ID#000002", 10);
	strcpy(header.description, "Copyleft 1995 EWE&U Conductions and one Retreated Gravi\032");
	header.instruments = 1;
	header.pat_voices = 14;
	header.pat_channels = 0;
	header.nr_waveforms = vlayer_list[0][2];
	header.master_volume = 127;
	header.data_size = 0; /* ?? */
	memcpy(header.sf2magic, "SF2EXT\0", 7);
	header.instrument_number = 1;
	strcpy(header.instrument_name, "Bleahnoise");
	header.instrument_size = 0; /* ?? sample_left_datasize + sample_right_datasize; */
	header.layer_count = 1;
/* sf2layer[9] */
	header.layer_duplicate = 0;
	header.layer_number = 0;
	header.layer_size = 0; /* ?? */
	header.num_samples = vlayer_list[0][2];
/* sf2layer2[10] */

	header.velocity_count = vlayer_count;
	for (i = 0; i < 9; i++) {
		header.sf2layer[i].velmin = vlayer_list[i][0];
		header.sf2layer[i].velmax = vlayer_list[i][1];
		header.sf2layer[i].left_samples = vlayer_list[i][2];
		header.sf2layer[i].right_samples = vlayer_list[i][3];
	}
	for (i = 0; i < 10; i++) {
		header.sf2layer2[i].velmin = vlayer_list[i+9][0];
		header.sf2layer2[i].velmax = vlayer_list[i+9][1];
		header.sf2layer2[i].left_samples = vlayer_list[i+9][2];
		header.sf2layer2[i].right_samples = vlayer_list[i+9][3];
	}
	//vlayer_list[0][0] = header.sf2layer[0].velmin = 0;
	//vlayer_list[0][1] = header.sf2layer[0].velmax = 127;
	//vlayer_list[0][2] = header.sf2layer[0].left_samples = left_sample_count;
	//vlayer_list[0][3] = header.sf2layer[0].right_samples = right_sample_count;

	memcpy (buf, (char *) &header, sizeof (header));
	fix_header_write(buf, &header);


	if ((stereofd = open(outfile, O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)) < 0) {
		fprintf(stderr, "Can't open output file %s\n", outfile);
		return;
	}

	if ( write(stereofd, buf, sizeof(header)) != sizeof(header) ) {
		fprintf(stderr, "Write error\n");
		return;
	}


  for (vlayer = 0; vlayer < vlayer_count; vlayer++) {

   for (stereo_layer = 0; stereo_layer < stereo_channels; stereo_layer++) {

    for (i = 0; i < vlayer_list[vlayer][2]; i++) {
	int32 region_start, region_end, region_bytes;
	int32 datasize, data_width, loop_start, loop_end;
	unsigned char *left_buf, *right_buf;

	r = vlayer_region_left[vlayer][i];
	datasize = region_datasize[r];
	left_buf = region_left_sample[r];
	right_buf = region_right_sample[r];
	data_width = region_samplesize[r]/8;
	if (stereo_layer && !right_buf) continue;

/* sample header */  
	memset((char *)&sample, 0, sizeof(sample));  /* patch header is 239, sample header is 96. sum = 335 */

	region_start = region[r][OFFSET];
	region_end = region[r][END];
	if (region_end <= 0) region_end = datasize/data_width;
	region_bytes = (region_end - region_start) * data_width;
	total_region_bytes += region_bytes;

	if (!region[r][LOOP_START]) loop_start = 0;
	else loop_start = region[r][LOOP_START] - region_start;
	if (!region[r][LOOP_END]) loop_end = region_end - region_start;
	else loop_end = region[r][LOOP_END] - region_start;

	region_bytes = (region_end - region_start) * data_width;
printf("region %d has %d bytes of %d total; using %d\n", r, region_bytes, datasize, total_region_bytes);
printf("\tvolume %f, ampeg_release %f, loop_mode %d\n",
	region_flt[r][VOLUME], region_flt[r][AMPEG_RELEASE], region[r][LOOP_MODE]);

	if (stereo_layer) strcpy(sample.name, "bleahR");
	else if (right_buf) strcpy(sample.name, "bleahL");
	else strcpy(sample.name, "bleahM");
	sample.fractions = 0;
	sample.len = region_bytes;
	sample.loop_start = loop_start * 2;
	sample.loop_end = loop_end * 2;
	sample.base_freq = region_samplerate[r];
	sample.low_note = freq_table[region[r][LOKEY] ];
	sample.high_note = freq_table[region[r][HIKEY] ];
	sample.base_note = freq_table[region[r][PITCH_KEYCENTER] ];
	sample.detune = 512;
	sample.panning = 7;

	sample.tremolo_sweep = 0;
	sample.tremolo_rate = 0;
	sample.tremolo_depth = 0;
	sample.vibrato_sweep = 0;
	sample.vibrato_rate = 0;
	sample.vibrato_depth = 0;
	sample.modes = region_modes[r];
	sample.scale_frequency = region[r][PITCH_KEYCENTER];
	sample.scale_factor = 1024;

	sample.volume = 255;

	make_sample(&sample, r);

	memcpy (buf, (char *) &sample, sizeof (sample));
	fix_sample_write(buf, &sample);

	write(stereofd, buf, sizeof (sample));

  /* wave data */
	if (!stereo_layer)
		write(stereofd, left_buf + data_width * region_start, region_bytes);
	else
		write(stereofd, right_buf + data_width * region_start, region_bytes);

     } /* for each key range */
   } /* for each stereo channel */
  } /* for each vlayer */

}
#endif



