shithub: sox

Download patch

ref: 09be0dfccb00898ec6f9ffaa3ec6f4133705420f
parent: d329019a4e48bc361c4f2700b32785af8bb76050
author: robs <robs>
date: Wed Mar 19 18:48:52 EDT 2008

Made sox.c work with sox.h; had to move some stuff around

--- a/src/8svx.c
+++ b/src/8svx.c
@@ -43,7 +43,7 @@
 
         if (! ft->seekable)
         {
-                sox_fail_errno(ft,SOX_EINVAL,"8svx input file must be a file, not a pipe");
+                lsx_fail_errno(ft,SOX_EINVAL,"8svx input file must be a file, not a pipe");
                 return (SOX_EOF);
         }
         rate = 0;
@@ -50,49 +50,49 @@
         channels = 1;
 
         /* read FORM chunk */
-        if (sox_reads(ft, buf, 4) == SOX_EOF || strncmp(buf, "FORM", 4) != 0)
+        if (lsx_reads(ft, buf, 4) == SOX_EOF || strncmp(buf, "FORM", 4) != 0)
         {
-                sox_fail_errno(ft, SOX_EHDR, "Header did not begin with magic word 'FORM'");
+                lsx_fail_errno(ft, SOX_EHDR, "Header did not begin with magic word 'FORM'");
                 return(SOX_EOF);
         }
-        sox_readdw(ft, &totalsize);
-        if (sox_reads(ft, buf, 4) == SOX_EOF || strncmp(buf, "8SVX", 4) != 0)
+        lsx_readdw(ft, &totalsize);
+        if (lsx_reads(ft, buf, 4) == SOX_EOF || strncmp(buf, "8SVX", 4) != 0)
         {
-                sox_fail_errno(ft, SOX_EHDR, "'FORM' chunk does not specify '8SVX' as type");
+                lsx_fail_errno(ft, SOX_EHDR, "'FORM' chunk does not specify '8SVX' as type");
                 return(SOX_EOF);
         }
 
         /* read chunks until 'BODY' (or end) */
-        while (sox_reads(ft, buf, 4) == SOX_SUCCESS && strncmp(buf,"BODY",4) != 0) {
+        while (lsx_reads(ft, buf, 4) == SOX_SUCCESS && strncmp(buf,"BODY",4) != 0) {
                 if (strncmp(buf,"VHDR",4) == 0) {
-                        sox_readdw(ft, &chunksize);
+                        lsx_readdw(ft, &chunksize);
                         if (chunksize != 20)
                         {
-                                sox_fail_errno(ft, SOX_EHDR, "VHDR chunk has bad size");
+                                lsx_fail_errno(ft, SOX_EHDR, "VHDR chunk has bad size");
                                 return(SOX_EOF);
                         }
-                        sox_seeki(ft,12,SEEK_CUR);
-                        sox_readw(ft, &rate);
-                        sox_seeki(ft,1,SEEK_CUR);
-                        sox_readbuf(ft, buf,1);
+                        lsx_seeki(ft,12,SEEK_CUR);
+                        lsx_readw(ft, &rate);
+                        lsx_seeki(ft,1,SEEK_CUR);
+                        lsx_readbuf(ft, buf,1);
                         if (buf[0] != 0)
                         {
-                                sox_fail_errno(ft, SOX_EFMT, "Unsupported data compression");
+                                lsx_fail_errno(ft, SOX_EFMT, "Unsupported data compression");
                                 return(SOX_EOF);
                         }
-                        sox_seeki(ft,4,SEEK_CUR);
+                        lsx_seeki(ft,4,SEEK_CUR);
                         continue;
                 }
 
                 if (strncmp(buf,"ANNO",4) == 0) {
-                        sox_readdw(ft, &chunksize);
+                        lsx_readdw(ft, &chunksize);
                         if (chunksize & 1)
                                 chunksize++;
                         chunk_buf = (char *) xmalloc(chunksize + 2);
-                        if (sox_readbuf(ft, chunk_buf,(size_t)chunksize)
+                        if (lsx_readbuf(ft, chunk_buf,(size_t)chunksize)
                                         != chunksize)
                         {
-                                sox_fail_errno(ft, SOX_EHDR, "Couldn't read all of header");
+                                lsx_fail_errno(ft, SOX_EHDR, "Couldn't read all of header");
                                 return(SOX_EOF);
                         }
                         chunk_buf[chunksize] = '\0';
@@ -103,14 +103,14 @@
                 }
 
                 if (strncmp(buf,"NAME",4) == 0) {
-                        sox_readdw(ft, &chunksize);
+                        lsx_readdw(ft, &chunksize);
                         if (chunksize & 1)
                                 chunksize++;
                         chunk_buf = (char *) xmalloc(chunksize + 1);
-                        if (sox_readbuf(ft, chunk_buf,(size_t)chunksize)
+                        if (lsx_readbuf(ft, chunk_buf,(size_t)chunksize)
                                         != chunksize)
                         {
-                                sox_fail_errno(ft, SOX_EHDR, "Couldn't read all of header");
+                                lsx_fail_errno(ft, SOX_EHDR, "Couldn't read all of header");
                                 return(SOX_EOF);
                         }
                         chunk_buf[chunksize] = '\0';
@@ -121,13 +121,13 @@
                 }
 
                 if (strncmp(buf,"CHAN",4) == 0) {
-                        sox_readdw(ft, &chunksize);
+                        lsx_readdw(ft, &chunksize);
                         if (chunksize != 4)
                         {
-                                sox_fail_errno(ft, SOX_EHDR, "Couldn't read all of header");
+                                lsx_fail_errno(ft, SOX_EHDR, "Couldn't read all of header");
                                 return(SOX_EOF);
                         }
-                        sox_readdw(ft, &channels);
+                        lsx_readdw(ft, &channels);
                         channels = (channels & 0x01) +
                                         ((channels & 0x02) >> 1) +
                                         ((channels & 0x04) >> 2) +
@@ -137,10 +137,10 @@
                 }
 
                 /* some other kind of chunk */
-                sox_readdw(ft, &chunksize);
+                lsx_readdw(ft, &chunksize);
                 if (chunksize & 1)
                         chunksize++;
-                sox_seeki(ft,(int32_t)chunksize,SEEK_CUR);
+                lsx_seeki(ft,(int32_t)chunksize,SEEK_CUR);
                 continue;
 
         }
@@ -147,15 +147,15 @@
 
         if (rate == 0)
         {
-                sox_fail_errno(ft, SOX_ERATE, "Invalid sample rate");
+                lsx_fail_errno(ft, SOX_ERATE, "Invalid sample rate");
                 return(SOX_EOF);
         }
         if (strncmp(buf,"BODY",4) != 0)
         {
-                sox_fail_errno(ft, SOX_EHDR, "BODY chunk not found");
+                lsx_fail_errno(ft, SOX_EHDR, "BODY chunk not found");
                 return(SOX_EOF);
         }
-        sox_readdw(ft, &(p->nsamples));
+        lsx_readdw(ft, &(p->nsamples));
 
         ft->length = p->nsamples;
         ft->signal.channels = channels;
@@ -165,12 +165,12 @@
 
         /* open files to channels */
         p->ch[0] = ft->fp;
-        chan1_pos = sox_tell(ft);
+        chan1_pos = lsx_tell(ft);
 
         for (i = 1; i < channels; i++) {
                 if ((p->ch[i] = fopen(ft->filename, "rb")) == NULL)
                 {
-                        sox_fail_errno(ft,errno,"Can't open channel file '%s'",
+                        lsx_fail_errno(ft,errno,"Can't open channel file '%s'",
                                 ft->filename);
                         return(SOX_EOF);
                 }
@@ -178,12 +178,12 @@
                 /* position channel files */
                 if (fseeko(p->ch[i],chan1_pos,SEEK_SET))
                 {
-                    sox_fail_errno (ft,errno,"Can't position channel %d",i);
+                    lsx_fail_errno (ft,errno,"Can't position channel %d",i);
                     return(SOX_EOF);
                 }
                 if (fseeko(p->ch[i],(off_t)(p->nsamples/channels*i),SEEK_CUR))
                 {
-                    sox_fail_errno (ft,errno,"Can't seek channel %d",i);
+                    lsx_fail_errno (ft,errno,"Can't seek channel %d",i);
                     return(SOX_EOF);
                 }
         }
@@ -243,7 +243,7 @@
         for (i = 1; i < ft->signal.channels; i++) {
                 if ((p->ch[i] = tmpfile()) == NULL)
                 {
-                        sox_fail_errno(ft,errno,"Can't open channel output file");
+                        lsx_fail_errno(ft,errno,"Can't open channel output file");
                         return(SOX_EOF);
                 }
         }
@@ -294,13 +294,13 @@
         for (i = 1; i < ft->signal.channels; i++) {
                 if (fseeko(p->ch[i], (off_t)0, 0))
                 {
-                        sox_fail_errno (ft,errno,"Can't rewind channel output file %d",i);
+                        lsx_fail_errno (ft,errno,"Can't rewind channel output file %d",i);
                         return(SOX_EOF);
                 }
                 while (!feof(p->ch[i])) {
                         len = fread(svxbuf, 1, 512, p->ch[i]);
                         if (fwrite (svxbuf, 1, len, p->ch[0]) != len) {
-                          sox_fail_errno (ft,errno,"Can't write channel output file %d",i);
+                          lsx_fail_errno (ft,errno,"Can't write channel output file %d",i);
                           return SOX_EOF;
                         }
                 }
@@ -309,12 +309,12 @@
 
         /* add a pad byte if BODY size is odd */
         if(p->nsamples % 2 != 0)
-            sox_writeb(ft, '\0');
+            lsx_writeb(ft, '\0');
 
         /* fixup file sizes in header */
-        if (sox_seeki(ft, 0, 0) != 0)
+        if (lsx_seeki(ft, 0, 0) != 0)
         {
-                sox_fail_errno(ft,errno,"can't rewind output file to rewrite 8SVX header");
+                lsx_fail_errno(ft,errno,"can't rewind output file to rewrite 8SVX header");
                 return(SOX_EOF);
         }
         svxwriteheader(ft, p->nsamples);
@@ -332,31 +332,31 @@
         /* FORM size must be even */
         if(formsize % 2 != 0) formsize++;
 
-        sox_writes(ft, "FORM");
-        sox_writedw(ft, formsize);  /* size of file */
-        sox_writes(ft, "8SVX"); /* File type */
+        lsx_writes(ft, "FORM");
+        lsx_writedw(ft, formsize);  /* size of file */
+        lsx_writes(ft, "8SVX"); /* File type */
 
-        sox_writes(ft, "VHDR");
-        sox_writedw(ft, 20); /* number of bytes to follow */
-        sox_writedw(ft, nsamples/ft->signal.channels);  /* samples, 1-shot */
-        sox_writedw(ft, 0);  /* samples, repeat */
-        sox_writedw(ft, 0);  /* samples per repeat cycle */
-        sox_writew(ft, min(65535, (unsigned)(ft->signal.rate + .5)));
-        sox_writeb(ft,1); /* number of octabes */
-        sox_writeb(ft,0); /* data compression (none) */
-        sox_writew(ft,1); sox_writew(ft,0); /* volume */
+        lsx_writes(ft, "VHDR");
+        lsx_writedw(ft, 20); /* number of bytes to follow */
+        lsx_writedw(ft, nsamples/ft->signal.channels);  /* samples, 1-shot */
+        lsx_writedw(ft, 0);  /* samples, repeat */
+        lsx_writedw(ft, 0);  /* samples per repeat cycle */
+        lsx_writew(ft, min(65535, (unsigned)(ft->signal.rate + .5)));
+        lsx_writeb(ft,1); /* number of octabes */
+        lsx_writeb(ft,0); /* data compression (none) */
+        lsx_writew(ft,1); lsx_writew(ft,0); /* volume */
 
-        sox_writes(ft, "ANNO");
-        sox_writedw(ft, 32); /* length of block */
-        sox_writes(ft, "File created by Sound Exchange  ");
+        lsx_writes(ft, "ANNO");
+        lsx_writedw(ft, 32); /* length of block */
+        lsx_writes(ft, "File created by Sound Exchange  ");
 
-        sox_writes(ft, "CHAN");
-        sox_writedw(ft, 4);
-        sox_writedw(ft, (ft->signal.channels == 2) ? 6u :
+        lsx_writes(ft, "CHAN");
+        lsx_writedw(ft, 4);
+        lsx_writedw(ft, (ft->signal.channels == 2) ? 6u :
                    (ft->signal.channels == 4) ? 15u : 2u);
 
-        sox_writes(ft, "BODY");
-        sox_writedw(ft, nsamples); /* samples in file */
+        lsx_writes(ft, "BODY");
+        lsx_writedw(ft, nsamples); /* samples in file */
 }
 
 SOX_FORMAT_HANDLER(svx)
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -19,34 +19,35 @@
 
 # Format with: !xargs echo|tr ' ' '\n'|sort|column|expand|sed 's/^/  /'
 set(effects_srcs
-  biquad          earwax          mcompand        polyphas        splice
-  biquads         echo            mixer           remix           stat
-  chorus          echos           noiseprof       repeat          stretch
-  compand         effects         noisered        resample        swap
-  compandt        fade            normalise       reverb          synth
-  contrast        FFT             pad             reverse         tempo
-  dcshift         filter          pan             silence         tremolo
-  delay           flanger         phaser          skeleff         trim
-  dither          key             pitch           speed           vol
+  biquad          earwax          mixer           remix           stat
+  biquads         echo            noiseprof       repeat          stretch
+  chorus          echos           noisered        resample        swap
+  compand         fade            normalise       reverb          synth
+  compandt        FFT             pad             reverse         tempo
+  contrast        filter          pan             silence         tremolo
+  dcshift         flanger         phaser          skeleff         trim
+  delay           key             pitch           speed           vol
+  dither          mcompand        polyphas        splice
 )
 set(formats_srcs
-  8svx            cvsd-fmt        htk             s1-fmt          u1-fmt
-  adpcm           dat             ima-fmt         s2-fmt          u2-fmt
-  adpcms          dvms-fmt        ima_rw          s3-fmt          u3-fmt
-  aifc-fmt        formats         la-fmt          s4-fmt          u4-fmt
-  aiff            g711            lpc10.c         sf              ul-fmt
-  aiff-fmt        g721            lu-fmt          skelform        voc
-  al-fmt          g723_24         maud            smp             vox
-  au              g723_40         nulfile         sounder         vox-fmt
-  avr             g72x            prc             soundtool       wav
-  cdr             gsm.c           raw             sphere          wve
-  cvsd            hcom            raw-fmt         tx16w           xa
+  8svx            cvsd-fmt        ima-fmt         s2-fmt          u2-fmt
+  adpcm           dat             ima_rw          s3-fmt          u3-fmt
+  adpcms          dvms-fmt        la-fmt          s4-fmt          u4-fmt
+  aifc-fmt        g711            lpc10.c         sf              ul-fmt
+  aiff            g721            lu-fmt          skelform        voc
+  aiff-fmt        g723_24         maud            smp             vox
+  al-fmt          g723_40         nulfile         sounder         vox-fmt
+  au              g72x            prc             soundtool       wav
+  avr             gsm.c           raw             sphere          wve
+  cdr             hcom            raw-fmt         tx16w           xa
+  cvsd            htk             s1-fmt          u1-fmt
 )
 add_library(lib${PROJECT_NAME}
-  ${effects_srcs}         misc                    util
-  ${formats_srcs}         ${optional_srcs}        xmalloc
-  getopt                  soxio
-  getopt1                 soxstdint
+  effects                 ${formats_srcs}         ${optional_srcs}
+  effects_i               getopt                  util
+  ${effects_srcs}         getopt1                 xmalloc
+  formats                 libsox soxstdint
+  formats_i               libsox_i
 )
 add_executable(${PROJECT_NAME} ${PROJECT_NAME}.c)
 target_link_libraries(${PROJECT_NAME} lib${PROJECT_NAME} lpc10 ${optional_libs})
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -200,7 +200,7 @@
 	  pan.c phaser.c pitch.c polyphas.c rabbit.c remix.c repeat.c \
 	  resample.c reverb.c reverse.c silence.c skeleff.c speed.c	\
 	  splice.c stat.c stretch.c swap.c synth.c tempo.c tremolo.c trim.c \
-	  vol.c normalise.c delay.c contrast.c
+	  vol.c normalise.c delay.c contrast.c effects_i.c
 libsfx_la_CFLAGS = @SAMPLERATE_CFLAGS@
 libsfx_la_LIBADD = @SAMPLERATE_LIBS@ libsox.la
 
@@ -210,9 +210,9 @@
 
 libsox_la_SOURCES = adpcms.c adpcms.h aiff.c aiff.h cvsd.c cvsd.h cvsdfilt.h \
 	  g711.c g711.h g721.c g723_24.c g723_40.c g72x.c g72x.h vox.c vox.h \
-	  raw.c raw.h formats.c formats.h misc.c sox_i.h skelform.c \
-	  soxio.c util.c xmalloc.c xmalloc.h getopt.c getopt1.c getopt.h \
-	  soxconfig.h
+	  raw.c raw.h formats.c formats.h formats_i.c sox_i.h skelform.c \
+	  util.c xmalloc.c xmalloc.h getopt.c getopt1.c getopt.h \
+	  soxconfig.h util.h libsox.c libsox_i.c
 libsox_la_CFLAGS = 
 
 if HAVE_LIBLTDL
--- a/src/adpcms.c
+++ b/src/adpcms.c
@@ -156,7 +156,7 @@
 
   sox_adpcm_reset(state, type);
   
-  return sox_rawstart(ft, sox_true, sox_false, sox_true, type, 4);
+  return lsx_rawstart(ft, sox_true, sox_false, sox_true, type, 4);
 }
 
 int sox_adpcm_oki_start(sox_format_t * ft, adpcm_io_t state)
@@ -194,7 +194,7 @@
     state->store.flag = 0;
     ++n;
   }
-  while (n < len && sox_read_b_buf(ft, &byte, 1) == 1) {
+  while (n < len && lsx_read_b_buf(ft, &byte, 1) == 1) {
     word = adpcm_decode(byte >> 4, &state->encoder);
     *buffer++ = SOX_SIGNED_16BIT_TO_SAMPLE(word, ft->clips);
 
@@ -263,7 +263,7 @@
       state->file.buf[state->file.count++] = byte;
 
       if (state->file.count >= state->file.size) {
-        sox_writebuf(ft, state->file.buf, state->file.count);
+        lsx_writebuf(ft, state->file.buf, state->file.count);
 
         state->file.count = 0;
       }
@@ -300,7 +300,7 @@
     state->file.buf[state->file.count++] = byte;
   }
   if (state->file.count > 0)
-    sox_writebuf(ft, state->file.buf, state->file.count);
+    lsx_writebuf(ft, state->file.buf, state->file.count);
 }
 
 /******************************************************************************
--- a/src/aiff.c
+++ b/src/aiff.c
@@ -65,7 +65,7 @@
         new_offset += (channel_block - alignment);
     new_offset += aiff->dataStart;
 
-    ft->sox_errno = sox_seeki(ft, (sox_ssize_t)new_offset, SEEK_SET);
+    ft->sox_errno = lsx_seeki(ft, (sox_ssize_t)new_offset, SEEK_SET);
 
     if (ft->sox_errno == SOX_SUCCESS)
         aiff->nsamples = ft->length - (new_offset / size);
@@ -111,16 +111,16 @@
         int rc;
 
         /* FORM chunk */
-        if (sox_reads(ft, buf, 4) == SOX_EOF || strncmp(buf, "FORM", 4) != 0)
+        if (lsx_reads(ft, buf, 4) == SOX_EOF || strncmp(buf, "FORM", 4) != 0)
         {
-                sox_fail_errno(ft,SOX_EHDR,"AIFF header does not begin with magic word 'FORM'");
+                lsx_fail_errno(ft,SOX_EHDR,"AIFF header does not begin with magic word 'FORM'");
                 return(SOX_EOF);
         }
-        sox_readdw(ft, &totalsize);
-        if (sox_reads(ft, buf, 4) == SOX_EOF || (strncmp(buf, "AIFF", 4) != 0 && 
+        lsx_readdw(ft, &totalsize);
+        if (lsx_reads(ft, buf, 4) == SOX_EOF || (strncmp(buf, "AIFF", 4) != 0 && 
             strncmp(buf, "AIFC", 4) != 0))
         {
-                sox_fail_errno(ft,SOX_EHDR,"AIFF 'FORM' chunk does not specify 'AIFF' or 'AIFC' as type");
+                lsx_fail_errno(ft,SOX_EHDR,"AIFF 'FORM' chunk does not specify 'AIFF' or 'AIFC' as type");
                 return(SOX_EOF);
         }
 
@@ -128,7 +128,7 @@
         /* Skip everything but the COMM chunk and the SSND chunk */
         /* The SSND chunk must be the last in the file */
         while (1) {
-                if (sox_reads(ft, buf, 4) == SOX_EOF)
+                if (lsx_reads(ft, buf, 4) == SOX_EOF)
                 {
                         if (ssndsize > 0)
                         {
@@ -136,21 +136,21 @@
                         }
                         else
                         {
-                                sox_fail_errno(ft,SOX_EHDR,"Missing SSND chunk in AIFF file");
+                                lsx_fail_errno(ft,SOX_EHDR,"Missing SSND chunk in AIFF file");
                                 return(SOX_EOF);
                         }
                 }
                 if (strncmp(buf, "COMM", 4) == 0) {
                         /* COMM chunk */
-                        sox_readdw(ft, &chunksize);
-                        sox_readw(ft, &channels);
-                        sox_readdw(ft, &frames);
-                        sox_readw(ft, &bits);
+                        lsx_readdw(ft, &chunksize);
+                        lsx_readw(ft, &channels);
+                        lsx_readdw(ft, &frames);
+                        lsx_readw(ft, &bits);
                         rate = read_ieee_extended(ft);
                         chunksize -= 18;
                         if (chunksize > 0)
                         {
-                            sox_reads(ft, buf, 4);
+                            lsx_reads(ft, buf, 4);
                             chunksize -= 4;
                             if (strncmp(buf, "sowt", 4) == 0)
                             {
@@ -161,19 +161,19 @@
                             else if (strncmp(buf, "NONE", 4) != 0)
                             {
                                 buf[4] = 0;
-                                sox_fail_errno(ft,SOX_EHDR,"AIFC files that contain compressed data are not supported: %s",buf);
+                                lsx_fail_errno(ft,SOX_EHDR,"AIFC files that contain compressed data are not supported: %s",buf);
                                 return(SOX_EOF);
                             }
                         }
                         while(chunksize-- > 0)
-                            sox_readb(ft, (unsigned char *)&trash8);
+                            lsx_readb(ft, (unsigned char *)&trash8);
                         foundcomm = 1;
                 }
                 else if (strncmp(buf, "SSND", 4) == 0) {
                         /* SSND chunk */
-                        sox_readdw(ft, &chunksize);
-                        sox_readdw(ft, &offset);
-                        sox_readdw(ft, &blocksize);
+                        lsx_readdw(ft, &chunksize);
+                        lsx_readdw(ft, &offset);
+                        lsx_readdw(ft, &blocksize);
                         chunksize -= 8;
                         ssndsize = chunksize;
                         /* word-align chunksize in case it wasn't
@@ -184,14 +184,14 @@
                         if (!ft->seekable)
                                 break;
                         /* else, seek to end of sound and hunt for more */
-                        seekto = sox_tell(ft);
-                        sox_seeki(ft, (sox_ssize_t)chunksize, SEEK_CUR); 
+                        seekto = lsx_tell(ft);
+                        lsx_seeki(ft, (sox_ssize_t)chunksize, SEEK_CUR); 
                 }
                 else if (strncmp(buf, "MARK", 4) == 0) {
                         /* MARK chunk */
-                        sox_readdw(ft, &chunksize);
+                        lsx_readdw(ft, &chunksize);
                         if (chunksize >= sizeof(nmarks)) {
-                          sox_readw(ft, &nmarks);
+                          lsx_readw(ft, &nmarks);
                           chunksize -= sizeof(nmarks);
                         }
                         else nmarks = 0;
@@ -214,14 +214,14 @@
 
                                 if (chunksize < 6)
                                     break;
-                                sox_readw(ft, &(marks[i].id));
-                                sox_readdw(ft, &(marks[i].position));
+                                lsx_readw(ft, &(marks[i].id));
+                                lsx_readdw(ft, &(marks[i].position));
                                 chunksize -= 6;
                                 /* If error reading length then
                                  * don't try to read more bytes
                                  * based on that value.
                                  */
-                                if (sox_readb(ft, &len) != SOX_SUCCESS)
+                                if (lsx_readb(ft, &len) != SOX_SUCCESS)
                                     break;
                                 --chunksize;
                                 if (len > chunksize)
@@ -231,7 +231,7 @@
                                     read_len = 39;
                                 for(j = 0; j < len && chunksize; j++) 
                                 {
-                                    sox_readb(ft, &tmp_c);
+                                    lsx_readb(ft, &tmp_c);
                                     if (j < read_len)
                                         marks[i].name[j] = tmp_c;
                                     chunksize--;
@@ -239,7 +239,7 @@
                                 marks[i].name[read_len] = 0;
                                 if ((len & 1) == 0 && chunksize) {
                                         chunksize--;
-                                        sox_readb(ft, (unsigned char *)&trash8);
+                                        lsx_readb(ft, (unsigned char *)&trash8);
                                 }
                         }
                         /* HA HA!  Sound Designer (and others) makes */
@@ -246,47 +246,47 @@
                         /* bogus files. It spits out bogus chunksize */
                         /* for MARK field */
                         while(chunksize-- > 0)
-                            sox_readb(ft, (unsigned char *)&trash8);
+                            lsx_readb(ft, (unsigned char *)&trash8);
                 }
                 else if (strncmp(buf, "INST", 4) == 0) {
                         /* INST chunk */
-                        sox_readdw(ft, &chunksize);
-                        sox_readb(ft, (unsigned char *)&(ft->instr.MIDInote));
-                        sox_readb(ft, (unsigned char *)&trash8);
-                        sox_readb(ft, (unsigned char *)&(ft->instr.MIDIlow));
-                        sox_readb(ft, (unsigned char *)&(ft->instr.MIDIhi));
+                        lsx_readdw(ft, &chunksize);
+                        lsx_readb(ft, (unsigned char *)&(ft->instr.MIDInote));
+                        lsx_readb(ft, (unsigned char *)&trash8);
+                        lsx_readb(ft, (unsigned char *)&(ft->instr.MIDIlow));
+                        lsx_readb(ft, (unsigned char *)&(ft->instr.MIDIhi));
                         /* Low  velocity */
-                        sox_readb(ft, (unsigned char *)&trash8);
+                        lsx_readb(ft, (unsigned char *)&trash8);
                         /* Hi  velocity */
-                        sox_readb(ft, (unsigned char *)&trash8);
-                        sox_readw(ft, (unsigned short *)&trash16);/* gain */
-                        sox_readw(ft, &looptype); /* sustain loop */
+                        lsx_readb(ft, (unsigned char *)&trash8);
+                        lsx_readw(ft, (unsigned short *)&trash16);/* gain */
+                        lsx_readw(ft, &looptype); /* sustain loop */
                         ft->loops[0].type = looptype;
-                        sox_readw(ft, &sustainLoopBegin); /* begin marker */
-                        sox_readw(ft, &sustainLoopEnd);    /* end marker */
-                        sox_readw(ft, &looptype); /* release loop */
+                        lsx_readw(ft, &sustainLoopBegin); /* begin marker */
+                        lsx_readw(ft, &sustainLoopEnd);    /* end marker */
+                        lsx_readw(ft, &looptype); /* release loop */
                         ft->loops[1].type = looptype;
-                        sox_readw(ft, &releaseLoopBegin);  /* begin marker */
-                        sox_readw(ft, &releaseLoopEnd);    /* end marker */
+                        lsx_readw(ft, &releaseLoopBegin);  /* begin marker */
+                        lsx_readw(ft, &releaseLoopEnd);    /* end marker */
 
                         foundinstr = 1;
                 }
                 else if (strncmp(buf, "APPL", 4) == 0) {
-                        sox_readdw(ft, &chunksize);
+                        lsx_readdw(ft, &chunksize);
                         /* word-align chunksize in case it wasn't
                          * done by writing application already.
                          */
                         chunksize += (chunksize % 2);
                         while(chunksize-- > 0)
-                            sox_readb(ft, (unsigned char *)&trash8);
+                            lsx_readb(ft, (unsigned char *)&trash8);
                 }
                 else if (strncmp(buf, "ALCH", 4) == 0) {
                         /* I think this is bogus and gets grabbed by APPL */
                         /* INST chunk */
-                        sox_readdw(ft, &trash32);                /* ENVS - jeez! */
-                        sox_readdw(ft, &chunksize);
+                        lsx_readdw(ft, &trash32);                /* ENVS - jeez! */
+                        lsx_readdw(ft, &chunksize);
                         while(chunksize-- > 0)
-                            sox_readb(ft, (unsigned char *)&trash8);
+                            lsx_readb(ft, (unsigned char *)&trash8);
                 }
                 else if (strncmp(buf, "ANNO", 4) == 0) {
                   rc = textChunk(&annotation, "Annotation:", ft);
@@ -296,7 +296,7 @@
                     return(SOX_EOF);
                   }
                   if (annotation)
-                    append_comments(&ft->comments, annotation);
+                    sox_append_comments(&ft->comments, annotation);
                   free(annotation);
                 }
                 else if (strncmp(buf, "COMT", 4) == 0) {
@@ -306,7 +306,7 @@
                     return(SOX_EOF);
                   }
                   if (comment)
-                    append_comments(&ft->comments, comment);
+                    sox_append_comments(&ft->comments, comment);
                   free(comment);
                 }
                 else if (strncmp(buf, "AUTH", 4) == 0) {
@@ -340,21 +340,21 @@
                   free(copyright);
                 }
                 else {
-                        if (sox_eof(ft))
+                        if (lsx_eof(ft))
                                 break;
                         buf[4] = 0;
                         sox_debug("AIFFstartread: ignoring '%s' chunk", buf);
-                        sox_readdw(ft, &chunksize);
-                        if (sox_eof(ft))
+                        lsx_readdw(ft, &chunksize);
+                        if (lsx_eof(ft))
                                 break;
-                        /* Skip the chunk using sox_readb() so we may read
+                        /* Skip the chunk using lsx_readb() so we may read
                            from a pipe */
                         while (chunksize-- > 0) {
-                            if (sox_readb(ft, (unsigned char *)&trash8) == SOX_EOF)
+                            if (lsx_readb(ft, (unsigned char *)&trash8) == SOX_EOF)
                                         break;
                         }
                 }
-                if (sox_eof(ft))
+                if (lsx_eof(ft))
                         break;
         }
 
@@ -365,10 +365,10 @@
         if (ft->seekable)
         {
                 if (seekto > 0)
-                        sox_seeki(ft, seekto, SEEK_SET);
+                        lsx_seeki(ft, seekto, SEEK_SET);
                 else
                 {
-                        sox_fail_errno(ft,SOX_EOF,"AIFF: no sound data on input file");
+                        lsx_fail_errno(ft,SOX_EOF,"AIFF: no sound data on input file");
                         return(SOX_EOF);
                 }
         }
@@ -377,9 +377,9 @@
             sox_warn("AIFF header has invalid blocksize.  Ignoring but expect a premature EOF");
 
         while (offset-- > 0) {
-                if (sox_readb(ft, (unsigned char *)&trash8) == SOX_EOF)
+                if (lsx_readb(ft, (unsigned char *)&trash8) == SOX_EOF)
                 {
-                        sox_fail_errno(ft,errno,"unexpected EOF while skipping AIFF offset");
+                        lsx_fail_errno(ft,errno,"unexpected EOF while skipping AIFF offset");
                         return(SOX_EOF);
                 }
         }
@@ -400,7 +400,7 @@
                     ft->encoding.bits_per_sample = 32;
                 else
                 {
-                    sox_fail_errno(ft,SOX_EFMT,"unsupported sample size in AIFF header: %d", bits);
+                    lsx_fail_errno(ft,SOX_EFMT,"unsupported sample size in AIFF header: %d", bits);
                     return(SOX_EOF);
                 }
         } else  {
@@ -410,7 +410,7 @@
                         || (ft->encoding.bits_per_sample == 0)) {
                   sox_report("You must specify # channels, sample rate, signed/unsigned,");
                   sox_report("and 8/16 on the command line.");
-                  sox_fail_errno(ft,SOX_EFMT,"Bogus AIFF file: no COMM section.");
+                  lsx_fail_errno(ft,SOX_EFMT,"Bogus AIFF file: no COMM section.");
                   return(SOX_EOF);
                 }
 
@@ -474,13 +474,13 @@
         }
         reportInstrument(ft);
 
-        /* Needed because of sox_rawread() */
-        rc = sox_rawstartread(ft);
+        /* Needed because of lsx_rawread() */
+        rc = lsx_rawstartread(ft);
         if (rc)
             return rc;
 
         ft->length = aiff->nsamples;    /* for seeking */
-        aiff->dataStart = sox_tell(ft);
+        aiff->dataStart = lsx_tell(ft);
 
         return(SOX_SUCCESS);
 }
@@ -515,12 +515,12 @@
 static int textChunk(char **text, char *chunkDescription, sox_format_t * ft) 
 {
   uint32_t chunksize;
-  sox_readdw(ft, &chunksize);
+  lsx_readdw(ft, &chunksize);
   /* allocate enough memory to hold the text including a terminating \0 */
   *text = (char *) xmalloc((size_t) chunksize + 1);
-  if (sox_readbuf(ft, *text, chunksize) != chunksize)
+  if (lsx_readbuf(ft, *text, chunksize) != chunksize)
   {
-    sox_fail_errno(ft,SOX_EOF,"AIFF: Unexpected EOF in %s header", chunkDescription);
+    lsx_fail_errno(ft,SOX_EOF,"AIFF: Unexpected EOF in %s header", chunkDescription);
     return(SOX_EOF);
   }
   *(*text + chunksize) = '\0';
@@ -528,9 +528,9 @@
         {
                 /* Read past pad byte */
                 char c;
-                if (sox_readbuf(ft, &c, 1) != 1)
+                if (lsx_readbuf(ft, &c, 1) != 1)
                 {
-                sox_fail_errno(ft,SOX_EOF,"AIFF: Unexpected EOF in %s header", chunkDescription);
+                lsx_fail_errno(ft,SOX_EOF,"AIFF: Unexpected EOF in %s header", chunkDescription);
                         return(SOX_EOF);
                 }
         }
@@ -551,17 +551,17 @@
   unsigned int totalReadLength = 0;
   unsigned int commentIndex;
 
-  sox_readdw(ft, &chunksize);
-  sox_readw(ft, &numComments);
+  lsx_readdw(ft, &chunksize);
+  lsx_readw(ft, &numComments);
   totalReadLength += 2; /* chunksize doesn't count */
   for(commentIndex = 0; commentIndex < numComments; commentIndex++) {
     unsigned short commentLength;
 
-    sox_readdw(ft, &timeStamp);
-    sox_readw(ft, &markerId);
-    sox_readw(ft, &commentLength);
+    lsx_readdw(ft, &timeStamp);
+    lsx_readw(ft, &markerId);
+    lsx_readw(ft, &commentLength);
     if (((size_t)totalCommentLength) + commentLength > USHRT_MAX) {
-        sox_fail_errno(ft,SOX_EOF,"AIFF: Comment too long in %s header", chunkDescription);
+        lsx_fail_errno(ft,SOX_EOF,"AIFF: Comment too long in %s header", chunkDescription);
         return(SOX_EOF);
     }
     totalCommentLength += commentLength;
@@ -573,8 +573,8 @@
       *text = xrealloc(*text, (size_t) totalCommentLength + 1);
     }
 
-    if (sox_readbuf(ft, *text + totalCommentLength - commentLength, commentLength) != commentLength) {
-        sox_fail_errno(ft,SOX_EOF,"AIFF: Unexpected EOF in %s header", chunkDescription);
+    if (lsx_readbuf(ft, *text + totalCommentLength - commentLength, commentLength) != commentLength) {
+        lsx_fail_errno(ft,SOX_EOF,"AIFF: Unexpected EOF in %s header", chunkDescription);
         return(SOX_EOF);
     }
     *(*text + totalCommentLength) = '\0';
@@ -582,8 +582,8 @@
     if (commentLength % 2) {
         /* Read past pad byte */
         char c;
-        if (sox_readbuf(ft, &c, 1) != 1) {
-            sox_fail_errno(ft,SOX_EOF,"AIFF: Unexpected EOF in %s header", chunkDescription);
+        if (lsx_readbuf(ft, &c, 1) != 1) {
+            lsx_fail_errno(ft,SOX_EOF,"AIFF: Unexpected EOF in %s header", chunkDescription);
             return(SOX_EOF);
         }
     }
@@ -594,7 +594,7 @@
        size_t i;
        char c;
        for (i=0; i < chunksize - totalReadLength; i++ )
-           sox_readbuf(ft, &c, 1);
+           lsx_readbuf(ft, &c, 1);
   }
   return(SOX_SUCCESS);
 }
@@ -606,7 +606,7 @@
 
         if ((sox_size_t)len > aiff->nsamples)
                 len = aiff->nsamples;
-        done = sox_rawread(ft, buf, len);
+        done = lsx_rawread(ft, buf, len);
         if (done == 0 && aiff->nsamples != 0)
                 sox_warn("Premature EOF on AIFF input file");
         aiff->nsamples -= done;
@@ -621,13 +621,13 @@
 
         if (!ft->seekable)
         {
-            while (! sox_eof(ft)) 
+            while (! lsx_eof(ft)) 
             {
-                if (sox_readbuf(ft, buf, 4) != 4)
+                if (lsx_readbuf(ft, buf, 4) != 4)
                         break;
 
-                sox_readdw(ft, &chunksize);
-                if (sox_eof(ft))
+                lsx_readdw(ft, &chunksize);
+                if (lsx_eof(ft))
                         break;
                 buf[4] = '\0';
                 sox_warn("Ignoring AIFF tail chunk: '%s', %d bytes long", 
@@ -636,7 +636,7 @@
                         sox_warn("       You're stripping MIDI/loop info!");
                 while (chunksize-- > 0) 
                 {
-                        if (sox_readb(ft, (unsigned char *)&trash) == SOX_EOF)
+                        if (lsx_readb(ft, (unsigned char *)&trash) == SOX_EOF)
                                 break;
                 }
             }
@@ -659,8 +659,8 @@
         aiff_t aiff = (aiff_t ) ft->priv;
         int rc;
 
-        /* Needed because sox_rawwrite() */
-        rc = sox_rawstartwrite(ft);
+        /* Needed because lsx_rawwrite() */
+        rc = lsx_rawstartwrite(ft);
         if (rc)
             return rc;
 
@@ -679,7 +679,7 @@
 {
         aiff_t aiff = (aiff_t ) ft->priv;
         aiff->nsamples += len;
-        sox_rawwrite(ft, buf, len);
+        lsx_rawwrite(ft, buf, len);
         return(len);
 }
 
@@ -692,17 +692,17 @@
         if (aiff->nsamples % 2 == 1 && ft->encoding.bits_per_sample == 8 && ft->signal.channels == 1)
         {
             sox_sample_t buf = 0;
-            sox_rawwrite(ft, &buf, 1);
+            lsx_rawwrite(ft, &buf, 1);
         }
 
         if (!ft->seekable)
         {
-            sox_fail_errno(ft,SOX_EOF,"Non-seekable file.");
+            lsx_fail_errno(ft,SOX_EOF,"Non-seekable file.");
             return(SOX_EOF);
         }
-        if (sox_seeki(ft, 0, SEEK_SET) != 0)
+        if (lsx_seeki(ft, 0, SEEK_SET) != 0)
         {
-                sox_fail_errno(ft,errno,"can't rewind output file to rewrite AIFF header");
+                lsx_fail_errno(ft,errno,"can't rewind output file to rewrite AIFF header");
                 return(SOX_EOF);
         }
         return(aiffwriteheader(ft, aiff->nsamples / ft->signal.channels));
@@ -717,7 +717,7 @@
         unsigned i;
         sox_size_t padded_comment_size = 0, comment_size = 0;
         sox_size_t comment_chunk_size = 0;
-        char * comment = cat_comments(ft->comments);
+        char * comment = sox_cat_comments(ft->comments);
 
         /* MARK and INST chunks */
         if (ft->instr.nloops) {
@@ -739,7 +739,7 @@
                 bits = 32;
         else
         {
-                sox_fail_errno(ft,SOX_EFMT,"unsupported output encoding/size for AIFF header");
+                lsx_fail_errno(ft,SOX_EFMT,"unsupported output encoding/size for AIFF header");
                 return(SOX_EOF);
         }
 
@@ -758,96 +758,96 @@
           hsize += 8 /* COMT hdr */ + comment_chunk_size; 
         }
 
-        sox_writes(ft, "FORM"); /* IFF header */
+        lsx_writes(ft, "FORM"); /* IFF header */
         /* file size */
-        sox_writedw(ft, hsize + nframes * (ft->encoding.bits_per_sample >> 3) * ft->signal.channels); 
-        sox_writes(ft, "AIFF"); /* File type */
+        lsx_writedw(ft, hsize + nframes * (ft->encoding.bits_per_sample >> 3) * ft->signal.channels); 
+        lsx_writes(ft, "AIFF"); /* File type */
 
         /* Now we write the COMT comment chunk using the precomputed sizes */
         if (ft->comments)
         {
-          sox_writes(ft, "COMT");
-          sox_writedw(ft, comment_chunk_size);
+          lsx_writes(ft, "COMT");
+          lsx_writedw(ft, comment_chunk_size);
 
           /* one comment */
-          sox_writew(ft, 1);
+          lsx_writew(ft, 1);
 
           /* time stamp of comment, Unix knows of time from 1/1/1970,
              Apple knows time from 1/1/1904 */
-          sox_writedw(ft, (unsigned)((sox_globals.repeatable? 0 : time(NULL)) + 2082844800));
+          lsx_writedw(ft, (unsigned)((sox_globals.repeatable? 0 : time(NULL)) + 2082844800));
 
           /* A marker ID of 0 indicates the comment is not associated
              with a marker */
-          sox_writew(ft, 0);
+          lsx_writew(ft, 0);
 
           /* now write the count and the bytes of text */
-          sox_writew(ft, padded_comment_size);
-          sox_writes(ft, comment);
+          lsx_writew(ft, padded_comment_size);
+          lsx_writes(ft, comment);
           if (comment_size != padded_comment_size)
-                sox_writes(ft, " ");
+                lsx_writes(ft, " ");
         }
         free(comment);
 
         /* COMM chunk -- describes encoding (and #frames) */
-        sox_writes(ft, "COMM");
-        sox_writedw(ft, 18); /* COMM chunk size */
-        sox_writew(ft, ft->signal.channels); /* nchannels */
-        sox_writedw(ft, nframes); /* number of frames */
-        sox_writew(ft, bits); /* sample width, in bits */
+        lsx_writes(ft, "COMM");
+        lsx_writedw(ft, 18); /* COMM chunk size */
+        lsx_writew(ft, ft->signal.channels); /* nchannels */
+        lsx_writedw(ft, nframes); /* number of frames */
+        lsx_writew(ft, bits); /* sample width, in bits */
         write_ieee_extended(ft, (double)ft->signal.rate);
 
         /* MARK chunk -- set markers */
         if (ft->instr.nloops) {
-                sox_writes(ft, "MARK");
+                lsx_writes(ft, "MARK");
                 if (ft->instr.nloops > 2)
                         ft->instr.nloops = 2;
-                sox_writedw(ft, 2 + 16u*ft->instr.nloops);
-                sox_writew(ft, ft->instr.nloops);
+                lsx_writedw(ft, 2 + 16u*ft->instr.nloops);
+                lsx_writew(ft, ft->instr.nloops);
 
                 for(i = 0; i < ft->instr.nloops; i++) {
-                        sox_writew(ft, i + 1);
-                        sox_writedw(ft, ft->loops[i].start);
-                        sox_writeb(ft, 0);
-                        sox_writeb(ft, 0);
-                        sox_writew(ft, i*2 + 1);
-                        sox_writedw(ft, ft->loops[i].start + ft->loops[i].length);
-                        sox_writeb(ft, 0);
-                        sox_writeb(ft, 0);
+                        lsx_writew(ft, i + 1);
+                        lsx_writedw(ft, ft->loops[i].start);
+                        lsx_writeb(ft, 0);
+                        lsx_writeb(ft, 0);
+                        lsx_writew(ft, i*2 + 1);
+                        lsx_writedw(ft, ft->loops[i].start + ft->loops[i].length);
+                        lsx_writeb(ft, 0);
+                        lsx_writeb(ft, 0);
                 }
 
-                sox_writes(ft, "INST");
-                sox_writedw(ft, 20);
+                lsx_writes(ft, "INST");
+                lsx_writedw(ft, 20);
                 /* random MIDI shit that we default on */
-                sox_writeb(ft, (uint8_t)ft->instr.MIDInote);
-                sox_writeb(ft, 0);                       /* detune */
-                sox_writeb(ft, (uint8_t)ft->instr.MIDIlow);
-                sox_writeb(ft, (uint8_t)ft->instr.MIDIhi);
-                sox_writeb(ft, 1);                       /* low velocity */
-                sox_writeb(ft, 127);                     /* hi  velocity */
-                sox_writew(ft, 0);                               /* gain */
+                lsx_writeb(ft, (uint8_t)ft->instr.MIDInote);
+                lsx_writeb(ft, 0);                       /* detune */
+                lsx_writeb(ft, (uint8_t)ft->instr.MIDIlow);
+                lsx_writeb(ft, (uint8_t)ft->instr.MIDIhi);
+                lsx_writeb(ft, 1);                       /* low velocity */
+                lsx_writeb(ft, 127);                     /* hi  velocity */
+                lsx_writew(ft, 0);                               /* gain */
 
                 /* sustain loop */
-                sox_writew(ft, ft->loops[0].type);
-                sox_writew(ft, 1);                               /* marker 1 */
-                sox_writew(ft, 3);                               /* marker 3 */
+                lsx_writew(ft, ft->loops[0].type);
+                lsx_writew(ft, 1);                               /* marker 1 */
+                lsx_writew(ft, 3);                               /* marker 3 */
                 /* release loop, if there */
                 if (ft->instr.nloops == 2) {
-                        sox_writew(ft, ft->loops[1].type);
-                        sox_writew(ft, 2);                       /* marker 2 */
-                        sox_writew(ft, 4);                       /* marker 4 */
+                        lsx_writew(ft, ft->loops[1].type);
+                        lsx_writew(ft, 2);                       /* marker 2 */
+                        lsx_writew(ft, 4);                       /* marker 4 */
                 } else {
-                        sox_writew(ft, 0);                       /* no release loop */
-                        sox_writew(ft, 0);
-                        sox_writew(ft, 0);
+                        lsx_writew(ft, 0);                       /* no release loop */
+                        lsx_writew(ft, 0);
+                        lsx_writew(ft, 0);
                 }
         }
 
         /* SSND chunk -- describes data */
-        sox_writes(ft, "SSND");
+        lsx_writes(ft, "SSND");
         /* chunk size */
-        sox_writedw(ft, 8 + nframes * ft->signal.channels * (ft->encoding.bits_per_sample >> 3)); 
-        sox_writedw(ft, 0); /* offset */
-        sox_writedw(ft, 0); /* block size */
+        lsx_writedw(ft, 8 + nframes * ft->signal.channels * (ft->encoding.bits_per_sample >> 3)); 
+        lsx_writedw(ft, 0); /* offset */
+        lsx_writedw(ft, 0); /* block size */
         return(SOX_SUCCESS);
 }
 
@@ -856,8 +856,8 @@
         aiff_t aiff = (aiff_t ) ft->priv;
         int rc;
 
-        /* Needed because sox_rawwrite() */
-        rc = sox_rawstartwrite(ft);
+        /* Needed because lsx_rawwrite() */
+        rc = lsx_rawstartwrite(ft);
         if (rc)
             return rc;
 
@@ -881,17 +881,17 @@
         if (aiff->nsamples % 2 == 1 && ft->encoding.bits_per_sample == 8 && ft->signal.channels == 1)
         {
             sox_sample_t buf = 0;
-            sox_rawwrite(ft, &buf, 1);
+            lsx_rawwrite(ft, &buf, 1);
         }
 
         if (!ft->seekable)
         {
-            sox_fail_errno(ft,SOX_EOF,"Non-seekable file.");
+            lsx_fail_errno(ft,SOX_EOF,"Non-seekable file.");
             return(SOX_EOF);
         }
-        if (sox_seeki(ft, 0, SEEK_SET) != 0)
+        if (lsx_seeki(ft, 0, SEEK_SET) != 0)
         {
-                sox_fail_errno(ft,errno,"can't rewind output file to rewrite AIFC header");
+                lsx_fail_errno(ft,errno,"can't rewind output file to rewrite AIFC header");
                 return(SOX_EOF);
         }
         return(aifcwriteheader(ft, aiff->nsamples / ft->signal.channels));
@@ -918,39 +918,39 @@
                 bits = 32;
         else
         {
-                sox_fail_errno(ft,SOX_EFMT,"unsupported output encoding/size for AIFC header");
+                lsx_fail_errno(ft,SOX_EFMT,"unsupported output encoding/size for AIFC header");
                 return(SOX_EOF);
         }
 
-        sox_writes(ft, "FORM"); /* IFF header */
+        lsx_writes(ft, "FORM"); /* IFF header */
         /* file size */
-        sox_writedw(ft, hsize + nframes * (ft->encoding.bits_per_sample >> 3) * ft->signal.channels); 
-        sox_writes(ft, "AIFC"); /* File type */
+        lsx_writedw(ft, hsize + nframes * (ft->encoding.bits_per_sample >> 3) * ft->signal.channels); 
+        lsx_writes(ft, "AIFC"); /* File type */
 
         /* FVER chunk */
-        sox_writes(ft, "FVER");
-        sox_writedw(ft, 4); /* FVER chunk size */
-        sox_writedw(ft, 0xa2805140); /* version_date(May23,1990,2:40pm) */
+        lsx_writes(ft, "FVER");
+        lsx_writedw(ft, 4); /* FVER chunk size */
+        lsx_writedw(ft, 0xa2805140); /* version_date(May23,1990,2:40pm) */
 
         /* COMM chunk -- describes encoding (and #frames) */
-        sox_writes(ft, "COMM");
-        sox_writedw(ft, 18+4+1+15); /* COMM chunk size */
-        sox_writew(ft, ft->signal.channels); /* nchannels */
-        sox_writedw(ft, nframes); /* number of frames */
-        sox_writew(ft, bits); /* sample width, in bits */
+        lsx_writes(ft, "COMM");
+        lsx_writedw(ft, 18+4+1+15); /* COMM chunk size */
+        lsx_writew(ft, ft->signal.channels); /* nchannels */
+        lsx_writedw(ft, nframes); /* number of frames */
+        lsx_writew(ft, bits); /* sample width, in bits */
         write_ieee_extended(ft, (double)ft->signal.rate);
 
-        sox_writes(ft, "NONE"); /*compression_type*/
-        sox_writeb(ft, 14);
-        sox_writes(ft, "not compressed");
-        sox_writeb(ft, 0);
+        lsx_writes(ft, "NONE"); /*compression_type*/
+        lsx_writeb(ft, 14);
+        lsx_writes(ft, "not compressed");
+        lsx_writeb(ft, 0);
 
         /* SSND chunk -- describes data */
-        sox_writes(ft, "SSND");
+        lsx_writes(ft, "SSND");
         /* chunk size */
-        sox_writedw(ft, 8 + nframes * ft->signal.channels * (ft->encoding.bits_per_sample >> 3)); 
-        sox_writedw(ft, 0); /* offset */
-        sox_writedw(ft, 0); /* block size */
+        lsx_writedw(ft, 8 + nframes * ft->signal.channels * (ft->encoding.bits_per_sample >> 3)); 
+        lsx_writedw(ft, 0); /* offset */
+        lsx_writedw(ft, 0); /* block size */
 
         /* Any Private chunks shall appear after the required chunks (FORM,FVER,COMM,SSND) */
         return(SOX_SUCCESS);
@@ -959,9 +959,9 @@
 static double read_ieee_extended(sox_format_t * ft)
 {
         char buf[10];
-        if (sox_readbuf(ft, buf, 10) != 10)
+        if (lsx_readbuf(ft, buf, 10) != 10)
         {
-                sox_fail_errno(ft,SOX_EOF,"EOF while reading IEEE extended number");
+                lsx_fail_errno(ft,SOX_EOF,"EOF while reading IEEE extended number");
                 return(SOX_EOF);
         }
         return ConvertFromIeeeExtended((unsigned char *)buf);
@@ -975,7 +975,7 @@
                 x,
                 buf[0], buf[1], buf[2], buf[3], buf[4],
                 buf[5], buf[6], buf[7], buf[8], buf[9]);
-        (void)sox_writebuf(ft, buf, 10);
+        (void)lsx_writebuf(ft, buf, 10);
 }
 
 
--- a/src/alsa.c
+++ b/src/alsa.c
@@ -104,7 +104,7 @@
             case SOX_ENCODING_SIGN2:
                 if (!(snd_pcm_format_mask_test(fmask, SND_PCM_FORMAT_S8)))
                 {
-                    sox_fail_errno(ft,SOX_EFMT,"ALSA driver does not support signed byte samples");
+                    lsx_fail_errno(ft,SOX_EFMT,"ALSA driver does not support signed byte samples");
                     return SOX_EOF;
                 }
                 *fmt = SND_PCM_FORMAT_S8;
@@ -112,7 +112,7 @@
             case SOX_ENCODING_UNSIGNED:
                 if (!(snd_pcm_format_mask_test(fmask, SND_PCM_FORMAT_U8)))
                 {
-                    sox_fail_errno(ft,SOX_EFMT,"ALSA driver does not support unsigned byte samples");
+                    lsx_fail_errno(ft,SOX_EFMT,"ALSA driver does not support unsigned byte samples");
                     return SOX_EOF;
                 }
                 *fmt = SND_PCM_FORMAT_U8;
@@ -146,7 +146,7 @@
             case SOX_ENCODING_SIGN2:
                 if (!(snd_pcm_format_mask_test(fmask, SND_PCM_FORMAT_S16)))
                 {
-                    sox_fail_errno(ft,SOX_EFMT,"ALSA driver does not support signed word samples");
+                    lsx_fail_errno(ft,SOX_EFMT,"ALSA driver does not support signed word samples");
                     return SOX_EOF;
                 }
                 *fmt = SND_PCM_FORMAT_S16;
@@ -154,7 +154,7 @@
             case SOX_ENCODING_UNSIGNED:
                 if (!(snd_pcm_format_mask_test(fmask, SND_PCM_FORMAT_U16)))
                 {
-                    sox_fail_errno(ft,SOX_EFMT,"ALSA driver does not support unsigned word samples");
+                    lsx_fail_errno(ft,SOX_EFMT,"ALSA driver does not support unsigned word samples");
                     return SOX_EOF;
                 }
                 *fmt = SND_PCM_FORMAT_U16;
@@ -164,7 +164,7 @@
         }
     }
     else {
-        sox_fail_errno(ft,SOX_EFMT,"ALSA driver does not support %s %u-bit output",
+        lsx_fail_errno(ft,SOX_EFMT,"ALSA driver does not support %s %u-bit output",
                       sox_encodings_str[(unsigned char)ft->encoding.encoding], ft->encoding.bits_per_sample);
         return SOX_EOF;
     }
@@ -186,18 +186,18 @@
     snd_pcm_format_mask_t *fmask = NULL;
     sox_signalinfo_t client_signal = ft->signal;
 
-    set_signal_defaults(&ft->signal);
+    lsx_set_signal_defaults(&ft->signal);
 
     if ((err = snd_pcm_open(&(alsa->pcm_handle), ft->filename, 
                             mode, 0)) < 0) 
     {
-        sox_fail_errno(ft, SOX_EPERM, "cannot open audio device");
+        lsx_fail_errno(ft, SOX_EPERM, "cannot open audio device");
         goto open_error;
     }
 
     if ((err = snd_pcm_hw_params_malloc(&hw_params)) < 0) 
     {
-        sox_fail_errno(ft, SOX_ENOMEM, 
+        lsx_fail_errno(ft, SOX_ENOMEM, 
                       "cannot allocate hardware parameter structure");
         goto open_error;
     }
@@ -204,7 +204,7 @@
 
     if ((err = snd_pcm_hw_params_any(alsa->pcm_handle, hw_params)) < 0) 
     {
-        sox_fail_errno(ft, SOX_EPERM,
+        lsx_fail_errno(ft, SOX_EPERM,
                       "cannot initialize hardware parameter structure");
         goto open_error;
     }
@@ -213,7 +213,7 @@
     /* Turn off software resampling */
     err = snd_pcm_hw_params_set_rate_resample(alsa->pcm_handle, hw_params, 0);
     if (err < 0) {
-        sox_fail_errno(ft, SOX_EPERM, "Resampling setup failed for playback");
+        lsx_fail_errno(ft, SOX_EPERM, "Resampling setup failed for playback");
         goto open_error;
     }
 #endif
@@ -221,7 +221,7 @@
     if ((err = snd_pcm_hw_params_set_access(alsa->pcm_handle, hw_params, 
                                             SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
     {
-        sox_fail_errno(ft, SOX_EPERM,
+        lsx_fail_errno(ft, SOX_EPERM,
                       "cannot set access type");
         goto open_error;
     }
@@ -249,7 +249,7 @@
     if ((err = snd_pcm_hw_params_set_format(alsa->pcm_handle, 
                                             hw_params, fmt)) < 0) 
     {
-        sox_fail_errno(ft, SOX_EPERM, "cannot set sample format");
+        lsx_fail_errno(ft, SOX_EPERM, "cannot set sample format");
         goto open_error;
     }
 
@@ -269,7 +269,7 @@
                                                &rate,
                                                &dir)) < 0) 
     {
-        sox_fail_errno(ft, SOX_EPERM, "cannot set sample rate");
+        lsx_fail_errno(ft, SOX_EPERM, "cannot set sample rate");
         goto open_error;
     }
     snd_pcm_hw_params_get_rate(hw_params, 
@@ -288,7 +288,7 @@
                                               hw_params, 
                                               ft->signal.channels)) < 0) 
     {
-        sox_fail_errno(ft, SOX_EPERM, "cannot set channel count");
+        lsx_fail_errno(ft, SOX_EPERM, "cannot set channel count");
         goto open_error;
     }
 
@@ -297,13 +297,13 @@
 
     if (snd_pcm_hw_params_get_buffer_size_min(hw_params, &buffer_size_min) < 0)
     {
-        sox_fail_errno(ft, SOX_EPERM, "Error getting min buffer size.");
+        lsx_fail_errno(ft, SOX_EPERM, "Error getting min buffer size.");
         goto open_error;
     }
 
     if (snd_pcm_hw_params_get_buffer_size_max(hw_params, &buffer_size_max) < 0)
     {
-        sox_fail_errno(ft, SOX_EPERM, "Error getting max buffer size.");
+        lsx_fail_errno(ft, SOX_EPERM, "Error getting max buffer size.");
         goto open_error;
     }
 
@@ -311,7 +311,7 @@
     if (snd_pcm_hw_params_get_period_size_min(hw_params, 
                                               &period_size_min, &dir) < 0)
     {
-        sox_fail_errno(ft, SOX_EPERM, "Error getting min period size.");
+        lsx_fail_errno(ft, SOX_EPERM, "Error getting min period size.");
         goto open_error;
     }
 
@@ -319,7 +319,7 @@
     if (snd_pcm_hw_params_get_period_size_max(hw_params, 
                                               &period_size_max, &dir) < 0)
     {
-        sox_fail_errno(ft, SOX_EPERM, "Error getting max buffer size.");
+        lsx_fail_errno(ft, SOX_EPERM, "Error getting max buffer size.");
         goto open_error;
     }
 
@@ -335,7 +335,7 @@
     if (snd_pcm_hw_params_set_period_size_near(alsa->pcm_handle, hw_params, 
                                                &period_size, &dir) < 0) 
     {
-        sox_fail_errno(ft, SOX_EPERM, "Error setting periods.");
+        lsx_fail_errno(ft, SOX_EPERM, "Error setting periods.");
         goto open_error;
     }
     snd_pcm_hw_params_get_period_size(hw_params, &period_size, &dir);
@@ -343,7 +343,7 @@
     dir = 0;
     if (snd_pcm_hw_params_set_buffer_size_near(alsa->pcm_handle, hw_params, 
                                                &buffer_size) < 0) {
-        sox_fail_errno(ft, SOX_EPERM, "Error setting buffer size.");
+        lsx_fail_errno(ft, SOX_EPERM, "Error setting buffer size.");
         goto open_error;
     }
 
@@ -350,13 +350,13 @@
     snd_pcm_hw_params_get_buffer_size(hw_params, &buffer_size);
     if (period_size * 2 > buffer_size)
     {
-        sox_fail_errno(ft, SOX_EPERM, "Buffer too small. Could not use.");
+        lsx_fail_errno(ft, SOX_EPERM, "Buffer too small. Could not use.");
         goto open_error;
     }
 
     if ((err = snd_pcm_hw_params(alsa->pcm_handle, hw_params)) < 0) 
     {
-        sox_fail_errno(ft, SOX_EPERM, "cannot set parameters");
+        lsx_fail_errno(ft, SOX_EPERM, "cannot set parameters");
         goto open_error;
     }
 
@@ -365,7 +365,7 @@
 
     if ((err = snd_pcm_prepare(alsa->pcm_handle)) < 0) 
     {
-        sox_fail_errno(ft, SOX_EPERM, "cannot prepare audio interface for use");
+        lsx_fail_errno(ft, SOX_EPERM, "cannot prepare audio interface for use");
         goto open_error;
     }
 
@@ -448,7 +448,7 @@
         uint16_t datum = *((uint16_t *)buf2);
         buf2++; buf2++;
         if (swap)
-            datum = sox_swapw(datum);
+            datum = lsx_swapw(datum);
 
         *buf1++ = SOX_UNSIGNED_16BIT_TO_SAMPLE(datum,);
     }
@@ -461,7 +461,7 @@
         int16_t datum = *((int16_t *)buf2);
         buf2++; buf2++;
         if (swap)
-            datum = sox_swapw(datum);
+            datum = lsx_swapw(datum);
 
         *buf1++ = SOX_SIGNED_16BIT_TO_SAMPLE(datum,);
     }
@@ -479,7 +479,7 @@
           case SOX_ENCODING_SIGN2:    read_buf = sb_read_buf; break;
           case SOX_ENCODING_UNSIGNED: read_buf = ub_read_buf; break;
           default:
-            sox_fail_errno(ft,SOX_EFMT,"Do not support this encoding for this data size");
+            lsx_fail_errno(ft,SOX_EFMT,"Do not support this encoding for this data size");
             return 0;
         }
         break;
@@ -488,12 +488,12 @@
           case SOX_ENCODING_SIGN2:    read_buf = sw_read_buf; break;
           case SOX_ENCODING_UNSIGNED: read_buf = uw_read_buf; break;
           default:
-            sox_fail_errno(ft,SOX_EFMT,"Do not support this encoding for this data size");
+            lsx_fail_errno(ft,SOX_EFMT,"Do not support this encoding for this data size");
             return 0;
         }
         break;
       default:
-        sox_fail_errno(ft,SOX_EFMT,"Do not support this data size for this handler");
+        lsx_fail_errno(ft,SOX_EFMT,"Do not support this data size for this handler");
         return 0;
     }
 
@@ -507,7 +507,7 @@
           (nsamp - len)/ft->signal.channels); /* ALSA takes "frame" counts. */
       if ((int)n < 0) {
         if (xrun_recovery(alsa->pcm_handle, (int)n) < 0) {
-          sox_fail_errno(ft, SOX_EPERM, "ALSA read error");
+          lsx_fail_errno(ft, SOX_EPERM, "ALSA read error");
           return 0;
         }
       } else {
@@ -553,7 +553,7 @@
     {
         uint16_t datum = SOX_SAMPLE_TO_UNSIGNED_16BIT(*buf2++, *clips);
         if (swap)
-            datum = sox_swapw(datum);
+            datum = lsx_swapw(datum);
         *(uint16_t *)buf1 = datum;
         buf1++; buf1++;
     }
@@ -565,7 +565,7 @@
     {
         int16_t datum = SOX_SAMPLE_TO_SIGNED_16BIT(*buf2++, *clips);
         if (swap)
-            datum = sox_swapw(datum);
+            datum = lsx_swapw(datum);
         *(int16_t *)buf1 = datum;
         buf1++; buf1++;
     }
@@ -588,7 +588,7 @@
                     write_buf = sox_ub_write_buf;
                     break;
                 default:
-                    sox_fail_errno(ft,SOX_EFMT,"this encoding is not supported for this data size");
+                    lsx_fail_errno(ft,SOX_EFMT,"this encoding is not supported for this data size");
                     return 0;
             }
             break;
@@ -602,12 +602,12 @@
                     write_buf = sox_uw_write_buf;
                     break;
                 default:
-                    sox_fail_errno(ft,SOX_EFMT,"this encoding is not supported for this data size");
+                    lsx_fail_errno(ft,SOX_EFMT,"this encoding is not supported for this data size");
                     return 0;
             }
             break;
         default:
-            sox_fail_errno(ft,SOX_EFMT,"this data size is not supported by this handler");
+            lsx_fail_errno(ft,SOX_EFMT,"this data size is not supported by this handler");
             return 0;
     }
 
@@ -627,7 +627,7 @@
           errno = 0;
         if (err < 0) {
           if (xrun_recovery(alsa->pcm_handle, err) < 0) {
-            sox_fail_errno(ft, SOX_EPERM, "ALSA write error");
+            lsx_fail_errno(ft, SOX_EPERM, "ALSA write error");
             return 0;
           }
         } else
--- a/src/amr.h
+++ b/src/amr.h
@@ -35,10 +35,10 @@
   size_t n_1;
   UWord8 coded[AMR_CODED_MAX];
 
-  if (sox_readbuf(ft, &coded[0], 1) != 1)
+  if (lsx_readbuf(ft, &coded[0], 1) != 1)
     return AMR_FRAME;
   n_1 = block_size[(coded[0] >> 3) & 0x0F] - 1;
-  if (sox_readbuf(ft, &coded[1], n_1) != n_1)
+  if (lsx_readbuf(ft, &coded[1], n_1) != n_1)
     return AMR_FRAME;
   D_IF_decode(amr->state, coded, amr->pcm, 0);
   return 0;
@@ -49,9 +49,9 @@
   amr_t amr = (amr_t) ft->priv;
   UWord8 coded[AMR_CODED_MAX];
 #include "amr1.h"
-  sox_bool result = sox_writebuf(ft, coded, (unsigned)n) == (unsigned)n;
+  sox_bool result = lsx_writebuf(ft, coded, (unsigned)n) == (unsigned)n;
   if (!result)
-    sox_fail_errno(ft, errno, "write error");
+    lsx_fail_errno(ft, errno, "write error");
   return result;
 }
 
@@ -63,10 +63,10 @@
   amr->pcm_index = AMR_FRAME;
   amr->state = D_IF_init();
 
-  if (sox_readchars(ft, buffer, sizeof(buffer)))
+  if (lsx_readchars(ft, buffer, sizeof(buffer)))
     return SOX_EOF;
   if (memcmp(buffer, magic, sizeof(buffer))) {
-    sox_fail_errno(ft, SOX_EHDR, "invalid magic number");
+    lsx_fail_errno(ft, SOX_EHDR, "invalid magic number");
     return SOX_EOF;
   }
   ft->signal.rate = AMR_RATE;
@@ -104,7 +104,7 @@
   if (ft->encoding.compression != HUGE_VAL) {
     amr->mode = ft->encoding.compression;
     if (amr->mode != ft->encoding.compression || amr->mode > AMR_MODE_MAX) {
-      sox_fail_errno(ft, SOX_EINVAL, "compression level must be a whole number from 0 to %i", AMR_MODE_MAX);
+      lsx_fail_errno(ft, SOX_EINVAL, "compression level must be a whole number from 0 to %i", AMR_MODE_MAX);
       return SOX_EOF;
     }
   }
@@ -111,7 +111,7 @@
   else amr->mode = 0;
 
 #include "amr2.h"
-  sox_writes(ft, magic);
+  lsx_writes(ft, magic);
   amr->pcm_index = 0;
   return SOX_SUCCESS;
 }
--- a/src/ao.c
+++ b/src/ao.c
@@ -37,7 +37,7 @@
 {
   ao_priv_t ao = (ao_priv_t)ft->priv;
 
-  set_signal_defaults(&ft->signal);
+  lsx_set_signal_defaults(&ft->signal);
   ao->buf_size = sox_globals.bufsiz - (sox_globals.bufsiz % (ft->encoding.bits_per_sample >> 3));
   ao->buf_size *= (ft->encoding.bits_per_sample >> 3);
   ao->buf = xmalloc(ao->buf_size);
@@ -44,7 +44,7 @@
 
   if (!ao->buf)
   {
-      sox_fail_errno(ft, SOX_ENOMEM, "Can not allocate memory for ao driver");
+      lsx_fail_errno(ft, SOX_ENOMEM, "Can not allocate memory for ao driver");
       return SOX_EOF;
   }
 
@@ -83,7 +83,7 @@
     {
         uint16_t datum = SOX_SAMPLE_TO_SIGNED_16BIT(*buf2++, *clips);
         if (swap)
-            datum = sox_swapw(datum);
+            datum = lsx_swapw(datum);
         *(uint16_t *)buf1 = datum;
         buf1++; buf1++;
     }
--- a/src/au.c
+++ b/src/au.c
@@ -22,10 +22,10 @@
 
 /* Magic numbers used in Sun and NeXT audio files */
 static struct {char str[4]; sox_bool reverse_bytes; char const * desc;} id[] = {
-  {"\x2e\x73\x6e\x64", SOX_IS_LITTLEENDIAN, "big-endian `.snd'"},
-  {"\x64\x6e\x73\x2e", SOX_IS_BIGENDIAN   , "little-endian `.snd'"},
-  {"\x00\x64\x73\x2e", SOX_IS_BIGENDIAN   , "little-endian `\\0ds.' (for DEC)"},
-  {"\x2e\x73\x64\x00", SOX_IS_LITTLEENDIAN, "big-endian `\\0ds.'"},
+  {"\x2e\x73\x6e\x64", MACHINE_IS_LITTLEENDIAN, "big-endian `.snd'"},
+  {"\x64\x6e\x73\x2e", MACHINE_IS_BIGENDIAN   , "little-endian `.snd'"},
+  {"\x00\x64\x73\x2e", MACHINE_IS_BIGENDIAN   , "little-endian `\\0ds.' (for DEC)"},
+  {"\x2e\x73\x64\x00", MACHINE_IS_LITTLEENDIAN, "big-endian `\\0ds.'"},
   {"    ", 0, NULL}
 };
 #define FIXED_HDR     24
@@ -97,7 +97,7 @@
   unsigned char           in_byte;
 
   if (p->in_bits < (int)ft->encoding.bits_per_sample) {
-    if (sox_read_b_buf(ft, &in_byte, 1) != 1) {
+    if (lsx_read_b_buf(ft, &in_byte, 1) != 1) {
       *code = 0;
       return -1;
     }
@@ -134,26 +134,26 @@
   unsigned i, bits_per_sample;
   sox_encoding_t encoding;
 
-  if (sox_readchars(ft, magic, sizeof(magic)))
+  if (lsx_readchars(ft, magic, sizeof(magic)))
     return SOX_EOF;
  
   for (i = 0; id[i].desc && memcmp(magic, id[i].str, sizeof(magic)); ++i);
   if (!id[i].desc) {
-    sox_fail_errno(ft, SOX_EHDR, "au: can't find Sun/NeXT/DEC identifier");
+    lsx_fail_errno(ft, SOX_EHDR, "au: can't find Sun/NeXT/DEC identifier");
     return SOX_EOF;
   }
   sox_report("found %s identifier", id[i].desc);
   ft->encoding.reverse_bytes = id[i].reverse_bytes;
 
-  if (sox_readdw(ft, &hdr_size) ||
-      sox_readdw(ft, &data_size) ||   /* Can be SUN_UNSPEC */
-      sox_readdw(ft, &ft_encoding) ||
-      sox_readdw(ft, &rate) ||
-      sox_readdw(ft, &channels))
+  if (lsx_readdw(ft, &hdr_size) ||
+      lsx_readdw(ft, &data_size) ||   /* Can be SUN_UNSPEC */
+      lsx_readdw(ft, &ft_encoding) ||
+      lsx_readdw(ft, &rate) ||
+      lsx_readdw(ft, &channels))
     return SOX_EOF;
 
   if (hdr_size < FIXED_HDR) {
-    sox_fail_errno(ft, SOX_EHDR, "header size %u is too small", hdr_size);
+    lsx_fail_errno(ft, SOX_EHDR, "header size %u is too small", hdr_size);
     return SOX_EOF;
   }
   if (hdr_size < FIXED_HDR + 4)
@@ -161,7 +161,7 @@
 
   if (!(encoding = sox_enc(ft_encoding, &bits_per_sample))) {
     int n = min(ft_encoding, Unknown_other);
-    sox_fail_errno(ft, SOX_EFMT, "unsupported encoding `%s' (%#x)", str[n], ft_encoding);
+    lsx_fail_errno(ft, SOX_EFMT, "unsupported encoding `%s' (%#x)", str[n], ft_encoding);
     return SOX_EOF;
   }
 
@@ -179,35 +179,35 @@
   if (hdr_size > FIXED_HDR) {
     size_t info_size = hdr_size - FIXED_HDR;
     char * buf = xcalloc(1, info_size + 1); /* +1 ensures null-terminated */
-    if (sox_readchars(ft, buf, info_size) != SOX_SUCCESS) {
+    if (lsx_readchars(ft, buf, info_size) != SOX_SUCCESS) {
       free(buf);
       return SOX_EOF;
     }
-    append_comments(&ft->comments, buf);
+    sox_append_comments(&ft->comments, buf);
     free(buf);
   }
   if (data_size == SUN_UNSPEC)
     data_size = 0;  /* libSoX uses 0 for unspecified */
-  return sox_check_read_params(ft, channels, (sox_rate_t)rate,
+  return lsx_check_read_params(ft, channels, (sox_rate_t)rate,
       encoding, bits_per_sample, div_bits(data_size, bits_per_sample));
 }
 
 static int write_header(sox_format_t * ft)
 {
-  char * comment  = cat_comments(ft->comments);
+  char * comment  = sox_cat_comments(ft->comments);
   size_t len      = strlen(comment) + 1;     /* Write out null-terminated */
   size_t info_len = max(4, (len + 3) & ~3u); /* Minimum & multiple of 4 bytes */
   size_t size     = ft->olength? ft->olength : ft->length;
-  int i = ft->encoding.reverse_bytes == SOX_IS_BIGENDIAN? 2 : 0;
+  int i = ft->encoding.reverse_bytes == MACHINE_IS_BIGENDIAN? 2 : 0;
   sox_bool error  = sox_false
-  ||sox_writechars(ft, id[i].str, sizeof(id[i].str))
-  ||sox_writedw(ft, FIXED_HDR + info_len)
-  ||sox_writedw(ft, size? size*(ft->encoding.bits_per_sample >> 3) : SUN_UNSPEC)
-  ||sox_writedw(ft, ft_enc(ft->encoding.bits_per_sample, ft->encoding.encoding))
-  ||sox_writedw(ft, (unsigned)(ft->signal.rate + .5))
-  ||sox_writedw(ft, ft->signal.channels)
-  ||sox_writechars(ft, comment, len)
-  ||sox_padbytes(ft, info_len - len);
+  ||lsx_writechars(ft, id[i].str, sizeof(id[i].str))
+  ||lsx_writedw(ft, FIXED_HDR + info_len)
+  ||lsx_writedw(ft, size? size*(ft->encoding.bits_per_sample >> 3) : SUN_UNSPEC)
+  ||lsx_writedw(ft, ft_enc(ft->encoding.bits_per_sample, ft->encoding.encoding))
+  ||lsx_writedw(ft, (unsigned)(ft->signal.rate + .5))
+  ||lsx_writedw(ft, ft->signal.channels)
+  ||lsx_writechars(ft, comment, len)
+  ||lsx_padbytes(ft, info_len - len);
   free(comment);
   return error? SOX_EOF: SOX_SUCCESS;
 }
@@ -224,9 +224,9 @@
   static sox_format_handler_t const handler = {SOX_LIB_VERSION_CODE,
     "PCM file format used widely on Sun systems",
     names, SOX_FILE_BIG_END | SOX_FILE_REWIND,
-    startread, sox_rawread, NULL,
-    write_header, sox_rawwrite, NULL,
-    sox_rawseek, write_encodings, NULL
+    startread, lsx_rawread, NULL,
+    write_header, lsx_rawwrite, NULL,
+    lsx_rawseek, write_encodings, NULL
   };
   return &handler;
 }
--- a/src/avr.c
+++ b/src/avr.c
@@ -68,16 +68,16 @@
   avr_t avr = (avr_t)ft->priv;
   int rc;
 
-  sox_reads(ft, avr->magic, 4);
+  lsx_reads(ft, avr->magic, 4);
 
   if (strncmp (avr->magic, AVR_MAGIC, 4)) {
-    sox_fail_errno(ft,SOX_EHDR,"AVR: unknown header");
+    lsx_fail_errno(ft,SOX_EHDR,"AVR: unknown header");
     return(SOX_EOF);
   }
 
-  sox_readbuf(ft, avr->name, sizeof(avr->name));
+  lsx_readbuf(ft, avr->name, sizeof(avr->name));
 
-  sox_readw (ft, &(avr->mono));
+  lsx_readw (ft, &(avr->mono));
   if (avr->mono) {
     ft->signal.channels = 2;
   }
@@ -85,7 +85,7 @@
     ft->signal.channels = 1;
   }
 
-  sox_readw (ft, &(avr->rez));
+  lsx_readw (ft, &(avr->rez));
   if (avr->rez == 8) {
     ft->encoding.bits_per_sample = 8;
   }
@@ -93,11 +93,11 @@
     ft->encoding.bits_per_sample = 16;
   }
   else {
-    sox_fail_errno(ft,SOX_EFMT,"AVR: unsupported sample resolution");
+    lsx_fail_errno(ft,SOX_EFMT,"AVR: unsupported sample resolution");
     return(SOX_EOF);
   }
 
-  sox_readw (ft, &(avr->sign));
+  lsx_readw (ft, &(avr->sign));
   if (avr->sign) {
     ft->encoding.encoding = SOX_ENCODING_SIGN2;
   }
@@ -105,11 +105,11 @@
     ft->encoding.encoding = SOX_ENCODING_UNSIGNED;
   }
 
-  sox_readw (ft, &(avr->loop));
+  lsx_readw (ft, &(avr->loop));
 
-  sox_readw (ft, &(avr->midi));
+  lsx_readw (ft, &(avr->midi));
 
-  sox_readdw (ft, &(avr->rate));
+  lsx_readdw (ft, &(avr->rate));
   /*
    * No support for AVRs created by ST-Replay,
    * Replay Proffesional and PRO-Series 12.
@@ -118,23 +118,23 @@
    */
   ft->signal.rate = (avr->rate & 0x00ffffff);
 
-  sox_readdw (ft, &(avr->size));
+  lsx_readdw (ft, &(avr->size));
 
-  sox_readdw (ft, &(avr->lbeg));
+  lsx_readdw (ft, &(avr->lbeg));
 
-  sox_readdw (ft, &(avr->lend));
+  lsx_readdw (ft, &(avr->lend));
 
-  sox_readw (ft, &(avr->res1));
+  lsx_readw (ft, &(avr->res1));
 
-  sox_readw (ft, &(avr->res2));
+  lsx_readw (ft, &(avr->res2));
 
-  sox_readw (ft, &(avr->res3));
+  lsx_readw (ft, &(avr->res3));
 
-  sox_readbuf(ft, avr->ext, sizeof(avr->ext));
+  lsx_readbuf(ft, avr->ext, sizeof(avr->ext));
 
-  sox_readbuf(ft, avr->user, sizeof(avr->user));
+  lsx_readbuf(ft, avr->user, sizeof(avr->user));
 
-  rc = sox_rawstartread (ft);
+  rc = lsx_rawstartread (ft);
   if (rc)
       return rc;
 
@@ -147,97 +147,97 @@
   int rc;
 
   if (!ft->seekable) {
-    sox_fail_errno(ft,SOX_EOF,"AVR: file is not seekable");
+    lsx_fail_errno(ft,SOX_EOF,"AVR: file is not seekable");
     return(SOX_EOF);
   }
 
-  rc = sox_rawstartwrite (ft);
+  rc = lsx_rawstartwrite (ft);
   if (rc)
       return rc;
 
   /* magic */
-  sox_writes(ft, AVR_MAGIC);
+  lsx_writes(ft, AVR_MAGIC);
 
   /* name */
-  sox_writeb(ft, 0);
-  sox_writeb(ft, 0);
-  sox_writeb(ft, 0);
-  sox_writeb(ft, 0);
-  sox_writeb(ft, 0);
-  sox_writeb(ft, 0);
-  sox_writeb(ft, 0);
-  sox_writeb(ft, 0);
+  lsx_writeb(ft, 0);
+  lsx_writeb(ft, 0);
+  lsx_writeb(ft, 0);
+  lsx_writeb(ft, 0);
+  lsx_writeb(ft, 0);
+  lsx_writeb(ft, 0);
+  lsx_writeb(ft, 0);
+  lsx_writeb(ft, 0);
 
   /* mono */
   if (ft->signal.channels == 1) {
-    sox_writew (ft, 0);
+    lsx_writew (ft, 0);
   }
   else if (ft->signal.channels == 2) {
-    sox_writew (ft, 0xffff);
+    lsx_writew (ft, 0xffff);
   }
   else {
-    sox_fail_errno(ft,SOX_EFMT,"AVR: number of channels not supported");
+    lsx_fail_errno(ft,SOX_EFMT,"AVR: number of channels not supported");
     return(0);
   }
 
   /* rez */
   if (ft->encoding.bits_per_sample == 8) {
-    sox_writew (ft, 8);
+    lsx_writew (ft, 8);
   }
   else if (ft->encoding.bits_per_sample == 16) {
-    sox_writew (ft, 16);
+    lsx_writew (ft, 16);
   }
   else {
-    sox_fail_errno(ft,SOX_EFMT,"AVR: unsupported sample resolution");
+    lsx_fail_errno(ft,SOX_EFMT,"AVR: unsupported sample resolution");
     return(SOX_EOF);
   }
 
   /* sign */
   if (ft->encoding.encoding == SOX_ENCODING_SIGN2) {
-    sox_writew (ft, 0xffff);
+    lsx_writew (ft, 0xffff);
   }
   else if (ft->encoding.encoding == SOX_ENCODING_UNSIGNED) {
-    sox_writew (ft, 0);
+    lsx_writew (ft, 0);
   }
   else {
-    sox_fail_errno(ft,SOX_EFMT,"AVR: unsupported encoding");
+    lsx_fail_errno(ft,SOX_EFMT,"AVR: unsupported encoding");
     return(SOX_EOF);
   }
 
   /* loop */
-  sox_writew (ft, 0xffff);
+  lsx_writew (ft, 0xffff);
 
   /* midi */
-  sox_writew (ft, 0xffff);
+  lsx_writew (ft, 0xffff);
 
   /* rate */
-  sox_writedw(ft, (unsigned)(ft->signal.rate + .5));
+  lsx_writedw(ft, (unsigned)(ft->signal.rate + .5));
 
   /* size */
   /* Don't know the size yet. */
-  sox_writedw (ft, 0);
+  lsx_writedw (ft, 0);
 
   /* lbeg */
-  sox_writedw (ft, 0);
+  lsx_writedw (ft, 0);
 
   /* lend */
   /* Don't know the size yet, so we can't set lend, either. */
-  sox_writedw (ft, 0);
+  lsx_writedw (ft, 0);
 
   /* res1 */
-  sox_writew (ft, 0);
+  lsx_writew (ft, 0);
 
   /* res2 */
-  sox_writew (ft, 0);
+  lsx_writew (ft, 0);
 
   /* res3 */
-  sox_writew (ft, 0);
+  lsx_writew (ft, 0);
 
   /* ext */
-  sox_writebuf(ft, (void *)"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", sizeof(avr->ext));
+  lsx_writebuf(ft, (void *)"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", sizeof(avr->ext));
 
   /* user */
-  sox_writebuf(ft, 
+  lsx_writebuf(ft, 
            (void *)"\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\0\0\0\0\0\0\0\0\0\0\0"
@@ -252,7 +252,7 @@
 
   avr->size += nsamp;
 
-  return (sox_rawwrite (ft, buf, nsamp));
+  return (lsx_rawwrite (ft, buf, nsamp));
 }
 
 static int stopwrite(sox_format_t * ft) 
@@ -262,12 +262,12 @@
   unsigned size = avr->size / ft->signal.channels;
 
   /* Fix size */
-  sox_seeki(ft, 26, SEEK_SET);
-  sox_writedw (ft, size);
+  lsx_seeki(ft, 26, SEEK_SET);
+  lsx_writedw (ft, size);
 
   /* Fix lend */
-  sox_seeki(ft, 34, SEEK_SET);
-  sox_writedw (ft, size);
+  lsx_seeki(ft, 34, SEEK_SET);
+  lsx_writedw (ft, size);
 
   return(SOX_SUCCESS);
 }
@@ -284,7 +284,7 @@
     "Audio Visual Research format; used on the Mac",
     names,
     SOX_FILE_BIG_END|SOX_FILE_MONO|SOX_FILE_STEREO,
-    startread, sox_rawread, NULL,
+    startread, lsx_rawread, NULL,
     startwrite, write_samples, stopwrite,
     NULL, write_encodings, NULL
   };
--- a/src/biquad.c
+++ b/src/biquad.c
@@ -45,7 +45,7 @@
       (n > width_pos && ((unsigned)(sscanf(argv[width_pos], "%lf%c %c", &p->width, &width_type, &dummy)-1) > 1 || p->width <= 0)) ||
       (n > gain_pos  && sscanf(argv[gain_pos], "%lf %c", &p->gain, &dummy) != 1) ||
       !strchr(allowed_width_types, width_type) || (width_type == 's' && p->width > 1))
-    return sox_usage(effp);
+    return lsx_usage(effp);
   p->width_type = strchr(all_width_types, width_type) - all_width_types;
   if (p->width_type >= strlen(all_width_types))
     p->width_type = 0;
--- a/src/cdr.c
+++ b/src/cdr.c
@@ -21,7 +21,7 @@
 
 static int start(sox_format_t * ft) 
 {
-  return sox_check_read_params(ft, 2, 44100., SOX_ENCODING_SIGN2, 16, (off_t)0);
+  return lsx_check_read_params(ft, 2, 44100., SOX_ENCODING_SIGN2, 16, (off_t)0);
 }
 
 static int stopwrite(sox_format_t * ft) 
@@ -30,7 +30,7 @@
   sox_size_t i = ft->olength % sector_num_samples;
 
   if (i) while (i++ < sector_num_samples)    /* Pad with silence to multiple */
-    sox_writew(ft, 0);                       /* of 1/75th of a second. */
+    lsx_writew(ft, 0);                       /* of 1/75th of a second. */
   return SOX_SUCCESS;
 }
 
@@ -43,9 +43,9 @@
     SOX_LIB_VERSION_CODE,
     "Red Book Compact Disc Digital Audio",
     names, SOX_FILE_BIG_END|SOX_FILE_STEREO,
-    start, sox_rawread, NULL,
-    NULL, sox_rawwrite, stopwrite,
-    sox_rawseek, write_encodings, write_rates
+    start, lsx_rawread, NULL,
+    NULL, lsx_rawwrite, stopwrite,
+    lsx_rawseek, write_encodings, write_rates
   };
   return &handler;
 }
--- a/src/chorus.c
+++ b/src/chorus.c
@@ -100,7 +100,7 @@
         i = 0;
 
         if ( ( n < 7 ) || (( n - 2 ) % 5 ) )
-          return sox_usage(effp);
+          return lsx_usage(effp);
 
         sscanf(argv[i++], "%f", &chorus->in_gain);
         sscanf(argv[i++], "%f", &chorus->out_gain);
@@ -119,7 +119,7 @@
                 else if ( ! strcmp(argv[i], "-t"))
                         chorus->modulation[chorus->num_chorus] = MOD_TRIANGLE;
                 else
-                  return sox_usage(effp);
+                  return lsx_usage(effp);
                 i++;
                 chorus->num_chorus++;
         }
@@ -202,10 +202,10 @@
                 chorus->lookup_tab[i] = (int *) xmalloc(sizeof (int) * chorus->length[i]);
 
                 if (chorus->modulation[i] == MOD_SINE)
-                  sox_generate_wave_table(SOX_WAVE_SINE, SOX_INT, chorus->lookup_tab[i],
+                  lsx_generate_wave_table(SOX_WAVE_SINE, SOX_INT, chorus->lookup_tab[i],
                                          (unsigned)chorus->length[i], 0., (double)chorus->depth_samples[i], 0.);
                 else
-                  sox_generate_wave_table(SOX_WAVE_TRIANGLE, SOX_INT, chorus->lookup_tab[i], 
+                  lsx_generate_wave_table(SOX_WAVE_TRIANGLE, SOX_INT, chorus->lookup_tab[i], 
                                          (unsigned)chorus->length[i],
                                          (double)(chorus->samples[i] - 1 - 2 * chorus->depth_samples[i]),
                                          (double)(chorus->samples[i] - 1), 3 * M_PI_2);
--- a/src/compand.c
+++ b/src/compand.c
@@ -69,7 +69,7 @@
   unsigned pairs, i, j, commas;
 
   if (n < 2 || n > 5)
-    return sox_usage(effp);
+    return lsx_usage(effp);
 
   /* Start by checking the attack and decay rates */
   for (s = argv[0], commas = 0; *s; ++s) if (*s == ',') ++commas;
--- a/src/contrast.c
+++ b/src/contrast.c
@@ -29,7 +29,7 @@
   p->contrast = 75;
   do {NUMERIC_PARAMETER(contrast, 0, 100)} while (0);
   p->contrast /= 750;
-  return argc?  sox_usage(effp) : SOX_SUCCESS;
+  return argc?  lsx_usage(effp) : SOX_SUCCESS;
 }
 
 static int flow(sox_effect_t * effp, const sox_sample_t * ibuf,
--- a/src/cvsd-fmt.c
+++ b/src/cvsd-fmt.c
@@ -28,7 +28,7 @@
     names, SOX_FILE_MONO,
     sox_cvsdstartread, sox_cvsdread, sox_cvsdstopread,
     sox_cvsdstartwrite, sox_cvsdwrite, sox_cvsdstopwrite,
-    sox_rawseek, write_encodings, NULL
+    lsx_rawseek, write_encodings, NULL
   };
   return &handler;
 }
--- a/src/cvsd.c
+++ b/src/cvsd.c
@@ -118,7 +118,7 @@
         p->cvsd_rate = (ft->signal.rate <= 24000) ? 16000 : 32000;
         ft->signal.rate = 8000;
         ft->signal.channels = 1;
-        sox_rawstart(ft, sox_true, sox_false, sox_true, SOX_ENCODING_CVSD, 1);
+        lsx_rawstart(ft, sox_true, sox_false, sox_true, SOX_ENCODING_CVSD, 1);
         /*
          * initialize the decoder
          */
@@ -203,7 +203,7 @@
         struct cvsdpriv *p = (struct cvsdpriv *) ft->priv;
 
         if (p->bit.cnt) {
-                sox_writeb(ft, p->bit.shreg);
+                lsx_writeb(ft, p->bit.shreg);
                 p->bytes_written++;
         }
         sox_debug("cvsd: min slope %f, max slope %f", 
@@ -234,7 +234,7 @@
         
         while (done < nsamp) {
                 if (!p->bit.cnt) {
-                        if (sox_read_b_buf(ft, &(p->bit.shreg), 1) != 1)
+                        if (lsx_read_b_buf(ft, &(p->bit.shreg), 1) != 1)
                                 return done;
                         p->bit.cnt = 8;
                         p->bit.mask = 1;
@@ -326,7 +326,7 @@
                 } else
                         p->c.enc.recon_int -= p->com.mla_int;
                 if ((++(p->bit.cnt)) >= 8) {
-                        sox_writeb(ft, p->bit.shreg);
+                        lsx_writeb(ft, p->bit.shreg);
                         p->bytes_written++;
                         p->bit.shreg = p->bit.cnt = 0;
                         p->bit.mask = 1;
@@ -343,6 +343,38 @@
 /*
  * DVMS file header
  */
+
+/* FIXME: eliminate these 4 functions */
+
+static uint32_t get32_le(unsigned char **p)
+{
+  uint32_t val = (((*p)[3]) << 24) | (((*p)[2]) << 16) | 
+          (((*p)[1]) << 8) | (**p);
+  (*p) += 4;
+  return val;
+}
+
+static uint16_t get16_le(unsigned char **p)
+{
+  unsigned val = (((*p)[1]) << 8) | (**p);
+  (*p) += 2;
+  return val;
+}
+
+static void put32_le(unsigned char **p, uint32_t val)
+{
+  *(*p)++ = val & 0xff;
+  *(*p)++ = (val >> 8) & 0xff;
+  *(*p)++ = (val >> 16) & 0xff;
+  *(*p)++ = (val >> 24) & 0xff;
+}
+
+static void put16_le(unsigned char **p, unsigned val)
+{
+  *(*p)++ = val & 0xff;
+  *(*p)++ = (val >> 8) & 0xff;
+}
+
 struct dvms_header {
         char          Filename[14];
         unsigned      Id;
@@ -371,7 +403,7 @@
         int i;
         unsigned sum;
 
-        if (sox_readbuf(ft, hdrbuf, sizeof(hdrbuf)) != sizeof(hdrbuf))
+        if (lsx_readbuf(ft, hdrbuf, sizeof(hdrbuf)) != sizeof(hdrbuf))
         {
                 return (SOX_EOF);
         }
@@ -437,12 +469,12 @@
                 sum += *pchs++;
         hdr->Crc = sum;
         put16_le(&pch, hdr->Crc);
-        if (sox_seeki(ft, 0, SEEK_SET) < 0)
+        if (lsx_seeki(ft, 0, SEEK_SET) < 0)
         {
                 sox_report("seek failed\n: %s",strerror(errno));
                 return (SOX_EOF);
         }
-        if (sox_writebuf(ft, hdrbuf, sizeof(hdrbuf)) != sizeof(hdrbuf))
+        if (lsx_writebuf(ft, hdrbuf, sizeof(hdrbuf)) != sizeof(hdrbuf))
         {
                 sox_report("%s",strerror(errno));
                 return (SOX_EOF);
@@ -456,7 +488,7 @@
 {
         struct cvsdpriv *p = (struct cvsdpriv *) ft->priv;
         size_t len;
-        char * comment = cat_comments(ft->comments);
+        char * comment = sox_cat_comments(ft->comments);
 
         memset(hdr->Filename, 0, sizeof(hdr->Filename));
         len = strlen(ft->filename);
@@ -487,7 +519,7 @@
 
         rc = dvms_read_header(ft, &hdr);
         if (rc){
-            sox_fail_errno(ft,SOX_EHDR,"unable to read DVMS header");
+            lsx_fail_errno(ft,SOX_EHDR,"unable to read DVMS header");
             return rc;
         }
 
@@ -529,7 +561,7 @@
         make_dvms_hdr(ft, &hdr);
         rc = dvms_write_header(ft, &hdr);
         if (rc){
-                sox_fail_errno(ft,rc,"cannot write DVMS header");
+                lsx_fail_errno(ft,rc,"cannot write DVMS header");
             return rc;
         }
 
@@ -552,15 +584,15 @@
             sox_warn("File not seekable");
             return (SOX_EOF);
         }
-        if (sox_seeki(ft, 0, 0) != 0)
+        if (lsx_seeki(ft, 0, 0) != 0)
         {
-                sox_fail_errno(ft,errno,"Can't rewind output file to rewrite DVMS header.");
+                lsx_fail_errno(ft,errno,"Can't rewind output file to rewrite DVMS header.");
                 return(SOX_EOF);
         }
         make_dvms_hdr(ft, &hdr);
         rc = dvms_write_header(ft, &hdr);
         if(rc){
-            sox_fail_errno(ft,rc,"cannot write DVMS header");
+            lsx_fail_errno(ft,rc,"cannot write DVMS header");
             return rc;
         }       
         return rc;
--- a/src/dat.c
+++ b/src/dat.c
@@ -31,7 +31,7 @@
     char sc;
 
     /* Read lines until EOF or first non-comment line */
-    while ((status = sox_reads(ft, inpstr, LINEWIDTH-1)) != SOX_EOF) {
+    while ((status = lsx_reads(ft, inpstr, LINEWIDTH-1)) != SOX_EOF) {
       inpstr[LINEWIDTH-1] = 0;
       if ((sscanf(inpstr," %c", &sc) != 0) && (sc != ';')) break;
       if (sscanf(inpstr," ; Sample Rate %ld", &rate)) {
@@ -66,9 +66,9 @@
     dat->deltat = 1.0 / (double)ft->signal.rate;
     /* Write format comments to start of file */
     sprintf(s,"; Sample Rate %ld\015\n", (long)ft->signal.rate);
-    sox_writes(ft, s);
+    lsx_writes(ft, s);
     sprintf(s,"; Channels %d\015\n", (int)ft->signal.channels);
-    sox_writes(ft, s);
+    lsx_writes(ft, s);
 
     return (SOX_SUCCESS);
 }
@@ -94,9 +94,9 @@
         strncpy(inpstr, ((dat_t)ft->priv)->prevline, LINEWIDTH);
         ((dat_t)ft->priv)->buffered=0;
       } else {
-        sox_reads(ft, inpstr, LINEWIDTH-1);
+        lsx_reads(ft, inpstr, LINEWIDTH-1);
         inpstr[LINEWIDTH-1] = 0;
-        if (sox_eof(ft)) return (done);
+        if (lsx_eof(ft)) return (done);
       }
 
       /* Skip over comments - ie. 0 or more whitespace, then ';' */
@@ -108,7 +108,7 @@
         retc = sscanf(&inpstr[inpPtr]," %lg%n", &sampval, &inpPtrInc);
         inpPtr += inpPtrInc;
         if (retc != 1) {
-          sox_fail_errno(ft,SOX_EOF,"Unable to read sample.");
+          lsx_fail_errno(ft,SOX_EOF,"Unable to read sample.");
           return 0;
         }
         sampval *= SOX_SAMPLE_MAX;
@@ -134,15 +134,15 @@
     /* Write time, then sample values, then CRLF newline */
     while(done < nsamp) {
       sprintf(s," %15.8g ",dat->timevalue);
-      sox_writes(ft, s);
+      lsx_writes(ft, s);
       for (i=0; i<ft->signal.channels; i++) {
         sampval = SOX_SAMPLE_TO_FLOAT_64BIT(*buf++, ft->clips);
         sprintf(s," %15.8g", sampval);
-        sox_writes(ft, s);
+        lsx_writes(ft, s);
         done++;
       }
       sprintf(s," \r\n");
-      sox_writes(ft, s);
+      lsx_writes(ft, s);
       dat->timevalue += dat->deltat;
     }
     return done;
--- a/src/dcshift.c
+++ b/src/dcshift.c
@@ -35,15 +35,15 @@
     dcs->uselimiter = 0; /* default is no limiter */
 
     if (n < 1)
-      return sox_usage(effp);
+      return lsx_usage(effp);
 
     if (n && (!sscanf(argv[0], "%lf", &dcs->dcshift)))
-      return sox_usage(effp);
+      return lsx_usage(effp);
 
     if (n>1)
     {
         if (!sscanf(argv[1], "%lf", &dcs->limitergain))
-          return sox_usage(effp);
+          return lsx_usage(effp);
 
         dcs->uselimiter = 1; /* ok, we'll use it */
         /* The following equation is derived so that there is no 
--- a/src/delay.c
+++ b/src/delay.c
@@ -48,10 +48,10 @@
 
   p->argv = xcalloc(p->argc = argc, sizeof(*p->argv));
   for (i = 0; i < p->argc; ++i) {
-    char const * next = sox_parsesamples(96000., p->argv[i] = xstrdup(argv[i]), &delay, 't');
+    char const * next = lsx_parsesamples(96000., p->argv[i] = xstrdup(argv[i]), &delay, 't');
     if (!next || *next) {
       kill(effp);
-      return sox_usage(effp);
+      return lsx_usage(effp);
     }
     if (delay > max_samples) {
       max_samples = delay;
@@ -76,8 +76,8 @@
   if (!p->max_arg)
     return SOX_EFF_NULL;
   if (effp->flow < p->argc)
-    sox_parsesamples(effp->in_signal.rate, p->argv[effp->flow], &p->buffer_size, 't');
-  sox_parsesamples(effp->in_signal.rate, p->max_arg, &max_delay, 't');
+    lsx_parsesamples(effp->in_signal.rate, p->argv[effp->flow], &p->buffer_size, 't');
+  lsx_parsesamples(effp->in_signal.rate, p->max_arg, &max_delay, 't');
   p->buffer_index = p->delay = 0;
   p->pad = max_delay - p->buffer_size;
   p->buffer = xmalloc(p->buffer_size * sizeof(*p->buffer));
--- a/src/dither.c
+++ b/src/dither.c
@@ -29,7 +29,7 @@
   dither_t dither = (dither_t) effp->priv;
 
   if (n > 1)
-    return sox_usage(effp);
+    return lsx_usage(effp);
   
   dither->amount = sqrt(2.); /* M_SQRT2 missing in some places */   /* Default to half a bit. */
   if (n == 1) {
@@ -39,7 +39,7 @@
     if (scanned == 1 && amount > 0)
       dither->amount *= amount;
     else
-      return sox_usage(effp);
+      return lsx_usage(effp);
   }
 
   return SOX_SUCCESS;
--- a/src/echo.c
+++ b/src/echo.c
@@ -89,7 +89,7 @@
         echo->num_delays = 0;
 
         if ((n < 4) || (n % 2))
-          return sox_usage(effp);
+          return lsx_usage(effp);
 
         i = 0;
         sscanf(argv[i++], "%f", &echo->in_gain);
--- a/src/echos.c
+++ b/src/echos.c
@@ -79,7 +79,7 @@
         echos->num_delays = 0;
 
         if ((n < 4) || (n % 2))
-          return sox_usage(effp);
+          return lsx_usage(effp);
 
         i = 0;
         sscanf(argv[i++], "%f", &echos->in_gain);
--- a/src/effects.c
+++ b/src/effects.c
@@ -36,15 +36,6 @@
 sox_effects_globals_t sox_effects_globals =
     {sox_plot_off, 1, &sox_globals};
 
-int sox_usage(sox_effect_t * effp)
-{
-  if (effp->handler.usage)
-    sox_fail("usage: %s", effp->handler.usage);
-  else
-    sox_fail("this effect takes no parameters");
-  return SOX_EOF;
-}
-
 /* Default effect handler functions for do-nothing situations: */
 
 static int default_function(sox_effect_t * effp UNUSED)
@@ -70,7 +61,7 @@
 /* Check that no parameters have been given */
 static int default_getopts(sox_effect_t * effp, int argc, char **argv UNUSED)
 {
-  return argc? sox_usage(effp) : SOX_SUCCESS;
+  return argc? lsx_usage(effp) : SOX_SUCCESS;
 }
 
 /* Partially initialise the effect structure; signal info will come later */
--- /dev/null
+++ b/src/effects_i.c
@@ -1,0 +1,207 @@
+/*
+ * Implements a libSoX internal interface for implementing effects.
+ * All public functions & data are prefixed with lsx_ .
+ *
+ * (c) 2005-8 Chris Bagwell and SoX contributors
+ *
+ * This library is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This library 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 Lesser
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this library.  If not, write to the Free Software Foundation,
+ * Fifth Floor, 51 Franklin Street, Boston, MA 02111-1301, USA.
+ */
+
+#include "sox_i.h"
+#include <math.h>
+#include <string.h>
+
+int lsx_usage(sox_effect_t * effp)
+{
+  if (effp->handler.usage)
+    sox_fail("usage: %s", effp->handler.usage);
+  else
+    sox_fail("this effect takes no parameters");
+  return SOX_EOF;
+}
+
+/* here for linear interp.  might be useful for other things */
+sox_sample_t lsx_gcd(sox_sample_t a, sox_sample_t b)
+{
+  if (b == 0)
+    return a;
+  else
+    return lsx_gcd(b, a % b);
+}
+
+sox_sample_t lsx_lcm(sox_sample_t a, sox_sample_t b)
+{
+  /* parenthesize this way to avoid sox_sample_t overflow in product term */
+  return a * (b / lsx_gcd(a, b));
+}
+
+enum_item const lsx_wave_enum[] = {
+  ENUM_ITEM(SOX_WAVE_,SINE)
+  ENUM_ITEM(SOX_WAVE_,TRIANGLE)
+  {0, 0}};
+
+void lsx_generate_wave_table(
+    lsx_wave_t wave_type,
+    sox_data_t data_type,
+    void *table,
+    uint32_t table_size,
+    double min,
+    double max,
+    double phase)
+{
+  uint32_t t;
+  uint32_t phase_offset = phase / M_PI / 2 * table_size + 0.5;
+
+  for (t = 0; t < table_size; t++)
+  {
+    uint32_t point = (t + phase_offset) % table_size;
+    double d;
+    switch (wave_type)
+    {
+      case SOX_WAVE_SINE:
+      d = (sin((double)point / table_size * 2 * M_PI) + 1) / 2;
+      break;
+
+      case SOX_WAVE_TRIANGLE:
+      d = (double)point * 2 / table_size;
+      switch (4 * point / table_size)
+      {
+        case 0:         d = d + 0.5; break;
+        case 1: case 2: d = 1.5 - d; break;
+        case 3:         d = d - 1.5; break;
+      }
+      break;
+
+      default: /* Oops! FIXME */
+        d = 0.0; /* Make sure we have a value */
+      break;
+    }
+    d  = d * (max - min) + min;
+    switch (data_type)
+    {
+      case SOX_FLOAT:
+        {
+          float *fp = (float *)table;
+          *fp++ = (float)d;
+          table = fp;
+          continue;
+        }
+      case SOX_DOUBLE:
+        {
+          double *dp = (double *)table;
+          *dp++ = d;
+          table = dp;
+          continue;
+        }
+      default: break;
+    }
+    d += d < 0? -0.5 : +0.5;
+    switch (data_type)
+    {
+      case SOX_SHORT:
+        {
+          short *sp = table;
+          *sp++ = (short)d;
+          table = sp;
+          continue;
+        }
+      case SOX_INT:
+        {
+          int *ip = table;
+          *ip++ = (int)d;
+          table = ip;
+          continue;
+        }
+      default: break;
+    }
+  }
+}
+
+/*
+ * lsx_parsesamples
+ *
+ * Parse a string for # of samples.  If string ends with a 's'
+ * then the string is interpreted as a user calculated # of samples.
+ * If string contains ':' or '.' or if it ends with a 't' then its
+ * treated as an amount of time.  This is converted into seconds and
+ * fraction of seconds and then use the sample rate to calculate
+ * # of samples.
+ * Returns NULL on error, pointer to next char to parse otherwise.
+ */
+char const * lsx_parsesamples(sox_rate_t rate, const char *str, sox_size_t *samples, int def)
+{
+    int found_samples = 0, found_time = 0;
+    int time = 0;
+    long long_samples;
+    float frac = 0;
+    char const * end;
+    char const * pos;
+    sox_bool found_colon, found_dot;
+
+    for (end = str; *end && strchr("0123456789:.ts", *end); ++end);
+    if (end == str)
+      return NULL;
+
+    pos = strchr(str, ':');
+    found_colon = pos && pos < end;
+    
+    pos = strchr(str, '.');
+    found_dot = pos && pos < end;
+
+    if (found_colon || found_dot || *(end-1) == 't')
+        found_time = 1;
+    else if (*(end-1) == 's')
+        found_samples = 1;
+
+    if (found_time || (def == 't' && !found_samples))
+    {
+        *samples = 0;
+
+        while(1)
+        {
+            if (str[0] != '.' && sscanf(str, "%d", &time) != 1)
+                return NULL;
+            *samples += time;
+
+            while (*str != ':' && *str != '.' && *str != 0)
+                str++;
+
+            if (*str == '.' || *str == 0)
+                break;
+
+            /* Skip past ':' */
+            str++;
+            *samples *= 60;
+        }
+
+        if (*str == '.')
+        {
+            if (sscanf(str, "%f", &frac) != 1)
+                return NULL;
+        }
+
+        *samples *= rate;
+        *samples += (rate * frac) + 0.5;
+        return end;
+    }
+    if (found_samples || (def == 's' && !found_time))
+    {
+        if (sscanf(str, "%ld", &long_samples) != 1)
+            return NULL;
+        *samples = long_samples;
+        return end;
+    }
+    return NULL;
+}
--- a/src/example1.c
+++ b/src/example1.c
@@ -67,7 +67,7 @@
 }
 
 /* 
- * Reads input file, applies vol & reverb effects, stores in output file.
+ * Reads input file, applies vol & flanger effects, stores in output file.
  * E.g. example1 monkey.au monkey.aiff
  */
 int main(int argc, char * argv[])
--- a/src/fade.c
+++ b/src/fade.c
@@ -52,7 +52,7 @@
     int t_argno;
 
     if (n < 1 || n > 4)
-         return sox_usage(effp);
+         return lsx_usage(effp);
 
     /* because sample rate is unavailable at this point we store the
      * string off for later computations.
@@ -76,8 +76,8 @@
     fade->in_stop_str = (char *)xmalloc(strlen(argv[0])+1);
     strcpy(fade->in_stop_str,argv[0]);
     /* Do a dummy parse to see if it will fail */
-    if (sox_parsesamples(0., fade->in_stop_str, &fade->in_stop, 't') == NULL)
-      return sox_usage(effp);
+    if (lsx_parsesamples(0., fade->in_stop_str, &fade->in_stop, 't') == NULL)
+      return lsx_usage(effp);
 
     fade->out_start_str = fade->out_stop_str = 0;
 
@@ -90,9 +90,9 @@
             strcpy(fade->out_stop_str,argv[t_argno]);
 
             /* Do a dummy parse to see if it will fail */
-            if (sox_parsesamples(0., fade->out_stop_str, 
+            if (lsx_parsesamples(0., fade->out_stop_str, 
                                 &fade->out_stop, 't') == NULL)
-              return sox_usage(effp);
+              return lsx_usage(effp);
         }
         else
         {
@@ -100,9 +100,9 @@
             strcpy(fade->out_start_str,argv[t_argno]);
 
             /* Do a dummy parse to see if it will fail */
-            if (sox_parsesamples(0., fade->out_start_str, 
+            if (lsx_parsesamples(0., fade->out_start_str, 
                                 &fade->out_start, 't') == NULL)
-              return sox_usage(effp);
+              return lsx_usage(effp);
         }
     } /* End for(t_argno) */
 
@@ -119,9 +119,9 @@
 
     /* converting time values to samples */
     fade->in_start = 0;
-    if (sox_parsesamples(effp->in_signal.rate, fade->in_stop_str,
+    if (lsx_parsesamples(effp->in_signal.rate, fade->in_stop_str,
                         &fade->in_stop, 't') == NULL)
-      return sox_usage(effp);
+      return lsx_usage(effp);
 
     fade->do_out = 0;
     /* See if user specified a stop time */
@@ -128,16 +128,16 @@
     if (fade->out_stop_str)
     {
         fade->do_out = 1;
-        if (sox_parsesamples(effp->in_signal.rate, fade->out_stop_str,
+        if (lsx_parsesamples(effp->in_signal.rate, fade->out_stop_str,
                             &fade->out_stop, 't') == NULL)
-          return sox_usage(effp);
+          return lsx_usage(effp);
 
         /* See if user wants to fade out. */
         if (fade->out_start_str)
         {
-            if (sox_parsesamples(effp->in_signal.rate, fade->out_start_str,
+            if (lsx_parsesamples(effp->in_signal.rate, fade->out_start_str,
                         &fade->out_start, 't') == NULL)
-              return sox_usage(effp);
+              return lsx_usage(effp);
             /* Fade time is relative to stop time. */
             fade->out_start = fade->out_stop - fade->out_start;
 
--- a/src/filter.c
+++ b/src/filter.c
@@ -74,10 +74,10 @@
         }
         sox_debug("freq: %d-%d", f->freq0, f->freq1);
         if (f->freq0 == 0 && f->freq1 == 0)
-          return sox_usage(effp);
+          return lsx_usage(effp);
 
         if ((n >= 2) && !sscanf(argv[1], "%ld", &f->Nwin))
-          return sox_usage(effp);
+          return lsx_usage(effp);
         else if (f->Nwin < 4) {
                 sox_fail("filter: window length (%ld) <4 is too short", f->Nwin);
                 return (SOX_EOF);
@@ -84,7 +84,7 @@
         }
 
         if ((n >= 3) && !sscanf(argv[2], "%lf", &f->beta))
-          return sox_usage(effp);
+          return lsx_usage(effp);
 
         sox_debug("filter opts: %d-%d, window-len %ld, beta %f", f->freq0, f->freq1, f->Nwin, f->beta);
         return (SOX_SUCCESS);
--- a/src/flac.c
+++ b/src/flac.c
@@ -94,7 +94,7 @@
     }
 
     for (i = 0; i < metadata->data.vorbis_comment.num_comments; ++i)
-      append_comment(&ft->comments, (char const *) metadata->data.vorbis_comment.comments[i].entry);
+      sox_append_comment(&ft->comments, (char const *) metadata->data.vorbis_comment.comments[i].entry);
   }
 }
 
@@ -106,7 +106,7 @@
 
   (void) flac;
 
-  sox_fail_errno(ft, SOX_EINVAL, "%s", FLAC__StreamDecoderErrorStatusString[status]);
+  lsx_fail_errno(ft, SOX_EINVAL, "%s", FLAC__StreamDecoderErrorStatusString[status]);
 }
 
 
@@ -119,7 +119,7 @@
   (void) flac;
 
   if (frame->header.bits_per_sample != decoder->bits_per_sample || frame->header.channels != decoder->channels || frame->header.sample_rate != decoder->sample_rate) {
-    sox_fail_errno(ft, SOX_EINVAL, "FLAC ERROR: parameters differ between frame and header");
+    lsx_fail_errno(ft, SOX_EINVAL, "FLAC ERROR: parameters differ between frame and header");
     return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
   }
 
@@ -138,7 +138,7 @@
   memset(decoder, 0, sizeof(*decoder));
   decoder->flac = FLAC__stream_decoder_new();
   if (decoder->flac == NULL) {
-    sox_fail_errno(ft, SOX_ENOMEM, "FLAC ERROR creating the decoder instance");
+    lsx_fail_errno(ft, SOX_ENOMEM, "FLAC ERROR creating the decoder instance");
     return SOX_EOF;
   }
 
@@ -160,13 +160,13 @@
     FLAC__decoder_error_callback,
     ft) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
 #endif
-    sox_fail_errno(ft, SOX_EHDR, "FLAC ERROR initialising decoder");
+    lsx_fail_errno(ft, SOX_EHDR, "FLAC ERROR initialising decoder");
     return SOX_EOF;
   }
 
 
   if (!FLAC__stream_decoder_process_until_end_of_metadata(decoder->flac)) {
-    sox_fail_errno(ft, SOX_EHDR, "FLAC ERROR whilst decoding metadata");
+    lsx_fail_errno(ft, SOX_EHDR, "FLAC ERROR whilst decoding metadata");
     return SOX_EOF;
   }
 
@@ -175,7 +175,7 @@
 #else
   if (FLAC__stream_decoder_get_state(decoder->flac) > FLAC__STREAM_DECODER_END_OF_STREAM) {
 #endif
-    sox_fail_errno(ft, SOX_EHDR, "FLAC ERROR during metadata decoding");
+    lsx_fail_errno(ft, SOX_EHDR, "FLAC ERROR during metadata decoding");
     return SOX_EOF;
   }
 
@@ -254,7 +254,7 @@
   sox_format_t * const ft = (sox_format_t *) client_data;
   (void) flac, (void) samples, (void) current_frame;
 
-  return sox_writebuf(ft, buffer, bytes) == bytes ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
+  return lsx_writebuf(ft, buffer, bytes) == bytes ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
 }
 
 
@@ -273,7 +273,7 @@
   (void) encoder;
   if (!ft->seekable)
     return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
-  else if (sox_seeki(ft, (sox_ssize_t)absolute_byte_offset, SEEK_SET) != SOX_SUCCESS)
+  else if (lsx_seeki(ft, (sox_ssize_t)absolute_byte_offset, SEEK_SET) != SOX_SUCCESS)
     return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
   else
     return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
@@ -309,7 +309,7 @@
     compression_level = ft->encoding.compression;
     if (compression_level != ft->encoding.compression || 
         compression_level > MAX_COMPRESSION) {
-      sox_fail_errno(ft, SOX_EINVAL,
+      lsx_fail_errno(ft, SOX_EINVAL,
                  "FLAC compression level must be a whole number from 0 to %i",
                  MAX_COMPRESSION);
       return SOX_EOF;
@@ -319,7 +319,7 @@
   memset(encoder, 0, sizeof(*encoder));
   encoder->flac = FLAC__stream_encoder_new();
   if (encoder->flac == NULL) {
-    sox_fail_errno(ft, SOX_ENOMEM, "FLAC ERROR creating the encoder instance");
+    lsx_fail_errno(ft, SOX_ENOMEM, "FLAC ERROR creating the encoder instance");
     return SOX_EOF;
   }
   encoder->decoded_samples = xmalloc(sox_globals.bufsiz * sizeof(FLAC__int32));
@@ -390,7 +390,7 @@
 
     encoder->metadata[encoder->num_metadata] = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE);
     if (encoder->metadata[encoder->num_metadata] == NULL) {
-      sox_fail_errno(ft, SOX_ENOMEM, "FLAC ERROR creating the encoder seek table template");
+      lsx_fail_errno(ft, SOX_ENOMEM, "FLAC ERROR creating the encoder seek table template");
       return SOX_EOF;
     }
     {
@@ -401,7 +401,7 @@
       sox_size_t total_samples = ft->length/ft->signal.channels;
       if (!FLAC__metadata_object_seektable_template_append_spaced_points(encoder->metadata[encoder->num_metadata], total_samples / samples + (total_samples % samples != 0), (FLAC__uint64)total_samples)) {
 #endif
-        sox_fail_errno(ft, SOX_ENOMEM, "FLAC ERROR creating the encoder seek table points");
+        lsx_fail_errno(ft, SOX_ENOMEM, "FLAC ERROR creating the encoder seek table points");
         return SOX_EOF;
       }
     }
@@ -442,7 +442,7 @@
 #endif
 
   if (status != FLAC__STREAM_ENCODER_OK) {
-    sox_fail_errno(ft, SOX_EINVAL, "%s", FLAC__StreamEncoderStateString[status]);
+    lsx_fail_errno(ft, SOX_EINVAL, "%s", FLAC__StreamEncoderStateString[status]);
     return SOX_EOF;
   }
   return SOX_SUCCESS;
@@ -492,7 +492,7 @@
     FLAC__metadata_object_delete(encoder->metadata[i]);
   free(encoder->decoded_samples);
   if (state != FLAC__STREAM_ENCODER_OK) {
-    sox_fail_errno(ft, SOX_EINVAL, "FLAC ERROR: failed to encode to end of stream");
+    lsx_fail_errno(ft, SOX_EINVAL, "FLAC ERROR: failed to encode to end of stream");
     return SOX_EOF;
   }
   return SOX_SUCCESS;
--- a/src/flanger.c
+++ b/src/flanger.c
@@ -72,7 +72,7 @@
   double     feedback_gain;
   double     delay_gain;
   double     speed;
-  sox_wave_t  wave_shape;
+  lsx_wave_t  wave_shape;
   double     channel_phase;
   interp_t   interpolation;
             
@@ -119,13 +119,13 @@
     NUMERIC_PARAMETER(feedback_gain,-95 , 95 )
     NUMERIC_PARAMETER(delay_gain   , 0  , 100)
     NUMERIC_PARAMETER(speed        , 0.1, 10 )
-    TEXTUAL_PARAMETER(wave_shape, sox_wave_enum)
+    TEXTUAL_PARAMETER(wave_shape, lsx_wave_enum)
     NUMERIC_PARAMETER(channel_phase, 0  , 100)
     TEXTUAL_PARAMETER(interpolation, interp_enum)
   } while (0);
 
   if (argc != 0)
-    return sox_usage(effp);
+    return lsx_usage(effp);
 
   sox_report("parameters:\n"
       "delay = %gms\n"
@@ -141,7 +141,7 @@
       p->feedback_gain,
       p->delay_gain,
       p->speed,
-      sox_wave_enum[p->wave_shape].text,
+      lsx_wave_enum[p->wave_shape].text,
       p->channel_phase,
       interp_enum[p->interpolation].text);
 
@@ -186,7 +186,7 @@
   /* Create the LFO lookup table: */
   f->lfo_length = effp->in_signal.rate / f->speed;
   f->lfo = xcalloc(f->lfo_length, sizeof(*f->lfo));
-  sox_generate_wave_table(
+  lsx_generate_wave_table(
       f->wave_shape,
       SOX_FLOAT,
       f->lfo,
--- a/src/formats.c
+++ b/src/formats.c
@@ -1,46 +1,1030 @@
 /*
- * Originally created: July 5, 1991
- * Copyright 1991 Lance Norskog And Sundry Contributors
- * This source code is freely redistributable and may be used for
- * any purpose.  This copyright notice must be maintained.
- * Lance Norskog And Sundry Contributors are not responsible for
- * the consequences of using this software.
+ * Implements the public API for using libSoX file formats.
+ * All public functions & data are prefixed with sox_ .
+ *
+ * (c) 2005-8 Chris Bagwell and SoX contributors
+ *
+ * This library is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This library 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 Lesser
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this library.  If not, write to the Free Software Foundation,
+ * Fifth Floor, 51 Franklin Street, Boston, MA 02111-1301, USA.
  */
 
 #include "sox_i.h"
+
+#include <assert.h>
+#include <ctype.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <math.h>
+#include <stdlib.h>
 #include <string.h>
+#include <sys/stat.h>
+#include <sys/types.h>
 
-/* File format handlers. */
+#ifdef HAVE_IO_H
+  #include <io.h>
+#endif
 
-#ifdef HAVE_LIBLTDL
-/* FIXME: Use a vector, not a fixed-size array */
-  #define MAX_FORMATS 256
-  unsigned sox_formats = 0;
-  sox_format_tab_t sox_format_fns[MAX_FORMATS];
+const char * const sox_encodings_str[] = {
+  "?",
+  "Signed Integer PCM",
+  "Unsigned Integer PCM",
+  "Floating Point PCM",
+  "Floating Point (text) PCM",
+  "FLAC",
+  "HCOM",
+  "", /* Lossless above, lossy below */
+  "u-law",
+  "A-law",
+  "G.721 ADPCM",
+  "G.723 ADPCM",
+  "CL ADPCM (from 8-bit)",
+  "CL ADPCM (from 16-bit)",
+  "MS ADPCM",
+  "IMA ADPCM",
+  "OKI ADPCM",
+  "GSM",
+  "MPEG audio (layer I, II or III)",
+  "Vorbis",
+  "AMR-WB",
+  "AMR-NB",
+  "CVSD",
+  "LPC10",
+};
+
+assert_static(array_length(sox_encodings_str) == SOX_ENCODINGS,
+    SIZE_MISMATCH_BETWEEN_sox_encodings_t_AND_sox_encodings_str);
+
+const char * const sox_encodings_short_str[] = {
+  "n/a",
+  "Signed PCM",
+  "Unsigned PCM",
+  "F.P. PCM",
+  "F.P. PCM",
+  "FLAC",
+  "HCOM",
+  "", /* Lossless above, lossy below */
+  "u-law",
+  "A-law",
+  "G.721 ADPCM",
+  "G.723 ADPCM",
+  "CL ADPCM (8)",
+  "CL ADPCM (16)",
+  "MS ADPCM",
+  "IMA ADPCM",
+  "OKI ADPCM",
+  "GSM",
+  "MPEG audio",
+  "Vorbis",
+  "AMR-WB",
+  "AMR-NB",
+  "CVSD",
+  "LPC10",
+};
+
+assert_static(array_length(sox_encodings_short_str) == SOX_ENCODINGS,
+    SIZE_MISMATCH_BETWEEN_sox_encodings_t_AND_sox_encodings_short_str);
+
+static char const * detect_magic(sox_format_t * ft, char const * ext)
+{
+  char data[256];
+  size_t len = lsx_readbuf(ft, data, sizeof(data));
+  #define MAGIC(type, p2, l2, d2, p1, l1, d1) if (len >= p1 + l1 && \
+      !memcmp(data + p1, d1, l1) && !memcmp(data + p2, d2, l2)) return #type;
+  MAGIC(voc   , 0, 0, ""     , 0, 20, "Creative Voice File\x1a")
+  MAGIC(smp   , 0, 0, ""     , 0, 17, "SOUND SAMPLE DATA")
+  MAGIC(wve   , 0, 0, ""     , 0, 15, "ALawSoundFile**")
+  MAGIC(amr-wb, 0, 0, ""     , 0,  9, "#!AMR-WB\n")
+  MAGIC(prc   , 0, 0, ""     , 0,  8, "\x37\x00\x00\x10\x6d\x00\x00\x10")
+  MAGIC(sph   , 0, 0, ""     , 0,  7, "NIST_1A")
+  MAGIC(amr-nb, 0, 0, ""     , 0,  6, "#!AMR\n")
+  MAGIC(txw   , 0, 0, ""     , 0,  6, "LM8953")
+  MAGIC(sndt  , 0, 0, ""     , 0,  6, "SOUND\x1a")
+  MAGIC(vorbis, 0, 4, "OggS" , 29, 6, "vorbis")
+  MAGIC(speex , 0, 4, "OggS" , 28, 6, "Speex")
+  MAGIC(hcom  ,65, 4, "FSSD" , 128,4, "HCOM")
+  MAGIC(wav   , 0, 4, "RIFF" , 8,  4, "WAVE")
+  MAGIC(wav   , 0, 4, "RIFX" , 8,  4, "WAVE")
+  MAGIC(aiff  , 0, 4, "FORM" , 8,  4, "AIFF")
+  MAGIC(aifc  , 0, 4, "FORM" , 8,  4, "AIFC")
+  MAGIC(8svx  , 0, 4, "FORM" , 8,  4, "8SVX")
+  MAGIC(maud  , 0, 4, "FORM" , 8,  4, "MAUD")
+  MAGIC(xa    , 0, 0, ""     , 0,  4, "XA\0\0")
+  MAGIC(xa    , 0, 0, ""     , 0,  4, "XAI\0")
+  MAGIC(xa    , 0, 0, ""     , 0,  4, "XAJ\0")
+  MAGIC(au    , 0, 0, ""     , 0,  4, ".snd")
+  MAGIC(au    , 0, 0, ""     , 0,  4, "dns.")
+  MAGIC(au    , 0, 0, ""     , 0,  4, "\0ds.")
+  MAGIC(au    , 0, 0, ""     , 0,  4, ".sd\0")
+  MAGIC(flac  , 0, 0, ""     , 0,  4, "fLaC")
+  MAGIC(avr   , 0, 0, ""     , 0,  4, "2BIT")
+  MAGIC(caf   , 0, 0, ""     , 0,  4, "caff")
+  MAGIC(paf   , 0, 0, ""     , 0,  4, " paf")
+  MAGIC(sf    , 0, 0, ""     , 0,  4, "\144\243\001\0")
+  MAGIC(sf    , 0, 0, ""     , 0,  4, "\0\001\243\144")
+  MAGIC(sf    , 0, 0, ""     , 0,  4, "\144\243\002\0")
+  MAGIC(sf    , 0, 0, ""     , 0,  4, "\0\002\243\144")
+  MAGIC(sf    , 0, 0, ""     , 0,  4, "\144\243\003\0")
+  MAGIC(sf    , 0, 0, ""     , 0,  4, "\0\003\243\144")
+  MAGIC(sf    , 0, 0, ""     , 0,  4, "\144\243\004\0")
+
+  if (ext && !strcasecmp(ext, "snd"))
+  MAGIC(sndr  , 7, 1, ""     , 0,  2, "\0")
+  #undef MAGIC
+  return NULL;
+}
+
+unsigned sox_precision(sox_encoding_t encoding, unsigned bits_per_sample)
+{
+  switch (encoding) {
+    case SOX_ENCODING_HCOM:       return !(bits_per_sample & 7) && (bits_per_sample >> 3) - 1 < 1? bits_per_sample: 0;
+    case SOX_ENCODING_FLAC:       return !(bits_per_sample & 7) && (bits_per_sample >> 3) - 1 < 3? bits_per_sample: 0;
+    case SOX_ENCODING_SIGN2:      return bits_per_sample <= 32? bits_per_sample : 0;
+    case SOX_ENCODING_UNSIGNED:   return !(bits_per_sample & 7) && (bits_per_sample >> 3) - 1 < 4? bits_per_sample: 0;
+
+    case SOX_ENCODING_ALAW:       return bits_per_sample == 8? 13: 0;
+    case SOX_ENCODING_ULAW:       return bits_per_sample == 8? 14: 0;
+
+    case SOX_ENCODING_CL_ADPCM:   return bits_per_sample? 8: 0;
+    case SOX_ENCODING_CL_ADPCM16: return bits_per_sample == 4? 13: 0;
+    case SOX_ENCODING_MS_ADPCM:   return bits_per_sample == 4? 14: 0;
+    case SOX_ENCODING_IMA_ADPCM:  return bits_per_sample == 4? 13: 0;
+    case SOX_ENCODING_OKI_ADPCM:  return bits_per_sample == 4? 12: 0;
+    case SOX_ENCODING_G721:       return bits_per_sample == 4? 12: 0;
+    case SOX_ENCODING_G723:       return bits_per_sample == 3? 8:
+                                         bits_per_sample == 5? 14: 0;
+    case SOX_ENCODING_CVSD:       return bits_per_sample == 1? 16: 0;
+
+    case SOX_ENCODING_GSM:
+    case SOX_ENCODING_MP3:
+    case SOX_ENCODING_VORBIS:
+    case SOX_ENCODING_AMR_WB:
+    case SOX_ENCODING_AMR_NB:
+    case SOX_ENCODING_LPC10:      return !bits_per_sample? 16: 0;
+
+    case SOX_ENCODING_FLOAT:      return bits_per_sample == 32 ? 24: bits_per_sample == 64 ? 53: 0;
+    case SOX_ENCODING_FLOAT_TEXT: return !bits_per_sample? 53: 0;
+
+    case SOX_ENCODINGS:
+    case SOX_ENCODING_LOSSLESS:
+    case SOX_ENCODING_UNKNOWN:    break;
+  }
+  return 0;
+}
+
+void sox_init_encodinginfo(sox_encodinginfo_t * e)
+{
+  e->reverse_bytes = SOX_OPTION_DEFAULT;
+  e->reverse_nibbles = SOX_OPTION_DEFAULT;
+  e->reverse_bits = SOX_OPTION_DEFAULT;
+  e->compression = HUGE_VAL;
+}
+
+/*--------------------------------- Comments ---------------------------------*/
+
+size_t sox_num_comments(sox_comments_t comments)
+{
+  size_t result = 0;
+  if (!comments)
+    return 0;
+  while (*comments++)
+    ++result;
+  return result;
+}
+
+void sox_append_comment(sox_comments_t * comments, char const * comment)
+{
+  size_t n = sox_num_comments(*comments);
+  *comments = xrealloc(*comments, (n + 2) * sizeof(**comments));
+  assert(comment);
+  (*comments)[n++] = xstrdup(comment);
+  (*comments)[n] = 0;
+}
+
+void sox_append_comments(sox_comments_t * comments, char const * comment)
+{
+  char * end;
+  if (comment) {
+    while ((end = strchr(comment, '\n'))) {
+      size_t len = end - comment;
+      char * c = xmalloc((len + 1) * sizeof(*c));
+      strncpy(c, comment, len);
+      c[len] = '\0';
+      sox_append_comment(comments, c);
+      comment += len + 1;
+      free(c);
+    }
+    if (*comment)
+      sox_append_comment(comments, comment);
+  }
+}
+
+sox_comments_t sox_copy_comments(sox_comments_t comments)
+{
+  sox_comments_t result = 0;
+
+  if (comments) while (*comments)
+    sox_append_comment(&result, *comments++);
+  return result;
+}
+
+void sox_delete_comments(sox_comments_t * comments)
+{
+  sox_comments_t p = *comments;
+
+  if (p) while (*p)
+    free(*p++);
+  free(*comments);
+  *comments = 0;
+}
+
+char * sox_cat_comments(sox_comments_t comments)
+{
+  sox_comments_t p = comments;
+  size_t len = 0;
+  char * result;
+
+  if (p) while (*p)
+    len += strlen(*p++) + 1;
+
+  result = xcalloc(len? len : 1, sizeof(*result));
+
+  if ((p = comments) && *p) {
+    strcpy(result, *p);
+    while (*++p)
+      strcat(strcat(result, "\n"), *p);
+  }
+  return result;
+}
+
+char const * sox_find_comment(sox_comments_t comments, char const * id)
+{
+  size_t len = strlen(id);
+
+  if (comments) for (;*comments; ++comments)
+    if (!strncasecmp(*comments, id, len) && (*comments)[len] == '=')
+      return *comments + len + 1;
+  return NULL;
+}
+
+static void set_endiannesses(sox_format_t * ft)
+{
+  if (ft->encoding.opposite_endian)
+    ft->encoding.reverse_bytes = (ft->handler.flags & SOX_FILE_ENDIAN)?
+      !(ft->handler.flags & SOX_FILE_ENDBIG) != MACHINE_IS_BIGENDIAN : sox_true;
+  else if (ft->encoding.reverse_bytes == SOX_OPTION_DEFAULT)
+    ft->encoding.reverse_bytes = (ft->handler.flags & SOX_FILE_ENDIAN)?
+      !(ft->handler.flags & SOX_FILE_ENDBIG) == MACHINE_IS_BIGENDIAN : sox_false;
+
+  /* FIXME: Change reports to suitable warnings if trying
+   * to override something that can't be overridden. */
+
+  if (ft->handler.flags & SOX_FILE_ENDIAN) {
+    if (ft->encoding.reverse_bytes ==
+        (!(ft->handler.flags & SOX_FILE_ENDBIG) != MACHINE_IS_BIGENDIAN))
+      sox_report("`%s': overriding file-type byte-order", ft->filename);
+  } else if (ft->encoding.reverse_bytes == sox_true)
+    sox_report("`%s': overriding machine byte-order", ft->filename);
+
+  if (ft->encoding.reverse_bits == SOX_OPTION_DEFAULT)
+    ft->encoding.reverse_bits = !!(ft->handler.flags & SOX_FILE_BIT_REV);
+  else if (ft->encoding.reverse_bits == !(ft->handler.flags & SOX_FILE_BIT_REV))
+      sox_report("`%s': overriding file-type bit-order", ft->filename);
+
+  if (ft->encoding.reverse_nibbles == SOX_OPTION_DEFAULT)
+    ft->encoding.reverse_nibbles = !!(ft->handler.flags & SOX_FILE_NIB_REV);
+  else
+    if (ft->encoding.reverse_nibbles == !(ft->handler.flags & SOX_FILE_NIB_REV))
+      sox_report("`%s': overriding file-type nibble-order", ft->filename);
+}
+
+static int is_seekable(sox_format_t * ft)
+{
+  struct stat st;
+
+  fstat(fileno(ft->fp), &st);
+  return ((st.st_mode & S_IFMT) == S_IFREG);
+}
+
+/* check that all settings have been given */
+static int sox_checkformat(sox_format_t * ft)
+{
+  ft->sox_errno = SOX_SUCCESS;
+
+  if (!ft->signal.rate) {
+    lsx_fail_errno(ft,SOX_EFMT,"sampling rate was not specified");
+    return SOX_EOF;
+  }
+  if (!ft->signal.precision) {
+    lsx_fail_errno(ft,SOX_EFMT,"data encoding was not specified");
+    return SOX_EOF;
+  }
+  return SOX_SUCCESS;
+}
+
+static char const * find_file_extension(char const * pathname)
+{
+  /* First, chop off any path portions of filename.  This
+   * prevents the next search from considering that part. */
+  char const * result = LAST_SLASH(pathname);
+  if (!result)
+    result = pathname;
+
+  /* Now look for an filename extension */
+  result = strrchr(result, '.');
+  if (result)
+    ++result;
+  return result;
+}
+
+static sox_bool is_uri(char const * text)
+{
+  if (!isalpha((int)*text))
+    return sox_false;
+  ++text;
+  do {
+    if (!isalnum((int)*text) && !strchr("+-.", *text))
+      return sox_false;
+    ++text;
+  } while (*text && *text != ':');
+  return *text == ':';
+}
+
+static FILE * xfopen(char const * identifier, char const * mode) 
+{ 
+  if (is_uri(identifier)) {
+    FILE * f = NULL;
+#ifdef HAVE_POPEN
+    char const * const command_format = "wget --no-check-certificate -q -O- \"%s\"";
+    char * command = xmalloc(strlen(command_format) + strlen(identifier)); 
+    sprintf(command, command_format, identifier); 
+    f = popen(command, "r"); 
+    free(command);
 #else
-  #define FORMAT(f) extern sox_format_handler_t const * sox_##f##_format_fn(void);
+    sox_fail("open URL support has not been built into SoX");
+#endif 
+    return f;
+  }
+  return fopen(identifier, mode);
+} 
+
+sox_format_t * sox_open_read(
+    char               const * path,
+    sox_signalinfo_t   const * signal,
+    sox_encodinginfo_t const * encoding,
+    char               const * filetype)
+{
+  sox_format_t * ft = xcalloc(1, sizeof(*ft));
+  sox_format_handler_t const * handler;
+
+  if (filetype) {
+    if (!(handler = sox_find_format(filetype, sox_false))) {
+      sox_fail("no handler for given file type `%s'", filetype);
+      goto error;
+    }
+    ft->handler = *handler;
+  }
+
+  if (!(ft->handler.flags & SOX_FILE_NOSTDIO)) {
+    if (!strcmp(path, "-")) { /* Use stdin if the filename is "-" */
+      if (sox_globals.stdin_in_use_by) {
+        sox_fail("`-' (stdin) already in use by `%s'", sox_globals.stdin_in_use_by);
+        goto error;
+      }
+      sox_globals.stdin_in_use_by = "audio input";
+      SET_BINARY_MODE(stdin);
+      ft->fp = stdin;
+    }
+    else if ((ft->fp = xfopen(path, "rb")) == NULL) {
+      sox_fail("can't open input file `%s': %s", path, strerror(errno));
+      goto error;
+    }
+    ft->seekable = is_seekable(ft);
+  }
+
+  if (!filetype) {
+    if (ft->seekable) {
+      filetype = detect_magic(ft, find_file_extension(path));
+      lsx_rewind(ft);
+    }
+    if (filetype) {
+      sox_report("detected file format type `%s'", filetype);
+      if (!(handler = sox_find_format(filetype, sox_false))) {
+        sox_fail("no handler for detected file type `%s'", filetype);
+        goto error;
+      }
+    }
+    else {
+      if (!(filetype = find_file_extension(path))) {
+        sox_fail("can't determine type of `%s'", path);
+        goto error;
+      }
+      if (!(handler = sox_find_format(filetype, sox_true))) {
+        sox_fail("no handler for file extension `%s'", filetype);
+        goto error;
+      }
+    }
+    ft->handler = *handler;
+    if (ft->handler.flags & SOX_FILE_NOSTDIO)
+      fclose(ft->fp);
+  }
+  if (!ft->handler.startread && !ft->handler.read) {
+    sox_fail("file type `%s' isn't readable", filetype);
+    goto error;
+  }
+  
+  ft->mode = 'r';
+  
+  if (signal)
+    ft->signal = *signal;
+  
+  if (encoding)
+    ft->encoding = *encoding;
+  else sox_init_encodinginfo(&ft->encoding);
+  set_endiannesses(ft);
+
+  ft->filetype = xstrdup(filetype);
+  ft->filename = xstrdup(path);
+
+  /* Read and write starters can change their formats. */
+  if (ft->handler.startread && (*ft->handler.startread)(ft) != SOX_SUCCESS) {
+    sox_fail("can't open input file `%s': %s", ft->filename, ft->sox_errstr);
+    goto error;
+  }
+
+  /* Fill in some defaults: */
+  if (!ft->signal.precision)
+    ft->signal.precision = sox_precision(ft->encoding.encoding, ft->encoding.bits_per_sample);
+  if (!(ft->handler.flags & SOX_FILE_PHONY) && !ft->signal.channels)
+    ft->signal.channels = 1;
+
+  if (sox_checkformat(ft) == SOX_SUCCESS)
+    return ft;
+  sox_fail("bad input format for file `%s': %s", ft->filename, ft->sox_errstr);
+
+error:
+  if (ft->fp && ft->fp != stdin)
+    fclose(ft->fp);
+  free(ft->filename);
+  free(ft->filetype);
+  free(ft);
+  return NULL;
+}
+
+sox_bool sox_format_supports_encoding(
+    char               const * path,
+    char               const * filetype,
+    sox_encodinginfo_t const * encoding)
+{
+  #define enc_arg(T) (T)handler->write_formats[i++]
+  sox_bool is_file_extension = filetype == NULL;
+  sox_format_handler_t const * handler;
+  unsigned i = 0, s;
+  sox_encoding_t e;
+
+  assert(path);
+  assert(encoding);
+  if (!filetype)
+    filetype = find_file_extension(path);
+
+  if (!filetype || !(handler = sox_find_format(filetype, is_file_extension)) ||
+      !handler->write_formats)
+    return sox_false;
+  while ((e = enc_arg(sox_encoding_t))) {
+    if (e == encoding->encoding) {
+      while ((s = enc_arg(unsigned)))
+        if (s == encoding->bits_per_sample)
+          return sox_true;
+      break;
+    }
+    while (enc_arg(unsigned));
+  }
+  return sox_false;
+  #undef enc_arg
+}
+
+static void set_output_format(sox_format_t * ft)
+{
+  sox_encoding_t e;
+  unsigned i, s;
+  unsigned const * encodings = ft->handler.write_formats;
+#define enc_arg(T) (T)encodings[i++]
+
+  if (ft->handler.write_rates){
+    if (!ft->signal.rate)
+      ft->signal.rate = ft->handler.write_rates[0];
+    else {
+      sox_rate_t r;
+      i = 0;
+      while ((r = ft->handler.write_rates[i++])) {
+        if (r == ft->signal.rate)
+          break;
+      }
+      if (r != ft->signal.rate) {
+        sox_rate_t given = ft->signal.rate, max = 0;
+        ft->signal.rate = HUGE_VAL;
+        i = 0;
+        while ((r = ft->handler.write_rates[i++])) {
+          if (r > given && r < ft->signal.rate)
+            ft->signal.rate = r;
+          else max = max(r, max);
+        }
+        if (ft->signal.rate == HUGE_VAL)
+          ft->signal.rate = max;
+        sox_warn("%s can't encode at %gHz; using %gHz", ft->handler.names[0], given, ft->signal.rate);
+      }
+    }
+  }
+  else if (!ft->signal.rate)
+    ft->signal.rate = SOX_DEFAULT_RATE;
+
+  if (ft->handler.flags & SOX_FILE_CHANS) {
+    if (ft->signal.channels == 1 && !(ft->handler.flags & SOX_FILE_MONO)) {
+      ft->signal.channels = (ft->handler.flags & SOX_FILE_STEREO)? 2 : 4;
+      sox_warn("%s can't encode mono; setting channels to %u", ft->handler.names[0], ft->signal.channels);
+    } else
+    if (ft->signal.channels == 2 && !(ft->handler.flags & SOX_FILE_STEREO)) {
+      ft->signal.channels = (ft->handler.flags & SOX_FILE_QUAD)? 4 : 1;
+      sox_warn("%s can't encode stereo; setting channels to %u", ft->handler.names[0], ft->signal.channels);
+    } else
+    if (ft->signal.channels == 4 && !(ft->handler.flags & SOX_FILE_QUAD)) {
+      ft->signal.channels = (ft->handler.flags & SOX_FILE_STEREO)? 2 : 1;
+      sox_warn("%s can't encode quad; setting channels to %u", ft->handler.names[0], ft->signal.channels);
+    }
+  } else ft->signal.channels = max(ft->signal.channels, 1);
+
+  if (!encodings)
+    return;
+  /* If an encoding has been given, check if it supported by this handler */
+  if (ft->encoding.encoding) {
+    i = 0;
+    while ((e = enc_arg(sox_encoding_t))) {
+      if (e == ft->encoding.encoding)
+        break;
+      while (enc_arg(unsigned));
+    }
+    if (e != ft->encoding.encoding) {
+      sox_warn("%s can't encode %s", ft->handler.names[0], sox_encodings_str[ft->encoding.encoding]);
+      ft->encoding.encoding = 0;
+    }
+    else {
+      unsigned max_p = 0;
+      unsigned max_p_s = 0;
+      unsigned given_size = 0;
+      sox_bool found = sox_false;
+      if (ft->encoding.bits_per_sample)
+        given_size = ft->encoding.bits_per_sample;
+      ft->encoding.bits_per_sample = 65;
+      while ((s = enc_arg(unsigned))) {
+        if (s == given_size)
+          found = sox_true;
+        if (sox_precision(e, s) >= ft->signal.precision) {
+          if (s < ft->encoding.bits_per_sample)
+            ft->encoding.bits_per_sample = s;
+        }
+        else if (sox_precision(e, s) > max_p) {
+          max_p = sox_precision(e, s);
+          max_p_s = s;
+        }
+      }
+      if (ft->encoding.bits_per_sample == 65)
+        ft->encoding.bits_per_sample = max_p_s;
+      if (given_size) {
+        if (found)
+          ft->encoding.bits_per_sample = given_size;
+        else sox_warn("%s can't encode %s to %u-bit", ft->handler.names[0], sox_encodings_str[ft->encoding.encoding], given_size);
+      }
+    }
+  }
+
+  /* If a size has been given, check if it supported by this handler */
+  if (!ft->encoding.encoding && ft->encoding.bits_per_sample) {
+    i = 0;
+    s= 0;
+    while (s != ft->encoding.bits_per_sample && (e = enc_arg(sox_encoding_t)))
+      while ((s = enc_arg(unsigned)) && s != ft->encoding.bits_per_sample);
+    if (s != ft->encoding.bits_per_sample) {
+      sox_warn("%s can't encode to %u-bit", ft->handler.names[0], ft->encoding.bits_per_sample);
+      ft->encoding.bits_per_sample = 0;
+    }
+    else ft->encoding.encoding = e;
+  }
+
+  /* Find the smallest lossless encoding with precision >= signal.precision */
+  if (!ft->encoding.encoding) {
+    ft->encoding.bits_per_sample = 65;
+    i = 0;
+    while ((e = enc_arg(sox_encoding_t)))
+      while ((s = enc_arg(unsigned)))
+        if (e < SOX_ENCODING_LOSSLESS &&
+            sox_precision(e, s) >= ft->signal.precision && s < ft->encoding.bits_per_sample) {
+          ft->encoding.encoding = e;
+          ft->encoding.bits_per_sample = s;
+        }
+  }
+
+  /* Find the smallest lossy encoding with precision >= signal precision,
+   * or, if none such, the highest precision encoding */
+  if (!ft->encoding.encoding) {
+    unsigned max_p = 0;
+    sox_encoding_t max_p_e = 0;
+    unsigned max_p_s = 0;
+    i = 0;
+    while ((e = enc_arg(sox_encoding_t)))
+      do {
+        s = enc_arg(unsigned);
+        if (sox_precision(e, s) >= ft->signal.precision) {
+          if (s < ft->encoding.bits_per_sample) {
+            ft->encoding.encoding = e;
+            ft->encoding.bits_per_sample = s;
+          }
+        }
+        else if (sox_precision(e, s) > max_p) {
+          max_p = sox_precision(e, s);
+          max_p_e = e;
+          max_p_s = s;
+        }
+      } while (s);
+    if (!ft->encoding.encoding) {
+      ft->encoding.encoding = max_p_e;
+      ft->encoding.bits_per_sample = max_p_s;
+    }
+  }
+  ft->signal.precision = min(ft->signal.precision, sox_precision(ft->encoding.encoding, ft->encoding.bits_per_sample));
+  #undef enc_arg
+}
+
+sox_format_t * sox_open_write(
+    sox_bool (*overwrite_permitted)(const char *filename),
+    char               const * path,
+    sox_signalinfo_t   const * signal,
+    sox_encodinginfo_t const * encoding,
+    char               const * filetype,
+    sox_comments_t                 comments,
+    sox_size_t                 length,
+    sox_instrinfo_t    const * instr,
+    sox_loopinfo_t     const * loops)
+{
+  sox_format_t * ft = xcalloc(sizeof(*ft), 1);
+  sox_format_handler_t const * handler;
+  int i;
+
+  if (!path || !signal) {
+    sox_fail("must specify file name and signal parameters to write file");
+    goto error;
+  }
+
+  if (filetype) {
+    if (!(handler = sox_find_format(filetype, sox_false))) {
+      sox_fail("no handler for given file type `%s'", filetype);
+      goto error;
+    }
+    ft->handler = *handler;
+  }
+  else {
+    if (!(filetype = find_file_extension(path))) {
+      sox_fail("can't determine type of `%s'", path);
+      goto error;
+    }
+    if (!(handler = sox_find_format(filetype, sox_true))) {
+      sox_fail("no handler for file extension `%s'", filetype);
+      goto error;
+    }
+    ft->handler = *handler;
+  }
+  if (!ft->handler.startwrite && !ft->handler.write) {
+    sox_fail("file type `%s' isn't writeable", filetype);
+    goto error;
+  }
+
+  if (!(ft->handler.flags & SOX_FILE_NOSTDIO)) {
+    if (!strcmp(path, "-")) { /* Use stdout if the filename is "-" */
+      if (sox_globals.stdout_in_use_by) {
+        sox_fail("`-' (stdout) already in use by `%s'", sox_globals.stdout_in_use_by);
+        goto error;
+      }
+      sox_globals.stdout_in_use_by = "audio output";
+      SET_BINARY_MODE(stdout);
+      ft->fp = stdout;
+    }
+    else {
+      struct stat st;
+      if (!stat(path, &st) && (st.st_mode & S_IFMT) == S_IFREG &&
+          (overwrite_permitted && !overwrite_permitted(path))) {
+        sox_fail("permission to overwrite '%s' denied", path);
+        goto error;
+      }
+      if ((ft->fp = fopen(path, "wb")) == NULL) {
+        sox_fail("can't open output file `%s': %s", path, strerror(errno));
+        goto error;
+      }
+    }
+
+    /* stdout tends to be line-buffered.  Override this */
+    /* to be Full Buffering. */
+    if (setvbuf (ft->fp, NULL, _IOFBF, sizeof(char) * sox_globals.bufsiz)) {
+      sox_fail("Can't set write buffer");
+      goto error;
+    }
+    ft->seekable = is_seekable(ft);
+  }
+
+  ft->mode = 'w';
+
+  ft->signal = *signal;
+  
+  if (encoding)
+    ft->encoding = *encoding;
+  else sox_init_encodinginfo(&ft->encoding);
+  set_endiannesses(ft);
+
+  ft->filetype = xstrdup(filetype);
+  ft->filename = xstrdup(path);
+
+  ft->comments = sox_copy_comments(comments);
+
+  if (loops) for (i = 0; i < SOX_MAX_NLOOPS; i++)
+    ft->loops[i] = loops[i];
+
+  /* leave SMPTE # alone since it's absolute */
+  if (instr)
+    ft->instr = *instr;
+
+  ft->length = length;
+  set_output_format(ft);
+
+  /* FIXME: doesn't cover the situation where
+   * codec changes audio length due to block alignment (e.g. 8svx, gsm): */
+  if (signal->rate && signal->channels)
+    ft->length = ft->length * ft->signal.rate / signal->rate *
+      ft->signal.channels / signal->channels + .5;
+
+  if ((ft->handler.flags & SOX_FILE_REWIND) && !ft->length && !ft->seekable)
+    sox_warn("can't seek in output file `%s'; length in file header will be unspecified", ft->filename);
+
+  /* Read and write starters can change their formats. */
+  if (ft->handler.startwrite && (ft->handler.startwrite)(ft) != SOX_SUCCESS){
+    sox_fail("can't open output file `%s': %s", ft->filename, ft->sox_errstr);
+    goto error;
+  }
+
+  if (sox_checkformat(ft) == SOX_SUCCESS)
+    return ft;
+  sox_fail("bad format for output file `%s': %s", ft->filename, ft->sox_errstr);
+
+error:
+  if (ft->fp && ft->fp != stdout)
+    fclose(ft->fp);
+  free(ft->filename);
+  free(ft->filetype);
+  free(ft);
+  return NULL;
+}
+
+sox_size_t sox_read(sox_format_t * ft, sox_sample_t * buf, sox_size_t len)
+{
+  sox_size_t actual = ft->handler.read? (*ft->handler.read)(ft, buf, len) : 0;
+  return (actual > len? 0 : actual);
+}
+
+sox_size_t sox_write(sox_format_t * ft, const sox_sample_t *buf, sox_size_t len)
+{
+  sox_size_t ret = ft->handler.write? (*ft->handler.write)(ft, buf, len) : 0;
+  ft->olength += ret;
+  return ret;
+}
+
+/* N.B. The file (if any) may already have been deleted. */
+int sox_close(sox_format_t * ft)
+{
+  int rc = SOX_SUCCESS;
+
+  if (ft->mode == 'r')
+    rc = ft->handler.stopread? (*ft->handler.stopread)(ft) : SOX_SUCCESS;
+  else {
+    if (ft->handler.flags & SOX_FILE_REWIND) {
+      if (ft->olength != ft->length && ft->seekable) {
+        rc = lsx_seeki(ft, 0, 0);
+        if (rc == SOX_SUCCESS)
+          rc = ft->handler.stopwrite? (*ft->handler.stopwrite)(ft)
+             : ft->handler.startwrite?(*ft->handler.startwrite)(ft) : SOX_SUCCESS;
+      }
+    }
+    else rc = ft->handler.stopwrite? (*ft->handler.stopwrite)(ft) : SOX_SUCCESS;
+  }
+
+  if (!(ft->handler.flags & SOX_FILE_NOSTDIO))
+    fclose(ft->fp);
+  free(ft->filename);
+  free(ft->filetype);
+  sox_delete_comments(&ft->comments);
+
+  free(ft);
+  return rc;
+}
+
+int sox_seek(sox_format_t * ft, sox_size_t offset, int whence)
+{
+    /* FIXME: Implement SOX_SEEK_CUR and SOX_SEEK_END. */
+    if (whence != SOX_SEEK_SET)
+        return SOX_EOF; /* FIXME: return SOX_EINVAL */
+
+    /* If file is a seekable file and this handler supports seeking,
+     * then invoke handler's function.
+     */
+    if (ft->seekable && ft->handler.seek)
+      return (*ft->handler.seek)(ft, offset);
+    return SOX_EOF; /* FIXME: return SOX_EBADF */
+}
+
+sox_bool sox_is_playlist(char const * filename)
+{
+  return strcaseends(filename, ".m3u") || strcaseends(filename, ".pls");
+}
+
+int sox_parse_playlist(sox_playlist_callback_t callback, void * p, char const * const listname)
+{
+  sox_bool const is_pls = strcaseends(listname, ".pls");
+  int const comment_char = "#;"[is_pls];
+  size_t text_length = 100;
+  char * text = xmalloc(text_length + 1);
+  char * dirname = xstrdup(listname);
+  char * slash_pos = LAST_SLASH(dirname);
+  FILE * file = xfopen(listname, "r");
+  char * filename;
+  int c, result = SOX_SUCCESS;
+
+  if (!slash_pos)
+    *dirname = '\0';
+  else
+    *slash_pos = '\0';
+
+  if (file == NULL) {
+    sox_fail("Can't open playlist file `%s': %s", listname, strerror(errno));
+    result = SOX_EOF;
+  }
+  else do {
+    size_t i = 0;
+    size_t begin = 0, end = 0;
+
+    while (isspace(c = getc(file)));
+    if (c == EOF)
+      break;
+    while (c != EOF && !strchr("\r\n", c) && c != comment_char) {
+      if (i == text_length)
+        text = xrealloc(text, (text_length <<= 1) + 1);
+      text[i++] = c;
+      if (!strchr(" \t\f", c))
+        end = i;
+      c = getc(file);
+    }
+    if (ferror(file))
+      break;
+    if (c == comment_char) {
+      do c = getc(file);
+      while (c != EOF && !strchr("\r\n", c));
+      if (ferror(file))
+        break;
+    }
+    text[end] = '\0';
+    if (is_pls) {
+      char dummy;
+      if (!strncasecmp(text, "file", 4) && sscanf(text + 4, "%*u=%c", &dummy) == 1)
+        begin = strchr(text + 5, '=') - text + 1;
+      else end = 0;
+    }
+    if (begin != end) {
+      char const * id = text + begin;
+
+      if (!dirname[0] || is_uri(id) || IS_ABSOLUTE(id))
+        filename = xstrdup(id);
+      else {
+        filename = xmalloc(strlen(dirname) + strlen(id) + 2); 
+        sprintf(filename, "%s/%s", dirname, id); 
+      }
+      if (sox_is_playlist(filename))
+        sox_parse_playlist(callback, p, filename);
+      else if (callback(p, filename))
+        c = EOF;
+      free(filename);
+    }
+  } while (c != EOF);
+
+  if (ferror(file)) {
+    sox_fail("Error reading playlist file `%s': %s", listname, strerror(errno));
+    result = SOX_EOF;
+  }
+  if (file) fclose(file);
+  free(text);
+  free(dirname);
+  return result;
+}
+
+#ifdef HAVE_LIBLTDL /* Plugin format handlers */
+
+#include <ltdl.h>
+#define MAX_FORMATS 256 /* FIXME: Use a vector, not a fixed-size array */
+#define MAX_NAME_LEN 1024 /* FIXME: Use vasprintf */
+
+static sox_bool plugins_initted = sox_false;
+
+sox_format_tab_t sox_format_fns[MAX_FORMATS + 1];
+
+static unsigned nformats = 0;
+
+static int init_format(const char *file, lt_ptr data)
+{
+  lt_dlhandle lth = lt_dlopenext(file);
+  const char *end = file + strlen(file);
+  const char prefix[] = "sox_fmt_";
+  char fnname[MAX_NAME_LEN];
+  char *start = strstr(file, prefix);
+
+  (void)data;
+  if (start && (start += sizeof(prefix) - 1) < end) {
+    int ret = snprintf(fnname, MAX_NAME_LEN, "sox_%.*s_format_fn", end - start, start);
+    if (ret > 0 && ret < MAX_NAME_LEN) {
+      union {sox_format_fn_t fn; lt_ptr ptr;} ltptr;
+      ltptr.ptr = lt_dlsym(lth, fnname);
+      sox_debug("opening format plugin `%s': library %p, entry point %p\n", fnname, (void *)lth, ltptr.ptr);
+      if (nformats < MAX_FORMATS && ltptr.fn && (ltptr.fn()->sox_lib_version_code & ~255) == (SOX_LIB_VERSION_CODE & ~255))
+        sox_format_fns[nformats++].fn = ltptr.fn;
+    }
+  }
+  return SOX_SUCCESS;
+}
+
+int sox_format_init(void) /* Find & load format handlers.  */
+{
+  int ret;
+
+  if ((ret = lt_dlinit()) != 0) {
+    sox_fail("lt_dlinit failed with %d error(s): %s", ret, lt_dlerror());
+    return SOX_EOF;
+  }
+  plugins_initted = sox_true;
+
+  lt_dlforeachfile(PKGLIBDIR, init_format, NULL);
+  return SOX_SUCCESS;
+}
+
+void sox_format_quit(void) /* Cleanup things.  */
+{
+  int ret;
+  if (plugins_initted && (ret = lt_dlexit()) != 0)
+    sox_fail("lt_dlexit failed with %d error(s): %s", ret, lt_dlerror());
+}
+
+#else /* Static format handlers */
+
+#define FORMAT(f) extern sox_format_handler_t const * sox_##f##_format_fn(void);
+#include "formats.h"
+#undef FORMAT
+
+sox_format_tab_t sox_format_fns[] = {
+  #define FORMAT(f) {NULL, sox_##f##_format_fn},
   #include "formats.h"
   #undef FORMAT
-  sox_format_tab_t sox_format_fns[] = {
-  #define FORMAT(f) {0, sox_##f##_format_fn},
-  #include "formats.h"
-  #undef FORMAT
-  };
-  unsigned sox_formats = array_length(sox_format_fns);
+  {NULL, NULL}
+};
+
+int sox_format_init(void) {return SOX_SUCCESS;}
+void sox_format_quit(void) {}
+
 #endif 
 
-/* Find a named format in the formats library */
+/* Find a named format in the formats library.
+ *
+ * (c) 2005-8 Chris Bagwell and SoX contributors.
+ * Copyright 1991 Lance Norskog And Sundry Contributors.
+ *
+ * This source code is freely redistributable and may be used for any
+ * purpose.  This copyright notice must be maintained.
+ *
+ * Lance Norskog, Sundry Contributors, Chris Bagwell and SoX contributors
+ * are not responsible for the consequences of using this software.
+ */
 sox_format_handler_t const * sox_find_format(char const * name, sox_bool no_dev)
 {
   sox_size_t f, n;
 
-  if (name) for (f = 0; f < sox_formats; ++f) {
-    sox_format_handler_t const * fh = sox_format_fns[f].fn();
+  if (name) for (f = 0; sox_format_fns[f].fn; ++f) {
+    sox_format_handler_t const * handler = sox_format_fns[f].fn();
 
-    if (!(no_dev && (fh->flags & SOX_FILE_DEVICE)))
-      for (n = 0; fh->names[n]; ++n)
-        if (!strcasecmp(fh->names[n], name))
-          return fh;                 /* Found it. */
+    if (!(no_dev && (handler->flags & SOX_FILE_DEVICE)))
+      for (n = 0; handler->names[n]; ++n)
+        if (!strcasecmp(handler->names[n], name))
+          return handler;                 /* Found it. */
   }
   return NULL;
 }
--- /dev/null
+++ b/src/formats_i.c
@@ -1,0 +1,469 @@
+/*
+ * Implements a libSoX internal interface for use in implementing file formats.
+ * All public functions & data are prefixed with lsx_ .
+ *
+ * (c) 2005-8 Chris Bagwell and SoX contributors
+ *
+ * This library is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This library 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 Lesser
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this library.  If not, write to the Free Software Foundation,
+ * Fifth Floor, 51 Franklin Street, Boston, MA 02111-1301, USA.
+ */
+
+#include "sox_i.h"
+#include <string.h>
+#include <sys/stat.h>
+#include <stdarg.h>
+
+void lsx_fail_errno(sox_format_t * ft, int sox_errno, const char *fmt, ...)
+{
+  va_list args;
+
+  ft->sox_errno = sox_errno;
+
+  va_start(args, fmt);
+#ifdef HAVE_VSNPRINTF
+  vsnprintf(ft->sox_errstr, sizeof(ft->sox_errstr), fmt, args);
+#else
+  vsprintf(ft->sox_errstr, fmt, args);
+#endif
+  va_end(args);
+  ft->sox_errstr[255] = '\0';
+}
+
+void lsx_set_signal_defaults(sox_signalinfo_t * signal)
+{
+  if (!signal->rate     ) signal->rate      = SOX_DEFAULT_RATE;
+  if (!signal->precision) signal->precision = SOX_DEFAULT_PRECISION;
+  if (!signal->channels ) signal->channels  = SOX_DEFAULT_CHANNELS;
+}
+
+int lsx_check_read_params(sox_format_t * ft, unsigned channels,
+    sox_rate_t rate, sox_encoding_t encoding, unsigned bits_per_sample, off_t length)
+{
+  ft->length = length;
+
+  if (ft->seekable)
+    ft->data_start = lsx_tell(ft);
+
+  if (channels && ft->signal.channels && ft->signal.channels != channels)
+    sox_warn("`%s': overriding number of channels", ft->filename);
+  else ft->signal.channels = channels;
+
+  if (rate && ft->signal.rate && ft->signal.rate != rate)
+    sox_warn("`%s': overriding sample rate", ft->filename);
+  else ft->signal.rate = rate;
+
+  if (encoding && ft->encoding.encoding && ft->encoding.encoding != encoding)
+    sox_warn("`%s': overriding encoding type", ft->filename);
+  else ft->encoding.encoding = encoding;
+
+  if (bits_per_sample && ft->encoding.bits_per_sample && ft->encoding.bits_per_sample != bits_per_sample)
+    sox_warn("`%s': overriding encoding size", ft->filename);
+  ft->encoding.bits_per_sample = bits_per_sample;
+
+  if (ft->encoding.bits_per_sample && lsx_filelength(ft)) {
+    off_t calculated_length = div_bits(lsx_filelength(ft) - ft->data_start, ft->encoding.bits_per_sample);
+    if (!ft->length)
+      ft->length = calculated_length;
+    else if (length != calculated_length)
+      sox_warn("`%s': file header gives the total number of samples as %u but file length indicates the number is in fact %u", ft->filename, (unsigned)length, (unsigned)calculated_length); /* FIXME: casts */
+  }
+
+  if (sox_precision(ft->encoding.encoding, ft->encoding.bits_per_sample))
+    return SOX_SUCCESS;
+  lsx_fail_errno(ft, EINVAL, "invalid format for this file type");
+  return SOX_EOF;
+}
+
+sox_sample_t lsx_sample_max(sox_encodinginfo_t const * encoding)
+{
+  unsigned precision = encoding->encoding == SOX_ENCODING_FLOAT?
+    SOX_SAMPLE_PRECISION : sox_precision(encoding->encoding, encoding->bits_per_sample);
+  unsigned shift = SOX_SAMPLE_PRECISION - min(precision, SOX_SAMPLE_PRECISION);
+  return (SOX_SAMPLE_MAX >> shift) << shift;
+}
+
+/* Read in a buffer of data of length len bytes.
+ * Returns number of bytes read.
+ */
+size_t lsx_readbuf(sox_format_t * ft, void *buf, sox_size_t len)
+{
+  size_t ret = fread(buf, 1, len, ft->fp);
+  if (ret != len && ferror(ft->fp))
+    lsx_fail_errno(ft, errno, "lsx_readbuf");
+  ft->tell += ret;
+  return ret;
+}
+
+/* Skip input without seeking. */
+int lsx_skipbytes(sox_format_t * ft, sox_size_t n)
+{
+  unsigned char trash;
+
+  while (n--)
+    if (lsx_readb(ft, &trash) == SOX_EOF)
+      return (SOX_EOF);
+  
+  return (SOX_SUCCESS);
+}
+
+/* Pad output. */
+int lsx_padbytes(sox_format_t * ft, sox_size_t n)
+{
+  while (n--)
+    if (lsx_writeb(ft, '\0') == SOX_EOF)
+      return (SOX_EOF);
+
+  return (SOX_SUCCESS);
+}
+
+/* Write a buffer of data of length bytes.
+ * Returns number of bytes written.
+ */
+size_t lsx_writebuf(sox_format_t * ft, void const * buf, sox_size_t len)
+{
+  size_t ret = fwrite(buf, 1, len, ft->fp);
+  if (ret != len) {
+    lsx_fail_errno(ft, errno, "error writing output file");
+    clearerr(ft->fp); /* Allows us to seek back to write header */
+  }
+  ft->tell += ret;
+  return ret;
+}
+
+sox_size_t lsx_filelength(sox_format_t * ft)
+{
+  struct stat st;
+  int ret = fstat(fileno(ft->fp), &st);
+
+  return ret? 0 : (sox_size_t)st.st_size;
+}
+
+int lsx_flush(sox_format_t * ft)
+{
+  return fflush(ft->fp);
+}
+
+sox_ssize_t lsx_tell(sox_format_t * ft)
+{
+  return ft->seekable? (sox_ssize_t)ftello(ft->fp) : ft->tell;
+}
+
+int lsx_eof(sox_format_t * ft)
+{
+  return feof(ft->fp);
+}
+
+int lsx_error(sox_format_t * ft)
+{
+  return ferror(ft->fp);
+}
+
+void lsx_rewind(sox_format_t * ft)
+{
+  rewind(ft->fp);
+}
+
+void lsx_clearerr(sox_format_t * ft)
+{
+  clearerr(ft->fp);
+}
+
+/* Implements traditional fseek() behavior.  Meant to abstract out
+ * file operations so that they could one day also work on memory
+ * buffers.
+ *
+ * N.B. Can only seek forwards on non-seekable streams!
+ */
+int lsx_seeki(sox_format_t * ft, sox_ssize_t offset, int whence)
+{
+    if (ft->seekable == 0) {
+        /* If a stream peel off chars else EPERM */
+        if (whence == SEEK_CUR) {
+            while (offset > 0 && !feof(ft->fp)) {
+                getc(ft->fp);
+                offset--;
+                ++ft->tell;
+            }
+            if (offset)
+                lsx_fail_errno(ft,SOX_EOF, "offset past EOF");
+            else
+                ft->sox_errno = SOX_SUCCESS;
+        } else
+            lsx_fail_errno(ft,SOX_EPERM, "file not seekable");
+    } else {
+        if (fseeko(ft->fp, (off_t)offset, whence) == -1)
+            lsx_fail_errno(ft,errno,strerror(errno));
+        else
+            ft->sox_errno = SOX_SUCCESS;
+    }
+    return ft->sox_errno;
+}
+
+int lsx_offset_seek(sox_format_t * ft, off_t byte_offset, sox_size_t to_sample)
+{
+  double wide_sample = to_sample - (to_sample % ft->signal.channels);
+  double to_d = wide_sample * ft->encoding.bits_per_sample / 8;
+  off_t to = to_d;
+  return (to != to_d)? SOX_EOF : lsx_seeki(ft, byte_offset + to, SEEK_SET);
+}
+
+/* Read and write known datatypes in "machine format".  Swap if indicated.
+ * They all return SOX_EOF on error and SOX_SUCCESS on success.
+ */
+/* Read n-char string (and possibly null-terminating).
+ * Stop reading and null-terminate string if either a 0 or \n is reached.
+ */
+int lsx_reads(sox_format_t * ft, char *c, sox_size_t len)
+{
+    char *sc;
+    char in;
+
+    sc = c;
+    do
+    {
+        if (lsx_readbuf(ft, &in, 1) != 1)
+        {
+            *sc = 0;
+            return (SOX_EOF);
+        }
+        if (in == 0 || in == '\n')
+            break;
+
+        *sc = in;
+        sc++;
+    } while (sc - c < (ptrdiff_t)len);
+    *sc = 0;
+    return(SOX_SUCCESS);
+}
+
+/* Write null-terminated string (without \0). */
+int lsx_writes(sox_format_t * ft, char const * c)
+{
+        if (lsx_writebuf(ft, c, strlen(c)) != strlen(c))
+                return(SOX_EOF);
+        return(SOX_SUCCESS);
+}
+
+/* return swapped 32-bit float */
+static void lsx_swapf(float * f)
+{
+    union {
+        uint32_t dw;
+        float f;
+    } u;
+
+    u.f= *f;
+    u.dw= (u.dw>>24) | ((u.dw>>8)&0xff00) | ((u.dw<<8)&0xff0000) | (u.dw<<24);
+    *f = u.f;
+}
+
+/* generic swap routine. Swap l and place in to f (datatype length = n) */
+static void swap(char *l, char *f, int n)
+{
+    register int i;
+
+    for (i= 0; i< n; i++)
+        f[i]= l[n-i-1];
+}
+
+static double lsx_swapdf(double df)
+{
+    double sdf;
+    swap((char *)&df, (char *)&sdf, sizeof(double));
+    return (sdf);
+}
+
+/* Lookup table to reverse the bit order of a byte. ie MSB become LSB */
+static uint8_t const cswap[256] = {
+  0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0, 0x10, 0x90, 0x50, 0xD0,
+  0x30, 0xB0, 0x70, 0xF0, 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8, 
+  0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8, 0x04, 0x84, 0x44, 0xC4, 
+  0x24, 0xA4, 0x64, 0xE4, 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
+  0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC, 0x1C, 0x9C, 0x5C, 0xDC,
+  0x3C, 0xBC, 0x7C, 0xFC, 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2, 
+  0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2, 0x0A, 0x8A, 0x4A, 0xCA, 
+  0x2A, 0xAA, 0x6A, 0xEA, 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
+  0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6, 0x16, 0x96, 0x56, 0xD6,
+  0x36, 0xB6, 0x76, 0xF6, 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE, 
+  0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE, 0x01, 0x81, 0x41, 0xC1, 
+  0x21, 0xA1, 0x61, 0xE1, 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
+  0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9, 0x19, 0x99, 0x59, 0xD9,
+  0x39, 0xB9, 0x79, 0xF9, 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5, 
+  0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5, 0x0D, 0x8D, 0x4D, 0xCD, 
+  0x2D, 0xAD, 0x6D, 0xED, 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
+  0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3, 0x13, 0x93, 0x53, 0xD3,
+  0x33, 0xB3, 0x73, 0xF3, 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB, 
+  0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB, 0x07, 0x87, 0x47, 0xC7, 
+  0x27, 0xA7, 0x67, 0xE7, 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
+  0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF, 0x1F, 0x9F, 0x5F, 0xDF,
+  0x3F, 0xBF, 0x7F, 0xFF
+};
+
+/* Utilities to byte-swap values, use libc optimized macros if possible  */
+#define TWIDDLE_BYTE(ub, type) \
+  do { \
+    if (ft->encoding.reverse_bits) \
+      ub = cswap[ub]; \
+    if (ft->encoding.reverse_nibbles) \
+      ub = ((ub & 15) << 4) | (ub >> 4); \
+  } while (0);
+
+#define TWIDDLE_WORD(uw, type) \
+  if (ft->encoding.reverse_bytes) \
+    uw = lsx_swap ## type(uw);
+
+#define TWIDDLE_FLOAT(f, type) \
+  if (ft->encoding.reverse_bytes) \
+    lsx_swapf(&f);
+
+/* N.B. This macro doesn't work for unaligned types (e.g. 3-byte
+   types). */
+#define READ_FUNC(type, size, ctype, twiddle) \
+  sox_size_t lsx_read_ ## type ## _buf( \
+      sox_format_t * ft, ctype *buf, sox_size_t len) \
+  { \
+    sox_size_t n, nread; \
+    nread = lsx_readbuf(ft, buf, len * size) / size; \
+    for (n = 0; n < nread; n++) \
+      twiddle(buf[n], type); \
+    return nread; \
+  }
+
+/* Unpack a 3-byte value from a uint8_t * */
+#define sox_unpack3(p) (ft->encoding.reverse_bytes == MACHINE_IS_BIGENDIAN? \
+  ((p)[0] | ((p)[1] << 8) | ((p)[2] << 16)) : \
+  ((p)[2] | ((p)[1] << 8) | ((p)[0] << 16)))
+
+/* This (slower) macro works for unaligned types (e.g. 3-byte types)
+   that need to be unpacked. */
+#define READ_FUNC_UNPACK(type, size, ctype, twiddle) \
+  sox_size_t lsx_read_ ## type ## _buf( \
+      sox_format_t * ft, ctype *buf, sox_size_t len) \
+  { \
+    sox_size_t n, nread; \
+    uint8_t *data = xmalloc(size * len); \
+    nread = lsx_readbuf(ft, data, len * size) / size; \
+    for (n = 0; n < nread; n++) \
+      buf[n] = sox_unpack ## size(data + n * size); \
+    free(data); \
+    return n; \
+  }
+
+READ_FUNC(b, 1, uint8_t, TWIDDLE_BYTE)
+READ_FUNC(w, 2, uint16_t, TWIDDLE_WORD)
+READ_FUNC_UNPACK(3, 3, uint24_t, TWIDDLE_WORD)
+READ_FUNC(dw, 4, uint32_t, TWIDDLE_WORD)
+READ_FUNC(f, sizeof(float), float, TWIDDLE_FLOAT)
+READ_FUNC(df, sizeof(double), double, TWIDDLE_WORD)
+
+#define READ1_FUNC(type, ctype) \
+int lsx_read ## type(sox_format_t * ft, ctype * datum) { \
+  if (lsx_read_ ## type ## _buf(ft, datum, 1) == 1) \
+    return SOX_SUCCESS; \
+  if (!lsx_error(ft)) \
+    lsx_fail_errno(ft, errno, premature_eof); \
+  return SOX_EOF; \
+}
+
+static char const premature_eof[] = "premature EOF";
+
+READ1_FUNC(b,  uint8_t)
+READ1_FUNC(w,  uint16_t)
+READ1_FUNC(3,  uint24_t)
+READ1_FUNC(dw, uint32_t)
+READ1_FUNC(f,  float)
+READ1_FUNC(df, double)
+
+int lsx_readchars(sox_format_t * ft, char * chars, sox_size_t len)
+{
+  size_t ret = lsx_readbuf(ft, chars, len);
+  if (ret == len)
+    return SOX_SUCCESS;
+  if (!lsx_error(ft))
+    lsx_fail_errno(ft, errno, premature_eof);
+  return SOX_EOF;
+}
+
+/* N.B. This macro doesn't work for unaligned types (e.g. 3-byte
+   types). */
+#define WRITE_FUNC(type, size, ctype, twiddle) \
+  sox_size_t lsx_write_ ## type ## _buf( \
+      sox_format_t * ft, ctype *buf, sox_size_t len) \
+  { \
+    sox_size_t n, nwritten; \
+    for (n = 0; n < len; n++) \
+      twiddle(buf[n], type); \
+    nwritten = lsx_writebuf(ft, buf, len * size); \
+    return nwritten / size; \
+  }
+
+/* Pack a 3-byte value to a uint8_t * */
+#define sox_pack3(p, v) do {if (ft->encoding.reverse_bytes == MACHINE_IS_BIGENDIAN)\
+{(p)[0] = v & 0xff; (p)[1] = (v >> 8) & 0xff; (p)[2] = (v >> 16) & 0xff;} else \
+{(p)[2] = v & 0xff; (p)[1] = (v >> 8) & 0xff; (p)[0] = (v >> 16) & 0xff;} \
+} while (0)
+
+/* This (slower) macro works for unaligned types (e.g. 3-byte types)
+   that need to be packed. */
+#define WRITE_FUNC_PACK(type, size, ctype, twiddle) \
+  sox_size_t lsx_write_ ## type ## _buf( \
+      sox_format_t * ft, ctype *buf, sox_size_t len) \
+  { \
+    sox_size_t n, nwritten; \
+    uint8_t *data = xmalloc(size * len); \
+    for (n = 0; n < len; n++) \
+      sox_pack ## size(data + n * size, buf[n]); \
+    nwritten = lsx_writebuf(ft, data, len * size); \
+    free(data); \
+    return nwritten / size; \
+  }
+
+WRITE_FUNC(b, 1, uint8_t, TWIDDLE_BYTE)
+WRITE_FUNC(w, 2, uint16_t, TWIDDLE_WORD)
+WRITE_FUNC_PACK(3, 3, uint24_t, TWIDDLE_WORD)
+WRITE_FUNC(dw, 4, uint32_t, TWIDDLE_WORD)
+WRITE_FUNC(f, sizeof(float), float, TWIDDLE_FLOAT)
+WRITE_FUNC(df, sizeof(double), double, TWIDDLE_WORD)
+
+#define WRITE1U_FUNC(type, ctype) \
+  int lsx_write ## type(sox_format_t * ft, unsigned d) \
+  { ctype datum = (ctype)d; \
+    return lsx_write_ ## type ## _buf(ft, &datum, 1) == 1 ? SOX_SUCCESS : SOX_EOF; \
+  }
+
+#define WRITE1S_FUNC(type, ctype) \
+  int lsx_writes ## type(sox_format_t * ft, signed d) \
+  { ctype datum = (ctype)d; \
+    return lsx_write_ ## type ## _buf(ft, &datum, 1) == 1 ? SOX_SUCCESS : SOX_EOF; \
+  }
+
+#define WRITE1_FUNC(type, ctype) \
+  int lsx_write ## type(sox_format_t * ft, ctype datum) \
+  { \
+    return lsx_write_ ## type ## _buf(ft, &datum, 1) == 1 ? SOX_SUCCESS : SOX_EOF; \
+  }
+
+WRITE1U_FUNC(b, uint8_t)
+WRITE1U_FUNC(w, uint16_t)
+WRITE1U_FUNC(3, uint24_t)
+WRITE1U_FUNC(dw, uint32_t)
+WRITE1S_FUNC(b, uint8_t)
+WRITE1S_FUNC(w, uint16_t)
+WRITE1_FUNC(df, double)
+
+int lsx_writef(sox_format_t * ft, double datum)
+{
+  float f = datum;
+  return lsx_write_f_buf(ft, &f, 1) == 1 ? SOX_SUCCESS : SOX_EOF;
+}
--- a/src/gsm.c
+++ b/src/gsm.c
@@ -68,7 +68,7 @@
         p->channels = ft->signal.channels;
         if (p->channels > MAXCHANS || p->channels <= 0)
         {
-                sox_fail_errno(ft,SOX_EFMT,"gsm: channels(%d) must be in 1-16", ft->signal.channels);
+                lsx_fail_errno(ft,SOX_EFMT,"gsm: channels(%d) must be in 1-16", ft->signal.channels);
                 return(SOX_EOF);
         }
 
@@ -76,7 +76,7 @@
                 p->handle[ch] = gsm_create();
                 if (!p->handle[ch])
                 {
-                        sox_fail_errno(ft,errno,"unable to create GSM stream");
+                        lsx_fail_errno(ft,errno,"unable to create GSM stream");
                         return (SOX_EOF);
                 }
         }
@@ -121,7 +121,7 @@
 
                 if (done>=samp) break;
 
-                r = sox_readbuf(ft, p->frames, p->channels * FRAMESIZE);
+                r = lsx_readbuf(ft, p->frames, p->channels * FRAMESIZE);
                 if (r != p->channels * FRAMESIZE)
                   break;
 
@@ -133,7 +133,7 @@
                         gbuff = p->sampleTop;
                         if (gsm_decode(p->handle[ch], p->frames + ch*FRAMESIZE, gbuff) < 0)
                         {
-                                sox_fail_errno(ft,errno,"error during GSM decode");
+                                lsx_fail_errno(ft,errno,"error during GSM decode");
                                 return (0);
                         }
                         
@@ -171,10 +171,10 @@
                         gsp += chans;
                 }
                 gsm_encode(p->handle[ch], gbuff, p->frames);
-                r = sox_writebuf(ft, p->frames, FRAMESIZE);
+                r = lsx_writebuf(ft, p->frames, FRAMESIZE);
                 if (r != FRAMESIZE)
                 {
-                        sox_fail_errno(ft,errno,"write error");
+                        lsx_fail_errno(ft,errno,"write error");
                         return(SOX_EOF);
                 }
         }
--- a/src/hcom.c
+++ b/src/hcom.c
@@ -27,6 +27,22 @@
 #include <stdlib.h>
 #include <errno.h>
 
+/* FIXME: eliminate these 2 functions */
+
+static void put32_be(unsigned char **p, int32_t val)
+{
+  *(*p)++ = (val >> 24) & 0xff;
+  *(*p)++ = (val >> 16) & 0xff;
+  *(*p)++ = (val >> 8) & 0xff;
+  *(*p)++ = val & 0xff;
+}
+
+static void put16_be(unsigned char **p, int val)
+{
+  *(*p)++ = (val >> 8) & 0xff;
+  *(*p)++ = val & 0xff;
+}
+
 /* Dictionary entry for Huffman (de)compression */
 typedef struct {
         long frequ;
@@ -66,54 +82,54 @@
 
 
         /* Skip first 65 bytes of header */
-        rc = sox_skipbytes(ft, 65);
+        rc = lsx_skipbytes(ft, 65);
         if (rc)
             return rc;
 
         /* Check the file type (bytes 65-68) */
-        if (sox_reads(ft, buf, 4) == SOX_EOF || strncmp(buf, "FSSD", 4) != 0)
+        if (lsx_reads(ft, buf, 4) == SOX_EOF || strncmp(buf, "FSSD", 4) != 0)
         {
-                sox_fail_errno(ft,SOX_EHDR,"Mac header type is not FSSD");
+                lsx_fail_errno(ft,SOX_EHDR,"Mac header type is not FSSD");
                 return (SOX_EOF);
         }
 
         /* Skip to byte 83 */
-        rc = sox_skipbytes(ft, 83-69);
+        rc = lsx_skipbytes(ft, 83-69);
         if (rc)
             return rc;
 
         /* Get essential numbers from the header */
-        sox_readdw(ft, &datasize); /* bytes 83-86 */
-        sox_readdw(ft, &rsrcsize); /* bytes 87-90 */
+        lsx_readdw(ft, &datasize); /* bytes 83-86 */
+        lsx_readdw(ft, &rsrcsize); /* bytes 87-90 */
 
         /* Skip the rest of the header (total 128 bytes) */
-        rc = sox_skipbytes(ft, 128-91);
+        rc = lsx_skipbytes(ft, 128-91);
         if (rc != 0)
             return rc;
 
         /* The data fork must contain a "HCOM" header */
-        if (sox_reads(ft, buf, 4) == SOX_EOF || strncmp(buf, "HCOM", 4) != 0)
+        if (lsx_reads(ft, buf, 4) == SOX_EOF || strncmp(buf, "HCOM", 4) != 0)
         {
-                sox_fail_errno(ft,SOX_EHDR,"Mac data fork is not HCOM");
+                lsx_fail_errno(ft,SOX_EHDR,"Mac data fork is not HCOM");
                 return (SOX_EOF);
         }
 
         /* Then follow various parameters */
-        sox_readdw(ft, &huffcount);
-        sox_readdw(ft, &checksum);
-        sox_readdw(ft, &compresstype);
+        lsx_readdw(ft, &huffcount);
+        lsx_readdw(ft, &checksum);
+        lsx_readdw(ft, &compresstype);
         if (compresstype > 1)
         {
-                sox_fail_errno(ft,SOX_EHDR,"Bad compression type in HCOM header");
+                lsx_fail_errno(ft,SOX_EHDR,"Bad compression type in HCOM header");
                 return (SOX_EOF);
         }
-        sox_readdw(ft, &divisor);
+        lsx_readdw(ft, &divisor);
         if (divisor == 0 || divisor > 4)
         {
-                sox_fail_errno(ft,SOX_EHDR,"Bad sampling rate divisor in HCOM header");
+                lsx_fail_errno(ft,SOX_EHDR,"Bad sampling rate divisor in HCOM header");
                 return (SOX_EOF);
         }
-        sox_readw(ft, &dictsize);
+        lsx_readw(ft, &dictsize);
 
         /* Translate to sox parameters */
         ft->encoding.encoding = SOX_ENCODING_HCOM;
@@ -126,13 +142,13 @@
 
         /* Read dictionary */
         for(i = 0; i < dictsize; i++) {
-                sox_readw(ft, (unsigned short *)&(p->dictionary[i].dict_leftson));
-                sox_readw(ft, (unsigned short *)&(p->dictionary[i].dict_rightson));
+                lsx_readw(ft, (unsigned short *)&(p->dictionary[i].dict_leftson));
+                lsx_readw(ft, (unsigned short *)&(p->dictionary[i].dict_rightson));
                 sox_debug("%d %d",
                        p->dictionary[i].dict_leftson,
                        p->dictionary[i].dict_rightson);
         }
-        rc = sox_skipbytes(ft, 1); /* skip pad byte */
+        rc = lsx_skipbytes(ft, 1); /* skip pad byte */
         if (rc)
             return rc;
 
@@ -159,7 +175,7 @@
                 /* The first byte is special */
                 if (p->huffcount == 0)
                         return 0; /* Don't know if this can happen... */
-                if (sox_readb(ft, &sample_rate) == SOX_EOF)
+                if (lsx_readb(ft, &sample_rate) == SOX_EOF)
                 {
                         return (0);
                 }
@@ -175,10 +191,10 @@
 
         while (p->huffcount > 0) {
                 if(p->nrbits == 0) {
-                        sox_readdw(ft, &(p->current));
-                        if (sox_eof(ft))
+                        lsx_readdw(ft, &(p->current));
+                        if (lsx_eof(ft))
                         {
-                                sox_fail_errno(ft,SOX_EOF,"unexpected EOF in HCOM data");
+                                lsx_fail_errno(ft,SOX_EOF,"unexpected EOF in HCOM data");
                                 return (0);
                         }
                         p->cksum += p->current;
@@ -218,12 +234,12 @@
 
         if (p->huffcount != 0)
         {
-                sox_fail_errno(ft,SOX_EFMT,"not all HCOM data read");
+                lsx_fail_errno(ft,SOX_EFMT,"not all HCOM data read");
                 return (SOX_EOF);
         }
         if(p->cksum != p->checksum)
         {
-                sox_fail_errno(ft,SOX_EFMT,"checksum error in HCOM data");
+                lsx_fail_errno(ft,SOX_EFMT,"checksum error in HCOM data");
                 return (SOX_EOF);
         }
         free((char *)p->dictionary);
@@ -423,19 +439,19 @@
   free((char *)p->data);
 
   /* Write the header */
-  sox_writebuf(ft, (void *)"\000\001A", 3); /* Dummy file name "A" */
-  sox_padbytes(ft, 65-3);
-  sox_writes(ft, "FSSD");
-  sox_padbytes(ft, 83-69);
-  sox_writedw(ft, compressed_len); /* compressed_data size */
-  sox_writedw(ft, 0); /* rsrc size */
-  sox_padbytes(ft, 128 - 91);
-  if (sox_error(ft)) {
-    sox_fail_errno(ft, errno, "write error in HCOM header");
+  lsx_writebuf(ft, (void *)"\000\001A", 3); /* Dummy file name "A" */
+  lsx_padbytes(ft, 65-3);
+  lsx_writes(ft, "FSSD");
+  lsx_padbytes(ft, 83-69);
+  lsx_writedw(ft, compressed_len); /* compressed_data size */
+  lsx_writedw(ft, 0); /* rsrc size */
+  lsx_padbytes(ft, 128 - 91);
+  if (lsx_error(ft)) {
+    lsx_fail_errno(ft, errno, "write error in HCOM header");
     rc = SOX_EOF;
-  } else if (sox_writebuf(ft, compressed_data, compressed_len) != compressed_len) {
+  } else if (lsx_writebuf(ft, compressed_data, compressed_len) != compressed_len) {
     /* Write the compressed_data fork */
-    sox_fail_errno(ft, errno, "can't write compressed HCOM data");
+    lsx_fail_errno(ft, errno, "can't write compressed HCOM data");
     rc = SOX_EOF;
   }
   free((char *)compressed_data);
@@ -442,7 +458,7 @@
 
   if (rc == SOX_SUCCESS)
     /* Pad the compressed_data fork to a multiple of 128 bytes */
-    sox_padbytes(ft, 128u - (compressed_len % 128));
+    lsx_padbytes(ft, 128u - (compressed_len % 128));
 
   return rc;
 }
--- a/src/htk.c
+++ b/src/htk.c
@@ -35,16 +35,16 @@
   uint32_t period_100ns, num_samples;
   uint16_t bytes_per_sample, parmKind;
 
-  if (sox_readdw(ft, &num_samples     ) ||
-      sox_readdw(ft, &period_100ns    ) ||
-      sox_readw (ft, &bytes_per_sample) ||
-      sox_readw (ft, &parmKind        )) return SOX_EOF;
+  if (lsx_readdw(ft, &num_samples     ) ||
+      lsx_readdw(ft, &period_100ns    ) ||
+      lsx_readw (ft, &bytes_per_sample) ||
+      lsx_readw (ft, &parmKind        )) return SOX_EOF;
   if (parmKind != Waveform) {
     int n = min(parmKind & 077, Unknown);
-    sox_fail_errno(ft, SOX_EFMT, "unsupported HTK type `%s' (0%o)", str[n], parmKind);
+    lsx_fail_errno(ft, SOX_EFMT, "unsupported HTK type `%s' (0%o)", str[n], parmKind);
     return SOX_EOF;
   }
-  return sox_check_read_params(ft, 1, 1e7 / period_100ns,
+  return lsx_check_read_params(ft, 1, 1e7 / period_100ns,
       SOX_ENCODING_SIGN2, (unsigned)bytes_per_sample << 3, (off_t)num_samples);
 }
 
@@ -54,10 +54,10 @@
 
   if (!ft->olength && floor(period_100ns) != period_100ns)
     sox_warn("rounding sample period %f (x 100ns) to nearest integer", period_100ns);
-  return sox_writedw(ft, ft->olength? ft->olength:ft->length)
-      || sox_writedw(ft, (uint32_t)(period_100ns + .5))
-      || sox_writew(ft, ft->encoding.bits_per_sample >> 3)
-      || sox_writew(ft, Waveform) ? SOX_EOF : SOX_SUCCESS;
+  return lsx_writedw(ft, ft->olength? ft->olength:ft->length)
+      || lsx_writedw(ft, (uint32_t)(period_100ns + .5))
+      || lsx_writew(ft, ft->encoding.bits_per_sample >> 3)
+      || lsx_writew(ft, Waveform) ? SOX_EOF : SOX_SUCCESS;
 }
 
 SOX_FORMAT_HANDLER(htk)
@@ -68,9 +68,9 @@
     SOX_LIB_VERSION_CODE,
     "PCM format used for Hidden Markov Model speech processing",
     names, SOX_FILE_BIG_END | SOX_FILE_MONO | SOX_FILE_REWIND,
-    start_read, sox_rawread, NULL,
-    write_header, sox_rawwrite, NULL,
-    sox_rawseek, write_encodings, NULL
+    start_read, lsx_rawread, NULL,
+    write_header, lsx_rawwrite, NULL,
+    lsx_rawseek, write_encodings, NULL
   };
   return &handler;
 }
--- a/src/ima-fmt.c
+++ b/src/ima-fmt.c
@@ -29,7 +29,7 @@
     names, SOX_FILE_MONO,
     sox_ima_start, sox_vox_read, sox_vox_stopread,
     sox_ima_start, sox_vox_write, sox_vox_stopwrite,
-    sox_rawseek, write_encodings, NULL
+    lsx_rawseek, write_encodings, NULL
   };
   return &handler;
 }
--- a/src/key.c
+++ b/src/key.c
@@ -34,7 +34,7 @@
   int pos = (argc && !strcmp(*argv, "-q"))? 1 : 0;
 
   if (argc <= pos || sscanf(argv[pos], "%lf %c", &d, &dummy) != 1)
-    return sox_usage(effp);
+    return lsx_usage(effp);
 
   effp->global_info->speed *= d = pow(2., d / 1200);  /* cents --> factor */
   sprintf(arg, "%g", 1 / d);
--- a/src/ladspa.c
+++ b/src/ladspa.c
@@ -177,7 +177,7 @@
         sox_debug("default argument for port %lu is %f", i, l_st->control[i]);
       } else {
         if (!sscanf(argv[0], "%lf", &arg))
-          return sox_usage(effp);
+          return lsx_usage(effp);
         l_st->control[i] = (LADSPA_Data)arg;
         sox_debug("argument for port %lu is %f", i, l_st->control[i]);
         n--; argv++;
@@ -186,7 +186,7 @@
   }
 
   /* Stop if we have any unused arguments */
-  return n? sox_usage(effp) : SOX_SUCCESS;
+  return n? lsx_usage(effp) : SOX_SUCCESS;
 }
 
 /*
--- /dev/null
+++ b/src/libsox.c
@@ -1,0 +1,86 @@
+/*
+ * Implements the public API for libSoX general functions
+ * All public functions & data are prefixed with sox_ .
+ *
+ * (c) 2006-8 Chris Bagwell and SoX contributors
+ *
+ * This library is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This library 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 Lesser
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this library.  If not, write to the Free Software Foundation,
+ * Fifth Floor, 51 Franklin Street, Boston, MA 02111-1301, USA.
+ */
+
+#include "sox_i.h"
+#include <string.h>
+
+const char *sox_version(void)
+{
+  static char versionstr[20];
+
+  sprintf(versionstr, "%d.%d.%d",
+          (SOX_LIB_VERSION_CODE & 0xff0000) >> 16,
+          (SOX_LIB_VERSION_CODE & 0x00ff00) >> 8,
+          (SOX_LIB_VERSION_CODE & 0x0000ff));
+  return(versionstr);
+}
+
+/* Default routine to output messages; can be overridden */
+static void output_message(
+    unsigned level, const char *filename, const char *fmt, va_list ap)
+{
+  if (sox_globals.verbosity >= level) {
+    sox_output_message(stderr, filename, fmt, ap);
+    fprintf(stderr, "\n");
+  }
+}
+
+sox_globals_t sox_globals = {
+  2,
+  output_message,
+  sox_false,
+  8192,
+  NULL, NULL, NULL};
+
+void sox_output_message(FILE *file, const char *filename, const char *fmt, va_list ap)
+{
+  char const * slash_pos = LAST_SLASH(filename);
+  char const * base_name = slash_pos? slash_pos + 1 : filename;
+  char const * dot_pos   = strrchr(base_name, '.');
+  fprintf(file, "%.*s: ", dot_pos? dot_pos - base_name : -1, base_name);
+  vfprintf(file, fmt, ap);
+}
+
+#undef sox_fail
+#undef sox_warn
+#undef sox_report
+#undef sox_debug
+#undef sox_debug_more
+#undef sox_debug_most
+
+#define SOX_MESSAGE_FUNCTION(name,level) \
+void name(char const * fmt, ...) { \
+  va_list ap; \
+  va_start(ap, fmt); \
+  if (sox_globals.output_message_handler) \
+    (*sox_globals.output_message_handler)(level,sox_globals.subsystem,fmt,ap); \
+  va_end(ap); \
+}
+
+SOX_MESSAGE_FUNCTION(sox_fail  , 1)
+SOX_MESSAGE_FUNCTION(sox_warn  , 2)
+SOX_MESSAGE_FUNCTION(sox_report, 3)
+SOX_MESSAGE_FUNCTION(sox_debug , 4)
+SOX_MESSAGE_FUNCTION(sox_debug_more , 5)
+SOX_MESSAGE_FUNCTION(sox_debug_most , 6)
+
+#undef SOX_MESSAGE_FUNCTION
+
--- /dev/null
+++ b/src/libsox_i.c
@@ -1,0 +1,14 @@
+/*
+ * libSoX internal functions that apply to both formats and effects
+ *
+ * Copyright 1998-2008 Chris Bagwell and SoX Contributors
+ * Copyright 1991 Lance Norskog And Sundry Contributors
+ *
+ * This source code is freely redistributable and may be used for
+ * any purpose.  This copyright notice must be maintained.
+ * Lance Norskog And Sundry Contributors are not responsible for
+ * the consequences of using this software.
+ */
+
+#include "sox_i.h"
+#include <string.h>
--- a/src/lpc10.c
+++ b/src/lpc10.c
@@ -71,7 +71,7 @@
      * then mask won't yet be 0.  */
     mask >>= 1;
     if ((mask == 0) || (i == len-1)) {
-      sox_writeb(ft, data);
+      lsx_writeb(ft, data);
       data = 0;
       mask = 0x80;
     }
@@ -104,8 +104,8 @@
   /* Unpack the array bits into coded_frame. */
   for (i = 0; i < len; i++) {
     if (i % 8 == 0) {
-      sox_read_b_buf(ft, &c, 1);
-      if (sox_eof(ft)) {
+      lsx_read_b_buf(ft, &c, 1);
+      if (lsx_eof(ft)) {
         return (i);
       }
     }
@@ -127,7 +127,7 @@
     return SOX_EOF;
   }
   lpc->samples = LPC10_SAMPLES_PER_FRAME;
-  return sox_check_read_params(ft, 1, 8000., SOX_ENCODING_LPC10, 0, (off_t)0);
+  return lsx_check_read_params(ft, 1, 8000., SOX_ENCODING_LPC10, 0, (off_t)0);
 }
 
 static int startwrite(sox_format_t * ft) 
--- a/src/maud.c
+++ b/src/maud.c
@@ -48,28 +48,28 @@
         int rc;
 
         /* Needed for rawread() */
-        rc = sox_rawstartread(ft);
+        rc = lsx_rawstartread(ft);
         if (rc)
             return rc;
 
         /* read FORM chunk */
-        if (sox_reads(ft, buf, 4) == SOX_EOF || strncmp(buf, "FORM", 4) != 0)
+        if (lsx_reads(ft, buf, 4) == SOX_EOF || strncmp(buf, "FORM", 4) != 0)
         {
-                sox_fail_errno(ft,SOX_EHDR,"MAUD: header does not begin with magic word 'FORM'");
+                lsx_fail_errno(ft,SOX_EHDR,"MAUD: header does not begin with magic word 'FORM'");
                 return (SOX_EOF);
         }
         
-        sox_readdw(ft, &trash32); /* totalsize */
+        lsx_readdw(ft, &trash32); /* totalsize */
         
-        if (sox_reads(ft, buf, 4) == SOX_EOF || strncmp(buf, "MAUD", 4) != 0)
+        if (lsx_reads(ft, buf, 4) == SOX_EOF || strncmp(buf, "MAUD", 4) != 0)
         {
-                sox_fail_errno(ft,SOX_EHDR,"MAUD: 'FORM' chunk does not specify 'MAUD' as type");
+                lsx_fail_errno(ft,SOX_EHDR,"MAUD: 'FORM' chunk does not specify 'MAUD' as type");
                 return(SOX_EOF);
         }
         
         /* read chunks until 'BODY' (or end) */
         
-        while (sox_reads(ft, buf, 4) == SOX_SUCCESS && strncmp(buf,"MDAT",4) != 0) {
+        while (lsx_reads(ft, buf, 4) == SOX_SUCCESS && strncmp(buf,"MDAT",4) != 0) {
                 
                 /*
                 buf[4] = 0;
@@ -78,10 +78,10 @@
                 
                 if (strncmp(buf,"MHDR",4) == 0) {
                         
-                        sox_readdw(ft, &chunksize);
+                        lsx_readdw(ft, &chunksize);
                         if (chunksize != 8*4) 
                         {
-                            sox_fail_errno(ft,SOX_EHDR,"MAUD: MHDR chunk has bad size");
+                            lsx_fail_errno(ft,SOX_EHDR,"MAUD: MHDR chunk has bad size");
                             return(SOX_EOF);
                         }
                         
@@ -88,25 +88,25 @@
                         /* fseeko(ft->fp,12,SEEK_CUR); */
 
                         /* number of samples stored in MDAT */
-                        sox_readdw(ft, &(p->nsamples));
+                        lsx_readdw(ft, &(p->nsamples));
 
                         /* number of bits per sample as stored in MDAT */
-                        sox_readw(ft, &bitpersam);
+                        lsx_readw(ft, &bitpersam);
 
                         /* number of bits per sample after decompression */
-                        sox_readw(ft, (unsigned short *)&trash16);
+                        lsx_readw(ft, (unsigned short *)&trash16);
 
-                        sox_readdw(ft, &nom);         /* clock source frequency */
-                        sox_readw(ft, &denom);       /* clock devide           */
+                        lsx_readdw(ft, &nom);         /* clock source frequency */
+                        lsx_readw(ft, &denom);       /* clock devide           */
                         if (denom == 0) 
                         {
-                            sox_fail_errno(ft,SOX_EHDR,"MAUD: frequency denominator == 0, failed");
+                            lsx_fail_errno(ft,SOX_EHDR,"MAUD: frequency denominator == 0, failed");
                             return (SOX_EOF);
                         }
                         
                         ft->signal.rate = nom / denom;
                         
-                        sox_readw(ft, &chaninf); /* channel information */
+                        lsx_readw(ft, &chaninf); /* channel information */
                         switch (chaninf) {
                         case 0:
                                 ft->signal.channels = 1;
@@ -115,22 +115,22 @@
                                 ft->signal.channels = 2;
                                 break;
                         default:
-                                sox_fail_errno(ft,SOX_EFMT,"MAUD: unsupported number of channels in file");
+                                lsx_fail_errno(ft,SOX_EFMT,"MAUD: unsupported number of channels in file");
                                 return (SOX_EOF);
                         }
                         
-                        sox_readw(ft, &chaninf); /* number of channels (mono: 1, stereo: 2, ...) */
+                        lsx_readw(ft, &chaninf); /* number of channels (mono: 1, stereo: 2, ...) */
                         if (chaninf != ft->signal.channels) 
                         {
-                                sox_fail_errno(ft,SOX_EFMT,"MAUD: unsupported number of channels in file");
+                                lsx_fail_errno(ft,SOX_EFMT,"MAUD: unsupported number of channels in file");
                             return(SOX_EOF);
                         }
                         
-                        sox_readw(ft, &chaninf); /* compression type */
+                        lsx_readw(ft, &chaninf); /* compression type */
                         
-                        sox_readdw(ft, &trash32); /* rest of chunk, unused yet */
-                        sox_readdw(ft, &trash32);
-                        sox_readdw(ft, &trash32);
+                        lsx_readdw(ft, &trash32); /* rest of chunk, unused yet */
+                        lsx_readdw(ft, &trash32);
+                        lsx_readdw(ft, &trash32);
                         
                         if (bitpersam == 8 && chaninf == 0) {
                                 ft->encoding.bits_per_sample = 8;
@@ -150,7 +150,7 @@
                         }
                         else 
                         {
-                                sox_fail_errno(ft,SOX_EFMT,"MAUD: unsupported compression type detected");
+                                lsx_fail_errno(ft,SOX_EFMT,"MAUD: unsupported compression type detected");
                                 return(SOX_EOF);
                         }
                         
@@ -158,14 +158,14 @@
                 }
                 
                 if (strncmp(buf,"ANNO",4) == 0) {
-                        sox_readdw(ft, &chunksize);
+                        lsx_readdw(ft, &chunksize);
                         if (chunksize & 1)
                                 chunksize++;
                         chunk_buf = (char *) xmalloc(chunksize + 1);
-                        if (sox_readbuf(ft, chunk_buf, chunksize) 
+                        if (lsx_readbuf(ft, chunk_buf, chunksize) 
                             != chunksize)
                         {
-                                sox_fail_errno(ft,SOX_EOF,"MAUD: Unexpected EOF in ANNO header");
+                                lsx_fail_errno(ft,SOX_EOF,"MAUD: Unexpected EOF in ANNO header");
                                 return(SOX_EOF);
                         }
                         chunk_buf[chunksize] = '\0';
@@ -176,10 +176,10 @@
                 }
                 
                 /* some other kind of chunk */
-                sox_readdw(ft, &chunksize);
+                lsx_readdw(ft, &chunksize);
                 if (chunksize & 1)
                         chunksize++;
-                sox_seeki(ft, (sox_ssize_t)chunksize, SEEK_CUR);
+                lsx_seeki(ft, (sox_ssize_t)chunksize, SEEK_CUR);
                 continue;
                 
         }
@@ -186,10 +186,10 @@
         
         if (strncmp(buf,"MDAT",4) != 0) 
         {
-            sox_fail_errno(ft,SOX_EFMT,"MAUD: MDAT chunk not found");
+            lsx_fail_errno(ft,SOX_EFMT,"MAUD: MDAT chunk not found");
             return(SOX_EOF);
         }
-        sox_readdw(ft, &(p->nsamples));
+        lsx_readdw(ft, &(p->nsamples));
         return(SOX_SUCCESS);
 }
 
@@ -199,7 +199,7 @@
         int rc;
 
         /* Needed for rawwrite() */
-        rc = sox_rawstartwrite(ft);
+        rc = lsx_rawstartwrite(ft);
         if (rc)
             return rc;
 
@@ -206,7 +206,7 @@
         /* If you have to seek around the output file */
         if (! ft->seekable) 
         {
-            sox_fail_errno(ft,SOX_EOF,"Output .maud file must be a file, not a pipe");
+            lsx_fail_errno(ft,SOX_EOF,"Output .maud file must be a file, not a pipe");
             return (SOX_EOF);
         }
         p->nsamples = 0x7f000000;
@@ -221,7 +221,7 @@
         
         p->nsamples += len;
         
-        return sox_rawwrite(ft, buf, len);
+        return lsx_rawwrite(ft, buf, len);
 }
 
 static int stopwrite(sox_format_t * ft) 
@@ -228,9 +228,9 @@
 {
         /* All samples are already written out. */
         
-        if (sox_seeki(ft, 0, 0) != 0) 
+        if (lsx_seeki(ft, 0, 0) != 0) 
         {
-            sox_fail_errno(ft,errno,"can't rewind output file to rewrite MAUD header");
+            lsx_fail_errno(ft,errno,"can't rewind output file to rewrite MAUD header");
             return(SOX_EOF);
         }
         
@@ -243,30 +243,30 @@
 {
         struct maudstuff * p = (struct maudstuff *) ft->priv;
         
-        sox_writes(ft, "FORM");
-        sox_writedw(ft, (p->nsamples* (ft->encoding.bits_per_sample >> 3)) + MAUDHEADERSIZE);  /* size of file */
-        sox_writes(ft, "MAUD"); /* File type */
+        lsx_writes(ft, "FORM");
+        lsx_writedw(ft, (p->nsamples* (ft->encoding.bits_per_sample >> 3)) + MAUDHEADERSIZE);  /* size of file */
+        lsx_writes(ft, "MAUD"); /* File type */
         
-        sox_writes(ft, "MHDR");
-        sox_writedw(ft,  8*4); /* number of bytes to follow */
-        sox_writedw(ft, p->nsamples);  /* number of samples stored in MDAT */
+        lsx_writes(ft, "MHDR");
+        lsx_writedw(ft,  8*4); /* number of bytes to follow */
+        lsx_writedw(ft, p->nsamples);  /* number of samples stored in MDAT */
         
         switch (ft->encoding.encoding) {
                 
         case SOX_ENCODING_UNSIGNED:
-          sox_writew(ft, 8); /* number of bits per sample as stored in MDAT */
-          sox_writew(ft, 8); /* number of bits per sample after decompression */
+          lsx_writew(ft, 8); /* number of bits per sample as stored in MDAT */
+          lsx_writew(ft, 8); /* number of bits per sample after decompression */
           break;
                 
         case SOX_ENCODING_SIGN2:
-          sox_writew(ft, 16); /* number of bits per sample as stored in MDAT */
-          sox_writew(ft, 16); /* number of bits per sample after decompression */
+          lsx_writew(ft, 16); /* number of bits per sample as stored in MDAT */
+          lsx_writew(ft, 16); /* number of bits per sample after decompression */
           break;
                 
         case SOX_ENCODING_ALAW:
         case SOX_ENCODING_ULAW:
-          sox_writew(ft, 8); /* number of bits per sample as stored in MDAT */
-          sox_writew(ft, 16); /* number of bits per sample after decompression */
+          lsx_writew(ft, 8); /* number of bits per sample as stored in MDAT */
+          lsx_writew(ft, 16); /* number of bits per sample after decompression */
           break;
 
         default:
@@ -273,16 +273,16 @@
           break;
         }
         
-        sox_writedw(ft, (unsigned)(ft->signal.rate + .5)); /* sample rate, Hz */
-        sox_writew(ft, (int) 1); /* clock devide */
+        lsx_writedw(ft, (unsigned)(ft->signal.rate + .5)); /* sample rate, Hz */
+        lsx_writew(ft, (int) 1); /* clock devide */
         
         if (ft->signal.channels == 1) {
-          sox_writew(ft, 0); /* channel information */
-          sox_writew(ft, 1); /* number of channels (mono: 1, stereo: 2, ...) */
+          lsx_writew(ft, 0); /* channel information */
+          lsx_writew(ft, 1); /* number of channels (mono: 1, stereo: 2, ...) */
         }
         else {
-          sox_writew(ft, 1);
-          sox_writew(ft, 2);
+          lsx_writew(ft, 1);
+          lsx_writew(ft, 2);
         }
         
         switch (ft->encoding.encoding) {
@@ -289,15 +289,15 @@
                 
         case SOX_ENCODING_UNSIGNED:
         case SOX_ENCODING_SIGN2:
-          sox_writew(ft, 0); /* no compression */
+          lsx_writew(ft, 0); /* no compression */
           break;
                 
         case SOX_ENCODING_ULAW:
-          sox_writew(ft, 3);
+          lsx_writew(ft, 3);
           break;
                 
         case SOX_ENCODING_ALAW:
-          sox_writew(ft, 2);
+          lsx_writew(ft, 2);
           break;
 
         default:
@@ -304,16 +304,16 @@
           break;
         }
         
-        sox_writedw(ft, 0); /* reserved */
-        sox_writedw(ft, 0); /* reserved */
-        sox_writedw(ft, 0); /* reserved */
+        lsx_writedw(ft, 0); /* reserved */
+        lsx_writedw(ft, 0); /* reserved */
+        lsx_writedw(ft, 0); /* reserved */
         
-        sox_writes(ft, "ANNO");
-        sox_writedw(ft, 30); /* length of block */
-        sox_writes(ft, "file create by Sound eXchange ");
+        lsx_writes(ft, "ANNO");
+        lsx_writedw(ft, 30); /* length of block */
+        lsx_writes(ft, "file create by Sound eXchange ");
         
-        sox_writes(ft, "MDAT");
-        sox_writedw(ft, p->nsamples * (ft->encoding.bits_per_sample >> 3)); /* samples in file */
+        lsx_writes(ft, "MDAT");
+        lsx_writedw(ft, p->nsamples * (ft->encoding.bits_per_sample >> 3)); /* samples in file */
 }
 
 SOX_FORMAT_HANDLER(maud)
@@ -329,7 +329,7 @@
     SOX_LIB_VERSION_CODE,
     "Used with the ‘Toccata’ sound-card on the Amiga",
     names, SOX_FILE_BIG_END | SOX_FILE_MONO | SOX_FILE_STEREO,
-    startread, sox_rawread, sox_rawstopread,
+    startread, lsx_rawread, lsx_rawstopread,
     startwrite, write_samples, stopwrite,
     NULL, write_encodings, NULL
   };
--- a/src/misc.c
+++ /dev/null
@@ -1,669 +1,0 @@
-/*
- * libSoX miscellaneous file-handling functions.
- */
-
-/*
- * July 5, 1991
- * Copyright 1991 Lance Norskog And Sundry Contributors
- * This source code is freely redistributable and may be used for
- * any purpose.  This copyright notice must be maintained.
- * Lance Norskog And Sundry Contributors are not responsible for
- * the consequences of using this software.
- */
-
-#include "sox_i.h"
-#include <math.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <stddef.h>
-#include <string.h>
-#include <ctype.h>
-#include <errno.h>
-/* for fstat */
-#include <sys/stat.h>
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-
-#ifdef HAVE_BYTESWAP_H
-#include <byteswap.h>
-#endif
-
-const char * const sox_encodings_str[] = {
-  "?",
-  "Signed Integer PCM",
-  "Unsigned Integer PCM",
-  "Floating Point PCM",
-  "Floating Point (text) PCM",
-  "FLAC",
-  "HCOM",
-  "", /* Lossless above, lossy below */
-  "u-law",
-  "A-law",
-  "G.721 ADPCM",
-  "G.723 ADPCM",
-  "CL ADPCM (from 8-bit)",
-  "CL ADPCM (from 16-bit)",
-  "MS ADPCM",
-  "IMA ADPCM",
-  "OKI ADPCM",
-  "GSM",
-  "MPEG audio (layer I, II or III)",
-  "Vorbis",
-  "AMR-WB",
-  "AMR-NB",
-  "CVSD",
-  "LPC10",
-};
-
-const char * const sox_encodings_short_str[] = {
-  "n/a",
-  "Signed PCM",
-  "Unsigned PCM",
-  "F.P. PCM",
-  "F.P. PCM",
-  "FLAC",
-  "HCOM",
-  "", /* Lossless above, lossy below */
-  "u-law",
-  "A-law",
-  "G.721 ADPCM",
-  "G.723 ADPCM",
-  "CL ADPCM (8)",
-  "CL ADPCM (16)",
-  "MS ADPCM",
-  "IMA ADPCM",
-  "OKI ADPCM",
-  "GSM",
-  "MPEG audio",
-  "Vorbis",
-  "AMR-WB",
-  "AMR-NB",
-  "CVSD",
-  "LPC10",
-};
-
-assert_static(array_length(sox_encodings_str) == SOX_ENCODINGS,
-    SIZE_MISMATCH_BETWEEN_sox_encodings_t_AND_sox_encodings_str);
-
-void sox_init_encodinginfo(sox_encodinginfo_t * e)
-{
-  e->reverse_bytes = SOX_OPTION_DEFAULT;
-  e->reverse_nibbles = SOX_OPTION_DEFAULT;
-  e->reverse_bits = SOX_OPTION_DEFAULT;
-  e->compression = HUGE_VAL;
-}
-
-unsigned sox_precision(sox_encoding_t encoding, unsigned bits_per_sample)
-{
-  switch (encoding) {
-    case SOX_ENCODING_HCOM:       return !(bits_per_sample & 7) && (bits_per_sample >> 3) - 1 < 1? bits_per_sample: 0;
-    case SOX_ENCODING_FLAC:       return !(bits_per_sample & 7) && (bits_per_sample >> 3) - 1 < 3? bits_per_sample: 0;
-    case SOX_ENCODING_SIGN2:      return bits_per_sample <= 32? bits_per_sample : 0;
-    case SOX_ENCODING_UNSIGNED:   return !(bits_per_sample & 7) && (bits_per_sample >> 3) - 1 < 4? bits_per_sample: 0;
-
-    case SOX_ENCODING_ALAW:       return bits_per_sample == 8? 13: 0;
-    case SOX_ENCODING_ULAW:       return bits_per_sample == 8? 14: 0;
-
-    case SOX_ENCODING_CL_ADPCM:   return bits_per_sample? 8: 0;
-    case SOX_ENCODING_CL_ADPCM16: return bits_per_sample == 4? 13: 0;
-    case SOX_ENCODING_MS_ADPCM:   return bits_per_sample == 4? 14: 0;
-    case SOX_ENCODING_IMA_ADPCM:  return bits_per_sample == 4? 13: 0;
-    case SOX_ENCODING_OKI_ADPCM:  return bits_per_sample == 4? 12: 0;
-    case SOX_ENCODING_G721:       return bits_per_sample == 4? 12: 0;
-    case SOX_ENCODING_G723:       return bits_per_sample == 3? 8:
-                                         bits_per_sample == 5? 14: 0;
-    case SOX_ENCODING_CVSD:       return bits_per_sample == 1? 16: 0;
-
-    case SOX_ENCODING_GSM:
-    case SOX_ENCODING_MP3:
-    case SOX_ENCODING_VORBIS:
-    case SOX_ENCODING_AMR_WB:
-    case SOX_ENCODING_AMR_NB:
-    case SOX_ENCODING_LPC10:      return !bits_per_sample? 16: 0;
-
-    case SOX_ENCODING_FLOAT:      return bits_per_sample == 32 ? 24: bits_per_sample == 64 ? 53: 0;
-    case SOX_ENCODING_FLOAT_TEXT: return !bits_per_sample? 53: 0;
-
-    case SOX_ENCODINGS:
-    case SOX_ENCODING_LOSSLESS:
-    case SOX_ENCODING_UNKNOWN:    break;
-  }
-  return 0;
-}
-
-int sox_check_read_params(sox_format_t * ft, unsigned channels,
-    sox_rate_t rate, sox_encoding_t encoding, unsigned bits_per_sample, off_t length)
-{
-  ft->length = length;
-
-  if (ft->seekable)
-    ft->data_start = sox_tell(ft);
-
-  if (channels && ft->signal.channels && ft->signal.channels != channels)
-    sox_warn("`%s': overriding number of channels", ft->filename);
-  else ft->signal.channels = channels;
-
-  if (rate && ft->signal.rate && ft->signal.rate != rate)
-    sox_warn("`%s': overriding sample rate", ft->filename);
-  else ft->signal.rate = rate;
-
-  if (encoding && ft->encoding.encoding && ft->encoding.encoding != encoding)
-    sox_warn("`%s': overriding encoding type", ft->filename);
-  else ft->encoding.encoding = encoding;
-
-  if (bits_per_sample && ft->encoding.bits_per_sample && ft->encoding.bits_per_sample != bits_per_sample)
-    sox_warn("`%s': overriding encoding size", ft->filename);
-  ft->encoding.bits_per_sample = bits_per_sample;
-
-  if (ft->encoding.bits_per_sample && sox_filelength(ft)) {
-    off_t calculated_length = div_bits(sox_filelength(ft) - ft->data_start, ft->encoding.bits_per_sample);
-    if (!ft->length)
-      ft->length = calculated_length;
-    else if (length != calculated_length)
-      sox_warn("`%s': file header gives the total number of samples as %u but file length indicates the number is in fact %u", ft->filename, (unsigned)length, (unsigned)calculated_length); /* FIXME: casts */
-  }
-
-  if (sox_precision(ft->encoding.encoding, ft->encoding.bits_per_sample))
-    return SOX_SUCCESS;
-  sox_fail_errno(ft, EINVAL, "invalid format for this file type");
-  return SOX_EOF;
-}
-
-sox_sample_t sox_sample_max(sox_encodinginfo_t const * encoding)
-{
-  unsigned precision = encoding->encoding == SOX_ENCODING_FLOAT?
-    SOX_SAMPLE_PRECISION : sox_precision(encoding->encoding, encoding->bits_per_sample);
-  unsigned shift = SOX_SAMPLE_PRECISION - min(precision, SOX_SAMPLE_PRECISION);
-  return (SOX_SAMPLE_MAX >> shift) << shift;
-}
-
-/* Lookup table to reverse the bit order of a byte. ie MSB become LSB */
-uint8_t const cswap[256] = {
-  0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0, 0x10, 0x90, 0x50, 0xD0,
-  0x30, 0xB0, 0x70, 0xF0, 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8, 
-  0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8, 0x04, 0x84, 0x44, 0xC4, 
-  0x24, 0xA4, 0x64, 0xE4, 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
-  0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC, 0x1C, 0x9C, 0x5C, 0xDC,
-  0x3C, 0xBC, 0x7C, 0xFC, 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2, 
-  0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2, 0x0A, 0x8A, 0x4A, 0xCA, 
-  0x2A, 0xAA, 0x6A, 0xEA, 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
-  0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6, 0x16, 0x96, 0x56, 0xD6,
-  0x36, 0xB6, 0x76, 0xF6, 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE, 
-  0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE, 0x01, 0x81, 0x41, 0xC1, 
-  0x21, 0xA1, 0x61, 0xE1, 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
-  0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9, 0x19, 0x99, 0x59, 0xD9,
-  0x39, 0xB9, 0x79, 0xF9, 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5, 
-  0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5, 0x0D, 0x8D, 0x4D, 0xCD, 
-  0x2D, 0xAD, 0x6D, 0xED, 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
-  0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3, 0x13, 0x93, 0x53, 0xD3,
-  0x33, 0xB3, 0x73, 0xF3, 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB, 
-  0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB, 0x07, 0x87, 0x47, 0xC7, 
-  0x27, 0xA7, 0x67, 0xE7, 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
-  0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF, 0x1F, 0x9F, 0x5F, 0xDF,
-  0x3F, 0xBF, 0x7F, 0xFF
-};
-
-/* Utilities */
-
-/* Read in a buffer of data of length len bytes.
- * Returns number of bytes read.
- */
-size_t sox_readbuf(sox_format_t * ft, void *buf, sox_size_t len)
-{
-  size_t ret = fread(buf, 1, len, ft->fp);
-  if (ret != len && ferror(ft->fp))
-    sox_fail_errno(ft, errno, "sox_readbuf");
-  ft->tell += ret;
-  return ret;
-}
-
-/* Skip input without seeking. */
-int sox_skipbytes(sox_format_t * ft, sox_size_t n)
-{
-  unsigned char trash;
-
-  while (n--)
-    if (sox_readb(ft, &trash) == SOX_EOF)
-      return (SOX_EOF);
-  
-  return (SOX_SUCCESS);
-}
-
-/* Pad output. */
-int sox_padbytes(sox_format_t * ft, sox_size_t n)
-{
-  while (n--)
-    if (sox_writeb(ft, '\0') == SOX_EOF)
-      return (SOX_EOF);
-
-  return (SOX_SUCCESS);
-}
-
-/* Write a buffer of data of length bytes.
- * Returns number of bytes written.
- */
-
-size_t sox_writebuf(sox_format_t * ft, void const * buf, sox_size_t len)
-{
-  size_t ret = fwrite(buf, 1, len, ft->fp);
-  if (ret != len) {
-    sox_fail_errno(ft, errno, "error writing output file");
-    clearerr(ft->fp); /* Allows us to seek back to write header */
-  }
-  ft->tell += ret;
-  return ret;
-}
-
-sox_size_t sox_filelength(sox_format_t * ft)
-{
-  struct stat st;
-  int ret = fstat(fileno(ft->fp), &st);
-
-  return ret? 0 : (sox_size_t)st.st_size;
-}
-
-int sox_flush(sox_format_t * ft)
-{
-  return fflush(ft->fp);
-}
-
-sox_ssize_t sox_tell(sox_format_t * ft)
-{
-  return ft->seekable? (sox_ssize_t)ftello(ft->fp) : ft->tell;
-}
-
-int sox_eof(sox_format_t * ft)
-{
-  return feof(ft->fp);
-}
-
-int sox_error(sox_format_t * ft)
-{
-  return ferror(ft->fp);
-}
-
-void sox_rewind(sox_format_t * ft)
-{
-  rewind(ft->fp);
-}
-
-void sox_clearerr(sox_format_t * ft)
-{
-  clearerr(ft->fp);
-}
-
-/* Read and write known datatypes in "machine format".  Swap if indicated.
- * They all return SOX_EOF on error and SOX_SUCCESS on success.
- */
-/* Read n-char string (and possibly null-terminating).
- * Stop reading and null-terminate string if either a 0 or \n is reached.
- */
-int sox_reads(sox_format_t * ft, char *c, sox_size_t len)
-{
-    char *sc;
-    char in;
-
-    sc = c;
-    do
-    {
-        if (sox_readbuf(ft, &in, 1) != 1)
-        {
-            *sc = 0;
-            return (SOX_EOF);
-        }
-        if (in == 0 || in == '\n')
-            break;
-
-        *sc = in;
-        sc++;
-    } while (sc - c < (ptrdiff_t)len);
-    *sc = 0;
-    return(SOX_SUCCESS);
-}
-
-/* Write null-terminated string (without \0). */
-int sox_writes(sox_format_t * ft, char const * c)
-{
-        if (sox_writebuf(ft, c, strlen(c)) != strlen(c))
-                return(SOX_EOF);
-        return(SOX_SUCCESS);
-}
-
-uint32_t get32_le(unsigned char **p)
-{
-        uint32_t val = (((*p)[3]) << 24) | (((*p)[2]) << 16) | 
-                (((*p)[1]) << 8) | (**p);
-        (*p) += 4;
-        return val;
-}
-
-uint16_t get16_le(unsigned char **p)
-{
-        unsigned val = (((*p)[1]) << 8) | (**p);
-        (*p) += 2;
-        return val;
-}
-
-void put32_le(unsigned char **p, uint32_t val)
-{
-        *(*p)++ = val & 0xff;
-        *(*p)++ = (val >> 8) & 0xff;
-        *(*p)++ = (val >> 16) & 0xff;
-        *(*p)++ = (val >> 24) & 0xff;
-}
-
-void put16_le(unsigned char **p, unsigned val)
-{
-        *(*p)++ = val & 0xff;
-        *(*p)++ = (val >> 8) & 0xff;
-}
-
-void put32_be(unsigned char **p, int32_t val)
-{
-  *(*p)++ = (val >> 24) & 0xff;
-  *(*p)++ = (val >> 16) & 0xff;
-  *(*p)++ = (val >> 8) & 0xff;
-  *(*p)++ = val & 0xff;
-}
-
-void put16_be(unsigned char **p, int val)
-{
-  *(*p)++ = (val >> 8) & 0xff;
-  *(*p)++ = val & 0xff;
-}
-
-/* generic swap routine. Swap l and place in to f (datatype length = n) */
-static void sox_swap(char *l, char *f, int n)
-{
-    register int i;
-
-    for (i= 0; i< n; i++)
-        f[i]= l[n-i-1];
-}
-
-/* return swapped 32-bit float */
-void sox_swapf(float * f)
-{
-    union {
-        uint32_t dw;
-        float f;
-    } u;
-
-    u.f= *f;
-    u.dw= (u.dw>>24) | ((u.dw>>8)&0xff00) | ((u.dw<<8)&0xff0000) | (u.dw<<24);
-    *f = u.f;
-}
-
-uint32_t sox_swap3(uint24_t udw)
-{
-    return ((udw >> 16) & 0xff) | (udw & 0xff00) | ((udw << 16) & 0xff0000);
-}
-
-double sox_swapdf(double df)
-{
-    double sdf;
-    sox_swap((char *)&df, (char *)&sdf, sizeof(double));
-    return (sdf);
-}
-
-/* here for linear interp.  might be useful for other things */
-sox_sample_t sox_gcd(sox_sample_t a, sox_sample_t b)
-{
-  if (b == 0)
-    return a;
-  else
-    return sox_gcd(b, a % b);
-}
-
-sox_sample_t sox_lcm(sox_sample_t a, sox_sample_t b)
-{
-  /* parenthesize this way to avoid sox_sample_t overflow in product term */
-  return a * (b / sox_gcd(a, b));
-}
-
-char const * find_file_extension(char const * pathname)
-{
-  /* First, chop off any path portions of filename.  This
-   * prevents the next search from considering that part. */
-  char const * result = LAST_SLASH(pathname);
-  if (!result)
-    result = pathname;
-
-  /* Now look for an filename extension */
-  result = strrchr(result, '.');
-  if (result)
-    ++result;
-  return result;
-}
-
-#ifndef HAVE_STRCASECMP
-/*
- * Portable strcasecmp() function
- */
-int strcasecmp(const char *s1, const char *s2)
-{
-  while (*s1 && (toupper(*s1) == toupper(*s2)))
-    s1++, s2++;
-  return toupper(*s1) - toupper(*s2);
-}
-
-int strncasecmp(char const *s1, char const * s2, size_t n)
-{
-  while (--n && *s1 && (toupper(*s1) == toupper(*s2)))
-    s1++, s2++;
-  return toupper(*s1) - toupper(*s2);
-}
-#endif
-
-sox_bool strcaseends(char const * str, char const * end)
-{
-  size_t str_len = strlen(str), end_len = strlen(end);
-  return str_len >= end_len && !strcasecmp(str + str_len - end_len, end);
-}
-
-sox_bool strends(char const * str, char const * end)
-{
-  size_t str_len = strlen(str), end_len = strlen(end);
-  return str_len >= end_len && !strcmp(str + str_len - end_len, end);
-}
-
-#ifndef HAVE_STRDUP
-/*
- * Portable strdup() function
- */
-char *strdup(const char *s)
-{
-    return strcpy((char *)xmalloc(strlen(s) + 1), s);
-}
-#endif
-
-
-
-void sox_generate_wave_table(
-    sox_wave_t wave_type,
-    sox_data_t data_type,
-    void *table,
-    uint32_t table_size,
-    double min,
-    double max,
-    double phase)
-{
-  uint32_t t;
-  uint32_t phase_offset = phase / M_PI / 2 * table_size + 0.5;
-
-  for (t = 0; t < table_size; t++)
-  {
-    uint32_t point = (t + phase_offset) % table_size;
-    double d;
-    switch (wave_type)
-    {
-      case SOX_WAVE_SINE:
-      d = (sin((double)point / table_size * 2 * M_PI) + 1) / 2;
-      break;
-
-      case SOX_WAVE_TRIANGLE:
-      d = (double)point * 2 / table_size;
-      switch (4 * point / table_size)
-      {
-        case 0:         d = d + 0.5; break;
-        case 1: case 2: d = 1.5 - d; break;
-        case 3:         d = d - 1.5; break;
-      }
-      break;
-
-      default: /* Oops! FIXME */
-        d = 0.0; /* Make sure we have a value */
-      break;
-    }
-    d  = d * (max - min) + min;
-    switch (data_type)
-    {
-      case SOX_FLOAT:
-        {
-          float *fp = (float *)table;
-          *fp++ = (float)d;
-          table = fp;
-          continue;
-        }
-      case SOX_DOUBLE:
-        {
-          double *dp = (double *)table;
-          *dp++ = d;
-          table = dp;
-          continue;
-        }
-      default: break;
-    }
-    d += d < 0? -0.5 : +0.5;
-    switch (data_type)
-    {
-      case SOX_SHORT:
-        {
-          short *sp = table;
-          *sp++ = (short)d;
-          table = sp;
-          continue;
-        }
-      case SOX_INT:
-        {
-          int *ip = table;
-          *ip++ = (int)d;
-          table = ip;
-          continue;
-        }
-      default: break;
-    }
-  }
-}
-
-
-
-const char *sox_version(void)
-{
-    static char versionstr[20];
-
-    sprintf(versionstr, "%d.%d.%d",
-            (SOX_LIB_VERSION_CODE & 0xff0000) >> 16,
-            (SOX_LIB_VERSION_CODE & 0x00ff00) >> 8,
-            (SOX_LIB_VERSION_CODE & 0x0000ff));
-    return(versionstr);
-}
-
-/* Implements traditional fseek() behavior.  Meant to abstract out
- * file operations so that they could one day also work on memory
- * buffers.
- *
- * N.B. Can only seek forwards on non-seekable streams!
- */
-int sox_seeki(sox_format_t * ft, sox_ssize_t offset, int whence)
-{
-    if (ft->seekable == 0) {
-        /* If a stream peel off chars else EPERM */
-        if (whence == SEEK_CUR) {
-            while (offset > 0 && !feof(ft->fp)) {
-                getc(ft->fp);
-                offset--;
-                ++ft->tell;
-            }
-            if (offset)
-                sox_fail_errno(ft,SOX_EOF, "offset past EOF");
-            else
-                ft->sox_errno = SOX_SUCCESS;
-        } else
-            sox_fail_errno(ft,SOX_EPERM, "file not seekable");
-    } else {
-        if (fseeko(ft->fp, (off_t)offset, whence) == -1)
-            sox_fail_errno(ft,errno,strerror(errno));
-        else
-            ft->sox_errno = SOX_SUCCESS;
-    }
-    return ft->sox_errno;
-}
-
-int sox_offset_seek(sox_format_t * ft, off_t byte_offset, sox_size_t to_sample)
-{
-  double wide_sample = to_sample - (to_sample % ft->signal.channels);
-  double to_d = wide_sample * ft->encoding.bits_per_sample / 8;
-  off_t to = to_d;
-  return (to != to_d)? SOX_EOF : sox_seeki(ft, byte_offset + to, SEEK_SET);
-}
-
-enum_item const * find_enum_text(char const * text, enum_item const * enum_items)
-{
-  enum_item const * result = NULL; /* Assume not found */
-
-  while (enum_items->text)
-  {
-    if (strncasecmp(text, enum_items->text, strlen(text)) == 0)
-    {
-      if (result != NULL && result->value != enum_items->value)
-        return NULL;        /* Found ambiguity */
-      result = enum_items;  /* Found match */
-    }
-    ++enum_items;
-  }
-  return result;
-}
-
-enum_item const * find_enum_value(unsigned value, enum_item const * enum_items)
-{
-  for (;enum_items->text; ++enum_items)
-    if (value == enum_items->value)
-      return enum_items;
-  return NULL;
-}
-
-enum_item const sox_wave_enum[] = {
-  ENUM_ITEM(SOX_WAVE_,SINE)
-  ENUM_ITEM(SOX_WAVE_,TRIANGLE)
-  {0, 0}};
-
-sox_bool is_uri(char const * text)
-{
-  if (!isalpha((int)*text))
-    return sox_false;
-  ++text;
-  do {
-    if (!isalnum((int)*text) && !strchr("+-.", *text))
-      return sox_false;
-    ++text;
-  } while (*text && *text != ':');
-  return *text == ':';
-}
-
-FILE * xfopen(char const * identifier, char const * mode) 
-{ 
-  if (is_uri(identifier)) {
-    FILE * f = NULL;
-#ifdef HAVE_POPEN
-    char const * const command_format = "wget --no-check-certificate -q -O- \"%s\"";
-    char * command = xmalloc(strlen(command_format) + strlen(identifier)); 
-    sprintf(command, command_format, identifier); 
-    f = popen(command, "r"); 
-    free(command);
-#endif 
-    return f;
-  }
-  return fopen(identifier, mode);
-} 
--- a/src/mixer.c
+++ b/src/mixer.c
@@ -64,7 +64,7 @@
         else if (!strcmp(argv[0], "-4")) mixer->mix = '4';
         else if (argv[0][0] == '-' && !isdigit((int)argv[0][1])
                 && argv[0][1] != '.')
-          return sox_usage(effp);
+          return lsx_usage(effp);
         else {
             int commas;
             char *s;
@@ -87,7 +87,7 @@
         mixer->mix = MIX_CENTER;
     }
     else
-      return sox_usage(effp);
+      return lsx_usage(effp);
 
     return (SOX_SUCCESS);
 }
@@ -542,7 +542,7 @@
 static int oops_getopts(sox_effect_t * effp, int argc, char * * argv UNUSED) 
 {
   char * args[] = {"1,1,-1,-1"};
-  return argc? sox_usage(effp) : sox_mixer_effect_fn()->getopts(effp, array_length(args), args);
+  return argc? lsx_usage(effp) : sox_mixer_effect_fn()->getopts(effp, array_length(args), args);
 }
 
 sox_effect_handler_t const * sox_oops_effect_fn(void)
--- a/src/mp3-duration.h
+++ b/src/mp3-duration.h
@@ -62,7 +62,7 @@
         if ((utf8 = utf8_id3tag_findframe(tag, list[i][0], 0))) {
           char * comment = xmalloc(strlen(list[i][1]) + 1 + strlen((char *)utf8) + 1);
           sprintf(comment, "%s=%s", list[i][1], utf8);
-          append_comment(&ft->comments, comment);
+          sox_append_comment(&ft->comments, comment);
           free(comment);
           free(utf8);
         }
--- a/src/mp3.c
+++ b/src/mp3.c
@@ -106,7 +106,7 @@
      */
     memmove(p->InputBuffer, p->Stream->next_frame, remaining);
 
-    bytes_read = sox_readbuf(ft, p->InputBuffer+remaining,
+    bytes_read = lsx_readbuf(ft, p->InputBuffer+remaining,
                             INPUT_BUFFER_SIZE-remaining);
     if (bytes_read == 0)
     {
@@ -194,10 +194,10 @@
      * format.  The decoded frame will be saved off so that it
      * can be processed later.
      */
-    ReadSize = sox_readbuf(ft, p->InputBuffer, INPUT_BUFFER_SIZE);
+    ReadSize = lsx_readbuf(ft, p->InputBuffer, INPUT_BUFFER_SIZE);
     if (ReadSize < INPUT_BUFFER_SIZE) {
-      if (sox_eof(ft))
-        sox_fail_errno(ft, SOX_EOF, "input file too short");
+      if (lsx_eof(ft))
+        lsx_fail_errno(ft, SOX_EOF, "input file too short");
       return SOX_EOF;
     }
 
@@ -232,7 +232,7 @@
 
     if (p->Stream->error)
     {
-        sox_fail_errno(ft,SOX_EOF,"No valid MP3 frame found");
+        lsx_fail_errno(ft,SOX_EOF,"No valid MP3 frame found");
         return SOX_EOF;
     }
 
@@ -245,7 +245,7 @@
             ft->signal.channels = MAD_NCHANNELS(&p->Frame->header);
             break;
         default:
-            sox_fail_errno(ft, SOX_EFMT, "Cannot determine number of channels");
+            lsx_fail_errno(ft, SOX_EFMT, "Cannot determine number of channels");
             return SOX_EOF;
     }
 
@@ -350,7 +350,7 @@
 #else /*HAVE_MAD_H*/
 static int startread(sox_format_t * ft)
 {
-  sox_fail_errno(ft,SOX_EOF,"SoX was compiled without MP3 decoding support");
+  lsx_fail_errno(ft,SOX_EOF,"SoX was compiled without MP3 decoding support");
   return SOX_EOF;
 }
 #define sox_mp3read NULL
@@ -375,13 +375,13 @@
 
   p->gfp = lame_init();
   if (p->gfp == NULL){
-    sox_fail_errno(ft,SOX_EOF,"Initialization of LAME library failed");
+    lsx_fail_errno(ft,SOX_EOF,"Initialization of LAME library failed");
     return(SOX_EOF);
   }
 
   if (ft->signal.channels != SOX_ENCODING_UNKNOWN) {
     if ( (lame_set_num_channels(p->gfp,(int)ft->signal.channels)) < 0) {
-        sox_fail_errno(ft,SOX_EOF,"Unsupported number of channels");
+        lsx_fail_errno(ft,SOX_EOF,"Unsupported number of channels");
         return(SOX_EOF);
     }
   }
@@ -401,7 +401,7 @@
   if (ft->encoding.compression != HUGE_VAL)
       sox_warn("-C option not supported for mp3; using default compression rate");
   if (lame_init_params(p->gfp) < 0){
-        sox_fail_errno(ft,SOX_EOF,"LAME initialization failed");
+        lsx_fail_errno(ft,SOX_EOF,"LAME initialization failed");
         return(SOX_EOF);
   }
   lame_set_errorf(p->gfp,null_error_func);
@@ -449,7 +449,7 @@
              (short signed int *)xmalloc(nsamples*
                                           sizeof(short signed int))) == NULL)
         {
-            sox_fail_errno(ft,SOX_ENOMEM,"Memory allocation failed");
+            lsx_fail_errno(ft,SOX_ENOMEM,"Memory allocation failed");
             goto end3;
         }
 
@@ -472,7 +472,7 @@
     mp3buffer_size = 1.25 * nsamples + 7200;
     if ((mp3buffer=(char *)xmalloc(mp3buffer_size)) == NULL)
     {
-        sox_fail_errno(ft,SOX_ENOMEM,"Memory allocation failed");
+        lsx_fail_errno(ft,SOX_ENOMEM,"Memory allocation failed");
         goto end2;
     }
 
@@ -479,13 +479,13 @@
     if ((written = lame_encode_buffer(p->gfp,buffer_l, buffer_r,
                                       nsamples, (unsigned char *)mp3buffer,
                                       (int)mp3buffer_size)) > mp3buffer_size){
-        sox_fail_errno(ft,SOX_EOF,"Encoding failed");
+        lsx_fail_errno(ft,SOX_EOF,"Encoding failed");
         goto end;
     }
 
-    if (sox_writebuf(ft, mp3buffer, written) < written)
+    if (lsx_writebuf(ft, mp3buffer, written) < written)
     {
-        sox_fail_errno(ft,SOX_EOF,"File write failed");
+        lsx_fail_errno(ft,SOX_EOF,"File write failed");
         goto end;
     }
 
@@ -510,10 +510,10 @@
   size_t written2;
   
   if ((written=lame_encode_flush(p->gfp, (unsigned char *)mp3buffer, 7200)) <0){
-    sox_fail_errno(ft,SOX_EOF,"Encoding failed");
+    lsx_fail_errno(ft,SOX_EOF,"Encoding failed");
   }
-  else if (sox_writebuf(ft, mp3buffer, written2 = written) < written2){
-    sox_fail_errno(ft,SOX_EOF,"File write failed");
+  else if (lsx_writebuf(ft, mp3buffer, written2 = written) < written2){
+    lsx_fail_errno(ft,SOX_EOF,"File write failed");
   }
 
   lame_close(p->gfp);
@@ -523,7 +523,7 @@
 #else /* HAVE_LAME_LAME_H */
 static int startwrite(sox_format_t * ft UNUSED)
 {
-  sox_fail_errno(ft,SOX_EOF,"SoX was compiled without MP3 encoding support");
+  lsx_fail_errno(ft,SOX_EOF,"SoX was compiled without MP3 encoding support");
   return SOX_EOF;
 }
 #define sox_mp3write NULL
--- a/src/noiseprof.c
+++ b/src/noiseprof.c
@@ -44,7 +44,7 @@
     if (n == 1) {
         data->output_filename = argv[0];
     } else if (n > 1)
-      return sox_usage(effp);
+      return lsx_usage(effp);
 
     return (SOX_SUCCESS);
 }
--- a/src/noisered.c
+++ b/src/noisered.c
@@ -51,7 +51,7 @@
     NUMERIC_PARAMETER(threshold, 0, 1);
   } while (0);
 
-  return argc? sox_usage(effp) : SOX_SUCCESS;
+  return argc? lsx_usage(effp) : SOX_SUCCESS;
 }
 
 /*
--- a/src/normalise.c
+++ b/src/normalise.c
@@ -39,7 +39,7 @@
   if (argc && !strcmp(*argv, "-i")) p->individual = sox_true, ++argv, --argc;
   if (argc > 1 || (argc == 1 &&
         (sscanf(*argv, "%lf%c", &p->level, &dummy) != 1 || p->level > 0)))
-    return sox_usage(effp);
+    return lsx_usage(effp);
   p->level = dB_to_linear(p->level);
   return SOX_SUCCESS;
 }
@@ -84,7 +84,7 @@
   int result = SOX_SUCCESS;
 
   if (!p->norm0) {
-    double max = sox_sample_max(effp->out_encoding);
+    double max = lsx_sample_max(effp->out_encoding);
     p->norm0 = p->level * min(max / p->max, (double)SOX_SAMPLE_MIN / p->min);
     rewind(p->tmp_file);
   }
--- a/src/oss.c
+++ b/src/oss.c
@@ -48,7 +48,7 @@
     sox_fileinfo_t *file = (sox_fileinfo_t *)ft->priv;
     sox_signalinfo_t client_signal = ft->signal;
 
-    set_signal_defaults(&ft->signal);
+    lsx_set_signal_defaults(&ft->signal);
     if (ft->encoding.bits_per_sample == 8) {
         sampletype = AFMT_U8;
         samplesize = 8;
@@ -63,9 +63,9 @@
     else if (ft->encoding.bits_per_sample == 16) {
         /* Attempt to use endian that user specified */
         if (ft->encoding.reverse_bytes)
-            sampletype = (SOX_IS_BIGENDIAN) ? AFMT_S16_LE : AFMT_S16_BE;
+            sampletype = (MACHINE_IS_BIGENDIAN) ? AFMT_S16_LE : AFMT_S16_BE;
         else
-            sampletype = (SOX_IS_BIGENDIAN) ? AFMT_S16_BE : AFMT_S16_LE;
+            sampletype = (MACHINE_IS_BIGENDIAN) ? AFMT_S16_BE : AFMT_S16_LE;
         samplesize = 16;
         if (ft->encoding.encoding == SOX_ENCODING_UNKNOWN)
             ft->encoding.encoding = SOX_ENCODING_SIGN2;
@@ -78,9 +78,9 @@
     else {
         /* Attempt to use endian that user specified */
         if (ft->encoding.reverse_bytes)
-            sampletype = (SOX_IS_BIGENDIAN) ? AFMT_S16_LE : AFMT_S16_BE;
+            sampletype = (MACHINE_IS_BIGENDIAN) ? AFMT_S16_LE : AFMT_S16_BE;
         else
-            sampletype = (SOX_IS_BIGENDIAN) ? AFMT_S16_BE : AFMT_S16_LE;
+            sampletype = (MACHINE_IS_BIGENDIAN) ? AFMT_S16_BE : AFMT_S16_LE;
         samplesize = 16;
         ft->encoding.bits_per_sample = 16;
         ft->encoding.encoding = SOX_ENCODING_SIGN2;
@@ -92,7 +92,7 @@
 
     if (ioctl(fileno(ft->fp), SNDCTL_DSP_RESET, 0) < 0)
     {
-        sox_fail_errno(ft,SOX_EOF,"Unable to reset OSS driver.  Possibly accessing an invalid file/device");
+        lsx_fail_errno(ft,SOX_EOF,"Unable to reset OSS driver.  Possibly accessing an invalid file/device");
         return(SOX_EOF);
     }
 
@@ -120,7 +120,7 @@
                 ft->encoding.encoding = SOX_ENCODING_SIGN2;
                 sox_report("OSS driver doesn't like unsigned bytes");
                 sox_report("Forcing to signed words");
-                sampletype = (SOX_IS_BIGENDIAN) ? AFMT_S16_BE : AFMT_S16_LE;
+                sampletype = (MACHINE_IS_BIGENDIAN) ? AFMT_S16_BE : AFMT_S16_LE;
                 samplesize = 16;
             }
             /* determine which 16-bit format to use */
@@ -142,7 +142,7 @@
     /* Give up and exit */
     if (rc < 0 || tmp != sampletype)
     {
-        sox_fail_errno(ft,SOX_EOF,"Unable to set the sample size to %d", samplesize);
+        lsx_fail_errno(ft,SOX_EOF,"Unable to set the sample size to %d", samplesize);
         return (SOX_EOF);
     }
 
@@ -189,7 +189,7 @@
     file->size = 0;
     ioctl (fileno(ft->fp), SNDCTL_DSP_GETBLKSIZE, &file->size);
     if (file->size < 4 || file->size > 65536) {
-            sox_fail_errno(ft,SOX_EOF,"Invalid audio buffer size %d", file->size);
+            lsx_fail_errno(ft,SOX_EOF,"Invalid audio buffer size %d", file->size);
             return (SOX_EOF);
     }
     file->count = 0;
@@ -197,7 +197,7 @@
     file->buf = (char *)xmalloc(file->size);
 
     if (ioctl(fileno(ft->fp), SNDCTL_DSP_SYNC, NULL) < 0) {
-        sox_fail_errno(ft,SOX_EOF,"Unable to sync dsp");
+        lsx_fail_errno(ft,SOX_EOF,"Unable to sync dsp");
         return (SOX_EOF);
     }
 
@@ -217,8 +217,8 @@
     SOX_LIB_VERSION_CODE,
     "Open Sound Sytem device driver for unix-like systems",
     names, SOX_FILE_DEVICE,
-    ossinit, sox_rawread, sox_rawstopread,
-    ossinit, sox_rawwrite, sox_rawstopwrite,
+    ossinit, lsx_rawread, lsx_rawstopread,
+    ossinit, lsx_rawwrite, lsx_rawstopwrite,
     NULL, write_encodings, NULL
   };
   return &handler;
--- a/src/pad.c
+++ b/src/pad.c
@@ -44,19 +44,19 @@
   for (i = 0; i < p->npads; ++i) {
     if (argv) /* 1st parse only */
       p->pads[i].str = xstrdup(argv[i]);
-    next = sox_parsesamples(rate, p->pads[i].str, &p->pads[i].pad, 't');
+    next = lsx_parsesamples(rate, p->pads[i].str, &p->pads[i].pad, 't');
     if (next == NULL) break;
     if (*next == '\0')
       p->pads[i].start = i? SOX_SIZE_MAX : 0;
     else {
       if (*next != '@') break;
-      next = sox_parsesamples(rate, next+1, &p->pads[i].start, 't');
+      next = lsx_parsesamples(rate, next+1, &p->pads[i].start, 't');
       if (next == NULL || *next != '\0') break;
     }
     if (i > 0 && p->pads[i].start <= p->pads[i-1].start) break;
   }
   if (i < p->npads)
-    return sox_usage(effp);
+    return lsx_usage(effp);
   return SOX_SUCCESS;
 }
 
--- a/src/pan.c
+++ b/src/pan.c
@@ -36,7 +36,7 @@
     
     if (n && (!sscanf(argv[0], "%lf", &pan->dir) || 
               pan->dir < -1.0 || pan->dir > 1.0))
-      return sox_usage(effp);
+      return lsx_usage(effp);
 
     return SOX_SUCCESS;
 }
--- a/src/phaser.c
+++ b/src/phaser.c
@@ -85,7 +85,7 @@
         phaser_t phaser = (phaser_t) effp->priv;
 
         if (!((n == 5) || (n == 6)))
-          return sox_usage(effp);
+          return lsx_usage(effp);
 
         sscanf(argv[0], "%f", &phaser->in_gain);
         sscanf(argv[1], "%f", &phaser->out_gain);
@@ -99,7 +99,7 @@
                 else if ( ! strcmp(argv[5], "-t"))
                         phaser->modulation = MOD_TRIANGLE;
                 else
-                  return sox_usage(effp);
+                  return lsx_usage(effp);
         }
         return (SOX_SUCCESS);
 }
@@ -157,10 +157,10 @@
         phaser->lookup_tab = (int *) xmalloc(sizeof (int) * phaser->length);
 
         if (phaser->modulation == MOD_SINE)
-          sox_generate_wave_table(SOX_WAVE_SINE, SOX_INT, phaser->lookup_tab,
+          lsx_generate_wave_table(SOX_WAVE_SINE, SOX_INT, phaser->lookup_tab,
               phaser->length, 0., (double)(phaser->maxsamples - 1), 0.);
         else
-          sox_generate_wave_table(SOX_WAVE_TRIANGLE, SOX_INT, phaser->lookup_tab,
+          lsx_generate_wave_table(SOX_WAVE_TRIANGLE, SOX_INT, phaser->lookup_tab,
               phaser->length, 0., (double)(2 * (phaser->maxsamples - 1)), 3 * M_PI_2);
         phaser->counter = 0;
         phaser->phase = 0;
--- a/src/pitch.c
+++ b/src/pitch.c
@@ -252,12 +252,12 @@
     pitch->shift = 0.0; /* default is no change */
 
     if (n && !sscanf(argv[0], "%lf", &pitch->shift))
-      return sox_usage(effp);
+      return lsx_usage(effp);
 
     /* sweep size in ms */
     pitch->width = PITCH_DEFAULT_WIDTH;
     if (n>1 && !sscanf(argv[1], "%lf", &pitch->width))
-      return sox_usage(effp);
+      return lsx_usage(effp);
 
     /* interpole option */
     pitch->interopt = PITCH_INTERPOLE_DEFAULT;
@@ -274,7 +274,7 @@
             pitch->interopt = PITCH_INTERPOLE_CUB;
             break;
         default:
-            return sox_usage(effp);
+            return lsx_usage(effp);
         }
     }
 
@@ -301,7 +301,7 @@
             pitch->fadeopt = PITCH_FADE_COS;
             break;
         default:
-            return sox_usage(effp);
+            return lsx_usage(effp);
         }
     }
     
@@ -308,7 +308,7 @@
     pitch->coef = 0.25;
     if (n>4 && (!sscanf(argv[4], "%lf", &pitch->coef) ||
                 pitch->coef<0.0 || pitch->coef>0.5))
-      return sox_usage(effp);
+      return lsx_usage(effp);
 
     return SOX_SUCCESS;
 }
--- a/src/polyphas.c
+++ b/src/polyphas.c
@@ -354,7 +354,7 @@
 
     effp->out_signal.channels = effp->in_signal.channels;
 
-    rate->lcmrate = sox_lcm((sox_sample_t)effp->in_signal.rate,
+    rate->lcmrate = lsx_lcm((sox_sample_t)effp->in_signal.rate,
                            (sox_sample_t)effp->out_signal.rate);
 
     /* Cursory check for LCM overflow.
--- a/src/prc.c
+++ b/src/prc.c
@@ -74,7 +74,7 @@
 {
   prc_t p = (prc_t)ft->priv;
   if (ft->encoding.encoding == SOX_ENCODING_ALAW)
-    return sox_offset_seek(ft, p->data_start, offset);
+    return lsx_offset_seek(ft, p->data_start, offset);
   return SOX_EOF;
 }
 
@@ -117,7 +117,7 @@
 
 static int prc_checkheader(sox_format_t * ft, char *head)
 {
-  sox_readbuf(ft, head, sizeof(prc_header));
+  lsx_readbuf(ft, head, sizeof(prc_header));
   return memcmp(head, prc_header, sizeof(prc_header)) == 0;
 }
 
@@ -135,29 +135,29 @@
   if (prc_checkheader(ft, head))
     sox_debug("Found Psion Record header");
   else {
-      sox_fail_errno(ft,SOX_EHDR,"Not a Psion Record file");
+      lsx_fail_errno(ft,SOX_EHDR,"Not a Psion Record file");
       return (SOX_EOF);
   }
 
-  sox_readb(ft, &byte);
+  lsx_readb(ft, &byte);
   if ((byte & 0x3) != 0x2) {
-    sox_fail_errno(ft, SOX_EHDR, "Invalid length byte for application name string %d", (int)(byte));
+    lsx_fail_errno(ft, SOX_EHDR, "Invalid length byte for application name string %d", (int)(byte));
     return SOX_EOF;
   }
 
   byte >>= 2;
   assert(byte < 64);
-  sox_reads(ft, appname, byte);
+  lsx_reads(ft, appname, byte);
   if (strncasecmp(appname, "record.app", byte) != 0) {
-    sox_fail_errno(ft, SOX_EHDR, "Invalid application name string %.63s", appname);
+    lsx_fail_errno(ft, SOX_EHDR, "Invalid application name string %.63s", appname);
     return SOX_EOF;
   }
         
-  sox_readdw(ft, &len);
+  lsx_readdw(ft, &len);
   p->nsamp = len;
   sox_debug("Number of samples: %d", len);
 
-  sox_readdw(ft, &encoding);
+  lsx_readdw(ft, &encoding);
   sox_debug("Encoding of samples: %x", encoding);
   if (encoding == 0)
     ft->encoding.encoding = SOX_ENCODING_ALAW;
@@ -164,24 +164,24 @@
   else if (encoding == 0x100001a1)
     ft->encoding.encoding = SOX_ENCODING_IMA_ADPCM;
   else {
-    sox_fail_errno(ft, SOX_EHDR, "Unrecognised encoding");
+    lsx_fail_errno(ft, SOX_EHDR, "Unrecognised encoding");
     return SOX_EOF;
   }
 
-  sox_readw(ft, &reps);    /* Number of repeats */
+  lsx_readw(ft, &reps);    /* Number of repeats */
   sox_debug("Repeats: %d", reps);
         
-  sox_readb(ft, &volume);
+  lsx_readb(ft, &volume);
   sox_debug("Volume: %d", (unsigned)volume);
   if (volume < 1 || volume > 5)
     sox_warn("Volume %d outside range 1..5", volume);
 
-  sox_readb(ft, &byte);   /* Unused and seems always zero */
+  lsx_readb(ft, &byte);   /* Unused and seems always zero */
 
-  sox_readdw(ft, &repgap); /* Time between repeats in usec */
+  lsx_readdw(ft, &repgap); /* Time between repeats in usec */
   sox_debug("Time between repeats (usec): %u", repgap);
 
-  sox_readdw(ft, &listlen); /* Length of samples list */
+  lsx_readdw(ft, &listlen); /* Length of samples list */
   sox_debug("Number of bytes in samples list: %u", listlen);
 
   if (ft->signal.rate != 0 && ft->signal.rate != 8000)
@@ -192,12 +192,12 @@
     sox_report("PRC only supports 1 channel; overriding.");
   ft->signal.channels = 1;
 
-  p->data_start = sox_tell(ft);
+  p->data_start = lsx_tell(ft);
   ft->length = p->nsamp / ft->signal.channels;
 
   if (ft->encoding.encoding == SOX_ENCODING_ALAW) {
     ft->encoding.bits_per_sample = 8;
-    if (sox_rawstartread(ft))
+    if (lsx_rawstartread(ft))
       return SOX_EOF;
   } else if (ft->encoding.encoding == SOX_ENCODING_IMA_ADPCM) {
     p->frame_samp = 0;
@@ -209,7 +209,7 @@
 }
 
 /* Read a variable-length encoded count */
-/* Ignore return code of sox_readb, as it doesn't really matter if EOF
+/* Ignore return code of lsx_readb, as it doesn't really matter if EOF
    is delayed until the caller. */
 static unsigned read_cardinal(sox_format_t * ft)
 {
@@ -216,7 +216,7 @@
   unsigned a;
   uint8_t byte;
 
-  if (sox_readb(ft, &byte) == SOX_EOF)
+  if (lsx_readb(ft, &byte) == SOX_EOF)
     return (unsigned)SOX_EOF;
   sox_debug_more("Cardinal byte 1: %x", byte);
   a = byte;
@@ -223,7 +223,7 @@
   if (!(a & 1))
     a >>= 1;
   else {
-    if (sox_readb(ft, &byte) == SOX_EOF)
+    if (lsx_readb(ft, &byte) == SOX_EOF)
       return (unsigned)SOX_EOF;
     sox_debug_more("Cardinal byte 2: %x", byte);
     a |= byte << 8;
@@ -230,11 +230,11 @@
     if (!(a & 2))
       a >>= 2;
     else if (!(a & 4)) {
-      if (sox_readb(ft, &byte) == SOX_EOF)
+      if (lsx_readb(ft, &byte) == SOX_EOF)
         return (unsigned)SOX_EOF;
       sox_debug_more("Cardinal byte 3: %x", byte);
       a |= byte << 16;
-      if (sox_readb(ft, &byte) == SOX_EOF)
+      if (lsx_readb(ft, &byte) == SOX_EOF)
         return (unsigned)SOX_EOF;
       sox_debug_more("Cardinal byte 4: %x", byte);
       a |= byte << 24;
@@ -267,7 +267,7 @@
       /* Discard length of compressed data */
       sox_debug_more("compressed length %d", read_cardinal(ft));
       /* Discard length of BListL */
-      sox_readdw(ft, &trash);
+      lsx_readdw(ft, &trash);
       sox_debug_more("list length %d", trash);
 
       /* Reset CODEC for start of frame */
@@ -281,7 +281,7 @@
     return read;
   } else {
     p->nsamp += samp;
-    return sox_rawread(ft, buf, samp);
+    return lsx_rawread(ft, buf, samp);
   }
 }
 
@@ -309,7 +309,7 @@
   prc_t p = (prc_t)ft->priv;
 
   if (ft->encoding.encoding == SOX_ENCODING_ALAW) {
-    if (sox_rawstartwrite(ft))
+    if (lsx_rawstartwrite(ft))
       return SOX_EOF;
   } else if (ft->encoding.encoding == SOX_ENCODING_IMA_ADPCM) {
     if (sox_adpcm_ima_start(ft, &p->adpcm))
@@ -323,7 +323,7 @@
 
   prcwriteheader(ft);
 
-  p->data_start = sox_tell(ft);
+  p->data_start = lsx_tell(ft);
 
   return SOX_SUCCESS;
 }
@@ -335,27 +335,27 @@
   if (a < 0x80) {
     byte = a << 1;
     sox_debug_more("Cardinal byte 1: %x", byte);
-    sox_writeb(ft, byte);
+    lsx_writeb(ft, byte);
   } else if (a < 0x8000) {
     byte = (a << 2) | 1;
     sox_debug_more("Cardinal byte 1: %x", byte);
-    sox_writeb(ft, byte);
+    lsx_writeb(ft, byte);
     byte = a >> 6;
     sox_debug_more("Cardinal byte 2: %x", byte);
-    sox_writeb(ft, byte);
+    lsx_writeb(ft, byte);
   } else {
     byte = (a << 3) | 3;
     sox_debug_more("Cardinal byte 1: %x", byte);
-    sox_writeb(ft, byte);
+    lsx_writeb(ft, byte);
     byte = a >> 5;
     sox_debug_more("Cardinal byte 2: %x", byte);
-    sox_writeb(ft, byte);
+    lsx_writeb(ft, byte);
     byte = a >> 13;
     sox_debug_more("Cardinal byte 3: %x", byte);
-    sox_writeb(ft, byte);
+    lsx_writeb(ft, byte);
     byte = a >> 21;
     sox_debug_more("Cardinal byte 4: %x", byte);
-    sox_writeb(ft, byte);
+    lsx_writeb(ft, byte);
   }
 }
 
@@ -373,7 +373,7 @@
     write_cardinal(ft, (samp / 2) + (samp % 2) + 4);
     /* Write length again (seems to be a BListL) */
     sox_debug_more("list length %d", samp);
-    sox_writedw(ft, samp);
+    lsx_writedw(ft, samp);
     sox_adpcm_reset(&p->adpcm, ft->encoding.encoding);
     written1 = sox_adpcm_write(ft, &p->adpcm, buf, samp);
     if (written1 != samp)
@@ -381,7 +381,7 @@
     sox_adpcm_flush(ft, &p->adpcm);
     written += written1;
   } else
-    written = sox_rawwrite(ft, buf, nsamp);
+    written = lsx_rawwrite(ft, buf, nsamp);
   p->nsamp += written;
   return written;
 }
@@ -390,7 +390,7 @@
 {
   prc_t p = (prc_t)ft->priv;
 
-  p->nbytes = sox_tell(ft) - p->data_start;
+  p->nbytes = lsx_tell(ft) - p->data_start;
 
   if (!ft->seekable) {
       sox_warn("Header will have invalid file length since file is not seekable");
@@ -397,8 +397,8 @@
       return SOX_SUCCESS;
   }
 
-  if (sox_seeki(ft, 0, 0) != 0) {
-      sox_fail_errno(ft,errno,"Can't rewind output file to rewrite Psion header.");
+  if (lsx_seeki(ft, 0, 0) != 0) {
+      lsx_fail_errno(ft,errno,"Can't rewind output file to rewrite Psion header.");
       return(SOX_EOF);
   }
   prcwriteheader(ft);
@@ -409,24 +409,24 @@
 {
   prc_t p = (prc_t)ft->priv;
 
-  sox_writebuf(ft, prc_header, sizeof(prc_header));
-  sox_writes(ft, "\x2arecord.app");
+  lsx_writebuf(ft, prc_header, sizeof(prc_header));
+  lsx_writes(ft, "\x2arecord.app");
 
   sox_debug("Number of samples: %d",p->nsamp);
-  sox_writedw(ft, p->nsamp);
+  lsx_writedw(ft, p->nsamp);
 
   if (ft->encoding.encoding == SOX_ENCODING_ALAW)
-    sox_writedw(ft, 0);
+    lsx_writedw(ft, 0);
   else
-    sox_writedw(ft, 0x100001a1); /* ADPCM */
+    lsx_writedw(ft, 0x100001a1); /* ADPCM */
   
-  sox_writew(ft, 0);             /* Number of repeats */
-  sox_writeb(ft, 3);             /* Volume: use default value of Record.app */
-  sox_writeb(ft, 0);             /* Unused and seems always zero */
-  sox_writedw(ft, 0);            /* Time between repeats in usec */
+  lsx_writew(ft, 0);             /* Number of repeats */
+  lsx_writeb(ft, 3);             /* Volume: use default value of Record.app */
+  lsx_writeb(ft, 0);             /* Unused and seems always zero */
+  lsx_writedw(ft, 0);            /* Time between repeats in usec */
 
   sox_debug("Number of bytes: %d", p->nbytes);
-  sox_writedw(ft, p->nbytes);    /* Number of bytes of data */
+  lsx_writedw(ft, p->nbytes);    /* Number of bytes of data */
 }
 
 SOX_FORMAT_HANDLER(prc)
--- a/src/rabbit.c
+++ b/src/rabbit.c
@@ -68,11 +68,11 @@
   r->out_rate = HUGE_VAL;
   if (argc) {
     if (sscanf(*argv, "%lf %c", &r->out_rate, &dummy) != 1 || r->out_rate <= 0) 
-      return sox_usage(effp);
+      return lsx_usage(effp);
     argc--; argv++;
   }
 
-  return argc? sox_usage(effp) : SOX_SUCCESS;
+  return argc? lsx_usage(effp) : SOX_SUCCESS;
 }
 
 /*
--- a/src/raw-fmt.c
+++ b/src/raw-fmt.c
@@ -19,7 +19,7 @@
 #include "sox_i.h"
  
 static int raw_start(sox_format_t * ft) {
-  return sox_rawstart(ft, sox_false, sox_false, sox_true, SOX_ENCODING_UNKNOWN, 0);
+  return lsx_rawstart(ft, sox_false, sox_false, sox_true, SOX_ENCODING_UNKNOWN, 0);
 }
 
 SOX_FORMAT_HANDLER(raw)
@@ -36,9 +36,9 @@
     SOX_LIB_VERSION_CODE,
     "Raw PCM, mu-law, or A-law",
     names, 0,
-    raw_start, sox_rawread , NULL,
-    raw_start, sox_rawwrite, NULL,
-    sox_rawseek, encodings, NULL
+    raw_start, lsx_rawread , NULL,
+    raw_start, lsx_rawwrite, NULL,
+    lsx_rawseek, encodings, NULL
   };
   return &handler;
 }
--- a/src/raw.c
+++ b/src/raw.c
@@ -20,14 +20,14 @@
 #define SOX_SAMPLE_TO_ULAW_BYTE(d,c) sox_14linear2ulaw(SOX_SAMPLE_TO_SIGNED_16BIT(d,c) >> 2)
 #define SOX_SAMPLE_TO_ALAW_BYTE(d,c) sox_13linear2alaw(SOX_SAMPLE_TO_SIGNED_16BIT(d,c) >> 3)
 
-int sox_rawseek(sox_format_t * ft, sox_size_t offset)
+int lsx_rawseek(sox_format_t * ft, sox_size_t offset)
 {
-  return sox_offset_seek(ft, ft->data_start, offset);
+  return lsx_offset_seek(ft, ft->data_start, offset);
 }
 
-/* Works nicely for starting read and write; sox_rawstart{read,write}
+/* Works nicely for starting read and write; lsx_rawstart{read,write}
    are #defined in sox_i.h */
-int sox_rawstart(sox_format_t * ft, sox_bool default_rate, sox_bool default_channels, sox_bool default_length, sox_encoding_t encoding, unsigned size)
+int lsx_rawstart(sox_format_t * ft, sox_bool default_rate, sox_bool default_channels, sox_bool default_length, sox_encoding_t encoding, unsigned size)
 {
   if (default_rate && ft->signal.rate == 0) {
     sox_warn("'%s': sample rate not specified; trying 8kHz", ft->filename);
@@ -54,18 +54,18 @@
   }
 
   if (!ft->length && ft->mode == 'r' && default_length && ft->encoding.bits_per_sample)
-    ft->length = div_bits(sox_filelength(ft), ft->encoding.bits_per_sample);
+    ft->length = div_bits(lsx_filelength(ft), ft->encoding.bits_per_sample);
 
   return SOX_SUCCESS;
 }
 
 #define READ_SAMPLES_FUNC(type, size, sign, ctype, uctype, cast) \
-  sox_size_t sox_read_ ## sign ## type ## _samples( \
+  static sox_size_t sox_read_ ## sign ## type ## _samples( \
       sox_format_t * ft, sox_sample_t *buf, sox_size_t len) \
   { \
     sox_size_t n, nread; \
     ctype *data = xmalloc(sizeof(ctype) * len); \
-    nread = sox_read_ ## type ## _buf(ft, (uctype *)data, len); \
+    nread = lsx_read_ ## type ## _buf(ft, (uctype *)data, len); \
     for (n = 0; n < nread; n++) \
       *buf++ = cast(data[n], ft->clips); \
     free(data); \
@@ -72,21 +72,21 @@
     return nread; \
   }
 
-static READ_SAMPLES_FUNC(b, 1, u, uint8_t, uint8_t, SOX_UNSIGNED_8BIT_TO_SAMPLE)
-static READ_SAMPLES_FUNC(b, 1, s, int8_t, uint8_t, SOX_SIGNED_8BIT_TO_SAMPLE)
-static READ_SAMPLES_FUNC(b, 1, ulaw, uint8_t, uint8_t, SOX_ULAW_BYTE_TO_SAMPLE)
-static READ_SAMPLES_FUNC(b, 1, alaw, uint8_t, uint8_t, SOX_ALAW_BYTE_TO_SAMPLE)
-static READ_SAMPLES_FUNC(w, 2, u, uint16_t, uint16_t, SOX_UNSIGNED_16BIT_TO_SAMPLE)
-static READ_SAMPLES_FUNC(w, 2, s, int16_t, uint16_t, SOX_SIGNED_16BIT_TO_SAMPLE)
-static READ_SAMPLES_FUNC(3, 3, u, uint24_t, uint24_t, SOX_UNSIGNED_24BIT_TO_SAMPLE)
-static READ_SAMPLES_FUNC(3, 3, s, int24_t, uint24_t, SOX_SIGNED_24BIT_TO_SAMPLE)
-static READ_SAMPLES_FUNC(dw, 4, u, uint32_t, uint32_t, SOX_UNSIGNED_32BIT_TO_SAMPLE)
-static READ_SAMPLES_FUNC(dw, 4, s, int32_t, uint32_t, SOX_SIGNED_32BIT_TO_SAMPLE)
-static READ_SAMPLES_FUNC(f, sizeof(float), su, float, float, SOX_FLOAT_32BIT_TO_SAMPLE)
-static READ_SAMPLES_FUNC(df, sizeof(double), su, double, double, SOX_FLOAT_64BIT_TO_SAMPLE)
+READ_SAMPLES_FUNC(b, 1, u, uint8_t, uint8_t, SOX_UNSIGNED_8BIT_TO_SAMPLE)
+READ_SAMPLES_FUNC(b, 1, s, int8_t, uint8_t, SOX_SIGNED_8BIT_TO_SAMPLE)
+READ_SAMPLES_FUNC(b, 1, ulaw, uint8_t, uint8_t, SOX_ULAW_BYTE_TO_SAMPLE)
+READ_SAMPLES_FUNC(b, 1, alaw, uint8_t, uint8_t, SOX_ALAW_BYTE_TO_SAMPLE)
+READ_SAMPLES_FUNC(w, 2, u, uint16_t, uint16_t, SOX_UNSIGNED_16BIT_TO_SAMPLE)
+READ_SAMPLES_FUNC(w, 2, s, int16_t, uint16_t, SOX_SIGNED_16BIT_TO_SAMPLE)
+READ_SAMPLES_FUNC(3, 3, u, uint24_t, uint24_t, SOX_UNSIGNED_24BIT_TO_SAMPLE)
+READ_SAMPLES_FUNC(3, 3, s, int24_t, uint24_t, SOX_SIGNED_24BIT_TO_SAMPLE)
+READ_SAMPLES_FUNC(dw, 4, u, uint32_t, uint32_t, SOX_UNSIGNED_32BIT_TO_SAMPLE)
+READ_SAMPLES_FUNC(dw, 4, s, int32_t, uint32_t, SOX_SIGNED_32BIT_TO_SAMPLE)
+READ_SAMPLES_FUNC(f, sizeof(float), su, float, float, SOX_FLOAT_32BIT_TO_SAMPLE)
+READ_SAMPLES_FUNC(df, sizeof(double), su, double, double, SOX_FLOAT_64BIT_TO_SAMPLE)
 
 #define WRITE_SAMPLES_FUNC(type, size, sign, ctype, uctype, cast) \
-  sox_size_t sox_write_ ## sign ## type ## _samples( \
+  static sox_size_t sox_write_ ## sign ## type ## _samples( \
       sox_format_t * ft, sox_sample_t *buf, sox_size_t len) \
   { \
     sox_size_t n, nwritten; \
@@ -93,23 +93,23 @@
     ctype *data = xmalloc(sizeof(ctype) * len); \
     for (n = 0; n < len; n++) \
       data[n] = cast(buf[n], ft->clips); \
-    nwritten = sox_write_ ## type ## _buf(ft, (uctype *)data, len); \
+    nwritten = lsx_write_ ## type ## _buf(ft, (uctype *)data, len); \
     free(data); \
     return nwritten; \
   }
 
-static WRITE_SAMPLES_FUNC(b, 1, u, uint8_t, uint8_t, SOX_SAMPLE_TO_UNSIGNED_8BIT)
-static WRITE_SAMPLES_FUNC(b, 1, s, int8_t, uint8_t, SOX_SAMPLE_TO_SIGNED_8BIT)
-static WRITE_SAMPLES_FUNC(b, 1, ulaw, uint8_t, uint8_t, SOX_SAMPLE_TO_ULAW_BYTE)
-static WRITE_SAMPLES_FUNC(b, 1, alaw, uint8_t, uint8_t, SOX_SAMPLE_TO_ALAW_BYTE)
-static WRITE_SAMPLES_FUNC(w, 2, u, uint16_t, uint16_t, SOX_SAMPLE_TO_UNSIGNED_16BIT)
-static WRITE_SAMPLES_FUNC(w, 2, s, int16_t, uint16_t, SOX_SAMPLE_TO_SIGNED_16BIT)
-static WRITE_SAMPLES_FUNC(3, 3, u, uint24_t, uint24_t, SOX_SAMPLE_TO_UNSIGNED_24BIT)
-static WRITE_SAMPLES_FUNC(3, 3, s, int24_t, uint24_t, SOX_SAMPLE_TO_SIGNED_24BIT)
-static WRITE_SAMPLES_FUNC(dw, 4, u, uint32_t, uint32_t, SOX_SAMPLE_TO_UNSIGNED_32BIT)
-static WRITE_SAMPLES_FUNC(dw, 4, s, int32_t, uint32_t, SOX_SAMPLE_TO_SIGNED_32BIT)
-static WRITE_SAMPLES_FUNC(f, sizeof(float), su, float, float, SOX_SAMPLE_TO_FLOAT_32BIT)
-static WRITE_SAMPLES_FUNC(df, sizeof(double), su, double, double, SOX_SAMPLE_TO_FLOAT_64BIT)
+WRITE_SAMPLES_FUNC(b, 1, u, uint8_t, uint8_t, SOX_SAMPLE_TO_UNSIGNED_8BIT)
+WRITE_SAMPLES_FUNC(b, 1, s, int8_t, uint8_t, SOX_SAMPLE_TO_SIGNED_8BIT)
+WRITE_SAMPLES_FUNC(b, 1, ulaw, uint8_t, uint8_t, SOX_SAMPLE_TO_ULAW_BYTE)
+WRITE_SAMPLES_FUNC(b, 1, alaw, uint8_t, uint8_t, SOX_SAMPLE_TO_ALAW_BYTE)
+WRITE_SAMPLES_FUNC(w, 2, u, uint16_t, uint16_t, SOX_SAMPLE_TO_UNSIGNED_16BIT)
+WRITE_SAMPLES_FUNC(w, 2, s, int16_t, uint16_t, SOX_SAMPLE_TO_SIGNED_16BIT)
+WRITE_SAMPLES_FUNC(3, 3, u, uint24_t, uint24_t, SOX_SAMPLE_TO_UNSIGNED_24BIT)
+WRITE_SAMPLES_FUNC(3, 3, s, int24_t, uint24_t, SOX_SAMPLE_TO_SIGNED_24BIT)
+WRITE_SAMPLES_FUNC(dw, 4, u, uint32_t, uint32_t, SOX_SAMPLE_TO_UNSIGNED_32BIT)
+WRITE_SAMPLES_FUNC(dw, 4, s, int32_t, uint32_t, SOX_SAMPLE_TO_SIGNED_32BIT)
+WRITE_SAMPLES_FUNC(f, sizeof(float), su, float, float, SOX_SAMPLE_TO_FLOAT_32BIT)
+WRITE_SAMPLES_FUNC(df, sizeof(double), su, double, double, SOX_SAMPLE_TO_FLOAT_64BIT)
 
 typedef sox_size_t (ft_io_fun)(sox_format_t * ft, sox_sample_t *buf, sox_size_t len);
 
@@ -176,16 +176,16 @@
       break;
 
     default:
-      sox_fail_errno(ft,SOX_EFMT,"this handler does not support this data size");
+      lsx_fail_errno(ft,SOX_EFMT,"this handler does not support this data size");
       return NULL;
     }
 
-    sox_fail_errno(ft,SOX_EFMT,"this encoding is not supported for this data size");
+    lsx_fail_errno(ft,SOX_EFMT,"this encoding is not supported for this data size");
     return NULL;
 }
 
 /* Read a stream of some type into SoX's internal buffer format. */
-sox_size_t sox_rawread(sox_format_t * ft, sox_sample_t *buf, sox_size_t nsamp)
+sox_size_t lsx_rawread(sox_format_t * ft, sox_sample_t *buf, sox_size_t nsamp)
 {
     ft_io_fun * read_buf = check_format(ft, sox_false);
 
@@ -196,7 +196,7 @@
 }
 
 /* Writes SoX's internal buffer format to buffer of various data types. */
-sox_size_t sox_rawwrite(sox_format_t * ft, const sox_sample_t *buf, sox_size_t nsamp)
+sox_size_t lsx_rawwrite(sox_format_t * ft, const sox_sample_t *buf, sox_size_t nsamp)
 {
     ft_io_fun *write_buf = check_format(ft, sox_true);
 
--- a/src/raw.h
+++ b/src/raw.h
@@ -18,7 +18,7 @@
 
 #define RAW_FORMAT0(id, size, flags, encoding) \
 static int id ## _start(sox_format_t * ft) { \
-  return sox_rawstart(ft, sox_true, sox_true, sox_true, SOX_ENCODING_ ## encoding, size); \
+  return lsx_rawstart(ft, sox_true, sox_true, sox_true, SOX_ENCODING_ ## encoding, size); \
 } \
 const sox_format_handler_t *sox_ ## id ## _format_fn(void); \
 const sox_format_handler_t *sox_ ## id ## _format_fn(void) { \
@@ -27,8 +27,8 @@
   static sox_format_handler_t handler = { \
     SOX_LIB_VERSION_CODE, "Raw audio", \
     names, flags, \
-    id ## _start, sox_rawread , NULL, \
-    id ## _start, sox_rawwrite, NULL, \
+    id ## _start, lsx_rawread , NULL, \
+    id ## _start, lsx_rawwrite, NULL, \
     NULL, write_encodings, NULL \
   }; \
   return &handler; \
--- a/src/remix.c
+++ b/src/remix.c
@@ -46,7 +46,7 @@
     SEP = (SEPARATORS)[strlen(SEPARATORS) - 1]; \
     n = sscanf(text, SCAN"%c", &VAR, &SEP); \
     if (VAR < MIN || (n == 2 && !strchr(SEPARATORS, SEP))) \
-      return sox_usage(effp); \
+      return lsx_usage(effp); \
     text = end? end + 1 : text + strlen(text); \
   } \
 } while (0)
@@ -71,7 +71,7 @@
       PARSE(sep1, "%i", chan1, 0, separators);
       if (!chan1) {
        if (j || *text)
-         return sox_usage(effp);
+         return lsx_usage(effp);
        continue;
       }
       if (sep1 == '-')
--- a/src/repeat.c
+++ b/src/repeat.c
@@ -37,7 +37,7 @@
         repeat_t repeat = (repeat_t)effp->priv;
 
         if (n != 1)
-          return sox_usage(effp);
+          return lsx_usage(effp);
 
         if (!(sscanf(argv[0], "%i", &repeat->repeats))) {
                 sox_fail("could not parse repeat parameter");
--- a/src/resample.c
+++ b/src/resample.c
@@ -169,7 +169,7 @@
         }
 
         if ((n >= 1) && (sscanf(argv[0], "%lf", &r->rolloff) != 1)) {
-          return sox_usage(effp);
+          return lsx_usage(effp);
         } else if ((r->rolloff <= 0.01) || (r->rolloff >= 1.0)) {
           sox_fail("rolloff factor (%f) no good, should be 0.01<x<1.0", r->rolloff);
           return(SOX_EOF);
@@ -177,7 +177,7 @@
 
 
         if ((n >= 2) && !sscanf(argv[1], "%lf", &r->beta)) {
-          return sox_usage(effp);
+          return lsx_usage(effp);
         } else if (r->beta <= 2.0) {
         	r->beta = 0;
                 sox_debug("opts: Nuttall window, cutoff %f", r->rolloff);
@@ -202,7 +202,7 @@
 
   r->Factor = effp->out_signal.rate / effp->in_signal.rate;
 
-  gcdrate = sox_gcd((long) effp->in_signal.rate, (long) effp->out_signal.rate);
+  gcdrate = lsx_gcd((long) effp->in_signal.rate, (long) effp->out_signal.rate);
   r->a = effp->in_signal.rate / gcdrate;
   r->b = effp->out_signal.rate / gcdrate;
 
--- a/src/reverb.c
+++ b/src/reverb.c
@@ -193,7 +193,7 @@
     NUMERIC_PARAMETER(wet_gain_dB, -10, 10)
   } while (0);
 
-  return argc ? sox_usage(effp) : SOX_SUCCESS;
+  return argc ? lsx_usage(effp) : SOX_SUCCESS;
 }
 
 static int start(sox_effect_t * effp)
--- a/src/sf.c
+++ b/src/sf.c
@@ -23,13 +23,13 @@
 
 /* Magic numbers used in IRCAM audio files */
 static struct {char str[4]; sox_bool reverse_bytes; char const * desc;} id[] = {
-  {"\144\243\001\0", SOX_IS_BIGENDIAN   , "little-endian VAX (native)"},
-  {"\0\001\243\144", SOX_IS_LITTLEENDIAN, "big-endian VAX"},
-  {"\144\243\002\0", SOX_IS_LITTLEENDIAN, "big-endian Sun (native)"},
-  {"\0\002\243\144", SOX_IS_BIGENDIAN   , "little-endian Sun"},
-  {"\144\243\003\0", SOX_IS_BIGENDIAN   , "little-endian MIPS (DEC)"},
-  {"\0\003\243\144", SOX_IS_LITTLEENDIAN, "big-endian MIPS (SGI)"},
-  {"\144\243\004\0", SOX_IS_LITTLEENDIAN, "big-endian NeXT"},
+  {"\144\243\001\0", MACHINE_IS_BIGENDIAN   , "little-endian VAX (native)"},
+  {"\0\001\243\144", MACHINE_IS_LITTLEENDIAN, "big-endian VAX"},
+  {"\144\243\002\0", MACHINE_IS_LITTLEENDIAN, "big-endian Sun (native)"},
+  {"\0\002\243\144", MACHINE_IS_BIGENDIAN   , "little-endian Sun"},
+  {"\144\243\003\0", MACHINE_IS_BIGENDIAN   , "little-endian MIPS (DEC)"},
+  {"\0\003\243\144", MACHINE_IS_LITTLEENDIAN, "big-endian MIPS (SGI)"},
+  {"\144\243\004\0", MACHINE_IS_LITTLEENDIAN, "big-endian NeXT"},
   {"    ", 0, NULL}
 };
 #define FIXED_HDR     1024
@@ -77,60 +77,60 @@
   sox_encoding_t encoding;
   uint16_t code, size;
 
-  if (sox_readchars(ft, magic, sizeof(magic)))
+  if (lsx_readchars(ft, magic, sizeof(magic)))
     return SOX_EOF;
  
   for (i = 0; id[i].desc && memcmp(magic, id[i].str, sizeof(magic)); ++i);
   if (!id[i].desc) {
-    sox_fail_errno(ft, SOX_EHDR, "sf: can't find IRCAM identifier");
+    lsx_fail_errno(ft, SOX_EHDR, "sf: can't find IRCAM identifier");
     return SOX_EOF;
   }
   sox_report("found %s identifier", id[i].desc);
   ft->encoding.reverse_bytes = id[i].reverse_bytes;
 
-  if (sox_readf(ft, &rate) || sox_readdw(ft, &channels) || sox_readdw(ft, &ft_encoding))
+  if (lsx_readf(ft, &rate) || lsx_readdw(ft, &channels) || lsx_readdw(ft, &ft_encoding))
     return SOX_EOF;
   
   if (!(encoding = sox_enc(ft_encoding, &bits_per_sample))) {
-    sox_fail_errno(ft, SOX_EFMT, "sf: unsupported encoding %#x)", ft_encoding);
+    lsx_fail_errno(ft, SOX_EFMT, "sf: unsupported encoding %#x)", ft_encoding);
     return SOX_EOF;
   }
   do {
-    if (sox_readw(ft, &code) || sox_readw(ft, &size))
+    if (lsx_readw(ft, &code) || lsx_readw(ft, &size))
       return SOX_EOF;
     if (code == SF_COMMENT) {
       char * buf = xcalloc(1, (size_t)size + 1); /* +1 ensures null-terminated */
-      if (sox_readchars(ft, buf, size) != SOX_SUCCESS) {
+      if (lsx_readchars(ft, buf, size) != SOX_SUCCESS) {
         free(buf);
         return SOX_EOF;
       }
-      append_comments(&ft->comments, buf);
+      sox_append_comments(&ft->comments, buf);
       free(buf);
     }
-    else if (sox_skipbytes(ft, size))
+    else if (lsx_skipbytes(ft, size))
       return SOX_EOF;
   } while (code);
-  if (sox_skipbytes(ft, FIXED_HDR - (sox_size_t)sox_tell(ft)))
+  if (lsx_skipbytes(ft, FIXED_HDR - (sox_size_t)lsx_tell(ft)))
     return SOX_EOF;
   
-  return sox_check_read_params(ft, channels, rate, encoding, bits_per_sample, (off_t)0);
+  return lsx_check_read_params(ft, channels, rate, encoding, bits_per_sample, (off_t)0);
 }
 
 static int write_header(sox_format_t * ft)
 {
-  char * comment  = cat_comments(ft->comments);
+  char * comment  = sox_cat_comments(ft->comments);
   size_t len      = min(FIXED_HDR - 26, strlen(comment)) + 1; /* null-terminated */
   size_t info_len = max(4, (len + 3) & ~3u); /* Minimum & multiple of 4 bytes */
-  int i = ft->encoding.reverse_bytes == SOX_IS_BIGENDIAN? 0 : 2;
+  int i = ft->encoding.reverse_bytes == MACHINE_IS_BIGENDIAN? 0 : 2;
   sox_bool error  = sox_false
-  ||sox_writechars(ft, id[i].str, sizeof(id[i].str))
-  ||sox_writef(ft, ft->signal.rate)
-  ||sox_writedw(ft, ft->signal.channels)
-  ||sox_writedw(ft, ft_enc(ft->encoding.bits_per_sample, ft->encoding.encoding))
-  ||sox_writew(ft, SF_COMMENT)
-  ||sox_writew(ft, info_len)
-  ||sox_writechars(ft, comment, len)
-  ||sox_padbytes(ft, FIXED_HDR - 20 - len);
+  ||lsx_writechars(ft, id[i].str, sizeof(id[i].str))
+  ||lsx_writef(ft, ft->signal.rate)
+  ||lsx_writedw(ft, ft->signal.channels)
+  ||lsx_writedw(ft, ft_enc(ft->encoding.bits_per_sample, ft->encoding.encoding))
+  ||lsx_writew(ft, SF_COMMENT)
+  ||lsx_writew(ft, info_len)
+  ||lsx_writechars(ft, comment, len)
+  ||lsx_padbytes(ft, FIXED_HDR - 20 - len);
   free(comment);
   return error? SOX_EOF: SOX_SUCCESS;
 }
@@ -147,9 +147,9 @@
   static sox_format_handler_t const handler = {SOX_LIB_VERSION_CODE,
     "Institut de Recherche et Coordination Acoustique/Musique",
     names, SOX_FILE_LIT_END,
-    startread, sox_rawread, NULL,
-    write_header, sox_rawwrite, NULL,
-    sox_rawseek, write_encodings, NULL
+    startread, lsx_rawread, NULL,
+    write_header, lsx_rawwrite, NULL,
+    lsx_rawseek, write_encodings, NULL
   };
   return &handler;
 }
--- a/src/silence.c
+++ b/src/silence.c
@@ -94,12 +94,12 @@
     }
 
     if (n < 1)
-      return sox_usage(effp);
+      return lsx_usage(effp);
 
     /* Parse data related to trimming front side */
     silence->start = sox_false;
     if (sscanf(argv[0], "%d", &silence->start_periods) != 1)
-      return sox_usage(effp);
+      return lsx_usage(effp);
     if (silence->start_periods < 0)
     {
         sox_fail("Periods must not be negative");
@@ -112,7 +112,7 @@
     {
         silence->start = sox_true;
         if (n < 2)
-          return sox_usage(effp);
+          return lsx_usage(effp);
 
         /* We do not know the sample rate so we can not fully
          * parse the duration info yet.  So save argument off
@@ -121,14 +121,14 @@
         silence->start_duration_str = (char *)xmalloc(strlen(argv[0])+1);
         strcpy(silence->start_duration_str,argv[0]);
         /* Perform a fake parse to do error checking */
-        if (sox_parsesamples(0.,silence->start_duration_str,
+        if (lsx_parsesamples(0.,silence->start_duration_str,
                     &silence->start_duration,'s') == NULL)
-          return sox_usage(effp);
+          return lsx_usage(effp);
 
         parse_count = sscanf(argv[1], "%lf%c", &silence->start_threshold, 
                 &silence->start_unit);
         if (parse_count < 1)
-          return sox_usage(effp);
+          return lsx_usage(effp);
         else if (parse_count < 2)
             silence->start_unit = '%';
 
@@ -141,9 +141,9 @@
     if (n > 0)
     {
         if (n < 3)
-          return sox_usage(effp);
+          return lsx_usage(effp);
         if (sscanf(argv[0], "%d", &silence->stop_periods) != 1)
-          return sox_usage(effp);
+          return lsx_usage(effp);
         if (silence->stop_periods < 0)
         {
             silence->stop_periods = -silence->stop_periods;
@@ -162,14 +162,14 @@
         silence->stop_duration_str = (char *)xmalloc(strlen(argv[0])+1);
         strcpy(silence->stop_duration_str,argv[0]);
         /* Perform a fake parse to do error checking */
-        if (sox_parsesamples(0.,silence->stop_duration_str,
+        if (lsx_parsesamples(0.,silence->stop_duration_str,
                     &silence->stop_duration,'s') == NULL)
-          return sox_usage(effp);
+          return lsx_usage(effp);
 
         parse_count = sscanf(argv[1], "%lf%c", &silence->stop_threshold, 
                              &silence->stop_unit);
         if (parse_count < 1)
-          return sox_usage(effp);
+          return lsx_usage(effp);
         else if (parse_count < 2)
             silence->stop_unit = '%';
 
@@ -183,7 +183,7 @@
         if ((silence->start_unit != '%') && (silence->start_unit != 'd'))
         {
             sox_fail("Invalid unit specified");
-            return sox_usage(effp);
+            return lsx_usage(effp);
         }
         if ((silence->start_unit == '%') && ((silence->start_threshold < 0.0)
             || (silence->start_threshold > 100.0)))
@@ -238,15 +238,15 @@
         /* Now that we know sample rate, reparse duration. */
         if (silence->start)
         {
-            if (sox_parsesamples(effp->in_signal.rate, silence->start_duration_str,
+            if (lsx_parsesamples(effp->in_signal.rate, silence->start_duration_str,
                                 &silence->start_duration, 's') == NULL)
-              return sox_usage(effp);
+              return lsx_usage(effp);
         }
         if (silence->stop)
         {
-            if (sox_parsesamples(effp->in_signal.rate,silence->stop_duration_str,
+            if (lsx_parsesamples(effp->in_signal.rate,silence->stop_duration_str,
                                 &silence->stop_duration,'s') == NULL)
-              return sox_usage(effp);
+              return lsx_usage(effp);
         }
 
         if (silence->start)
--- a/src/skeleff.c
+++ b/src/skeleff.c
@@ -38,7 +38,7 @@
   skeleff_t UNUSED skeleff = (skeleff_t)effp->priv;
 
   if (n && n != 1)
-    return sox_usage(effp);
+    return lsx_usage(effp);
 
   return SOX_SUCCESS;
 }
--- a/src/skelform.c
+++ b/src/skelform.c
@@ -48,7 +48,7 @@
 
   /* If you need to seek around the input file. */
   if (!ft->seekable) {
-    sox_fail_errno(ft, SOX_EOF, "skel inputfile must be a file");
+    lsx_fail_errno(ft, SOX_EOF, "skel inputfile must be a file");
     return SOX_EOF;
   }
 
@@ -62,12 +62,12 @@
   ft->signal.channels = 1; /* or 2 or 3 ... */
   ft->encoding.bits_per_sample = 8; /* or 16 ... */
   ft->encoding.encoding = SOX_ENCODING_UNSIGNED; /* or SIGN2 ... */
-  append_comment(&ft->comments, "any comment in file header.");
+  sox_append_comment(&ft->comments, "any comment in file header.");
 
   /* If your format doesn't have a header then samples_in_file
    * can be determined by the file size.
    */
-  samples_in_file = sox_filelength(ft) / (ft->encoding.bits_per_sample >> 3);
+  samples_in_file = lsx_filelength(ft) / (ft->encoding.bits_per_sample >> 3);
 
   /* If you can detect the length of your file, record it here. */
   ft->length = samples_in_file;
@@ -165,7 +165,7 @@
   case 8:
     switch (ft->encoding.encoding) {
     case SOX_ENCODING_UNSIGNED:
-      while (done < len && sox_writeb(ft, SOX_SAMPLE_TO_UNSIGNED_8BIT(*buf++, ft->clips)) == SOX_SUCCESS)
+      while (done < len && lsx_writeb(ft, SOX_SAMPLE_TO_UNSIGNED_8BIT(*buf++, ft->clips)) == SOX_SUCCESS)
         ++done;
       break;
     default:
--- a/src/smp.c
+++ b/src/smp.c
@@ -78,31 +78,31 @@
         int i;
         int16_t trash16;
 
-        sox_readw(ft, (unsigned short *)&trash16); /* read reserved word */
+        lsx_readw(ft, (unsigned short *)&trash16); /* read reserved word */
         for(i = 0; i < 8; i++) {        /* read the 8 loops */
-                sox_readdw(ft, &(trailer->loops[i].start));
+                lsx_readdw(ft, &(trailer->loops[i].start));
                 ft->loops[i].start = trailer->loops[i].start;
-                sox_readdw(ft, &(trailer->loops[i].end));
+                lsx_readdw(ft, &(trailer->loops[i].end));
                 ft->loops[i].length = 
                         trailer->loops[i].end - trailer->loops[i].start;
-                sox_readb(ft, (unsigned char *)&(trailer->loops[i].type));
+                lsx_readb(ft, (unsigned char *)&(trailer->loops[i].type));
                 ft->loops[i].type = trailer->loops[i].type;
-                sox_readw(ft, (unsigned short *)&(trailer->loops[i].count));
+                lsx_readw(ft, (unsigned short *)&(trailer->loops[i].count));
                 ft->loops[i].count = trailer->loops[i].count;
         }
         for(i = 0; i < 8; i++) {        /* read the 8 markers */
-                if (sox_readbuf(ft, trailer->markers[i].name, MARKERLEN) != MARKERLEN)
+                if (lsx_readbuf(ft, trailer->markers[i].name, MARKERLEN) != MARKERLEN)
                 {
-                    sox_fail_errno(ft,SOX_EHDR,"EOF in SMP");
+                    lsx_fail_errno(ft,SOX_EHDR,"EOF in SMP");
                     return(SOX_EOF);
                 }
                 trailer->markers[i].name[MARKERLEN] = 0;
-                sox_readdw(ft, &(trailer->markers[i].position));
+                lsx_readdw(ft, &(trailer->markers[i].position));
         }
-        sox_readb(ft, (unsigned char *)&(trailer->MIDInote));
-        sox_readdw(ft, &(trailer->rate));
-        sox_readdw(ft, &(trailer->SMPTEoffset));
-        sox_readdw(ft, &(trailer->CycleSize));
+        lsx_readb(ft, (unsigned char *)&(trailer->MIDInote));
+        lsx_readdw(ft, &(trailer->rate));
+        lsx_readdw(ft, &(trailer->SMPTEoffset));
+        lsx_readdw(ft, &(trailer->CycleSize));
         return(SOX_SUCCESS);
 }
 
@@ -147,25 +147,25 @@
 {
         int i;
 
-        sox_writew(ft, 0);                       /* write the reserved word */
+        lsx_writew(ft, 0);                       /* write the reserved word */
         for(i = 0; i < 8; i++) {        /* write the 8 loops */
-                sox_writedw(ft, trailer->loops[i].start);
-                sox_writedw(ft, trailer->loops[i].end);
-                sox_writeb(ft, trailer->loops[i].type);
-                sox_writew(ft, trailer->loops[i].count);
+                lsx_writedw(ft, trailer->loops[i].start);
+                lsx_writedw(ft, trailer->loops[i].end);
+                lsx_writeb(ft, trailer->loops[i].type);
+                lsx_writew(ft, trailer->loops[i].count);
         }
         for(i = 0; i < 8; i++) {        /* write the 8 markers */
-                if (sox_writes(ft, trailer->markers[i].name) == SOX_EOF)
+                if (lsx_writes(ft, trailer->markers[i].name) == SOX_EOF)
                 {
-                    sox_fail_errno(ft,SOX_EHDR,"EOF in SMP");
+                    lsx_fail_errno(ft,SOX_EHDR,"EOF in SMP");
                     return(SOX_EOF);
                 }
-                sox_writedw(ft, trailer->markers[i].position);
+                lsx_writedw(ft, trailer->markers[i].position);
         }
-        sox_writeb(ft, (uint8_t)(trailer->MIDInote));
-        sox_writedw(ft, trailer->rate);
-        sox_writedw(ft, trailer->SMPTEoffset);
-        sox_writedw(ft, trailer->CycleSize);
+        lsx_writeb(ft, (uint8_t)(trailer->MIDInote));
+        lsx_writedw(ft, trailer->rate);
+        lsx_writedw(ft, trailer->SMPTEoffset);
+        lsx_writedw(ft, trailer->CycleSize);
         return(SOX_SUCCESS);
 }
 
@@ -186,7 +186,7 @@
         new_offset += (channel_block - alignment);
     new_offset += smp->dataStart;
 
-    ft->sox_errno = sox_seeki(ft, (sox_ssize_t)new_offset, SEEK_SET);
+    ft->sox_errno = lsx_seeki(ft, (sox_ssize_t)new_offset, SEEK_SET);
 
     if( ft->sox_errno == SOX_SUCCESS )
         smp->NoOfSamps = ft->length - (new_offset / (ft->encoding.bits_per_sample >> 3));
@@ -211,24 +211,24 @@
         /* If you need to seek around the input file. */
         if (! ft->seekable)
         {
-                sox_fail_errno(ft,SOX_EOF,"SMP input file must be a file, not a pipe");
+                lsx_fail_errno(ft,SOX_EOF,"SMP input file must be a file, not a pipe");
                 return(SOX_EOF);
         }
 
         /* Read SampleVision header */
-        if (sox_readbuf(ft, (char *)&header, HEADERSIZE) != HEADERSIZE)
+        if (lsx_readbuf(ft, (char *)&header, HEADERSIZE) != HEADERSIZE)
         {
-                sox_fail_errno(ft,SOX_EHDR,"unexpected EOF in SMP header");
+                lsx_fail_errno(ft,SOX_EHDR,"unexpected EOF in SMP header");
                 return(SOX_EOF);
         }
         if (strncmp(header.Id, SVmagic, 17) != 0)
         {
-                sox_fail_errno(ft,SOX_EHDR,"SMP header does not begin with magic word %s", SVmagic);
+                lsx_fail_errno(ft,SOX_EHDR,"SMP header does not begin with magic word %s", SVmagic);
                 return(SOX_EOF);
         }
         if (strncmp(header.version, SVvers, 4) != 0)
         {
-                sox_fail_errno(ft,SOX_EHDR,"SMP header is not version %s", SVvers);
+                lsx_fail_errno(ft,SOX_EHDR,"SMP header is not version %s", SVvers);
                 return(SOX_EOF);
         }
 
@@ -243,30 +243,30 @@
           ;
         sprintf(smp->comment, "%.*s: %.*s", namelen+1, header.name,
                 commentlen+1, header.comments);
-        append_comments(&ft->comments, smp->comment);
+        sox_append_comments(&ft->comments, smp->comment);
 
         /* Extract out the sample size (always intel format) */
-        sox_readdw(ft, &(smp->NoOfSamps));
+        lsx_readdw(ft, &(smp->NoOfSamps));
         /* mark the start of the sample data */
-        samplestart = sox_tell(ft);
+        samplestart = lsx_tell(ft);
 
         /* seek from the current position (the start of sample data) by */
         /* NoOfSamps * sizeof(int16_t) */
-        if (sox_seeki(ft, (sox_ssize_t)(smp->NoOfSamps * 2), 1) == -1)
+        if (lsx_seeki(ft, (sox_ssize_t)(smp->NoOfSamps * 2), 1) == -1)
         {
-                sox_fail_errno(ft,errno,"SMP unable to seek to trailer");
+                lsx_fail_errno(ft,errno,"SMP unable to seek to trailer");
                 return(SOX_EOF);
         }
         if (readtrailer(ft, &trailer))
         {
-                sox_fail_errno(ft,SOX_EHDR,"unexpected EOF in SMP trailer");
+                lsx_fail_errno(ft,SOX_EHDR,"unexpected EOF in SMP trailer");
                 return(SOX_EOF);
         }
 
         /* seek back to the beginning of the data */
-        if (sox_seeki(ft, (sox_ssize_t)samplestart, 0) == -1) 
+        if (lsx_seeki(ft, (sox_ssize_t)samplestart, 0) == -1) 
         {
-                sox_fail_errno(ft,errno,"SMP unable to seek back to start of sample data");
+                lsx_fail_errno(ft,errno,"SMP unable to seek back to start of sample data");
                 return(SOX_EOF);
         }
 
@@ -324,7 +324,7 @@
         sox_size_t done = 0;
         
         for(; done < len && smp->NoOfSamps; done++, smp->NoOfSamps--) {
-                sox_readw(ft, &datum);
+                lsx_readw(ft, &datum);
                 /* scale signed up to long's range */
                 *buf++ = SOX_SIGNED_16BIT_TO_SAMPLE(datum,);
         }
@@ -335,12 +335,12 @@
 {
         smp_t smp = (smp_t) ft->priv;
         struct smpheader header;
-        char * comment = cat_comments(ft->comments);
+        char * comment = sox_cat_comments(ft->comments);
 
         /* If you have to seek around the output file */
         if (! ft->seekable)
         {
-                sox_fail_errno(ft,SOX_EOF,"Output .smp file must be a file, not a pipe");
+                lsx_fail_errno(ft,SOX_EOF,"Output .smp file must be a file, not a pipe");
                 return(SOX_EOF);
         }
 
@@ -351,12 +351,12 @@
         free(comment);
 
         /* Write file header */
-        if(sox_writebuf(ft, &header, HEADERSIZE) != HEADERSIZE)
+        if(lsx_writebuf(ft, &header, HEADERSIZE) != HEADERSIZE)
         {
-            sox_fail_errno(ft,errno,"SMP: Can't write header completely");
+            lsx_fail_errno(ft,errno,"SMP: Can't write header completely");
             return(SOX_EOF);
         }
-        sox_writedw(ft, 0);      /* write as zero length for now, update later */
+        lsx_writedw(ft, 0);      /* write as zero length for now, update later */
         smp->NoOfSamps = 0;
 
         return(SOX_SUCCESS);
@@ -370,7 +370,7 @@
 
         while(done < len) {
                 datum = (int) SOX_SAMPLE_TO_SIGNED_16BIT(*buf++, ft->clips);
-                sox_writew(ft, (uint16_t)datum);
+                lsx_writew(ft, (uint16_t)datum);
                 smp->NoOfSamps++;
                 done++;
         }
@@ -386,12 +386,12 @@
         /* Assign the trailer data */
         settrailer(ft, &trailer, ft->signal.rate);
         writetrailer(ft, &trailer);
-        if (sox_seeki(ft, 112, 0) == -1)
+        if (lsx_seeki(ft, 112, 0) == -1)
         {
-                sox_fail_errno(ft,errno,"SMP unable to seek back to save size");
+                lsx_fail_errno(ft,errno,"SMP unable to seek back to save size");
                 return(SOX_EOF);
         }
-        sox_writedw(ft, smp->NoOfSamps);
+        lsx_writedw(ft, smp->NoOfSamps);
 
         return(SOX_SUCCESS);
 }
--- a/src/sounder.c
+++ b/src/sounder.c
@@ -23,21 +23,21 @@
 {
   uint16_t type, rate;
 
-  if (sox_readw(ft, &type) || sox_readw(ft, &rate) || sox_skipbytes(ft, 4))
+  if (lsx_readw(ft, &type) || lsx_readw(ft, &rate) || lsx_skipbytes(ft, 4))
     return SOX_EOF;
   if (type) {
-    sox_fail_errno(ft, SOX_EHDR, "invalid Sounder header");
+    lsx_fail_errno(ft, SOX_EHDR, "invalid Sounder header");
     return SOX_EOF;
   }
-  return sox_check_read_params(ft, 1, (sox_rate_t)rate, SOX_ENCODING_UNSIGNED, 8, (off_t)0);
+  return lsx_check_read_params(ft, 1, (sox_rate_t)rate, SOX_ENCODING_UNSIGNED, 8, (off_t)0);
 }
 
 static int write_header(sox_format_t * ft)
 {
-  return sox_writew(ft, 0)   /* sample type */
-      || sox_writew(ft, min(65535, (unsigned)(ft->signal.rate + .5)))
-      || sox_writew(ft, 10)  /* speaker driver volume */
-      || sox_writew(ft, 4)?  /* speaker driver DC shift */
+  return lsx_writew(ft, 0)   /* sample type */
+      || lsx_writew(ft, min(65535, (unsigned)(ft->signal.rate + .5)))
+      || lsx_writew(ft, 10)  /* speaker driver volume */
+      || lsx_writew(ft, 4)?  /* speaker driver DC shift */
       SOX_EOF : SOX_SUCCESS;
 }
 
@@ -48,9 +48,9 @@
   static sox_format_handler_t const handler = {SOX_LIB_VERSION_CODE,
     "8-bit linear audio as used by Aaron Wallace's `Sounder' of 1991",
     names, SOX_FILE_LIT_END | SOX_FILE_MONO,
-    start_read, sox_rawread, NULL,
-    write_header, sox_rawwrite, NULL,
-    sox_rawseek, write_encodings, NULL
+    start_read, lsx_rawread, NULL,
+    write_header, lsx_rawwrite, NULL,
+    lsx_rawseek, write_encodings, NULL
   };
   return &handler;
 }
--- a/src/soundtool.c
+++ b/src/soundtool.c
@@ -29,23 +29,23 @@
   uint32_t nsamples;
   uint16_t rate;
 
-  if (sox_readchars(ft, id1, sizeof(ID1)) ||
-      sox_skipbytes(ft, 10) || sox_readdw(ft, &nsamples) ||
-      sox_readw(ft, &rate) || sox_skipbytes(ft, 6) ||
-      sox_readchars(ft, comments, text_field_len))
+  if (lsx_readchars(ft, id1, sizeof(ID1)) ||
+      lsx_skipbytes(ft, 10) || lsx_readdw(ft, &nsamples) ||
+      lsx_readw(ft, &rate) || lsx_skipbytes(ft, 6) ||
+      lsx_readchars(ft, comments, text_field_len))
     return SOX_EOF;
   if (memcmp(ID1, id1, sizeof(id1))) {
-    sox_fail_errno(ft, SOX_EHDR, "soundtool: can't find SoundTool identifier");
+    lsx_fail_errno(ft, SOX_EHDR, "soundtool: can't find SoundTool identifier");
     return SOX_EOF;
   }
   comments[text_field_len] = '\0'; /* Be defensive against incorrect files */
-  append_comments(&ft->comments, comments);
-  return sox_check_read_params(ft, 1, (sox_rate_t)rate, SOX_ENCODING_UNSIGNED, 8, (off_t)0);
+  sox_append_comments(&ft->comments, comments);
+  return lsx_check_read_params(ft, 1, (sox_rate_t)rate, SOX_ENCODING_UNSIGNED, 8, (off_t)0);
 }
 
 static int write_header(sox_format_t * ft)
 {
-  char * comment = cat_comments(ft->comments);
+  char * comment = sox_cat_comments(ft->comments);
   char text_buf[text_field_len];
   sox_size_t length = ft->olength? ft->olength:ft->length;
 
@@ -52,16 +52,16 @@
   memset(text_buf, 0, sizeof(text_buf));
   strncpy(text_buf, comment, text_field_len - 1);
   free(comment);
-  return sox_writechars(ft, ID1, sizeof(ID1))
-      || sox_writew  (ft, 0)      /* GSound: not used */
-      || sox_writedw (ft, length) /* length of complete sample */
-      || sox_writedw (ft, 0)      /* first byte to play from sample */
-      || sox_writedw (ft, length) /* first byte NOT to play from sample */
-      || sox_writew  (ft, min(65535, (unsigned)(ft->signal.rate + .5)))
-      || sox_writew  (ft, 0)      /* sample size/type */
-      || sox_writew  (ft, 10)     /* speaker driver volume */
-      || sox_writew  (ft, 4)      /* speaker driver DC shift */
-      || sox_writechars(ft, text_buf, sizeof(text_buf))?  SOX_EOF:SOX_SUCCESS;
+  return lsx_writechars(ft, ID1, sizeof(ID1))
+      || lsx_writew  (ft, 0)      /* GSound: not used */
+      || lsx_writedw (ft, length) /* length of complete sample */
+      || lsx_writedw (ft, 0)      /* first byte to play from sample */
+      || lsx_writedw (ft, length) /* first byte NOT to play from sample */
+      || lsx_writew  (ft, min(65535, (unsigned)(ft->signal.rate + .5)))
+      || lsx_writew  (ft, 0)      /* sample size/type */
+      || lsx_writew  (ft, 10)     /* speaker driver volume */
+      || lsx_writew  (ft, 4)      /* speaker driver DC shift */
+      || lsx_writechars(ft, text_buf, sizeof(text_buf))?  SOX_EOF:SOX_SUCCESS;
 }
 
 SOX_FORMAT_HANDLER(soundtool)
@@ -71,9 +71,9 @@
   static sox_format_handler_t const handler = {SOX_LIB_VERSION_CODE,
     "8-bit linear audio as used by Martin Hepperle's `SoundTool' of 1991/2",
     names, SOX_FILE_LIT_END | SOX_FILE_MONO | SOX_FILE_REWIND,
-    start_read, sox_rawread, NULL,
-    write_header, sox_rawwrite, NULL,
-    sox_rawseek, write_encodings, NULL
+    start_read, lsx_rawread, NULL,
+    write_header, lsx_rawwrite, NULL,
+    lsx_rawseek, write_encodings, NULL
   };
   return &handler;
 }
--- a/src/sox.c
+++ b/src/sox.c
@@ -22,7 +22,9 @@
  * USA.
  */
 
-#include "sox_i.h"
+#include "soxconfig.h"
+#include "sox.h"
+#include "util.h"
 #include "getopt.h"
 
 #include <errno.h>
@@ -97,7 +99,7 @@
   double volume;
   double replay_gain;
   rg_mode replay_gain_mode;
-  comments_t comments;
+  sox_comments_t comments;
 
   sox_format_t * ft;  /* libSoX file descriptor */
   sox_size_t volume_clips;
@@ -204,11 +206,11 @@
   }
 
   fprintf(output, "  Encoding: %-14s", sox_encodings_short_str[ft->encoding.encoding]);
-  text = find_comment(f->ft->comments, "Comment");
+  text = sox_find_comment(f->ft->comments, "Comment");
   if (!text)
-    text = find_comment(f->ft->comments, "Description");
+    text = sox_find_comment(f->ft->comments, "Description");
   if (!text)
-    text = find_comment(f->ft->comments, "Year");
+    text = sox_find_comment(f->ft->comments, "Year");
   if (text)
     fprintf(output, "Info: %s", text);
   fprintf(output, "\n");
@@ -215,10 +217,10 @@
 
   sprintf(buffer, "  Channels: %u @ %u-bit", ft->signal.channels, ft->signal.precision);
   fprintf(output, "%-25s", buffer);
-  text = find_comment(f->ft->comments, "Tracknumber");
+  text = sox_find_comment(f->ft->comments, "Tracknumber");
   if (text) {
     fprintf(output, "Track: %s", text);
-    text = find_comment(f->ft->comments, "Tracktotal");
+    text = sox_find_comment(f->ft->comments, "Tracktotal");
     if (text)
       fprintf(output, " of %s", text);
   }
@@ -226,7 +228,7 @@
 
   sprintf(buffer, "Samplerate: %gHz", ft->signal.rate);
   fprintf(output, "%-25s", buffer);
-  text = find_comment(f->ft->comments, "Album");
+  text = sox_find_comment(f->ft->comments, "Album");
   if (text)
     fprintf(output, "Album: %s", text);
   fprintf(output, "\n");
@@ -237,13 +239,13 @@
     fprintf(output, "%-24s", buffer);
   } else
     fprintf(output, "%-24s", "Replaygain: off");
-  text = find_comment(f->ft->comments, "Artist");
+  text = sox_find_comment(f->ft->comments, "Artist");
   if (text)
     fprintf(output, "Artist: %s", text);
   fprintf(output, "\n");
 
   fprintf(output, "  Duration: %-13s", ft->length? str_time((double)ws / ft->signal.rate) : "unknown");
-  text = find_comment(f->ft->comments, "Title");
+  text = sox_find_comment(f->ft->comments, "Title");
   if (text)
     fprintf(output, "Title: %s", text);
   fprintf(output, "\n\n");
@@ -293,7 +295,7 @@
   if (full) {
     if (ft->encoding.bits_per_sample > 8 || (ft->handler.flags & SOX_FILE_ENDIAN))
       fprintf(output, "Endian Type    : %s\n",
-          ft->encoding.reverse_bytes != SOX_IS_BIGENDIAN ? "big" : "little");
+          ft->encoding.reverse_bytes != MACHINE_IS_BIGENDIAN ? "big" : "little");
     if (ft->encoding.bits_per_sample)
       fprintf(output,
         "Reverse Nibbles: %s\n"
@@ -309,8 +311,8 @@
     fprintf(output, "Level adjust   : %g (linear gain)\n" , f->volume);
 
   if (!(ft->handler.flags & SOX_FILE_DEVICE) && ft->comments) {
-    if (num_comments(ft->comments) > 1) {
-      comments_t p = ft->comments;
+    if (sox_num_comments(ft->comments) > 1) {
+      sox_comments_t p = ft->comments;
       fprintf(output, "Comments       : \n");
       do fprintf(output, "%s\n", *p);
       while (*++p);
@@ -768,18 +770,18 @@
   sox_loopinfo_t loops[SOX_MAX_NLOOPS];
   double factor;
   int i;
-  comments_t comments = copy_comments(files[0]->ft->comments);
-  comments_t p = ofile->comments;
+  sox_comments_t comments = sox_copy_comments(files[0]->ft->comments);
+  sox_comments_t p = ofile->comments;
 
   if (!comments && !p)
-    append_comment(&comments, "Processed by SoX");
+    sox_append_comment(&comments, "Processed by SoX");
   else if (p) {
     if (!(*p)[0]) {
-      delete_comments(&comments);
+      sox_delete_comments(&comments);
       ++p;
     }
     while (*p)
-      append_comment(&comments, *p++);
+      sox_append_comment(&comments, *p++);
   }
 
   /*
@@ -805,7 +807,7 @@
                         olen,
                         &files[0]->ft->instr,
                         loops);
-  delete_comments(&comments);
+  sox_delete_comments(&comments);
 
   if (!ofile->ft)
     /* sox_open_write() will call sox_warn for most errors.
@@ -947,7 +949,7 @@
   char const * * format_list;
   char const * const * names;
 
-  for (i = 0, formats = 0; i < sox_formats; i++) {
+  for (i = formats = 0; sox_format_fns[i].fn; ++i) {
     char const * const *names = sox_format_fns[i].fn()->names;
     while (*names++)
       formats++;
@@ -955,7 +957,7 @@
   format_list = (const char **)xmalloc(formats * sizeof(char *));
 
   printf("AUDIO FILE FORMATS:");
-  for (i = 0, formats = 0; i < sox_formats; i++) {
+  for (i = formats = 0; sox_format_fns[i].fn; ++i) {
     sox_format_handler_t const * handler = sox_format_fns[i].fn();
     if (!(handler->flags & SOX_FILE_DEVICE))
       for (names = handler->names; *names; ++names)
@@ -967,7 +969,7 @@
   putchar('\n');
 
   printf("PLAYLIST FORMATS: m3u pls\nAUDIO DEVICES:");
-  for (i = 0, formats = 0; i < sox_formats; i++) {
+  for (i = formats = 0; sox_format_fns[i].fn; ++i) {
     sox_format_handler_t const * handler = sox_format_fns[i].fn();
     if ((handler->flags & SOX_FILE_DEVICE) && !(handler->flags & SOX_FILE_PHONY))
       for (names = handler->names; *names; ++names)
@@ -1152,7 +1154,7 @@
     else usage_format1(f);
   }
   else {
-    for (i = 0; i < sox_formats; ++i) {
+    for (i = 0; sox_format_fns[i].fn; ++i) {
       sox_format_handler_t const * f = sox_format_fns[i].fn();
       if (!(f->flags & SOX_FILE_PHONY))
         usage_format1(f);
@@ -1161,7 +1163,7 @@
   exit(1);
 }
 
-static void read_comment_file(comments_t * comments, char const * const filename)
+static void read_comment_file(sox_comments_t * comments, char const * const filename)
 {
   int c;
   size_t text_length = 100;
@@ -1186,7 +1188,7 @@
     }
     if (i) {
       text[i] = '\0';
-      append_comment(comments, text);
+      sox_append_comment(comments, text);
     }
   } while (c != EOF);
 
@@ -1280,7 +1282,7 @@
       switch (option_index) {
       case 0:
         if (optarg)
-          append_comment(&f->comments, optarg);
+          sox_append_comment(&f->comments, optarg);
         break;
 
       case 1:
@@ -1297,14 +1299,14 @@
         break;
 
       case 3:
-        append_comment(&f->comments, "");
+        sox_append_comment(&f->comments, "");
         read_comment_file(&f->comments, optarg);
         break;
 
       case 4:
-        append_comment(&f->comments, "");
+        sox_append_comment(&f->comments, "");
         if (optarg)
-          append_comment(&f->comments, optarg);
+          sox_append_comment(&f->comments, optarg);
         break;
 
       case 5:
@@ -1311,8 +1313,8 @@
         if (f->encoding.reverse_bytes != SOX_OPTION_DEFAULT || f->encoding.opposite_endian)
           usage("only one endian option per file is allowed");
         switch (enum_option(option_index, endian_options)) {
-          case ENDIAN_little: f->encoding.reverse_bytes = SOX_IS_BIGENDIAN; break;
-          case ENDIAN_big: f->encoding.reverse_bytes = SOX_IS_LITTLEENDIAN; break;
+          case ENDIAN_little: f->encoding.reverse_bytes = MACHINE_IS_BIGENDIAN; break;
+          case ENDIAN_big: f->encoding.reverse_bytes = MACHINE_IS_LITTLEENDIAN; break;
           case ENDIAN_swap: f->encoding.opposite_endian = sox_true; break;
         }
         break;
@@ -1431,8 +1433,8 @@
       if (f->encoding.reverse_bytes != SOX_OPTION_DEFAULT || f->encoding.opposite_endian)
         usage("only one endian option per file is allowed");
       switch (c) {
-        case 'L': f->encoding.reverse_bytes   = SOX_IS_BIGENDIAN;    break;
-        case 'B': f->encoding.reverse_bytes   = SOX_IS_LITTLEENDIAN; break;
+        case 'L': f->encoding.reverse_bytes   = MACHINE_IS_BIGENDIAN;    break;
+        case 'B': f->encoding.reverse_bytes   = MACHINE_IS_LITTLEENDIAN; break;
         case 'x': f->encoding.opposite_endian = sox_true;            break;
       }
       break;
@@ -1583,7 +1585,7 @@
     case bits: printf("%u\n", ft->encoding.bits_per_sample); break;
     case encoding: printf("%s\n", sox_encodings_str[ft->encoding.encoding]); break;
     case annotation: if (ft->comments) {
-      comments_t p = ft->comments;
+      sox_comments_t p = ft->comments;
       do printf("%s\n", *p); while (*++p);
     }
     break;
@@ -1623,11 +1625,11 @@
   return num_errors;
 }
 
-static void set_replay_gain(comments_t comments, file_t f)
+static void set_replay_gain(sox_comments_t comments, file_t f)
 {
   rg_mode rg = replay_gain_mode;
   int try = 2; /* Will try to find the other GAIN if preferred one not found */
-  size_t i, n = num_comments(comments);
+  size_t i, n = sox_num_comments(comments);
 
   if (rg != RG_off) while (try--) {
     char const * target =
@@ -1731,11 +1733,11 @@
   /* Simple heuristic to determine if replay-gain should be in album mode */
   if (sox_mode == sox_play && replay_gain_mode == RG_track && input_count > 1 &&
       cmp_comment_text(
-        find_comment(files[0]->ft->comments, "artist"),
-        find_comment(files[1]->ft->comments, "artist")) &&
+        sox_find_comment(files[0]->ft->comments, "artist"),
+        sox_find_comment(files[1]->ft->comments, "artist")) &&
       cmp_comment_text(
-        find_comment(files[0]->ft->comments, "album"),
-        find_comment(files[1]->ft->comments, "album")))
+        sox_find_comment(files[0]->ft->comments, "album"),
+        sox_find_comment(files[1]->ft->comments, "album")))
     replay_gain_mode = RG_album;
 
   for (i = 0; i < input_count; i++)
--- a/src/sox.h
+++ b/src/sox.h
@@ -12,26 +12,28 @@
 #ifndef SOX_H
 #define SOX_H
 
+#include <limits.h>
+#include <stdarg.h>
 #include <stddef.h> /* Ensure NULL etc. are available throughout SoX */
 #include <stdio.h>
 #include <stdlib.h>
-#include <limits.h>
 #include "soxstdint.h"
 
 /* Avoid warnings about unused parameters. */
 #ifdef __GNUC__
 #define UNUSED __attribute__ ((unused))
+#define PRINTF __attribute__ ((format (printf, 1, 2)))
 #else
 #define UNUSED
+#define PRINTF
 #endif
 
 /* The following is the API version of libSoX.  It is not meant
  * to follow the version number of SoX but it has historically.
  * Please do not count on these numbers being in sync.
- * The following is at 14.1.0
  */
-#define SOX_LIB_VERSION_CODE 0x0e0100
 #define SOX_LIB_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))
+#define SOX_LIB_VERSION_CODE SOX_LIB_VERSION(14, 1, 0)
 
 const char *sox_version(void);   /* Returns version number */
 
@@ -169,6 +171,27 @@
 #define SOX_SIZE_MAX (sox_size_t)(-1)
 typedef ptrdiff_t sox_ssize_t;
 
+typedef void (*sox_output_message_handler_t)(unsigned level, const char *filename, const char *fmt, va_list ap);
+
+typedef struct /* Global parameters (for effects & formats) */
+{
+/* public: */
+  unsigned     verbosity;
+  sox_output_message_handler_t output_message_handler;
+  sox_bool     repeatable;
+/* The following is used at times in libSoX when alloc()ing buffers
+ * to perform file I/O.  It can be useful to pass in similar sized
+ * data to get max performance.
+ */
+  sox_size_t   bufsiz;
+
+/* private: */
+  char const * stdin_in_use_by;
+  char const * stdout_in_use_by;
+  char const * subsystem;
+} sox_globals_t;
+extern sox_globals_t sox_globals;
+
 typedef double sox_rate_t;
 
 typedef struct { /* Signal parameters; 0 if unknown */
@@ -218,39 +241,32 @@
   unsigned bits_per_sample;  /* 0 if unknown or variable; uncompressed value if lossless; compressed value if lossy */
   double compression;      /* compression factor (where applicable) */
 
-  /* There is a delineation between these vars being tri-state and
-   * effectively boolean.  Logically the line falls between setting
-   * them up (could be done in libSoX, or by the libSoX client) and
-   * using them (in libSoX).  libSoX's logic to set them up includes
-   * knowledge of the machine default and the format default.  (The
-   * sox client logic adds to this a layer of overridability via user
-   * options.)  The physical delineation is in the somewhat
-   * snappily-named libSoX function `set_endianness_if_not_already_set'
-   * which is called at the right times (as files are openned) by the
-   * libSoX core, not by the file handlers themselves.  The file handlers
-   * indicate to the libSoX core if they have a preference using
-   * SOX_FILE_xxx flags.
-   */
-  sox_bool opposite_endian;
+  /* If these 3 variables are set to DEFAULT, then, during
+   * sox_open_read or sox_open_write, libSoX will set them to either
+   * NO or YES according to the machine or format default. */
   sox_option_t reverse_bytes;    /* endiannesses... */
   sox_option_t reverse_nibbles;
   sox_option_t reverse_bits;
+
+  sox_bool opposite_endian;
 } sox_encodinginfo_t;
 
+void sox_init_encodinginfo(sox_encodinginfo_t * e);
+unsigned sox_precision(sox_encoding_t encoding, unsigned pcm_size);
+
 /* Defaults for common hardware */
 #define SOX_DEFAULT_CHANNELS  2
 #define SOX_DEFAULT_RATE      48000
-#define SOX_DEFAULT_PRECISION      16
+#define SOX_DEFAULT_PRECISION 16
 #define SOX_DEFAULT_ENCODING  SOX_ENCODING_SIGN2
 
 /* Loop parameters */
 
-typedef struct  sox_loopinfo
-{
-    sox_size_t    start;          /* first sample */
-    sox_size_t    length;         /* length */
-    unsigned int  count;          /* number of repeats, 0=forever */
-    unsigned char type;           /* 0=no, 1=forward, 2=forward/back */
+typedef struct {
+  sox_size_t    start;          /* first sample */
+  sox_size_t    length;         /* length */
+  unsigned int  count;          /* number of repeats, 0=forever */
+  unsigned char type;           /* 0=no, 1=forward, 2=forward/back */
 } sox_loopinfo_t;
 
 /* Instrument parameters */
@@ -257,12 +273,11 @@
 
 /* vague attempt at generic information for sampler-specific info */
 
-typedef struct  sox_instrinfo
-{
-    char MIDInote;       /* for unity pitch playback */
-    char MIDIlow, MIDIhi;/* MIDI pitch-bend range */
-    char loopmode;       /* semantics of loop data */
-    unsigned nloops;     /* number of active loops (max SOX_MAX_NLOOPS) */
+typedef struct {
+  char MIDInote;       /* for unity pitch playback */
+  char MIDIlow, MIDIhi;/* MIDI pitch-bend range */
+  char loopmode;       /* semantics of loop data */
+  unsigned nloops;     /* number of active loops (max SOX_MAX_NLOOPS) */
 } sox_instrinfo_t;
 
 /* Loop modes, upper 4 bits mask the loop blass, lower 4 bits describe */
@@ -275,12 +290,11 @@
  * File buffer info.  Holds info so that data can be read in blocks.
  */
 
-typedef struct sox_fileinfo
-{
-    char          *buf;                 /* Pointer to data buffer */
-    size_t        size;                 /* Size of buffer */
-    size_t        count;                /* Count read in to buffer */
-    size_t        pos;                  /* Position in buffer */
+typedef struct {
+  char          *buf;                 /* Pointer to data buffer */
+  size_t        size;                 /* Size of buffer */
+  size_t        count;                /* Count read in to buffer */
+  size_t        pos;                  /* Position in buffer */
 } sox_fileinfo_t;
 
 
@@ -313,8 +327,16 @@
 #define SOX_MAX_FILE_PRIVSIZE    1000
 #define SOX_MAX_NLOOPS           8
 
-typedef char * * comments_t;
+typedef char * * sox_comments_t;
 
+size_t sox_num_comments(sox_comments_t comments);
+void sox_append_comment(sox_comments_t * comments, char const * comment);
+void sox_append_comments(sox_comments_t * comments, char const * comment);
+sox_comments_t sox_copy_comments(sox_comments_t comments);
+void sox_delete_comments(sox_comments_t * comments);
+char * sox_cat_comments(sox_comments_t comments);
+char const * sox_find_comment(sox_comments_t comments, char const * id);
+
 struct sox_format {
   /* Placing priv at the start of this structure ensures that it gets aligned
    * in memory in the optimal way for any structure to be cast over it. */
@@ -331,7 +353,7 @@
   sox_size_t       clips;           /* increment if clipping occurs */
   char             *filename;       /* file name */
   char             *filetype;       /* type of file */
-  comments_t       comments;        /* comment strings */
+  sox_comments_t       comments;        /* comment strings */
   FILE             *fp;             /* File stream pointer */
   int              sox_errno;       /* Failure error codes */
   char             sox_errstr[256]; /* Extend Failure text */
@@ -373,7 +395,7 @@
     sox_signalinfo_t   const * signal,
     sox_encodinginfo_t const * encoding,
     char               const * filetype,
-    comments_t                 comments,
+    sox_comments_t                 comments,
     sox_size_t                 length,
     sox_instrinfo_t    const * instr,
     sox_loopinfo_t     const * loops);
@@ -392,6 +414,7 @@
  * Structures for effects.
  */
 
+#define SOX_MAX_EFFECTS 20
 #define SOX_MAX_EFFECT_PRIVSIZE (2 * SOX_MAX_FILE_PRIVSIZE)
 
 #define SOX_EFF_CHAN     1           /* Effect can alter # of channels */
@@ -402,9 +425,15 @@
 #define SOX_EFF_NULL     32          /* Effect does nothing */
 #define SOX_EFF_DEPRECATED 64        /* Effect is living on borrowed time */
 
+typedef enum {sox_plot_off, sox_plot_octave, sox_plot_gnuplot} sox_plot_t;
 typedef struct sox_effect sox_effect_t;
+struct sox_effects_globals { /* Global parameters (for effects) */
+  sox_plot_t plot;         /* To help the user choose effect & options */
+  double speed;            /* Gather up all speed changes here, then resample */
+  sox_globals_t * global_info;
+};
 typedef struct sox_effects_globals sox_effects_globals_t;
-typedef enum {sox_plot_off, sox_plot_octave, sox_plot_gnuplot} sox_plot_t;
+extern sox_effects_globals_t sox_effects_globals;
 
 typedef struct {
   char const * name;
@@ -444,9 +473,18 @@
 
 /* Effects chain */
 
+typedef const sox_effect_handler_t *(*sox_effect_fn_t)(void);
+extern sox_effect_fn_t sox_effect_fns[];
 int sox_effect_set_imin(sox_effect_t * effp, sox_size_t imin);
 
-struct sox_effects_chain;
+struct sox_effects_chain {
+  sox_effect_t * effects[SOX_MAX_EFFECTS];
+  unsigned length;
+  sox_sample_t **ibufc, **obufc; /* Channel interleave buffers */
+  sox_effects_globals_t global_info;
+  sox_encodinginfo_t const * in_enc;
+  sox_encodinginfo_t const * out_enc;
+};
 typedef struct sox_effects_chain sox_effects_chain_t;
 sox_effects_chain_t * sox_create_effects_chain(
     sox_encodinginfo_t const * in_enc,
@@ -457,8 +495,6 @@
 sox_size_t sox_stop_effect(sox_effects_chain_t *, sox_size_t e);
 void sox_delete_effects(sox_effects_chain_t *);
 
-char const * sox_parsesamples(sox_rate_t rate, const char *str, sox_size_t *samples, int def);
-
 /* The following routines are unique to the trim effect.
  * sox_trim_get_start can be used to find what is the start
  * of the trim operation as specified by the user.
@@ -474,5 +510,30 @@
 typedef int (* sox_playlist_callback_t)(void *, char *);
 sox_bool sox_is_playlist(char const * filename);
 int sox_parse_playlist(sox_playlist_callback_t callback, void * p, char const * const listname);
+
+void sox_fail(const char *, ...) PRINTF;
+void sox_warn(const char *, ...) PRINTF;
+void sox_report(const char *, ...) PRINTF;
+void sox_debug(const char *, ...) PRINTF;
+void sox_debug_more(char const * fmt, ...) PRINTF;
+void sox_debug_most(char const * fmt, ...) PRINTF;
+
+#define sox_fail       sox_globals.subsystem=__FILE__,sox_fail
+#define sox_warn       sox_globals.subsystem=__FILE__,sox_warn
+#define sox_report     sox_globals.subsystem=__FILE__,sox_report
+#define sox_debug      sox_globals.subsystem=__FILE__,sox_debug
+#define sox_debug_more sox_globals.subsystem=__FILE__,sox_debug_more
+#define sox_debug_most sox_globals.subsystem=__FILE__,sox_debug_most
+
+void sox_output_message(FILE *file, const char *filename, const char *fmt, va_list ap);
+
+typedef const sox_format_handler_t *(*sox_format_fn_t)(void);
+
+typedef struct {
+  char *name;
+  sox_format_fn_t fn;
+} sox_format_tab_t;
+
+extern sox_format_tab_t sox_format_fns[];
 
 #endif
--- a/src/sox_i.h
+++ b/src/sox_i.h
@@ -1,9 +1,9 @@
 /*
  * libSoX Internal header
  *
- *   This file is meant for libsox internal use only
+ *   This file is meant for libSoX internal use only
  *
- * Copyright 2001-2007 Chris Bagwell and SoX Contributors
+ * Copyright 2001-2008 Chris Bagwell and SoX Contributors
  *
  * This source code is freely redistributable and may be used for
  * any purpose.  This copyright notice must be maintained.
@@ -16,88 +16,13 @@
 
 #include "soxconfig.h"
 #include "sox.h"
-#include "xmalloc.h"
+#include "util.h"
 
-#include <stdarg.h>
 #include <errno.h>
-
-#ifdef HAVE_BYTESWAP_H
-#include <byteswap.h>
-#endif
-
-/* various gcc optimizations and portablity defines */
-#ifdef __GNUC__
-#define NORET __attribute__((noreturn))
-#define PRINTF __attribute__ ((format (printf, 1, 2)))
-#else
-#define NORET
-#define PRINTF
-#endif
-
-#ifdef _MSC_VER
-#define __STDC__ 1
-#define S_IFMT   _S_IFMT
-#define S_IFREG  _S_IFREG
-#define O_BINARY _O_BINARY
-#define fstat _fstat
-#define ftime _ftime
-#define inline __inline
-#define isatty _isatty
-#define popen _popen
-#define stat _stat
-#define strdup _strdup
-#define timeb _timeb
-#endif
-
-#if defined(DOS) || defined(WIN32) || defined(__NT__) || defined(__DJGPP__) || defined(__OS2__)
-  #define LAST_SLASH(path) max(strrchr(path, '/'), strrchr(path, '\\'))
-  #define IS_ABSOLUTE(path) ((path)[0] == '/' || (path)[0] == '\\' || (path)[1] == ':')
-  #define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY)
-#else
-  #define LAST_SLASH(path) strrchr(path, '/')
-  #define IS_ABSOLUTE(path) ((path)[0] == '/')
-  #define SET_BINARY_MODE(file)
-#endif
-
-/* Compile-time ("static") assertion */
-/*   e.g. assert_static(sizeof(int) >= 4, int_type_too_small)    */
-#define assert_static(e,f) enum {assert_static__##f = 1/(e)}
-
-#ifdef min
-#undef min
-#endif
-#define min(a, b) ((a) <= (b) ? (a) : (b))
-
-#ifdef max
-#undef max
-#endif
-#define max(a, b) ((a) >= (b) ? (a) : (b))
-
-#define range_limit(x, lower, upper) (min(max(x, lower), upper))
-
-#define sqr(a) ((a) * (a))
-
-/* Array-length operator */
-#define array_length(a) (sizeof(a)/sizeof(a[0]))
-
-/* declared in misc.c */
-char const * find_file_extension(char const * pathname);
-typedef struct {char const *text; unsigned value;} enum_item;
-#define ENUM_ITEM(prefix, item) {#item, prefix##item},
-enum_item const * find_enum_text(
-    char const * text, enum_item const * enum_items);
-enum_item const * find_enum_value(unsigned value, enum_item const * enum_items);
 typedef enum {SOX_SHORT, SOX_INT, SOX_FLOAT, SOX_DOUBLE} sox_data_t;
-typedef enum {SOX_WAVE_SINE, SOX_WAVE_TRIANGLE} sox_wave_t;
-extern enum_item const sox_wave_enum[];
-sox_bool is_uri(char const * text);
-FILE * xfopen(char const * identifier, char const * mode);
+typedef enum {SOX_WAVE_SINE, SOX_WAVE_TRIANGLE} lsx_wave_t;
+extern enum_item const lsx_wave_enum[];
 
-/* Function we supply if it's missing from system libc */
-#ifndef HAVE_STRRSTR
-char *strrstr(const char *s, const char *t);
-#endif
-
 /* Define fseeko and ftello for platforms lacking them */
 #ifndef HAVE_FSEEKO
 #define fseeko fseek
@@ -111,8 +36,8 @@
 /* Digitise one cycle of a wave and store it as
  * a table of samples of a specified data-type.
  */
-void sox_generate_wave_table(
-    sox_wave_t wave_type,
+void lsx_generate_wave_table(
+    lsx_wave_t wave_type,
     sox_data_t data_type,
     void * table,       /* Really of type indicated by data_type. */
     uint32_t table_size,/* Number of points on the x-axis. */
@@ -119,9 +44,10 @@
     double min,         /* Minimum value on the y-axis. (e.g. -1) */
     double max,         /* Maximum value on the y-axis. (e.g. +1) */
     double phase);      /* Phase at 1st point; 0..2pi. (e.g. pi/2 for cosine) */
+char const * lsx_parsesamples(sox_rate_t rate, const char *str, sox_size_t *samples, int def);
 
-sox_sample_t sox_gcd(sox_sample_t a, sox_sample_t b);
-sox_sample_t sox_lcm(sox_sample_t a, sox_sample_t b);
+sox_sample_t lsx_gcd(sox_sample_t a, sox_sample_t b);
+sox_sample_t lsx_lcm(sox_sample_t a, sox_sample_t b);
 
 #ifndef HAVE_STRCASECMP
 int strcasecmp(const char *s1, const char *s2);
@@ -128,112 +54,76 @@
 int strncasecmp(char const * s1, char const * s2, size_t n);
 #endif
 
-sox_bool strcaseends(char const * str, char const * end);
-sox_bool strends(char const * str, char const * end);
-
 #ifndef HAVE_STRDUP
 char *strdup(const char *s);
 #endif
 
+#ifdef HAVE_BYTESWAP_H
+#include <byteswap.h>
+#define lsx_swapw(x) bswap_16(x)
+#define lsx_swapdw(x) bswap_32(x)
+#else
+#define lsx_swapw(uw) (((uw >> 8) | (uw << 8)) & 0xffff)
+#define lsx_swapdw(udw) ((udw >> 24) | ((udw >> 8) & 0xff00) | ((udw << 8) & 0xff0000) | (udw << 24))
+#endif
 
 
-/*---------------------------- Declared in misc.c ----------------------------*/
 
-/* Read and write basic data types from "ft" stream.  Uses ft->swap for
- * possible byte swapping.
- */
-size_t sox_readbuf(sox_format_t * ft, void *buf, sox_size_t len);
-int sox_skipbytes(sox_format_t * ft, sox_size_t n);
-int sox_padbytes(sox_format_t * ft, sox_size_t n);
-size_t sox_writebuf(sox_format_t * ft, void const *buf, sox_size_t len);
-int sox_reads(sox_format_t * ft, char *c, sox_size_t len);
-int sox_writes(sox_format_t * ft, char const * c);
-void set_signal_defaults(sox_signalinfo_t * signal);
-#define sox_writechars(ft, chars, len) (sox_writebuf(ft, chars, len) == len? SOX_SUCCESS : SOX_EOF)
+/*------------------------ Implemented in libsoxio.c -------------------------*/
 
-sox_size_t sox_read_b_buf(sox_format_t * ft, uint8_t *buf, sox_size_t len);
-sox_size_t sox_read_w_buf(sox_format_t * ft, uint16_t *buf, sox_size_t len);
-sox_size_t sox_read_3_buf(sox_format_t * ft, uint24_t *buf, sox_size_t len);
-sox_size_t sox_read_dw_buf(sox_format_t * ft, uint32_t *buf, sox_size_t len);
-sox_size_t sox_read_f_buf(sox_format_t * ft, float *buf, sox_size_t len);
-sox_size_t sox_read_df_buf(sox_format_t * ft, double *buf, sox_size_t len);
+/* Read and write basic data types from "ft" stream. */
+size_t lsx_readbuf(sox_format_t * ft, void *buf, sox_size_t len);
+int lsx_skipbytes(sox_format_t * ft, sox_size_t n);
+int lsx_padbytes(sox_format_t * ft, sox_size_t n);
+size_t lsx_writebuf(sox_format_t * ft, void const *buf, sox_size_t len);
+int lsx_reads(sox_format_t * ft, char *c, sox_size_t len);
+int lsx_writes(sox_format_t * ft, char const * c);
+void lsx_set_signal_defaults(sox_signalinfo_t * signal);
+#define lsx_writechars(ft, chars, len) (lsx_writebuf(ft, chars, len) == len? SOX_SUCCESS : SOX_EOF)
 
-sox_size_t sox_write_b_buf(sox_format_t * ft, uint8_t *buf, sox_size_t len);
-sox_size_t sox_write_w_buf(sox_format_t * ft, uint16_t *buf, sox_size_t len);
-sox_size_t sox_write_3_buf(sox_format_t * ft, uint24_t *buf, sox_size_t len);
-sox_size_t sox_write_dw_buf(sox_format_t * ft, uint32_t *buf, sox_size_t len);
-sox_size_t sox_write_f_buf(sox_format_t * ft, float *buf, sox_size_t len);
-sox_size_t sox_write_df_buf(sox_format_t * ft, double *buf, sox_size_t len);
+sox_size_t lsx_read_b_buf(sox_format_t * ft, uint8_t *buf, sox_size_t len);
+sox_size_t lsx_read_w_buf(sox_format_t * ft, uint16_t *buf, sox_size_t len);
+sox_size_t lsx_read_3_buf(sox_format_t * ft, uint24_t *buf, sox_size_t len);
+sox_size_t lsx_read_dw_buf(sox_format_t * ft, uint32_t *buf, sox_size_t len);
+sox_size_t lsx_read_f_buf(sox_format_t * ft, float *buf, sox_size_t len);
+sox_size_t lsx_read_df_buf(sox_format_t * ft, double *buf, sox_size_t len);
 
-int sox_read3(sox_format_t * ft, uint24_t * u3);
-int sox_readb(sox_format_t * ft, uint8_t * ub);
-int sox_readdf(sox_format_t * ft, double * d);
-int sox_readdw(sox_format_t * ft, uint32_t * udw);
-int sox_readf(sox_format_t * ft, float * f);
-int sox_readw(sox_format_t * ft, uint16_t * uw);
-int sox_readchars(sox_format_t * ft, char * chars, sox_size_t len);
+sox_size_t lsx_write_b_buf(sox_format_t * ft, uint8_t *buf, sox_size_t len);
+sox_size_t lsx_write_w_buf(sox_format_t * ft, uint16_t *buf, sox_size_t len);
+sox_size_t lsx_write_3_buf(sox_format_t * ft, uint24_t *buf, sox_size_t len);
+sox_size_t lsx_write_dw_buf(sox_format_t * ft, uint32_t *buf, sox_size_t len);
+sox_size_t lsx_write_f_buf(sox_format_t * ft, float *buf, sox_size_t len);
+sox_size_t lsx_write_df_buf(sox_format_t * ft, double *buf, sox_size_t len);
 
-int sox_write3(sox_format_t * ft, unsigned u3);
-int sox_writeb(sox_format_t * ft, unsigned ub);
-int sox_writedw(sox_format_t * ft, unsigned udw);
-int sox_writef(sox_format_t * ft, double f);
-int sox_writesb(sox_format_t * ft, signed);
-int sox_writesw(sox_format_t * ft, signed);
-int sox_writew(sox_format_t * ft, unsigned uw);
-int sox_writedf(sox_format_t * ft, double d);
+int lsx_read3(sox_format_t * ft, uint24_t * u3);
+int lsx_readb(sox_format_t * ft, uint8_t * ub);
+int lsx_readdf(sox_format_t * ft, double * d);
+int lsx_readdw(sox_format_t * ft, uint32_t * udw);
+int lsx_readf(sox_format_t * ft, float * f);
+int lsx_readw(sox_format_t * ft, uint16_t * uw);
+int lsx_readchars(sox_format_t * ft, char * chars, sox_size_t len);
 
-int sox_seeki(sox_format_t * ft, sox_ssize_t to_sample, int whence);
-int sox_offset_seek(sox_format_t * ft, off_t byte_offset, sox_size_t to_sample);
-sox_size_t sox_filelength(sox_format_t * ft);
-int sox_flush(sox_format_t * ft);
-sox_ssize_t sox_tell(sox_format_t * ft);
-int sox_eof(sox_format_t * ft);
-int sox_error(sox_format_t * ft);
-void sox_rewind(sox_format_t * ft);
-void sox_clearerr(sox_format_t * ft);
+int lsx_write3(sox_format_t * ft, unsigned u3);
+int lsx_writeb(sox_format_t * ft, unsigned ub);
+int lsx_writedw(sox_format_t * ft, unsigned udw);
+int lsx_writef(sox_format_t * ft, double f);
+int lsx_writesb(sox_format_t * ft, signed);
+int lsx_writesw(sox_format_t * ft, signed);
+int lsx_writew(sox_format_t * ft, unsigned uw);
+int lsx_writedf(sox_format_t * ft, double d);
 
-/* Utilities to read/write values endianness-independently */
-uint32_t get32_le(unsigned char **p);
-uint16_t get16_le(unsigned char **p);
-void put32_le(unsigned char **p, uint32_t val);
-void put16_le(unsigned char **p, unsigned val);
-void put32_be(unsigned char **p, int32_t val);
-void put16_be(unsigned char **p, int val);
+int lsx_seeki(sox_format_t * ft, sox_ssize_t to_sample, int whence);
+int lsx_offset_seek(sox_format_t * ft, off_t byte_offset, sox_size_t to_sample);
+sox_size_t lsx_filelength(sox_format_t * ft);
+int lsx_flush(sox_format_t * ft);
+sox_ssize_t lsx_tell(sox_format_t * ft);
+int lsx_eof(sox_format_t * ft);
+int lsx_error(sox_format_t * ft);
+void lsx_rewind(sox_format_t * ft);
+void lsx_clearerr(sox_format_t * ft);
 
-/* Utilities to byte-swap values, use libc optimized macros if possible  */
-#ifdef HAVE_BYTESWAP_H
-#define sox_swapw(x) bswap_16(x)
-#define sox_swapdw(x) bswap_32(x)
-#else
-#define sox_swapw(uw) (((uw >> 8) | (uw << 8)) & 0xffff)
-#define sox_swapdw(udw) ((udw >> 24) | ((udw >> 8) & 0xff00) | ((udw << 8) & 0xff0000) | (udw << 24))
-#endif
-void sox_swapf(float * f);
-uint32_t sox_swap3(uint32_t udw);
-double sox_swapdf(double d);
 
-
-
-/*---------------------------- Declared in util.c ----------------------------*/
-
-typedef void (*sox_output_message_handler_t)(unsigned level, const char *filename, const char *fmt, va_list ap);
-void sox_output_message(FILE *file, const char *filename, const char *fmt, va_list ap);
-
-void sox_fail(const char *, ...) PRINTF;
-void sox_warn(const char *, ...) PRINTF;
-void sox_report(const char *, ...) PRINTF;
-void sox_debug(const char *, ...) PRINTF;
-void sox_debug_more(char const * fmt, ...) PRINTF;
-void sox_debug_most(char const * fmt, ...) PRINTF;
-
-#define sox_fail       sox_globals.subsystem=__FILE__,sox_fail
-#define sox_warn       sox_globals.subsystem=__FILE__,sox_warn
-#define sox_report     sox_globals.subsystem=__FILE__,sox_report
-#define sox_debug      sox_globals.subsystem=__FILE__,sox_debug
-#define sox_debug_more sox_globals.subsystem=__FILE__,sox_debug_more
-#define sox_debug_most sox_globals.subsystem=__FILE__,sox_debug_most
-
-void sox_fail_errno(sox_format_t *, int, const char *, ...)
+void lsx_fail_errno(sox_format_t *, int, const char *, ...)
 #ifdef __GNUC__
 __attribute__ ((format (printf, 3, 4)));
 #else
@@ -240,58 +130,6 @@
 ;
 #endif
 
-size_t num_comments(comments_t comments);
-void append_comment(comments_t * comments, char const * comment);
-void append_comments(comments_t * comments, char const * comment);
-comments_t copy_comments(comments_t comments);
-void delete_comments(comments_t * comments);
-char * cat_comments(comments_t comments);
-char const * find_comment(comments_t comments, char const * id);
-
-
-
-#ifdef WORDS_BIGENDIAN
-#define SOX_IS_BIGENDIAN 1
-#define SOX_IS_LITTLEENDIAN 0
-#else
-#define SOX_IS_BIGENDIAN 0
-#define SOX_IS_LITTLEENDIAN 1
-#endif
-
-#ifndef M_PI
-#define M_PI    3.14159265358979323846
-#endif
-#ifndef M_PI_2
-#define M_PI_2  1.57079632679489661923  /* pi/2 */
-#endif
-#ifndef M_LN10
-#define M_LN10  2.30258509299404568402  /* natural log of 10 */
-#endif
-#define dB_to_linear(x) exp((x) * M_LN10 * 0.05)
-#define linear_to_dB(x) (log10(x) * 20)
-
-typedef struct sox_globals /* Global parameters (for effects & formats) */
-{
-  unsigned     verbosity;
-/* The following is used at times in libsox when alloc()ing buffers
- * to perform file I/O.  It can be useful to pass in similar sized
- * data to get max performance.
- */
-  sox_size_t   bufsiz;
-  char const * stdin_in_use_by;
-  char const * stdout_in_use_by;
-  sox_output_message_handler_t output_message_handler;
-  char const * subsystem;
-  sox_bool     repeatable;
-} sox_globals_t;
-
-struct sox_effects_globals /* Global parameters (for effects) */
-{
-  sox_plot_t plot;         /* To help the user choose effect & options */
-  double speed;            /* Gather up all speed changes here, then resample */
-  sox_globals_t * global_info;
-};
-
 typedef struct sox_formats_globals /* Global parameters (for formats) */
 {
   sox_globals_t * global_info;
@@ -298,55 +136,38 @@
 } sox_formats_globals;
 
 
-extern sox_globals_t sox_globals;
-extern sox_effects_globals_t sox_effects_globals;
-extern uint8_t const cswap[256];
 
 
 
 /*------------------------------ File Handlers -------------------------------*/
 
-void sox_init_encodinginfo(sox_encodinginfo_t * e);
-unsigned sox_precision(sox_encoding_t encoding, unsigned pcm_size);
-int sox_check_read_params(sox_format_t * ft, unsigned channels,
+int lsx_check_read_params(sox_format_t * ft, unsigned channels,
     sox_rate_t rate, sox_encoding_t encoding, unsigned bits_per_sample,
     off_t num_samples);
-sox_sample_t sox_sample_max(sox_encodinginfo_t const * encoding);
+sox_sample_t lsx_sample_max(sox_encodinginfo_t const * encoding);
 #define SOX_FORMAT_HANDLER(name) \
 sox_format_handler_t const * sox_##name##_format_fn(void); \
 sox_format_handler_t const * sox_##name##_format_fn(void)
 #define div_bits(size, bits) (off_t)((double)(size) * 8 / bits)
 
-typedef const sox_format_handler_t *(*sox_format_fn_t)(void);
-
-typedef struct {
-  char *name;
-  sox_format_fn_t fn;
-} sox_format_tab_t;
-
-extern unsigned sox_formats;
-extern sox_format_tab_t sox_format_fns[];
-
 /* Raw I/O */
-int sox_rawstartread(sox_format_t * ft);
-sox_size_t sox_rawread(sox_format_t * ft, sox_sample_t *buf, sox_size_t nsamp);
-int sox_rawstopread(sox_format_t * ft);
-int sox_rawstartwrite(sox_format_t * ft);
-sox_size_t sox_rawwrite(sox_format_t * ft, const sox_sample_t *buf, sox_size_t nsamp);
-int sox_rawseek(sox_format_t * ft, sox_size_t offset);
-int sox_rawstart(sox_format_t * ft, sox_bool default_rate, sox_bool default_channels, sox_bool default_length, sox_encoding_t encoding, unsigned size);
-#define sox_rawstartread(ft) sox_rawstart(ft, sox_false, sox_false, sox_false, SOX_ENCODING_UNKNOWN, 0)
-#define sox_rawstartwrite sox_rawstartread
-#define sox_rawstopread NULL
-#define sox_rawstopwrite NULL
+int lsx_rawstartread(sox_format_t * ft);
+sox_size_t lsx_rawread(sox_format_t * ft, sox_sample_t *buf, sox_size_t nsamp);
+int lsx_rawstopread(sox_format_t * ft);
+int lsx_rawstartwrite(sox_format_t * ft);
+sox_size_t lsx_rawwrite(sox_format_t * ft, const sox_sample_t *buf, sox_size_t nsamp);
+int lsx_rawseek(sox_format_t * ft, sox_size_t offset);
+int lsx_rawstart(sox_format_t * ft, sox_bool default_rate, sox_bool default_channels, sox_bool default_length, sox_encoding_t encoding, unsigned size);
+#define lsx_rawstartread(ft) lsx_rawstart(ft, sox_false, sox_false, sox_false, SOX_ENCODING_UNKNOWN, 0)
+#define lsx_rawstartwrite lsx_rawstartread
+#define lsx_rawstopread NULL
+#define lsx_rawstopwrite NULL
 
 
 
 /*--------------------------------- Effects ----------------------------------*/
 
-int sox_usage(sox_effect_t * effp);
-typedef const sox_effect_handler_t *(*sox_effect_fn_t)(void);
-extern sox_effect_fn_t sox_effect_fns[];
+int lsx_usage(sox_effect_t * effp);
 #define EFFECT(f) extern sox_effect_handler_t const * sox_##f##_effect_fn(void);
 #include "effects.h"
 #undef EFFECT
@@ -359,7 +180,7 @@
   if (end_ptr != *argv) { \
     if (d < min || d > max || *end_ptr != '\0') {\
       sox_fail("parameter `%s' must be between %g and %g", #name, (double)min, (double)max); \
-      return sox_usage(effp); \
+      return lsx_usage(effp); \
     } \
     p->name = d; \
     --argc, ++argv; \
@@ -375,15 +196,5 @@
     --argc, ++argv; \
   } \
 }
-
-struct sox_effects_chain {
-#define SOX_MAX_EFFECTS 20
-  sox_effect_t * effects[SOX_MAX_EFFECTS];
-  unsigned length;
-  sox_sample_t **ibufc, **obufc; /* Channel interleave buffers */
-  sox_effects_globals_t global_info;
-  sox_encodinginfo_t const * in_enc;
-  sox_encodinginfo_t const * out_enc;
-};
 
 #endif
--- a/src/soxio.c
+++ /dev/null
@@ -1,935 +1,0 @@
-/*
- * libSoX IO routines       (c) 2005-8 Chris Bagwell and SoX contributors
- *
- * This library is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or (at
- * your option) any later version.
- *
- * This library 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 Lesser
- * General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this library.  If not, write to the Free Software Foundation,
- * Fifth Floor, 51 Franklin Street, Boston, MA 02111-1301, USA.
- */
-
-#include "sox_i.h"
-
-#include <assert.h>
-#include <ctype.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <math.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-
-#ifdef HAVE_IO_H
-  #include <io.h>
-#endif
-
-#ifdef HAVE_LIBLTDL
-  #include <ltdl.h>
-#endif
-
-static void output_message(unsigned level, const char *filename, const char *fmt, va_list ap);
-
-sox_globals_t sox_globals = {2, 8192, NULL, NULL, output_message, NULL, sox_false};
-
-static void output_message(unsigned level, const char *filename, const char *fmt, va_list ap)
-{
-  if (sox_globals.verbosity >= level) {
-    sox_output_message(stderr, filename, fmt, ap);
-    fprintf(stderr, "\n");
-  }
-}
-
-/* Plugins */
-
-#ifdef HAVE_LIBLTDL
-static sox_bool plugins_initted = sox_false;
-
-#define MAX_NAME_LEN 1024 /* FIXME: Use vasprintf */
-static int init_format(const char *file, lt_ptr data)
-{
-  lt_dlhandle lth = lt_dlopenext(file);
-  const char *end = file + strlen(file);
-  const char prefix[] = "libsox_fmt_";
-  char fnname[MAX_NAME_LEN];
-  char *start = strstr(file, prefix);
-
-  (void)data;
-  if (start && (start += sizeof(prefix) - 1) < end) {
-    int ret = snprintf(fnname, MAX_NAME_LEN, "sox_%.*s_format_fn", end - start, start);
-    if (ret > 0 && ret < MAX_NAME_LEN) {
-      union {sox_format_fn_t fn; lt_ptr ptr;} ltptr;
-      ltptr.ptr = lt_dlsym(lth, fnname);
-      sox_debug("opening format plugin `%s': library %p, entry point %p\n", fnname, (void *)lth, ltptr.ptr);
-      if (ltptr.fn && (ltptr.fn()->sox_lib_version_code & ~255) == (SOX_LIB_VERSION_CODE & ~255)){
-        sox_format_fns[sox_formats].fn = ltptr.fn;
-        sox_formats++;
-      }
-    }
-  }
-  return 0;
-}
-#endif
-
-/*
- * Initialize list of known format handlers.
- */
-int sox_format_init(void)
-{
-#ifdef HAVE_LIBLTDL
-  int ret;
-
-  if ((ret = lt_dlinit()) != 0) {
-    sox_fail("lt_dlinit failed with %d error(s): %s", ret, lt_dlerror());
-    return SOX_EOF;
-  }
-  plugins_initted = sox_true;
-
-  lt_dlforeachfile(PKGLIBDIR, init_format, NULL);
-#endif
-  return SOX_SUCCESS;
-}
-
-/*
- * Cleanup things.
- */
-void sox_format_quit(void)
-{
-#ifdef HAVE_LIBLTDL
-  {
-    int ret;
-    if (plugins_initted && (ret = lt_dlexit()) != 0) {
-      sox_fail("lt_dlexit failed with %d error(s): %s", ret, lt_dlerror());
-    }
-  }
-#endif
-}
-
-/*
- * Check that we have a known format suffix string.
- */
-int sox_gettype(sox_format_t * ft, sox_bool is_file_extension)
-{
-  sox_format_handler_t const * handler;
-
-  if (!ft->filetype) {
-    sox_fail_errno(ft, SOX_EFMT, "unknown file type");
-    return SOX_EFMT;
-  }
-  handler = sox_find_format(ft->filetype, is_file_extension);
-  if (!handler) {
-    sox_fail_errno(ft, SOX_EFMT, "unknown file type `%s'", ft->filetype);
-    return SOX_EFMT;
-  }
-  ft->handler = *handler;
-  if (ft->mode == 'w' && !ft->handler.startwrite && !ft->handler.write) {
-    sox_fail_errno(ft, SOX_EFMT, "file type `%s' isn't writable", ft->filetype);
-    return SOX_EFMT;
-  }
-  return SOX_SUCCESS;
-}
-
-void set_signal_defaults(sox_signalinfo_t * signal)
-{
-  if (!signal->rate     ) signal->rate      = SOX_DEFAULT_RATE;
-  if (!signal->precision) signal->precision = SOX_DEFAULT_PRECISION;
-  if (!signal->channels ) signal->channels  = SOX_DEFAULT_CHANNELS;
-}
-
-static void set_endianness_if_not_already_set(sox_format_t * ft)
-{
-  if (ft->encoding.opposite_endian)
-    ft->encoding.reverse_bytes = (ft->handler.flags & SOX_FILE_ENDIAN)?
-      !(ft->handler.flags & SOX_FILE_ENDBIG) != SOX_IS_BIGENDIAN : sox_true;
-  else if (ft->encoding.reverse_bytes == SOX_OPTION_DEFAULT)
-    ft->encoding.reverse_bytes = (ft->handler.flags & SOX_FILE_ENDIAN)?
-      !(ft->handler.flags & SOX_FILE_ENDBIG) == SOX_IS_BIGENDIAN : sox_false;
-
-  if (ft->handler.flags & SOX_FILE_ENDIAN) {
-    if (ft->encoding.reverse_bytes ==
-        (!(ft->handler.flags & SOX_FILE_ENDBIG) != SOX_IS_BIGENDIAN))
-      sox_report("`%s': overriding file-type byte-order", ft->filename);
-  } else if (ft->encoding.reverse_bytes == sox_true)
-    sox_report("`%s': overriding machine byte-order", ft->filename);
-
-  if (ft->encoding.reverse_bits == SOX_OPTION_DEFAULT)
-    ft->encoding.reverse_bits = !!(ft->handler.flags & SOX_FILE_BIT_REV);
-  else if (ft->encoding.reverse_bits == !(ft->handler.flags & SOX_FILE_BIT_REV))
-      sox_report("`%s': overriding file-type bit-order", ft->filename);
-
-  if (ft->encoding.reverse_nibbles == SOX_OPTION_DEFAULT)
-    ft->encoding.reverse_nibbles = !!(ft->handler.flags & SOX_FILE_NIB_REV);
-  else
-    if (ft->encoding.reverse_nibbles == !(ft->handler.flags & SOX_FILE_NIB_REV))
-      sox_report("`%s': overriding file-type nibble-order", ft->filename);
-}
-
-static int is_seekable(sox_format_t * ft)
-{
-  struct stat st;
-
-  fstat(fileno(ft->fp), &st);
-  return ((st.st_mode & S_IFMT) == S_IFREG);
-}
-
-/* check that all settings have been given */
-static int sox_checkformat(sox_format_t * ft)
-{
-  ft->sox_errno = SOX_SUCCESS;
-
-  if (!ft->signal.rate) {
-    sox_fail_errno(ft,SOX_EFMT,"sampling rate was not specified");
-    return SOX_EOF;
-  }
-  if (!ft->signal.precision) {
-    sox_fail_errno(ft,SOX_EFMT,"data encoding was not specified");
-    return SOX_EOF;
-  }
-  return SOX_SUCCESS;
-}
-
-static char const * detect_magic(sox_format_t * ft, char const * ext)
-{
-  char data[256];
-  size_t len = sox_readbuf(ft, data, sizeof(data));
-  #define MAGIC(type, p2, l2, d2, p1, l1, d1) if (len >= p1 + l1 && \
-      !memcmp(data + p1, d1, l1) && !memcmp(data + p2, d2, l2)) return #type;
-  MAGIC(voc   , 0, 0, ""     , 0, 20, "Creative Voice File\x1a")
-  MAGIC(smp   , 0, 0, ""     , 0, 17, "SOUND SAMPLE DATA")
-  MAGIC(wve   , 0, 0, ""     , 0, 15, "ALawSoundFile**")
-  MAGIC(amr-wb, 0, 0, ""     , 0,  9, "#!AMR-WB\n")
-  MAGIC(prc   , 0, 0, ""     , 0,  8, "\x37\x00\x00\x10\x6d\x00\x00\x10")
-  MAGIC(sph   , 0, 0, ""     , 0,  7, "NIST_1A")
-  MAGIC(amr-nb, 0, 0, ""     , 0,  6, "#!AMR\n")
-  MAGIC(txw   , 0, 0, ""     , 0,  6, "LM8953")
-  MAGIC(sndt  , 0, 0, ""     , 0,  6, "SOUND\x1a")
-  MAGIC(vorbis, 0, 4, "OggS" , 29, 6, "vorbis")
-  MAGIC(speex , 0, 4, "OggS" , 28, 6, "Speex")
-  MAGIC(hcom  ,65, 4, "FSSD" , 128,4, "HCOM")
-  MAGIC(wav   , 0, 4, "RIFF" , 8,  4, "WAVE")
-  MAGIC(wav   , 0, 4, "RIFX" , 8,  4, "WAVE")
-  MAGIC(aiff  , 0, 4, "FORM" , 8,  4, "AIFF")
-  MAGIC(aifc  , 0, 4, "FORM" , 8,  4, "AIFC")
-  MAGIC(8svx  , 0, 4, "FORM" , 8,  4, "8SVX")
-  MAGIC(maud  , 0, 4, "FORM" , 8,  4, "MAUD")
-  MAGIC(xa    , 0, 0, ""     , 0,  4, "XA\0\0")
-  MAGIC(xa    , 0, 0, ""     , 0,  4, "XAI\0")
-  MAGIC(xa    , 0, 0, ""     , 0,  4, "XAJ\0")
-  MAGIC(au    , 0, 0, ""     , 0,  4, ".snd")
-  MAGIC(au    , 0, 0, ""     , 0,  4, "dns.")
-  MAGIC(au    , 0, 0, ""     , 0,  4, "\0ds.")
-  MAGIC(au    , 0, 0, ""     , 0,  4, ".sd\0")
-  MAGIC(flac  , 0, 0, ""     , 0,  4, "fLaC")
-  MAGIC(avr   , 0, 0, ""     , 0,  4, "2BIT")
-  MAGIC(caf   , 0, 0, ""     , 0,  4, "caff")
-  MAGIC(paf   , 0, 0, ""     , 0,  4, " paf")
-  MAGIC(sf    , 0, 0, ""     , 0,  4, "\144\243\001\0")
-  MAGIC(sf    , 0, 0, ""     , 0,  4, "\0\001\243\144")
-  MAGIC(sf    , 0, 0, ""     , 0,  4, "\144\243\002\0")
-  MAGIC(sf    , 0, 0, ""     , 0,  4, "\0\002\243\144")
-  MAGIC(sf    , 0, 0, ""     , 0,  4, "\144\243\003\0")
-  MAGIC(sf    , 0, 0, ""     , 0,  4, "\0\003\243\144")
-  MAGIC(sf    , 0, 0, ""     , 0,  4, "\144\243\004\0")
-
-  if (ext && !strcasecmp(ext, "snd"))
-  MAGIC(sndr  , 7, 1, ""     , 0,  2, "\0")
-  #undef MAGIC
-  return NULL;
-}
-
-sox_format_t * sox_open_read(
-    char               const * path,
-    sox_signalinfo_t   const * signal,
-    sox_encodinginfo_t const * encoding,
-    char               const * filetype)
-{
-  sox_format_t * ft = xcalloc(1, sizeof(*ft));
-  sox_format_handler_t const * handler;
-
-  if (filetype) {
-    if (!(handler = sox_find_format(filetype, sox_false))) {
-      sox_fail("no handler for given file type `%s'", filetype);
-      goto error;
-    }
-    ft->handler = *handler;
-  }
-
-  if (!(ft->handler.flags & SOX_FILE_NOSTDIO)) {
-    if (!strcmp(path, "-")) { /* Use stdin if the filename is "-" */
-      if (sox_globals.stdin_in_use_by) {
-        sox_fail("`-' (stdin) already in use by `%s'", sox_globals.stdin_in_use_by);
-        goto error;
-      }
-      sox_globals.stdin_in_use_by = "audio input";
-      SET_BINARY_MODE(stdin);
-      ft->fp = stdin;
-    }
-    else if ((ft->fp = xfopen(path, "rb")) == NULL) {
-      sox_fail("can't open input file `%s': %s", path, strerror(errno));
-      goto error;
-    }
-    ft->seekable = is_seekable(ft);
-  }
-
-  if (!filetype) {
-    if (ft->seekable) {
-      filetype = detect_magic(ft, find_file_extension(path));
-      sox_rewind(ft);
-    }
-    if (filetype) {
-      sox_report("detected file format type `%s'", filetype);
-      if (!(handler = sox_find_format(filetype, sox_false))) {
-        sox_fail("no handler for detected file type `%s'", filetype);
-        goto error;
-      }
-    }
-    else {
-      if (!(filetype = find_file_extension(path))) {
-        sox_fail("can't determine type of `%s'", path);
-        goto error;
-      }
-      if (!(handler = sox_find_format(filetype, sox_true))) {
-        sox_fail("no handler for file extension `%s'", filetype);
-        goto error;
-      }
-    }
-    ft->handler = *handler;
-  }
-  if (!ft->handler.startread && !ft->handler.read) {
-    sox_fail("file type `%s' isn't readable", filetype);
-    goto error;
-  }
-  
-  ft->mode = 'r';
-  
-  if (signal)
-    ft->signal = *signal;
-  
-  if (encoding)
-    ft->encoding = *encoding;
-  else sox_init_encodinginfo(&ft->encoding);
-  set_endianness_if_not_already_set(ft);
-
-  ft->filetype = xstrdup(filetype);
-  ft->filename = xstrdup(path);
-
-  /* Read and write starters can change their formats. */
-  if (ft->handler.startread && (*ft->handler.startread)(ft) != SOX_SUCCESS) {
-    sox_fail("can't open input file `%s': %s", ft->filename, ft->sox_errstr);
-    goto error;
-  }
-
-  /* Fill in some defaults: */
-  if (!ft->signal.precision)
-    ft->signal.precision = sox_precision(ft->encoding.encoding, ft->encoding.bits_per_sample);
-  if (!(ft->handler.flags & SOX_FILE_PHONY) && !ft->signal.channels)
-    ft->signal.channels = 1;
-
-  if (sox_checkformat(ft) == SOX_SUCCESS)
-    return ft;
-  sox_fail("bad input format for file `%s': %s", ft->filename, ft->sox_errstr);
-
-error:
-  if (ft->fp && ft->fp != stdin)
-    fclose(ft->fp);
-  free(ft->filename);
-  free(ft->filetype);
-  free(ft);
-  return NULL;
-}
-
-static void set_output_format(sox_format_t * ft)
-{
-  sox_encoding_t e;
-  unsigned i, s;
-  unsigned const * encodings = ft->handler.write_formats;
-#define enc_arg(T) (T)encodings[i++]
-
-  if (ft->handler.write_rates){
-    if (!ft->signal.rate)
-      ft->signal.rate = ft->handler.write_rates[0];
-    else {
-      sox_rate_t r;
-      i = 0;
-      while ((r = ft->handler.write_rates[i++])) {
-        if (r == ft->signal.rate)
-          break;
-      }
-      if (r != ft->signal.rate) {
-        sox_rate_t given = ft->signal.rate, max = 0;
-        ft->signal.rate = HUGE_VAL;
-        i = 0;
-        while ((r = ft->handler.write_rates[i++])) {
-          if (r > given && r < ft->signal.rate)
-            ft->signal.rate = r;
-          else max = max(r, max);
-        }
-        if (ft->signal.rate == HUGE_VAL)
-          ft->signal.rate = max;
-        sox_warn("%s can't encode at %gHz; using %gHz", ft->handler.names[0], given, ft->signal.rate);
-      }
-    }
-  }
-  else if (!ft->signal.rate)
-    ft->signal.rate = SOX_DEFAULT_RATE;
-
-  if (ft->handler.flags & SOX_FILE_CHANS) {
-    if (ft->signal.channels == 1 && !(ft->handler.flags & SOX_FILE_MONO)) {
-      ft->signal.channels = (ft->handler.flags & SOX_FILE_STEREO)? 2 : 4;
-      sox_warn("%s can't encode mono; setting channels to %u", ft->handler.names[0], ft->signal.channels);
-    } else
-    if (ft->signal.channels == 2 && !(ft->handler.flags & SOX_FILE_STEREO)) {
-      ft->signal.channels = (ft->handler.flags & SOX_FILE_QUAD)? 4 : 1;
-      sox_warn("%s can't encode stereo; setting channels to %u", ft->handler.names[0], ft->signal.channels);
-    } else
-    if (ft->signal.channels == 4 && !(ft->handler.flags & SOX_FILE_QUAD)) {
-      ft->signal.channels = (ft->handler.flags & SOX_FILE_STEREO)? 2 : 1;
-      sox_warn("%s can't encode quad; setting channels to %u", ft->handler.names[0], ft->signal.channels);
-    }
-  } else ft->signal.channels = max(ft->signal.channels, 1);
-
-  if (!encodings)
-    return;
-  /* If an encoding has been given, check if it supported by this handler */
-  if (ft->encoding.encoding) {
-    i = 0;
-    while ((e = enc_arg(sox_encoding_t))) {
-      if (e == ft->encoding.encoding)
-        break;
-      while (enc_arg(unsigned));
-    }
-    if (e != ft->encoding.encoding) {
-      sox_warn("%s can't encode %s", ft->handler.names[0], sox_encodings_str[ft->encoding.encoding]);
-      ft->encoding.encoding = 0;
-    }
-    else {
-      unsigned max_p = 0;
-      unsigned max_p_s = 0;
-      unsigned given_size = 0;
-      sox_bool found = sox_false;
-      if (ft->encoding.bits_per_sample)
-        given_size = ft->encoding.bits_per_sample;
-      ft->encoding.bits_per_sample = 65;
-      while ((s = enc_arg(unsigned))) {
-        if (s == given_size)
-          found = sox_true;
-        if (sox_precision(e, s) >= ft->signal.precision) {
-          if (s < ft->encoding.bits_per_sample)
-            ft->encoding.bits_per_sample = s;
-        }
-        else if (sox_precision(e, s) > max_p) {
-          max_p = sox_precision(e, s);
-          max_p_s = s;
-        }
-      }
-      if (ft->encoding.bits_per_sample == 65)
-        ft->encoding.bits_per_sample = max_p_s;
-      if (given_size) {
-        if (found)
-          ft->encoding.bits_per_sample = given_size;
-        else sox_warn("%s can't encode %s to %u-bit", ft->handler.names[0], sox_encodings_str[ft->encoding.encoding], given_size);
-      }
-    }
-  }
-
-  /* If a size has been given, check if it supported by this handler */
-  if (!ft->encoding.encoding && ft->encoding.bits_per_sample) {
-    i = 0;
-    s= 0;
-    while (s != ft->encoding.bits_per_sample && (e = enc_arg(sox_encoding_t)))
-      while ((s = enc_arg(unsigned)) && s != ft->encoding.bits_per_sample);
-    if (s != ft->encoding.bits_per_sample) {
-      sox_warn("%s can't encode to %u-bit", ft->handler.names[0], ft->encoding.bits_per_sample);
-      ft->encoding.bits_per_sample = 0;
-    }
-    else ft->encoding.encoding = e;
-  }
-
-  /* Find the smallest lossless encoding with precision >= signal.precision */
-  if (!ft->encoding.encoding) {
-    ft->encoding.bits_per_sample = 65;
-    i = 0;
-    while ((e = enc_arg(sox_encoding_t)))
-      while ((s = enc_arg(unsigned)))
-        if (e < SOX_ENCODING_LOSSLESS &&
-            sox_precision(e, s) >= ft->signal.precision && s < ft->encoding.bits_per_sample) {
-          ft->encoding.encoding = e;
-          ft->encoding.bits_per_sample = s;
-        }
-  }
-
-  /* Find the smallest lossy encoding with precision >= signal precision,
-   * or, if none such, the highest precision encoding */
-  if (!ft->encoding.encoding) {
-    unsigned max_p = 0;
-    sox_encoding_t max_p_e = 0;
-    unsigned max_p_s = 0;
-    i = 0;
-    while ((e = enc_arg(sox_encoding_t)))
-      do {
-        s = enc_arg(unsigned);
-        if (sox_precision(e, s) >= ft->signal.precision) {
-          if (s < ft->encoding.bits_per_sample) {
-            ft->encoding.encoding = e;
-            ft->encoding.bits_per_sample = s;
-          }
-        }
-        else if (sox_precision(e, s) > max_p) {
-          max_p = sox_precision(e, s);
-          max_p_e = e;
-          max_p_s = s;
-        }
-      } while (s);
-    if (!ft->encoding.encoding) {
-      ft->encoding.encoding = max_p_e;
-      ft->encoding.bits_per_sample = max_p_s;
-    }
-  }
-  ft->signal.precision = min(ft->signal.precision, sox_precision(ft->encoding.encoding, ft->encoding.bits_per_sample));
-  #undef enc_arg
-}
-
-sox_bool sox_format_supports_encoding(
-    char               const * path,
-    char               const * filetype,
-    sox_encodinginfo_t const * encoding)
-{
-  #define enc_arg(T) (T)ft.handler.write_formats[i++]
-  sox_encoding_t e;
-  unsigned i = 0, s;
-  sox_format_t ft;
-  sox_bool no_filetype_given = filetype == NULL;
-
-  assert(path);
-  assert(encoding);
-  ft.filetype = (char *)(filetype? filetype : find_file_extension(path));
-  if (sox_gettype(&ft, no_filetype_given) != SOX_SUCCESS ||
-      !ft.handler.write_formats)
-    return sox_false;
-  while ((e = enc_arg(sox_encoding_t))) {
-    if (e == encoding->encoding) {
-      while ((s = enc_arg(unsigned)))
-        if (s == encoding->bits_per_sample)
-          return sox_true;
-      break;
-    }
-    while (enc_arg(unsigned));
-  }
-  return sox_false;
-  #undef enc_arg
-}
-
-sox_format_t * sox_open_write(
-    sox_bool (*overwrite_permitted)(const char *filename),
-    char               const * path,
-    sox_signalinfo_t   const * signal,
-    sox_encodinginfo_t const * encoding,
-    char               const * filetype,
-    comments_t                 comments,
-    sox_size_t                 length,
-    sox_instrinfo_t    const * instr,
-    sox_loopinfo_t     const * loops)
-{
-  sox_bool no_filetype_given = filetype == NULL;
-  sox_format_t * ft = xcalloc(sizeof(*ft), 1);
-  int i;
-
-  if (!path || !signal) {
-    free(ft);
-    return NULL;
-  }
-
-  ft->filename = xstrdup(path);
-
-  if (!filetype) {
-    char const * extension = find_file_extension(ft->filename);
-    if (extension)
-      ft->filetype = xstrdup(extension);
-  } else ft->filetype = xstrdup(filetype);
-
-  ft->mode = 'w';
-  if (sox_gettype(ft, no_filetype_given) != SOX_SUCCESS) {
-    sox_fail("Can't open output file `%s': %s", ft->filename, ft->sox_errstr);
-    goto error;
-  }
-  ft->signal = *signal;
-  if (encoding)
-    ft->encoding = *encoding;
-  else sox_init_encodinginfo(&ft->encoding);
-
-  if (!(ft->handler.flags & SOX_FILE_NOSTDIO)) {
-    if (!strcmp(ft->filename, "-")) { /* Use stdout if the filename is "-" */
-      if (sox_globals.stdout_in_use_by) {
-        sox_fail("`-' (stdout) already in use by `%s'", sox_globals.stdout_in_use_by);
-        goto error;
-      }
-      sox_globals.stdout_in_use_by = "audio output";
-      SET_BINARY_MODE(stdout);
-      ft->fp = stdout;
-    }
-    else {
-      struct stat st;
-      if (!stat(ft->filename, &st) && (st.st_mode & S_IFMT) == S_IFREG &&
-          (overwrite_permitted && !overwrite_permitted(ft->filename))) {
-        sox_fail("Permission to overwrite '%s' denied", ft->filename);
-        goto error;
-      }
-      if ((ft->fp = fopen(ft->filename, "wb")) == NULL) {
-        sox_fail("can't open output file `%s': %s", ft->filename, strerror(errno));
-        goto error;
-      }
-    }
-
-    /* stdout tends to be line-buffered.  Override this */
-    /* to be Full Buffering. */
-    if (setvbuf (ft->fp, NULL, _IOFBF, sizeof(char) * sox_globals.bufsiz)) {
-      sox_fail("Can't set write buffer");
-      goto error;
-    }
-    ft->seekable = is_seekable(ft);
-  }
-
-  ft->comments = copy_comments(comments);
-
-  if (loops) for (i = 0; i < SOX_MAX_NLOOPS; i++)
-    ft->loops[i] = loops[i];
-
-  /* leave SMPTE # alone since it's absolute */
-  if (instr)
-    ft->instr = *instr;
-
-  ft->length = length;
-  set_endianness_if_not_already_set(ft);
-  set_output_format(ft);
-
-  /* FIXME: doesn't cover the situation where
-   * codec changes audio length due to block alignment (e.g. 8svx, gsm): */
-  if (signal->rate && signal->channels)
-    ft->length = ft->length * ft->signal.rate / signal->rate *
-      ft->signal.channels / signal->channels + .5;
-
-  if ((ft->handler.flags & SOX_FILE_REWIND) && !ft->length && !ft->seekable)
-    sox_warn("can't seek in output file `%s'; length in file header will be unspecified", ft->filename);
-
-  /* Read and write starters can change their formats. */
-  if (ft->handler.startwrite && (ft->handler.startwrite)(ft) != SOX_SUCCESS){
-    sox_fail("can't open output file `%s': %s", ft->filename, ft->sox_errstr);
-    goto error;
-  }
-
-  if (sox_checkformat(ft) == SOX_SUCCESS)
-    return ft;
-  sox_fail("bad format for output file `%s': %s", ft->filename, ft->sox_errstr);
-
-error:
-  if (ft->fp && ft->fp != stdout)
-    fclose(ft->fp);
-  free(ft->filename);
-  free(ft->filetype);
-  free(ft);
-  return NULL;
-}
-
-sox_size_t sox_read(sox_format_t * ft, sox_sample_t * buf, sox_size_t len)
-{
-  sox_size_t actual = ft->handler.read? (*ft->handler.read)(ft, buf, len) : 0;
-  return (actual > len? 0 : actual);
-}
-
-sox_size_t sox_write(sox_format_t * ft, const sox_sample_t *buf, sox_size_t len)
-{
-  sox_size_t ret = ft->handler.write? (*ft->handler.write)(ft, buf, len) : 0;
-  ft->olength += ret;
-  return ret;
-}
-
-#define TWIDDLE_BYTE(ub, type) \
-  do { \
-    if (ft->encoding.reverse_bits) \
-      ub = cswap[ub]; \
-    if (ft->encoding.reverse_nibbles) \
-      ub = ((ub & 15) << 4) | (ub >> 4); \
-  } while (0);
-
-#define TWIDDLE_WORD(uw, type) \
-  if (ft->encoding.reverse_bytes) \
-    uw = sox_swap ## type(uw);
-
-#define TWIDDLE_FLOAT(f, type) \
-  if (ft->encoding.reverse_bytes) \
-    sox_swapf(&f);
-
-/* N.B. This macro doesn't work for unaligned types (e.g. 3-byte
-   types). */
-#define READ_FUNC(type, size, ctype, twiddle) \
-  sox_size_t sox_read_ ## type ## _buf( \
-      sox_format_t * ft, ctype *buf, sox_size_t len) \
-  { \
-    sox_size_t n, nread; \
-    nread = sox_readbuf(ft, buf, len * size) / size; \
-    for (n = 0; n < nread; n++) \
-      twiddle(buf[n], type); \
-    return nread; \
-  }
-
-/* Unpack a 3-byte value from a uint8_t * */
-#define sox_unpack3(p) (ft->encoding.reverse_bytes == SOX_IS_BIGENDIAN? \
-  ((p)[0] | ((p)[1] << 8) | ((p)[2] << 16)) : \
-  ((p)[2] | ((p)[1] << 8) | ((p)[0] << 16)))
-
-/* This (slower) macro works for unaligned types (e.g. 3-byte types)
-   that need to be unpacked. */
-#define READ_FUNC_UNPACK(type, size, ctype, twiddle) \
-  sox_size_t sox_read_ ## type ## _buf( \
-      sox_format_t * ft, ctype *buf, sox_size_t len) \
-  { \
-    sox_size_t n, nread; \
-    uint8_t *data = xmalloc(size * len); \
-    nread = sox_readbuf(ft, data, len * size) / size; \
-    for (n = 0; n < nread; n++) \
-      buf[n] = sox_unpack ## size(data + n * size); \
-    free(data); \
-    return n; \
-  }
-
-READ_FUNC(b, 1, uint8_t, TWIDDLE_BYTE)
-READ_FUNC(w, 2, uint16_t, TWIDDLE_WORD)
-READ_FUNC_UNPACK(3, 3, uint24_t, TWIDDLE_WORD)
-READ_FUNC(dw, 4, uint32_t, TWIDDLE_WORD)
-READ_FUNC(f, sizeof(float), float, TWIDDLE_FLOAT)
-READ_FUNC(df, sizeof(double), double, TWIDDLE_WORD)
-
-#define READ1_FUNC(type, ctype) \
-int sox_read ## type(sox_format_t * ft, ctype * datum) { \
-  if (sox_read_ ## type ## _buf(ft, datum, 1) == 1) \
-    return SOX_SUCCESS; \
-  if (!sox_error(ft)) \
-    sox_fail_errno(ft, errno, premature_eof); \
-  return SOX_EOF; \
-}
-
-static char const premature_eof[] = "premature EOF";
-
-READ1_FUNC(b,  uint8_t)
-READ1_FUNC(w,  uint16_t)
-READ1_FUNC(3,  uint24_t)
-READ1_FUNC(dw, uint32_t)
-READ1_FUNC(f,  float)
-READ1_FUNC(df, double)
-
-int sox_readchars(sox_format_t * ft, char * chars, sox_size_t len)
-{
-  size_t ret = sox_readbuf(ft, chars, len);
-  if (ret == len)
-    return SOX_SUCCESS;
-  if (!sox_error(ft))
-    sox_fail_errno(ft, errno, premature_eof);
-  return SOX_EOF;
-}
-
-/* N.B. This macro doesn't work for unaligned types (e.g. 3-byte
-   types). */
-#define WRITE_FUNC(type, size, ctype, twiddle) \
-  sox_size_t sox_write_ ## type ## _buf( \
-      sox_format_t * ft, ctype *buf, sox_size_t len) \
-  { \
-    sox_size_t n, nwritten; \
-    for (n = 0; n < len; n++) \
-      twiddle(buf[n], type); \
-    nwritten = sox_writebuf(ft, buf, len * size); \
-    return nwritten / size; \
-  }
-
-/* Pack a 3-byte value to a uint8_t * */
-#define sox_pack3(p, v) do {if (ft->encoding.reverse_bytes == SOX_IS_BIGENDIAN)\
-{(p)[0] = v & 0xff; (p)[1] = (v >> 8) & 0xff; (p)[2] = (v >> 16) & 0xff;} else \
-{(p)[2] = v & 0xff; (p)[1] = (v >> 8) & 0xff; (p)[0] = (v >> 16) & 0xff;} \
-} while (0)
-
-/* This (slower) macro works for unaligned types (e.g. 3-byte types)
-   that need to be packed. */
-#define WRITE_FUNC_PACK(type, size, ctype, twiddle) \
-  sox_size_t sox_write_ ## type ## _buf( \
-      sox_format_t * ft, ctype *buf, sox_size_t len) \
-  { \
-    sox_size_t n, nwritten; \
-    uint8_t *data = xmalloc(size * len); \
-    for (n = 0; n < len; n++) \
-      sox_pack ## size(data + n * size, buf[n]); \
-    nwritten = sox_writebuf(ft, data, len * size); \
-    free(data); \
-    return nwritten / size; \
-  }
-
-WRITE_FUNC(b, 1, uint8_t, TWIDDLE_BYTE)
-WRITE_FUNC(w, 2, uint16_t, TWIDDLE_WORD)
-WRITE_FUNC_PACK(3, 3, uint24_t, TWIDDLE_WORD)
-WRITE_FUNC(dw, 4, uint32_t, TWIDDLE_WORD)
-WRITE_FUNC(f, sizeof(float), float, TWIDDLE_FLOAT)
-WRITE_FUNC(df, sizeof(double), double, TWIDDLE_WORD)
-
-#define WRITE1U_FUNC(type, ctype) \
-  int sox_write ## type(sox_format_t * ft, unsigned d) \
-  { ctype datum = (ctype)d; \
-    return sox_write_ ## type ## _buf(ft, &datum, 1) == 1 ? SOX_SUCCESS : SOX_EOF; \
-  }
-
-#define WRITE1S_FUNC(type, ctype) \
-  int sox_writes ## type(sox_format_t * ft, signed d) \
-  { ctype datum = (ctype)d; \
-    return sox_write_ ## type ## _buf(ft, &datum, 1) == 1 ? SOX_SUCCESS : SOX_EOF; \
-  }
-
-#define WRITE1_FUNC(type, ctype) \
-  int sox_write ## type(sox_format_t * ft, ctype datum) \
-  { \
-    return sox_write_ ## type ## _buf(ft, &datum, 1) == 1 ? SOX_SUCCESS : SOX_EOF; \
-  }
-
-WRITE1U_FUNC(b, uint8_t)
-WRITE1U_FUNC(w, uint16_t)
-WRITE1U_FUNC(3, uint24_t)
-WRITE1U_FUNC(dw, uint32_t)
-WRITE1S_FUNC(b, uint8_t)
-WRITE1S_FUNC(w, uint16_t)
-WRITE1_FUNC(df, double)
-
-int sox_writef(sox_format_t * ft, double datum)
-{
-  float f = datum;
-  return sox_write_f_buf(ft, &f, 1) == 1 ? SOX_SUCCESS : SOX_EOF;
-}
-
-/* N.B. The file (if any) may already have been deleted. */
-int sox_close(sox_format_t * ft)
-{
-  int rc = SOX_SUCCESS;
-
-  if (ft->mode == 'r')
-    rc = ft->handler.stopread? (*ft->handler.stopread)(ft) : SOX_SUCCESS;
-  else {
-    if (ft->handler.flags & SOX_FILE_REWIND) {
-      if (ft->olength != ft->length && ft->seekable) {
-        rc = sox_seeki(ft, 0, 0);
-        if (rc == SOX_SUCCESS)
-          rc = ft->handler.stopwrite? (*ft->handler.stopwrite)(ft)
-             : ft->handler.startwrite?(*ft->handler.startwrite)(ft) : SOX_SUCCESS;
-      }
-    }
-    else rc = ft->handler.stopwrite? (*ft->handler.stopwrite)(ft) : SOX_SUCCESS;
-  }
-
-  if (!(ft->handler.flags & SOX_FILE_NOSTDIO))
-    fclose(ft->fp);
-  free(ft->filename);
-  free(ft->filetype);
-  delete_comments(&ft->comments);
-
-  free(ft);
-  return rc;
-}
-
-int sox_seek(sox_format_t * ft, sox_size_t offset, int whence)
-{
-    /* FIXME: Implement SOX_SEEK_CUR and SOX_SEEK_END. */
-    if (whence != SOX_SEEK_SET)
-        return SOX_EOF; /* FIXME: return SOX_EINVAL */
-
-    /* If file is a seekable file and this handler supports seeking,
-     * then invoke handler's function.
-     */
-    if (ft->seekable && ft->handler.seek)
-      return (*ft->handler.seek)(ft, offset);
-    return SOX_EOF; /* FIXME: return SOX_EBADF */
-}
-
-sox_bool sox_is_playlist(char const * filename)
-{
-  return strcaseends(filename, ".m3u") || strcaseends(filename, ".pls");
-}
-
-int sox_parse_playlist(sox_playlist_callback_t callback, void * p, char const * const listname)
-{
-  sox_bool const is_pls = strcaseends(listname, ".pls");
-  int const comment_char = "#;"[is_pls];
-  size_t text_length = 100;
-  char * text = xmalloc(text_length + 1);
-  char * dirname = xstrdup(listname);
-  char * slash_pos = LAST_SLASH(dirname);
-  FILE * file = xfopen(listname, "r");
-  char * filename;
-  int c, result = SOX_SUCCESS;
-
-  if (!slash_pos)
-    *dirname = '\0';
-  else
-    *slash_pos = '\0';
-
-  if (file == NULL) {
-    sox_fail("Can't open playlist file `%s': %s", listname, strerror(errno));
-    result = SOX_EOF;
-  }
-  else do {
-    size_t i = 0;
-    size_t begin = 0, end = 0;
-
-    while (isspace(c = getc(file)));
-    if (c == EOF)
-      break;
-    while (c != EOF && !strchr("\r\n", c) && c != comment_char) {
-      if (i == text_length)
-        text = xrealloc(text, (text_length <<= 1) + 1);
-      text[i++] = c;
-      if (!strchr(" \t\f", c))
-        end = i;
-      c = getc(file);
-    }
-    if (ferror(file))
-      break;
-    if (c == comment_char) {
-      do c = getc(file);
-      while (c != EOF && !strchr("\r\n", c));
-      if (ferror(file))
-        break;
-    }
-    text[end] = '\0';
-    if (is_pls) {
-      char dummy;
-      if (!strncasecmp(text, "file", 4) && sscanf(text + 4, "%*u=%c", &dummy) == 1)
-        begin = strchr(text + 5, '=') - text + 1;
-      else end = 0;
-    }
-    if (begin != end) {
-      char const * id = text + begin;
-
-      if (!dirname[0] || is_uri(id) || IS_ABSOLUTE(id))
-        filename = xstrdup(id);
-      else {
-        filename = xmalloc(strlen(dirname) + strlen(id) + 2); 
-        sprintf(filename, "%s/%s", dirname, id); 
-      }
-      if (sox_is_playlist(filename))
-        sox_parse_playlist(callback, p, filename);
-      else if (callback(p, filename))
-        c = EOF;
-      free(filename);
-    }
-  } while (c != EOF);
-
-  if (ferror(file)) {
-    sox_fail("Error reading playlist file `%s': %s", listname, strerror(errno));
-    result = SOX_EOF;
-  }
-  if (file) fclose(file);
-  free(text);
-  free(dirname);
-  return result;
-}
--- a/src/speed.c
+++ b/src/speed.c
@@ -47,7 +47,7 @@
       }
     }
   }
-  return sox_usage(effp);
+  return lsx_usage(effp);
 }
 
 sox_effect_handler_t const *sox_speed_effect_fn(void)
--- a/src/sphere.c
+++ b/src/sphere.c
@@ -22,13 +22,13 @@
   char           * buf;
 
   /* Magic header */
-  if (sox_reads(ft, fldname, 8) || strncmp(fldname, "NIST_1A", 7) != 0) {
-    sox_fail_errno(ft, SOX_EHDR, "Sphere header does not begin with magic word 'NIST_1A'");
+  if (lsx_reads(ft, fldname, 8) || strncmp(fldname, "NIST_1A", 7) != 0) {
+    lsx_fail_errno(ft, SOX_EHDR, "Sphere header does not begin with magic word 'NIST_1A'");
     return (SOX_EOF);
   }
 
-  if (sox_reads(ft, fldsval, 8)) {
-    sox_fail_errno(ft, SOX_EHDR, "Error reading Sphere header");
+  if (lsx_reads(ft, fldsval, 8)) {
+    lsx_fail_errno(ft, SOX_EHDR, "Error reading Sphere header");
     return (SOX_EOF);
   }
 
@@ -39,8 +39,8 @@
   /* Skip what we have read so far */
   header_size -= 16;
 
-  if (sox_reads(ft, buf, header_size) == SOX_EOF) {
-    sox_fail_errno(ft, SOX_EHDR, "Error reading Sphere header");
+  if (lsx_reads(ft, buf, header_size) == SOX_EOF) {
+    lsx_fail_errno(ft, SOX_EHDR, "Error reading Sphere header");
     free(buf);
     return (SOX_EOF);
   }
@@ -63,7 +63,7 @@
       else if (!strcasecmp(fldsval, "pcm"))
         encoding = SOX_ENCODING_SIGN2;
       else {
-        sox_fail_errno(ft, SOX_EFMT, "sph: unsupported coding `%s'", fldsval);
+        lsx_fail_errno(ft, SOX_EFMT, "sph: unsupported coding `%s'", fldsval);
         free(buf);
         return SOX_EOF;
       }
@@ -71,18 +71,18 @@
     else if (strncmp(buf, "sample_byte_format", 18) == 0) {
       sscanf(buf, "%53s %15s %127s", fldname, fldtype, fldsval);
       if (strcmp(fldsval, "01") == 0)         /* Data is little endian. */
-        ft->encoding.reverse_bytes = SOX_IS_BIGENDIAN;
+        ft->encoding.reverse_bytes = MACHINE_IS_BIGENDIAN;
       else if (strcmp(fldsval, "10") == 0)    /* Data is big endian. */
-        ft->encoding.reverse_bytes = SOX_IS_LITTLEENDIAN;
+        ft->encoding.reverse_bytes = MACHINE_IS_LITTLEENDIAN;
       else if (strcmp(fldsval, "1")) {
-        sox_fail_errno(ft, SOX_EFMT, "sph: unsupported coding `%s'", fldsval);
+        lsx_fail_errno(ft, SOX_EFMT, "sph: unsupported coding `%s'", fldsval);
         free(buf);
         return SOX_EOF;
       }
     }
 
-    if (sox_reads(ft, buf, header_size) == SOX_EOF) {
-      sox_fail_errno(ft, SOX_EHDR, "Error reading Sphere header");
+    if (lsx_reads(ft, buf, header_size) == SOX_EOF) {
+      lsx_fail_errno(ft, SOX_EHDR, "Error reading Sphere header");
       free(buf);
       return (SOX_EOF);
     }
@@ -97,7 +97,7 @@
     encoding = SOX_ENCODING_UNSIGNED;
 
   while (header_size) {
-    bytes_read = sox_readbuf(ft, buf, header_size);
+    bytes_read = lsx_readbuf(ft, buf, header_size);
     if (bytes_read == 0) {
       free(buf);
       return (SOX_EOF);
@@ -110,18 +110,18 @@
     /* Check first four bytes of data to see if it's shorten compressed. */
     char           shorten_check[4];
 
-    if (sox_readchars(ft, shorten_check, sizeof(shorten_check)))
+    if (lsx_readchars(ft, shorten_check, sizeof(shorten_check)))
       return SOX_EOF;
-    sox_seeki(ft, -(sox_ssize_t)sizeof(shorten_check), SEEK_CUR);
+    lsx_seeki(ft, -(sox_ssize_t)sizeof(shorten_check), SEEK_CUR);
 
     if (!memcmp(shorten_check, "ajkg", sizeof(shorten_check))) {
-      sox_fail_errno(ft, SOX_EFMT,
+      lsx_fail_errno(ft, SOX_EFMT,
                      "File uses shorten compression, cannot handle this.");
       return (SOX_EOF);
     }
   }
 
-  return sox_check_read_params(ft, channels, (sox_rate_t)rate, encoding,
+  return lsx_check_read_params(ft, channels, (sox_rate_t)rate, encoding,
       bytes_per_sample << 3, (off_t)(num_samples * channels));
 }
 
@@ -130,38 +130,38 @@
   char buf[128];
   long samples = (ft->olength ? ft->olength : ft->length) / ft->signal.channels;
 
-  sox_writes(ft, "NIST_1A\n");
-  sox_writes(ft, "   1024\n");
+  lsx_writes(ft, "NIST_1A\n");
+  lsx_writes(ft, "   1024\n");
 
   if (samples) {
     sprintf(buf, "sample_count -i %ld\n", samples);
-    sox_writes(ft, buf);
+    lsx_writes(ft, buf);
   }
 
   sprintf(buf, "sample_n_bytes -i %d\n", ft->encoding.bits_per_sample >> 3);
-  sox_writes(ft, buf);
+  lsx_writes(ft, buf);
 
   sprintf(buf, "channel_count -i %d\n", ft->signal.channels);
-  sox_writes(ft, buf);
+  lsx_writes(ft, buf);
 
   if (ft->encoding.bits_per_sample == 8)
     sprintf(buf, "sample_byte_format -s1 1\n");
   else
     sprintf(buf, "sample_byte_format -s2 %s\n",
-            ft->encoding.reverse_bytes != SOX_IS_BIGENDIAN ? "10" : "01");
-  sox_writes(ft, buf);
+            ft->encoding.reverse_bytes != MACHINE_IS_BIGENDIAN ? "10" : "01");
+  lsx_writes(ft, buf);
 
   sprintf(buf, "sample_rate -i %u\n", (unsigned) (ft->signal.rate + .5));
-  sox_writes(ft, buf);
+  lsx_writes(ft, buf);
 
   if (ft->encoding.encoding == SOX_ENCODING_ULAW)
-    sox_writes(ft, "sample_coding -s4 ulaw\n");
+    lsx_writes(ft, "sample_coding -s4 ulaw\n");
   else
-    sox_writes(ft, "sample_coding -s3 pcm\n");
+    lsx_writes(ft, "sample_coding -s3 pcm\n");
 
-  sox_writes(ft, "end_head\n");
+  lsx_writes(ft, "end_head\n");
 
-  sox_padbytes(ft, 1024 - (sox_size_t)sox_tell(ft));
+  lsx_padbytes(ft, 1024 - (sox_size_t)lsx_tell(ft));
   return SOX_SUCCESS;
 }
 
@@ -178,9 +178,9 @@
     SOX_LIB_VERSION_CODE,
     "SPeech HEader Resources; defined by NIST",
     names, SOX_FILE_REWIND,
-    start_read, sox_rawread, NULL,
-    write_header, sox_rawwrite, NULL,
-    sox_rawseek, write_encodings, NULL
+    start_read, lsx_rawread, NULL,
+    write_header, lsx_rawwrite, NULL,
+    lsx_rawseek, write_encodings, NULL
   };
   return &handler;
 }
--- a/src/splice.c
+++ b/src/splice.c
@@ -102,15 +102,15 @@
 
     p->splices[i].overlap = p->splices[i].search = rate * 0.01 + .5;
 
-    next = sox_parsesamples(rate, p->splices[i].str, &p->splices[i].start, 't');
+    next = lsx_parsesamples(rate, p->splices[i].str, &p->splices[i].start, 't');
     if (next == NULL) break;
 
     if (*next == ',') {
-      next = sox_parsesamples(rate, next + 1, &p->splices[i].overlap, 't');
+      next = lsx_parsesamples(rate, next + 1, &p->splices[i].overlap, 't');
       if (next == NULL) break;
       p->splices[i].overlap *= 2;
       if (*next == ',') {
-        next = sox_parsesamples(rate, next + 1, &p->splices[i].search, 't');
+        next = lsx_parsesamples(rate, next + 1, &p->splices[i].search, 't');
         if (next == NULL) break;
         p->splices[i].search *= 2;
       }
@@ -126,7 +126,7 @@
     p->max_buffer_size = max(p->max_buffer_size, buffer_size);
   }
   if (i < p->nsplices)
-    return sox_usage(effp);
+    return lsx_usage(effp);
   return SOX_SUCCESS;
 }
 
--- a/src/stretch.c
+++ b/src/stretch.c
@@ -81,12 +81,12 @@
 
   if (n > 0 && !sscanf(argv[0], "%lf", &stretch->factor)) {
     sox_fail("error while parsing factor");
-    return sox_usage(effp);
+    return lsx_usage(effp);
   }
 
   if (n > 1 && !sscanf(argv[1], "%lf", &stretch->window)) {
     sox_fail("error while parsing window size");
-    return sox_usage(effp);
+    return lsx_usage(effp);
   }
 
   if (n > 2) {
@@ -97,7 +97,7 @@
       break;
     default:
       sox_fail("error while parsing fade type");
-      return sox_usage(effp);
+      return lsx_usage(effp);
     }
   }
 
@@ -107,12 +107,12 @@
  
   if (n > 3 && !sscanf(argv[3], "%lf", &stretch->shift)) {
     sox_fail("error while parsing shift ratio");
-    return sox_usage(effp);
+    return lsx_usage(effp);
   }
 
   if (stretch->shift > 1.0 || stretch->shift <= 0.0) {
     sox_fail("error with shift ratio value");
-    return sox_usage(effp);
+    return lsx_usage(effp);
   }
 
   /* default fading stuff... 
@@ -126,12 +126,12 @@
   
   if (n > 4 && !sscanf(argv[4], "%lf", &stretch->fading)) {
     sox_fail("error while parsing fading ratio");
-    return sox_usage(effp);
+    return lsx_usage(effp);
   }
 
   if (stretch->fading > 0.5 || stretch->fading < 0.0) {
     sox_fail("error with fading ratio value");
-    return sox_usage(effp);
+    return lsx_usage(effp);
   }
   
   return SOX_SUCCESS;
--- a/src/sunaudio.c
+++ b/src/sunaudio.c
@@ -52,7 +52,7 @@
 #endif
     char simple_hw=0;
 
-    set_signal_defaults(&ft->signal);
+    lsx_set_signal_defaults(&ft->signal);
 
     /* Hard-code for now. */
     file->count = 0;
@@ -65,7 +65,7 @@
 #ifdef __SVR4
     /* Read in old values, change to what we need and then send back */
     if (ioctl(fileno(ft->fp), AUDIO_GETDEV, &audio_dev) < 0) {
-        sox_fail_errno(ft,errno,"Unable to get device information.");
+        lsx_fail_errno(ft,errno,"Unable to get device information.");
         return(SOX_EOF);
     }
     sox_report("Hardware detected:  %s",audio_dev.name);
@@ -100,7 +100,7 @@
         if (ft->encoding.encoding != SOX_ENCODING_ULAW &&
             ft->encoding.encoding != SOX_ENCODING_ALAW &&
             ft->encoding.encoding != SOX_ENCODING_SIGN2) {
-            sox_fail_errno(ft,SOX_EFMT,"Sun audio driver only supports ULAW, ALAW, and signed linear for bytes.");
+            lsx_fail_errno(ft,SOX_EFMT,"Sun audio driver only supports ULAW, ALAW, and signed linear for bytes.");
                 return (SOX_EOF);
         }
         if ((ft->encoding.encoding == SOX_ENCODING_ULAW ||
@@ -114,12 +114,12 @@
     else if (ft->encoding.bits_per_sample == 16) {
         samplesize = 16;
         if (ft->encoding.encoding != SOX_ENCODING_SIGN2) {
-            sox_fail_errno(ft,SOX_EFMT,"Sun audio driver only supports signed linear for words.");
+            lsx_fail_errno(ft,SOX_EFMT,"Sun audio driver only supports signed linear for words.");
             return(SOX_EOF);
         }
     }
     else {
-        sox_fail_errno(ft,SOX_EFMT,"Sun audio driver only supports bytes and words");
+        lsx_fail_errno(ft,SOX_EFMT,"Sun audio driver only supports bytes and words");
         return(SOX_EOF);
     }
 
@@ -135,7 +135,7 @@
 
     /* Read in old values, change to what we need and then send back */
     if (ioctl(fileno(ft->fp), AUDIO_GETINFO, &audio_if) < 0) {
-        sox_fail_errno(ft,errno,"Unable to initialize /dev/audio");
+        lsx_fail_errno(ft,errno,"Unable to initialize /dev/audio");
         return(SOX_EOF);
     }
     audio_if.record.precision = samplesize;
@@ -151,19 +151,19 @@
 
     ioctl(fileno(ft->fp), AUDIO_SETINFO, &audio_if);
     if (audio_if.record.precision != samplesize) {
-        sox_fail_errno(ft,errno,"Unable to initialize sample size for /dev/audio");
+        lsx_fail_errno(ft,errno,"Unable to initialize sample size for /dev/audio");
         return(SOX_EOF);
     }
     if (audio_if.record.channels != ft->signal.channels) {
-        sox_fail_errno(ft,errno,"Unable to initialize number of channels for /dev/audio");
+        lsx_fail_errno(ft,errno,"Unable to initialize number of channels for /dev/audio");
         return(SOX_EOF);
     }
     if (audio_if.record.sample_rate != ft->signal.rate) {
-        sox_fail_errno(ft,errno,"Unable to initialize rate for /dev/audio");
+        lsx_fail_errno(ft,errno,"Unable to initialize rate for /dev/audio");
         return(SOX_EOF);
     }
     if (audio_if.record.encoding != encoding) {
-        sox_fail_errno(ft,errno,"Unable to initialize encoding for /dev/audio");
+        lsx_fail_errno(ft,errno,"Unable to initialize encoding for /dev/audio");
         return(SOX_EOF);
     }
     /* Flush any data in the buffers - its probably in the wrong format */
@@ -188,7 +188,7 @@
 #endif
     char simple_hw=0;
 
-    set_signal_defaults(&ft->signal);
+    lsx_set_signal_defaults(&ft->signal);
 
     /* Hard-code for now. */
     file->count = 0;
@@ -199,7 +199,7 @@
 #ifdef __SVR4
     /* Read in old values, change to what we need and then send back */
     if (ioctl(fileno(ft->fp), AUDIO_GETDEV, &audio_dev) < 0) {
-        sox_fail_errno(ft,errno,"Unable to get device information.");
+        lsx_fail_errno(ft,errno,"Unable to get device information.");
         return(SOX_EOF);
     }
     sox_report("Hardware detected:  %s",audio_dev.name);
@@ -270,7 +270,7 @@
 
     /* Read in old values, change to what we need and then send back */
     if (ioctl(fileno(ft->fp), AUDIO_GETINFO, &audio_if) < 0) {
-        sox_fail_errno(ft,errno,"Unable to initialize /dev/audio");
+        lsx_fail_errno(ft,errno,"Unable to initialize /dev/audio");
         return(SOX_EOF);
     }
     audio_if.play.precision = samplesize;
@@ -286,19 +286,19 @@
 
     ioctl(fileno(ft->fp), AUDIO_SETINFO, &audio_if);
     if (audio_if.play.precision != samplesize) {
-        sox_fail_errno(ft,errno,"Unable to initialize sample size for /dev/audio");
+        lsx_fail_errno(ft,errno,"Unable to initialize sample size for /dev/audio");
         return(SOX_EOF);
     }
     if (audio_if.play.channels != ft->signal.channels) {
-        sox_fail_errno(ft,errno,"Unable to initialize number of channels for /dev/audio");
+        lsx_fail_errno(ft,errno,"Unable to initialize number of channels for /dev/audio");
         return(SOX_EOF);
     }
     if (audio_if.play.sample_rate != ft->signal.rate) {
-        sox_fail_errno(ft,errno,"Unable to initialize rate for /dev/audio");
+        lsx_fail_errno(ft,errno,"Unable to initialize rate for /dev/audio");
         return(SOX_EOF);
     }
     if (audio_if.play.encoding != encoding) {
-        sox_fail_errno(ft,errno,"Unable to initialize encoding for /dev/audio");
+        lsx_fail_errno(ft,errno,"Unable to initialize encoding for /dev/audio");
         return(SOX_EOF);
     }
     /* Change to non-buffered I/O */
@@ -319,8 +319,8 @@
     SOX_LIB_VERSION_CODE,
     "Sun audio device driver",
     names, SOX_FILE_DEVICE,
-    sox_sunstartread, sox_rawread, sox_rawstopread,
-    sox_sunstartwrite, sox_rawwrite, sox_rawstopwrite,
+    sox_sunstartread, lsx_rawread, lsx_rawstopread,
+    sox_sunstartwrite, lsx_rawwrite, lsx_rawstopwrite,
     NULL, write_encodings, NULL
   };
   return &handler;
--- a/src/swap.c
+++ b/src/swap.c
@@ -33,7 +33,7 @@
     {
         swap->def_opts = 0;
         if (n != 2 && n != 4)
-          return sox_usage(effp);
+          return lsx_usage(effp);
         else if (n == 2)
         {
             sscanf(argv[0],"%d",&swap->order[0]);
--- a/src/synth.c
+++ b/src/synth.c
@@ -291,8 +291,8 @@
     synth->length_str = xmalloc(strlen(argv[argn]) + 1);
     strcpy(synth->length_str, argv[argn]);
     /* Do a dummy parse of to see if it will fail */
-    if (sox_parsesamples(0., synth->length_str, &synth->samples_to_do, 't') == NULL)
-      return sox_usage(effp);
+    if (lsx_parsesamples(0., synth->length_str, &synth->samples_to_do, 't') == NULL)
+      return lsx_usage(effp);
     argn++;
   }
 
@@ -387,12 +387,12 @@
   synth_t synth = (synth_t) effp->priv;
   size_t i;
 
-  synth->max = sox_sample_max(effp->out_encoding);
+  synth->max = lsx_sample_max(effp->out_encoding);
   synth->samples_done = 0;
 
   if (synth->length_str)
-    if (sox_parsesamples(effp->in_signal.rate, synth->length_str, &synth->samples_to_do, 't') == NULL)
-      return sox_usage(effp);
+    if (lsx_parsesamples(effp->in_signal.rate, synth->length_str, &synth->samples_to_do, 't') == NULL)
+      return lsx_usage(effp);
 
   synth->number_of_channels = effp->in_signal.channels;
   synth->channels = xcalloc(synth->number_of_channels, sizeof(*synth->channels));
--- a/src/tempo.c
+++ b/src/tempo.c
@@ -227,7 +227,7 @@
   } while (0);
 
   return argc || !p->factor || p->overlap_ms + p->search_ms >= p->segment_ms ?
-    sox_usage(effp) : SOX_SUCCESS;
+    lsx_usage(effp) : SOX_SUCCESS;
 }
 
 static int start(sox_effect_t * effp)
--- a/src/tremolo.c
+++ b/src/tremolo.c
@@ -29,7 +29,7 @@
       sscanf(argv[0], "%lf %c", &speed, &dummy) != 1 || speed < 0 ||
       (n > 1 && sscanf(argv[1], "%lf %c", &depth, &dummy) != 1) ||
       depth <= 0 || depth > 100)
-    return sox_usage(effp);
+    return lsx_usage(effp);
   args[2] = argv[0];
   sprintf(offset, "%g", 100 - depth / 2);
   args[3] = offset;
--- a/src/trim.c
+++ b/src/trim.c
@@ -39,17 +39,17 @@
             trim->length_str = (char *)xmalloc(strlen(argv[1])+1);
             strcpy(trim->length_str,argv[1]);
             /* Do a dummy parse to see if it will fail */
-            if (sox_parsesamples(0., trim->length_str, &trim->length, 't') == NULL)
-              return sox_usage(effp);
+            if (lsx_parsesamples(0., trim->length_str, &trim->length, 't') == NULL)
+              return lsx_usage(effp);
         case 1:
             trim->start_str = (char *)xmalloc(strlen(argv[0])+1);
             strcpy(trim->start_str,argv[0]);
             /* Do a dummy parse to see if it will fail */
-            if (sox_parsesamples(0., trim->start_str, &trim->start, 't') == NULL)
-              return sox_usage(effp);
+            if (lsx_parsesamples(0., trim->start_str, &trim->start, 't') == NULL)
+              return lsx_usage(effp);
             break;
         default:
-            return sox_usage(effp);
+            return lsx_usage(effp);
 
     }
     return (SOX_SUCCESS);
@@ -62,17 +62,17 @@
 {
     trim_t trim = (trim_t) effp->priv;
 
-    if (sox_parsesamples(effp->in_signal.rate, trim->start_str,
+    if (lsx_parsesamples(effp->in_signal.rate, trim->start_str,
                         &trim->start, 't') == NULL)
-      return sox_usage(effp);
+      return lsx_usage(effp);
     /* Account for # of channels */
     trim->start *= effp->in_signal.channels;
 
     if (trim->length_str)
     {
-        if (sox_parsesamples(effp->in_signal.rate, trim->length_str,
+        if (lsx_parsesamples(effp->in_signal.rate, trim->length_str,
                     &trim->length, 't') == NULL)
-          return sox_usage(effp);
+          return lsx_usage(effp);
     }
     else
         trim->length = 0;
--- a/src/tx16w.c
+++ b/src/tx16w.c
@@ -85,35 +85,35 @@
     /* If you need to seek around the input file. */
     if (! ft->seekable)
     {
-        sox_fail_errno(ft,SOX_EOF,"txw input file must be a file, not a pipe");
+        lsx_fail_errno(ft,SOX_EOF,"txw input file must be a file, not a pipe");
         return(SOX_EOF);
     }
 
     /* This is dumb but portable, just count the bytes til EOF */
-    while (sox_read_b_buf(ft, (unsigned char *)&trash, 1) == 1)
+    while (lsx_read_b_buf(ft, (unsigned char *)&trash, 1) == 1)
         num_samp_bytes++; 
     num_samp_bytes -= 32;         /* calculate num samples by sub header size */
-    sox_seeki(ft, 0, 0);           /* rewind file */
+    lsx_seeki(ft, 0, 0);           /* rewind file */
     sk->rest = num_samp_bytes;    /* set how many sample bytes to read */
 
     /* first 6 bytes are file type ID LM8953 */
-    sox_readb(ft, (unsigned char *)&filetype[0]);
-    sox_readb(ft, (unsigned char *)&filetype[1]);
-    sox_readb(ft, (unsigned char *)&filetype[2]);
-    sox_readb(ft, (unsigned char *)&filetype[3]);
-    sox_readb(ft, (unsigned char *)&filetype[4]);
-    sox_readb(ft, (unsigned char *)&filetype[5]);
+    lsx_readb(ft, (unsigned char *)&filetype[0]);
+    lsx_readb(ft, (unsigned char *)&filetype[1]);
+    lsx_readb(ft, (unsigned char *)&filetype[2]);
+    lsx_readb(ft, (unsigned char *)&filetype[3]);
+    lsx_readb(ft, (unsigned char *)&filetype[4]);
+    lsx_readb(ft, (unsigned char *)&filetype[5]);
     filetype[6] = '\0';
     for( c = 16; c > 0 ; c-- )    /* Discard next 16 bytes */
-        sox_readb(ft, (unsigned char *)&trash);
-    sox_readb(ft, (unsigned char *)&format);
-    sox_readb(ft, (unsigned char *)&sample_rate);
+        lsx_readb(ft, (unsigned char *)&trash);
+    lsx_readb(ft, (unsigned char *)&format);
+    lsx_readb(ft, (unsigned char *)&sample_rate);
     /*
      * save next 8 bytes - if sample rate is 0, then we need
      *  to look at gunk[2] and gunk[5] to get real rate
      */
     for( c = 0; c < 8; c++ )
-        sox_readb(ft, (unsigned char *)&(gunk[c]));
+        lsx_readb(ft, (unsigned char *)&(gunk[c]));
     /*
      * We should now be pointing at start of raw sample data in file 
      */
@@ -122,7 +122,7 @@
     sox_debug("Found header filetype %s",filetype);
     if(strcmp(filetype,"LM8953"))
     {
-        sox_fail_errno(ft,SOX_EHDR,"Invalid filetype ID in input file header, != LM8953");
+        lsx_fail_errno(ft,SOX_EHDR,"Invalid filetype ID in input file header, != LM8953");
         return(SOX_EOF);
     }
     /*
@@ -215,9 +215,9 @@
      */
     for(done = 0; done < len; ) {
         if(sk->rest < 3) break; /* Finished reading from file? */
-        sox_readb(ft, &uc1);
-        sox_readb(ft, &uc2);
-        sox_readb(ft, &uc3);
+        lsx_readb(ft, &uc1);
+        lsx_readb(ft, &uc2);
+        lsx_readb(ft, &uc3);
         sk->rest -= 3; /* adjust remaining for bytes we just read */
         s1 = (unsigned short) (uc1 << 4) | (((uc2 >> 4) & 017));
         s2 = (unsigned short) (uc3 << 4) | (( uc2 & 017 ));
@@ -244,7 +244,7 @@
     /* If you have to seek around the output file */
     if (! ft->seekable)
     {
-        sox_fail_errno(ft,SOX_EOF,"Output .txw file must be a file, not a pipe");
+        lsx_fail_errno(ft,SOX_EOF,"Output .txw file must be a file, not a pipe");
         return(SOX_EOF);
     }
 
@@ -251,7 +251,7 @@
     /* dummy numbers, just for place holder, real header is written
        at end of processing, since byte count is needed */
 
-    sox_writebuf(ft, &WH, 32);
+    lsx_writebuf(ft, &WH, 32);
     sk->bytes_out = 32;
     return(SOX_SUCCESS);
 }
@@ -272,9 +272,9 @@
 
     if (i < len) {
       w2 = *buf++ >> 20, ++i;
-      if (sox_writesb(ft, (w1 >> 4) & 0xFF) ||
-          sox_writesb(ft, (((w1 & 0x0F) << 4) | (w2 & 0x0F)) & 0xFF) ||
-          sox_writesb(ft, (w2 >> 4) & 0xFF)) {
+      if (lsx_writesb(ft, (w1 >> 4) & 0xFF) ||
+          lsx_writesb(ft, (((w1 & 0x0F) << 4) | (w2 & 0x0F)) & 0xFF) ||
+          lsx_writesb(ft, (w2 >> 4) & 0xFF)) {
         i = last_i;
         break;
       }
@@ -342,9 +342,9 @@
         AttackLength                       = 0x40;
         LoopLength                         = 0x40;
         for(i=sk->samples_out;i<0x80;i++) {
-            sox_writeb(ft, 0);
-            sox_writeb(ft, 0);
-            sox_writeb(ft, 0);
+            lsx_writeb(ft, 0);
+            lsx_writeb(ft, 0);
+            lsx_writeb(ft, 0);
             sk->bytes_out += 3;
         }
     }
@@ -352,7 +352,7 @@
     /* Fill up to 256 byte blocks; the TX16W seems to like that */
 
     while ((sk->bytes_out % 0x100) != 0) {
-        sox_writeb(ft, 0);
+        lsx_writeb(ft, 0);
         sk->bytes_out++;
     }
 
@@ -366,8 +366,8 @@
     WH.rpt_length[2] = (0x01 & (LoopLength >> 16)) +
         magic2[WH.sample_rate];
 
-    sox_rewind(ft);
-    sox_writebuf(ft, &WH, 32);
+    lsx_rewind(ft);
+    lsx_writebuf(ft, &WH, 32);
 
     return(SOX_SUCCESS);
 }
--- a/src/util.c
+++ b/src/util.c
@@ -1,233 +1,81 @@
 /*
- * util.c.
- * Utility functions mostly related to logging.
+ * General purpose, i.e. non SoX specific, utility functions
  *
- * July 5, 1991
- * Copyright 1991 Lance Norskog And Sundry Contributors
- * This source code is freely redistributable and may be used for
- * any purpose.  This copyright notice must be maintained.
- * Lance Norskog And Sundry Contributors are not responsible for
- * the consequences of using this software.
+ * (c) 2006-8 Chris Bagwell and SoX contributors
+ *
+ * This library is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This library 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 Lesser
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this library.  If not, write to the Free Software Foundation,
+ * Fifth Floor, 51 Franklin Street, Boston, MA 02111-1301, USA.
  */
 
-#include "sox_i.h"
-#include <assert.h>
+#include "soxconfig.h"
+#include "util.h"
 #include <string.h>
-#include <stdarg.h>
 
-
-void sox_output_message(FILE *file, const char *filename, const char *fmt, va_list ap)
+#ifndef HAVE_STRCASECMP
+int strcasecmp(const char * s1, const char * s2)
 {
-  char const * slash_pos = LAST_SLASH(filename);
-  char const * base_name = slash_pos? slash_pos + 1 : filename;
-  char const * dot_pos   = strrchr(base_name, '.');
-  fprintf(file, "%.*s: ", dot_pos? dot_pos - base_name : -1, base_name);
-  vfprintf(file, fmt, ap);
+  while (*s1 && (toupper(*s1) == toupper(*s2)))
+    s1++, s2++;
+  return toupper(*s1) - toupper(*s2);
 }
 
-#undef sox_fail
-#undef sox_warn
-#undef sox_report
-#undef sox_debug
-#undef sox_debug_more
-#undef sox_debug_most
-
-#define SOX_MESSAGE_FUNCTION(name,level) \
-void name(char const * fmt, ...) { \
-  va_list ap; \
-  va_start(ap, fmt); \
-  if (sox_globals.output_message_handler) \
-    (*sox_globals.output_message_handler)(level,sox_globals.subsystem,fmt,ap); \
-  va_end(ap); \
-}
-
-SOX_MESSAGE_FUNCTION(sox_fail  , 1)
-SOX_MESSAGE_FUNCTION(sox_warn  , 2)
-SOX_MESSAGE_FUNCTION(sox_report, 3)
-SOX_MESSAGE_FUNCTION(sox_debug , 4)
-SOX_MESSAGE_FUNCTION(sox_debug_more , 5)
-SOX_MESSAGE_FUNCTION(sox_debug_most , 6)
-
-#undef SOX_MESSAGE_FUNCTION
-
-void sox_fail_errno(sox_format_t * ft, int sox_errno, const char *fmt, ...)
+int strncasecmp(char const * s1, char const * s2, size_t n)
 {
-        va_list args;
-
-        ft->sox_errno = sox_errno;
-
-        va_start(args, fmt);
-#ifdef HAVE_VSNPRINTF
-        vsnprintf(ft->sox_errstr, sizeof(ft->sox_errstr), fmt, args);
-#else
-        vsprintf(ft->sox_errstr, fmt, args);
-#endif
-        va_end(args);
-        ft->sox_errstr[255] = '\0';
+  while (--n && *s1 && (toupper(*s1) == toupper(*s2)))
+    s1++, s2++;
+  return toupper(*s1) - toupper(*s2);
 }
+#endif
 
-/*
- * sox_parsesamples
- *
- * Parse a string for # of samples.  If string ends with a 's'
- * then the string is interpreted as a user calculated # of samples.
- * If string contains ':' or '.' or if it ends with a 't' then its
- * treated as an amount of time.  This is converted into seconds and
- * fraction of seconds and then use the sample rate to calculate
- * # of samples.
- * Returns NULL on error, pointer to next char to parse otherwise.
- */
-char const * sox_parsesamples(sox_rate_t rate, const char *str, sox_size_t *samples, int def)
+#ifndef HAVE_STRDUP
+char * strdup(char const * s)
 {
-    int found_samples = 0, found_time = 0;
-    int time = 0;
-    long long_samples;
-    float frac = 0;
-    char const * end;
-    char const * pos;
-    sox_bool found_colon, found_dot;
-
-    for (end = str; *end && strchr("0123456789:.ts", *end); ++end);
-    if (end == str)
-      return NULL;
-
-    pos = strchr(str, ':');
-    found_colon = pos && pos < end;
-    
-    pos = strchr(str, '.');
-    found_dot = pos && pos < end;
-
-    if (found_colon || found_dot || *(end-1) == 't')
-        found_time = 1;
-    else if (*(end-1) == 's')
-        found_samples = 1;
-
-    if (found_time || (def == 't' && !found_samples))
-    {
-        *samples = 0;
-
-        while(1)
-        {
-            if (str[0] != '.' && sscanf(str, "%d", &time) != 1)
-                return NULL;
-            *samples += time;
-
-            while (*str != ':' && *str != '.' && *str != 0)
-                str++;
-
-            if (*str == '.' || *str == 0)
-                break;
-
-            /* Skip past ':' */
-            str++;
-            *samples *= 60;
-        }
-
-        if (*str == '.')
-        {
-            if (sscanf(str, "%f", &frac) != 1)
-                return NULL;
-        }
-
-        *samples *= rate;
-        *samples += (rate * frac) + 0.5;
-        return end;
-    }
-    if (found_samples || (def == 's' && !found_time))
-    {
-        if (sscanf(str, "%ld", &long_samples) != 1)
-            return NULL;
-        *samples = long_samples;
-        return end;
-    }
-    return NULL;
+  return strcpy((char *)xmalloc(strlen(s) + 1), s);
 }
+#endif
 
-
-
-/*--------------------------------- Comments ---------------------------------*/
-
-size_t num_comments(comments_t comments)
+int strcaseends(char const * str, char const * end)
 {
-  size_t result = 0;
-  if (!comments)
-    return 0;
-  while (*comments++)
-    ++result;
-  return result;
+  size_t str_len = strlen(str), end_len = strlen(end);
+  return str_len >= end_len && !strcasecmp(str + str_len - end_len, end);
 }
 
-void append_comment(comments_t * comments, char const * comment)
+int strends(char const * str, char const * end)
 {
-  size_t n = num_comments(*comments);
-  *comments = xrealloc(*comments, (n + 2) * sizeof(**comments));
-  assert(comment);
-  (*comments)[n++] = xstrdup(comment);
-  (*comments)[n] = 0;
+  size_t str_len = strlen(str), end_len = strlen(end);
+  return str_len >= end_len && !strcmp(str + str_len - end_len, end);
 }
 
-void append_comments(comments_t * comments, char const * comment)
+enum_item const * find_enum_text(char const * text, enum_item const * enum_items)
 {
-  char * end;
-  if (comment) {
-    while ((end = strchr(comment, '\n'))) {
-      size_t len = end - comment;
-      char * c = xmalloc((len + 1) * sizeof(*c));
-      strncpy(c, comment, len);
-      c[len] = '\0';
-      append_comment(comments, c);
-      comment += len + 1;
-      free(c);
+  enum_item const * result = NULL; /* Assume not found */
+
+  while (enum_items->text) {
+    if (strncasecmp(text, enum_items->text, strlen(text)) == 0) {
+      if (result != NULL && result->value != enum_items->value)
+        return NULL;        /* Found ambiguity */
+      result = enum_items;  /* Found match */
     }
-    if (*comment)
-      append_comment(comments, comment);
+    ++enum_items;
   }
-}
-
-comments_t copy_comments(comments_t comments)
-{
-  comments_t result = 0;
-
-  if (comments) while (*comments)
-    append_comment(&result, *comments++);
   return result;
 }
 
-void delete_comments(comments_t * comments)
+enum_item const * find_enum_value(unsigned value, enum_item const * enum_items)
 {
-  comments_t p = *comments;
-
-  if (p) while (*p)
-    free(*p++);
-  free(*comments);
-  *comments = 0;
-}
-
-char * cat_comments(comments_t comments)
-{
-  comments_t p = comments;
-  size_t len = 0;
-  char * result;
-
-  if (p) while (*p)
-    len += strlen(*p++) + 1;
-
-  result = xcalloc(len? len : 1, sizeof(*result));
-
-  if ((p = comments) && *p) {
-    strcpy(result, *p);
-    while (*++p)
-      strcat(strcat(result, "\n"), *p);
-  }
-  return result;
-}
-
-char const * find_comment(comments_t comments, char const * id)
-{
-  size_t len = strlen(id);
-
-  if (comments) for (;*comments; ++comments)
-    if (!strncasecmp(*comments, id, len) && (*comments)[len] == '=')
-      return *comments + len + 1;
+  for (;enum_items->text; ++enum_items)
+    if (value == enum_items->value)
+      return enum_items;
   return NULL;
 }
--- /dev/null
+++ b/src/util.h
@@ -1,0 +1,100 @@
+/*
+ * General purpose, i.e. non SoX specific, utility functions and macros
+ *
+ * (c) 2006-8 Chris Bagwell and SoX contributors
+ *
+ * This library is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This library 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 Lesser
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this library.  If not, write to the Free Software Foundation,
+ * Fifth Floor, 51 Franklin Street, Boston, MA 02111-1301, USA.
+ */
+
+#include "xmalloc.h"
+
+#ifdef __GNUC__
+#define NORET __attribute__((noreturn))
+#define PRINTF __attribute__ ((format (printf, 1, 2)))
+#else
+#define NORET
+#define PRINTF
+#endif
+
+#ifdef _MSC_VER
+#define __STDC__ 1
+#define S_IFMT   _S_IFMT
+#define S_IFREG  _S_IFREG
+#define O_BINARY _O_BINARY
+#define fstat _fstat
+#define ftime _ftime
+#define inline __inline
+#define isatty _isatty
+#define popen _popen
+#define stat _stat
+#define strdup _strdup
+#define timeb _timeb
+#endif
+
+#if defined(DOS) || defined(WIN32) || defined(__NT__) || defined(__DJGPP__) || defined(__OS2__)
+  #define LAST_SLASH(path) max(strrchr(path, '/'), strrchr(path, '\\'))
+  #define IS_ABSOLUTE(path) ((path)[0] == '/' || (path)[0] == '\\' || (path)[1] == ':')
+  #define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY)
+#else
+  #define LAST_SLASH(path) strrchr(path, '/')
+  #define IS_ABSOLUTE(path) ((path)[0] == '/')
+  #define SET_BINARY_MODE(file)
+#endif
+
+#ifdef min
+#undef min
+#endif
+#define min(a, b) ((a) <= (b) ? (a) : (b))
+
+#ifdef max
+#undef max
+#endif
+#define max(a, b) ((a) >= (b) ? (a) : (b))
+
+/* Compile-time ("static") assertion */
+/*   e.g. assert_static(sizeof(int) >= 4, int_type_too_small)    */
+#define assert_static(e,f) enum {assert_static__##f = 1/(e)}
+#define range_limit(x, lower, upper) (min(max(x, lower), upper))
+#define array_length(a) (sizeof(a)/sizeof(a[0]))
+#define sqr(a) ((a) * (a))
+
+#ifndef M_PI
+#define M_PI    3.14159265358979323846
+#endif
+#ifndef M_PI_2
+#define M_PI_2  1.57079632679489661923  /* pi/2 */
+#endif
+#ifndef M_LN10
+#define M_LN10  2.30258509299404568402  /* natural log of 10 */
+#endif
+#define dB_to_linear(x) exp((x) * M_LN10 * 0.05)
+#define linear_to_dB(x) (log10(x) * 20)
+
+#ifdef WORDS_BIGENDIAN
+#define MACHINE_IS_BIGENDIAN 1
+#define MACHINE_IS_LITTLEENDIAN 0
+#else
+#define MACHINE_IS_BIGENDIAN 0
+#define MACHINE_IS_LITTLEENDIAN 1
+#endif
+
+int strcaseends(char const * str, char const * end);
+int strends(char const * str, char const * end);
+
+typedef struct {char const *text; unsigned value;} enum_item;
+#define ENUM_ITEM(prefix, item) {#item, prefix##item},
+enum_item const * find_enum_text(
+    char const * text, enum_item const * enum_items);
+enum_item const * find_enum_value(unsigned value, enum_item const * enum_items);
--- a/src/voc.c
+++ b/src/voc.c
@@ -223,23 +223,23 @@
   int ii;                       /* for getting rid of lseek */
   unsigned char uc;
 
-  if (sox_readbuf(ft, header, 20) != 20) {
-    sox_fail_errno(ft, SOX_EHDR, "unexpected EOF in VOC header");
+  if (lsx_readbuf(ft, header, 20) != 20) {
+    lsx_fail_errno(ft, SOX_EHDR, "unexpected EOF in VOC header");
     return (SOX_EOF);
   }
   if (strncmp(header, "Creative Voice File\032", 19)) {
-    sox_fail_errno(ft, SOX_EHDR, "VOC file header incorrect");
+    lsx_fail_errno(ft, SOX_EHDR, "VOC file header incorrect");
     return (SOX_EOF);
   }
 
   /* read the offset to data, from start of file */
   /* after this read we have read 20 bytes of header + 2 */
-  sox_readw(ft, &sbseek);
+  lsx_readw(ft, &sbseek);
 
   /* ANN:  read to skip the header, instead of lseek */
   /* this should allow use with pipes.... */
   for (ii = 22; ii < sbseek; ii++)
-    sox_readb(ft, &uc);
+    lsx_readb(ft, &uc);
 
   v->rate = -1;
   v->block_remaining = 0;
@@ -253,7 +253,7 @@
 
   /* get rate of data */
   if (v->rate == -1) {
-    sox_fail_errno(ft, SOX_EOF, "Input .voc file had no sound!");
+    lsx_fail_errno(ft, SOX_EOF, "Input .voc file had no sound!");
     return (SOX_EOF);
   }
 
@@ -350,7 +350,7 @@
       /* Read the data in the file */
       if (v->size <= 4) {
         if (!v->adpcm.setup.sign) {
-          if (sox_readb(ft, &uc) == SOX_EOF) {
+          if (lsx_readb(ft, &uc) == SOX_EOF) {
             sox_warn("VOC input: short file");
             v->block_remaining = 0;
             return done;
@@ -361,7 +361,7 @@
           --v->block_remaining;
           ++done;
         }
-        if (sox_readb(ft, &uc) == SOX_EOF) {
+        if (lsx_readb(ft, &uc) == SOX_EOF) {
           sox_warn("VOC input: short file");
           v->block_remaining = 0;
           return done;
@@ -407,7 +407,7 @@
       } else
         switch (v->size) {
           case 8:
-            if (sox_readb(ft, &uc) == SOX_EOF) {
+            if (lsx_readb(ft, &uc) == SOX_EOF) {
               sox_warn("VOC input: short file");
               v->block_remaining = 0;
               return done;
@@ -421,8 +421,8 @@
             }
             break;
           case 16:
-            sox_readw(ft, (unsigned short *) &sw);
-            if (sox_eof(ft)) {
+            lsx_readw(ft, (unsigned short *) &sw);
+            if (lsx_eof(ft)) {
               sox_warn("VOC input: short file");
               v->block_remaining = 0;
               return done;
@@ -458,7 +458,7 @@
   vs_t v = (vs_t) ft->priv;
 
   if (!ft->seekable) {
-    sox_fail_errno(ft, SOX_EOF,
+    lsx_fail_errno(ft, SOX_EOF,
                    "Output .voc file must be a file, not a pipe");
     return (SOX_EOF);
   }
@@ -466,10 +466,10 @@
   v->samples = 0;
 
   /* File format name and a ^Z (aborts printing under DOS) */
-  sox_writes(ft, "Creative Voice File\032");
-  sox_writew(ft, 26);   /* size of header */
-  sox_writew(ft, 0x10a);        /* major/minor version number */
-  sox_writew(ft, 0x1129);       /* checksum of version number */
+  lsx_writes(ft, "Creative Voice File\032");
+  lsx_writew(ft, 26);   /* size of header */
+  lsx_writew(ft, 0x10a);        /* major/minor version number */
+  lsx_writew(ft, 0x1129);       /* checksum of version number */
 
   return (SOX_SUCCESS);
 }
@@ -494,10 +494,10 @@
   while (done < len) {
     if (ft->encoding.bits_per_sample == 8) {
       uc = SOX_SAMPLE_TO_UNSIGNED_8BIT(*buf++, ft->clips);
-      sox_writeb(ft, uc);
+      lsx_writeb(ft, uc);
     } else {
       sw = (int) SOX_SAMPLE_TO_SIGNED_16BIT(*buf++, ft->clips);
-      sox_writesw(ft, sw);
+      lsx_writesw(ft, sw);
     }
     done++;
   }
@@ -513,24 +513,24 @@
   vs_t v = (vs_t) ft->priv;
   sox_sample_t datum;
 
-  sox_writeb(ft, 0);    /* End of file block code */
-  sox_seeki(ft, (sox_ssize_t) v->blockseek, 0); /* seek back to block length */
-  sox_seeki(ft, 1, 1);  /* seek forward one */
+  lsx_writeb(ft, 0);    /* End of file block code */
+  lsx_seeki(ft, (sox_ssize_t) v->blockseek, 0); /* seek back to block length */
+  lsx_seeki(ft, 1, 1);  /* seek forward one */
   if (v->silent) {
-    sox_writesw(ft, v->samples);
+    lsx_writesw(ft, v->samples);
   } else {
     if (ft->encoding.bits_per_sample == 8) {
       if (ft->signal.channels > 1) {
-        sox_seeki(ft, 8, 1);    /* forward 7 + 1 for new block header */
+        lsx_seeki(ft, 8, 1);    /* forward 7 + 1 for new block header */
       }
     }
     v->samples += 2;    /* adjustment: SBDK pp. 3-5 */
     datum = (v->samples * (ft->encoding.bits_per_sample >> 3)) & 0xff;
-    sox_writesb(ft, datum);     /* low byte of length */
+    lsx_writesb(ft, datum);     /* low byte of length */
     datum = ((v->samples * (ft->encoding.bits_per_sample >> 3)) >> 8) & 0xff;
-    sox_writesb(ft, datum);     /* middle byte of length */
+    lsx_writesb(ft, datum);     /* middle byte of length */
     datum = ((v->samples * (ft->encoding.bits_per_sample >> 3)) >> 16) & 0xff;
-    sox_writesb(ft, datum);     /* high byte of length */
+    lsx_writesb(ft, datum);     /* high byte of length */
   }
 }
 
@@ -564,34 +564,34 @@
   v->silent = 0;
   /* DO while we have no audio to read */
   while (v->block_remaining == 0) {
-    if (sox_eof(ft))
+    if (lsx_eof(ft))
       return SOX_EOF;
 
-    if (sox_readb(ft, &block) == SOX_EOF)
+    if (lsx_readb(ft, &block) == SOX_EOF)
       return SOX_EOF;
 
     if (block == VOC_TERM)
       return SOX_EOF;
 
-    if (sox_eof(ft))
+    if (lsx_eof(ft))
       return SOX_EOF;
 
-    sox_read3(ft, &sblen);
+    lsx_read3(ft, &sblen);
 
     /* Based on VOC block type, process the block */
     /* audio may be in one or multiple blocks */
     switch (block) {
       case VOC_DATA:
-        sox_readb(ft, &uc);
+        lsx_readb(ft, &uc);
         /* When DATA block preceeded by an EXTENDED     */
         /* block, the DATA blocks rate value is invalid */
         if (!v->extended) {
           if (uc == 0) {
-            sox_fail_errno(ft, SOX_EFMT, "Sample rate is zero?");
+            lsx_fail_errno(ft, SOX_EFMT, "Sample rate is zero?");
             return (SOX_EOF);
           }
           if ((v->rate != -1) && (uc != v->rate)) {
-            sox_fail_errno(ft, SOX_EFMT,
+            lsx_fail_errno(ft, SOX_EFMT,
                            "sample rate codes differ: %ld != %d", v->rate,
                            uc);
             return (SOX_EOF);
@@ -600,32 +600,32 @@
           ft->signal.rate = 1000000.0 / (256 - v->rate);
           v->channels = 1;
         }
-        sox_readb(ft, &uc);
+        lsx_readb(ft, &uc);
         v->format = uc;
         v->extended = 0;
         v->block_remaining = sblen - 2;
         return (SOX_SUCCESS);
       case VOC_DATA_16:
-        sox_readdw(ft, &new_rate_32);
+        lsx_readdw(ft, &new_rate_32);
         if (new_rate_32 == 0) {
-          sox_fail_errno(ft, SOX_EFMT, "Sample rate is zero?");
+          lsx_fail_errno(ft, SOX_EFMT, "Sample rate is zero?");
           return (SOX_EOF);
         }
         if ((v->rate != -1) && ((long) new_rate_32 != v->rate)) {
-          sox_fail_errno(ft, SOX_EFMT, "sample rate codes differ: %ld != %d",
+          lsx_fail_errno(ft, SOX_EFMT, "sample rate codes differ: %ld != %d",
                          v->rate, new_rate_32);
           return (SOX_EOF);
         }
         v->rate = new_rate_32;
         ft->signal.rate = new_rate_32;
-        sox_readb(ft, &uc);
+        lsx_readb(ft, &uc);
         v->size = uc;
-        sox_readb(ft, &(v->channels));
-        sox_readw(ft, &(v->format));    /* ANN: added format */
-        sox_readb(ft, (unsigned char *) &trash);        /* notused */
-        sox_readb(ft, (unsigned char *) &trash);        /* notused */
-        sox_readb(ft, (unsigned char *) &trash);        /* notused */
-        sox_readb(ft, (unsigned char *) &trash);        /* notused */
+        lsx_readb(ft, &(v->channels));
+        lsx_readw(ft, &(v->format));    /* ANN: added format */
+        lsx_readb(ft, (unsigned char *) &trash);        /* notused */
+        lsx_readb(ft, (unsigned char *) &trash);        /* notused */
+        lsx_readb(ft, (unsigned char *) &trash);        /* notused */
+        lsx_readb(ft, (unsigned char *) &trash);        /* notused */
         v->block_remaining = sblen - 12;
         return (SOX_SUCCESS);
       case VOC_CONT:
@@ -635,10 +635,10 @@
         {
           unsigned short period;
 
-          sox_readw(ft, &period);
-          sox_readb(ft, &uc);
+          lsx_readw(ft, &period);
+          lsx_readb(ft, &uc);
           if (uc == 0) {
-            sox_fail_errno(ft, SOX_EFMT, "Silence sample rate is zero");
+            lsx_fail_errno(ft, SOX_EFMT, "Silence sample rate is zero");
             return (SOX_EOF);
           }
           /*
@@ -655,8 +655,8 @@
           return (SOX_SUCCESS);
         }
       case VOC_MARKER:
-        sox_readb(ft, &uc);
-        sox_readb(ft, &uc);
+        lsx_readb(ft, &uc);
+        lsx_readb(ft, &uc);
         /* Falling! Falling! */
       case VOC_TEXT:
         {
@@ -666,7 +666,7 @@
 
           sox_warn("VOC TEXT");
           while (i--) {
-            sox_readb(ft, (unsigned char *) &c);
+            lsx_readb(ft, (unsigned char *) &c);
             /* FIXME: this needs to be tested but I couldn't
              * find a voc file with a VOC_TEXT chunk :(
              if (c != '\0' && c != '\r')
@@ -686,7 +686,7 @@
       case VOC_LOOPEND:
         sox_debug("skipping repeat loop");
         for (i = 0; i < sblen; i++)
-          sox_readb(ft, (unsigned char *) &trash);
+          lsx_readb(ft, (unsigned char *) &trash);
         break;
       case VOC_EXTENDED:
         /* An Extended block is followed by a data block */
@@ -694,19 +694,19 @@
         /* value from the extended block and not the     */
         /* data block.                                   */
         v->extended = 1;
-        sox_readw(ft, &new_rate_16);
+        lsx_readw(ft, &new_rate_16);
         if (new_rate_16 == 0) {
-          sox_fail_errno(ft, SOX_EFMT, "Sample rate is zero?");
+          lsx_fail_errno(ft, SOX_EFMT, "Sample rate is zero?");
           return (SOX_EOF);
         }
         if ((v->rate != -1) && (new_rate_16 != v->rate)) {
-          sox_fail_errno(ft, SOX_EFMT, "sample rate codes differ: %ld != %d",
+          lsx_fail_errno(ft, SOX_EFMT, "sample rate codes differ: %ld != %d",
                          v->rate, new_rate_16);
           return (SOX_EOF);
         }
         v->rate = new_rate_16;
-        sox_readb(ft, &uc); /* bits_per_sample */
-        sox_readb(ft, &uc);
+        lsx_readb(ft, &uc); /* bits_per_sample */
+        lsx_readb(ft, &uc);
         ft->signal.channels = uc? 2 : 1;      /* Stereo */
         /* Needed number of channels before finishing
          * compute for rate */
@@ -718,7 +718,7 @@
       default:
         sox_debug("skipping unknown block code %d", block);
         for (i = 0; i < sblen; i++)
-          sox_readb(ft, (unsigned char *) &trash);
+          lsx_readb(ft, (unsigned char *) &trash);
     }
   }
   return SOX_SUCCESS;
@@ -731,12 +731,12 @@
 {
   vs_t v = (vs_t) ft->priv;
 
-  v->blockseek = sox_tell(ft);
+  v->blockseek = lsx_tell(ft);
   if (v->silent) {
-    sox_writeb(ft, VOC_SILENCE);        /* Silence block code */
-    sox_writeb(ft, 0);  /* Period length */
-    sox_writeb(ft, 0);  /* Period length */
-    sox_writesb(ft, v->rate);   /* Rate code */
+    lsx_writeb(ft, VOC_SILENCE);        /* Silence block code */
+    lsx_writeb(ft, 0);  /* Period length */
+    lsx_writeb(ft, 0);  /* Period length */
+    lsx_writesb(ft, v->rate);   /* Rate code */
   } else {
     if (ft->encoding.bits_per_sample == 8) {
       /* 8-bit sample section.  By always setting the correct     */
@@ -746,36 +746,36 @@
       /* Prehaps the rate should be doubled though to make up for */
       /* double amount of samples for a given time????            */
       if (ft->signal.channels > 1) {
-        sox_writeb(ft, VOC_EXTENDED);   /* Voice Extended block code */
-        sox_writeb(ft, 4);      /* block length = 4 */
-        sox_writeb(ft, 0);      /* block length = 4 */
-        sox_writeb(ft, 0);      /* block length = 4 */
+        lsx_writeb(ft, VOC_EXTENDED);   /* Voice Extended block code */
+        lsx_writeb(ft, 4);      /* block length = 4 */
+        lsx_writeb(ft, 0);      /* block length = 4 */
+        lsx_writeb(ft, 0);      /* block length = 4 */
         v->rate = 65536 - (256000000.0 / (2 * ft->signal.rate)) + .5;
-        sox_writesw(ft, v->rate);       /* Rate code */
-        sox_writeb(ft, 0);      /* File is not packed */
-        sox_writeb(ft, 1);      /* samples are in stereo */
+        lsx_writesw(ft, v->rate);       /* Rate code */
+        lsx_writeb(ft, 0);      /* File is not packed */
+        lsx_writeb(ft, 1);      /* samples are in stereo */
       }
-      sox_writeb(ft, VOC_DATA); /* Voice Data block code */
-      sox_writeb(ft, 0);        /* block length (for now) */
-      sox_writeb(ft, 0);        /* block length (for now) */
-      sox_writeb(ft, 0);        /* block length (for now) */
+      lsx_writeb(ft, VOC_DATA); /* Voice Data block code */
+      lsx_writeb(ft, 0);        /* block length (for now) */
+      lsx_writeb(ft, 0);        /* block length (for now) */
+      lsx_writeb(ft, 0);        /* block length (for now) */
       v->rate = 256 - (1000000.0 / ft->signal.rate) + .5;
-      sox_writesb(ft, v->rate); /* Rate code */
-      sox_writeb(ft, 0);        /* 8-bit raw data */
+      lsx_writesb(ft, v->rate); /* Rate code */
+      lsx_writeb(ft, 0);        /* 8-bit raw data */
     } else {
-      sox_writeb(ft, VOC_DATA_16);      /* Voice Data block code */
-      sox_writeb(ft, 0);        /* block length (for now) */
-      sox_writeb(ft, 0);        /* block length (for now) */
-      sox_writeb(ft, 0);        /* block length (for now) */
+      lsx_writeb(ft, VOC_DATA_16);      /* Voice Data block code */
+      lsx_writeb(ft, 0);        /* block length (for now) */
+      lsx_writeb(ft, 0);        /* block length (for now) */
+      lsx_writeb(ft, 0);        /* block length (for now) */
       v->rate = ft->signal.rate + .5;
-      sox_writedw(ft, (unsigned) v->rate);      /* Rate code */
-      sox_writeb(ft, 16);       /* Sample Size */
-      sox_writeb(ft, ft->signal.channels);      /* Sample Size */
-      sox_writew(ft, 0x0004);   /* Encoding */
-      sox_writeb(ft, 0);        /* Unused */
-      sox_writeb(ft, 0);        /* Unused */
-      sox_writeb(ft, 0);        /* Unused */
-      sox_writeb(ft, 0);        /* Unused */
+      lsx_writedw(ft, (unsigned) v->rate);      /* Rate code */
+      lsx_writeb(ft, 16);       /* Sample Size */
+      lsx_writeb(ft, ft->signal.channels);      /* Sample Size */
+      lsx_writew(ft, 0x0004);   /* Encoding */
+      lsx_writeb(ft, 0);        /* Unused */
+      lsx_writeb(ft, 0);        /* Unused */
+      lsx_writeb(ft, 0);        /* Unused */
+      lsx_writeb(ft, 0);        /* Unused */
     }
   }
 }
--- a/src/vol.c
+++ b/src/vol.c
@@ -50,7 +50,7 @@
   
   /* Get the vol, and the type if it's in the same arg. */
   if (!argc || (have_type = sscanf(argv[0], "%lf %10s %c", &vol->gain, type_string, &dummy) - 1) > 1)
-    return sox_usage(effp);
+    return lsx_usage(effp);
   ++argv, --argc;
 
   /* No type yet? Get it from the next arg: */
@@ -63,7 +63,7 @@
   if (have_type) {
     enum_item const * p = find_enum_text(type_ptr, vol_types);
     if (!p)
-      return sox_usage(effp);
+      return lsx_usage(effp);
     switch (p->value) {
       case vol_dB: vol->gain = dB_to_linear(vol->gain); break;
       case vol_power: /* power to amplitude, keep phase change */
@@ -74,7 +74,7 @@
 
   if (argc) {
     if (fabs(vol->gain) < 1 || sscanf(*argv, "%lf %c", &vol->limitergain, &dummy) != 1 || vol->limitergain <= 0 || vol->limitergain >= 1)
-      return sox_usage(effp);
+      return lsx_usage(effp);
     
     vol->uselimiter = sox_true;
     /* The following equation is derived so that there is no 
@@ -189,7 +189,7 @@
   char * args[] = {0, "dB"};
 
   if (argc != 1)
-    return sox_usage(effp);
+    return lsx_usage(effp);
   args[0] = argv[0];
   return sox_vol_effect_fn()->getopts(effp, array_length(args), args);
 }
--- a/src/vorbis.c
+++ b/src/vorbis.c
@@ -107,7 +107,7 @@
 
   /* Init the decoder */
   if (ov_open_callbacks((void *) ft->fp, vb->vf, NULL, 0, callbacks) < 0) {
-    sox_fail_errno(ft, SOX_EHDR, "Input not an Ogg Vorbis audio stream");
+    lsx_fail_errno(ft, SOX_EHDR, "Input not an Ogg Vorbis audio stream");
     return (SOX_EOF);
   }
 
@@ -129,7 +129,7 @@
 
   /* Record comments */
   for (i = 0; i < vc->comments; i++)
-    append_comment(&ft->comments, vc->user_comments[i]);
+    sox_append_comment(&ft->comments, vc->user_comments[i]);
 
   /* Setup buffer */
   vb->buf_len = DEF_BUF_LEN;
@@ -225,8 +225,8 @@
 {
   int written;
 
-  written = sox_writebuf(ft, page->header, (sox_size_t) page->header_len);
-  written += sox_writebuf(ft, page->body, (sox_size_t) page->body_len);
+  written = lsx_writebuf(ft, page->header, (sox_size_t) page->header_len);
+  written += lsx_writebuf(ft, page->body, (sox_size_t) page->body_len);
 
   return written;
 }
@@ -242,7 +242,7 @@
   int i, ret = HEADER_OK;
 
   memset(&vc, 0, sizeof(vc));
-  vc.comments = num_comments(ft->comments);
+  vc.comments = sox_num_comments(ft->comments);
   if (vc.comments) {     /* Make the comment structure */
     vc.comment_lengths = xcalloc((size_t)vc.comments, sizeof(*vc.comment_lengths));
     vc.user_comments = xcalloc((size_t)vc.comments, sizeof(*vc.user_comments));
@@ -290,13 +290,13 @@
   /* TODO */
   rate = ft->signal.rate;
   if (rate)
-    sox_fail_errno(ft, SOX_EHDR,
+    lsx_fail_errno(ft, SOX_EHDR,
       "Error setting-up Ogg Vorbis encoder; check sample-rate & # of channels");
 
   /* Use encoding to average bit rate of VBR as specified by the -C option */
   if (ft->encoding.compression != HUGE_VAL) {
     if (ft->encoding.compression < -1 || ft->encoding.compression > 10) {
-      sox_fail_errno(ft, SOX_EINVAL,
+      lsx_fail_errno(ft, SOX_EINVAL,
                      "Vorbis compression quality nust be between -1 and 10");
       return SOX_EOF;
     }
@@ -310,7 +310,7 @@
   ogg_stream_init(&ve->os, rand());     /* Random serial number */
 
   if (write_vorbis_header(ft, ve) == HEADER_ERROR) {
-    sox_fail_errno(ft, SOX_EHDR,
+    lsx_fail_errno(ft, SOX_EHDR,
                    "Error writing header for Ogg Vorbis audio stream");
     return (SOX_EOF);
   }
--- a/src/vox-fmt.c
+++ b/src/vox-fmt.c
@@ -29,7 +29,7 @@
     names, SOX_FILE_MONO,
     sox_vox_start, sox_vox_read, sox_vox_stopread,
     sox_vox_start, sox_vox_write, sox_vox_stopwrite,
-    sox_rawseek, write_encodings, NULL
+    lsx_rawseek, write_encodings, NULL
   };
   return &handler;
 }
--- a/src/wav.c
+++ b/src/wav.c
@@ -86,7 +86,7 @@
     int samplesThisBlock;
 
     /* Pull in the packet and check the header */
-    bytesRead = sox_readbuf(ft, wav->packet, wav->blockAlign);
+    bytesRead = lsx_readbuf(ft, wav->packet, wav->blockAlign);
     samplesThisBlock = wav->samplesPerBlock;
     if (bytesRead < wav->blockAlign) 
     { 
@@ -127,7 +127,7 @@
     const char *errmsg;
 
     /* Pull in the packet and check the header */
-    bytesRead = sox_readbuf(ft, wav->packet, wav->blockAlign);
+    bytesRead = lsx_readbuf(ft, wav->packet, wav->blockAlign);
     samplesThisBlock = wav->samplesPerBlock;
     if (bytesRead < wav->blockAlign) 
     {
@@ -173,9 +173,9 @@
             ImaBlockMashI(chans, wav->samples, wav->samplesPerBlock, wav->state, wav->packet, 9);
         }
         /* write the compressed packet */
-        if (sox_writebuf(ft, wav->packet, wav->blockAlign) != wav->blockAlign)
+        if (lsx_writebuf(ft, wav->packet, wav->blockAlign) != wav->blockAlign)
         {
-            sox_fail_errno(ft,SOX_EOF,"write error");
+            lsx_fail_errno(ft,SOX_EOF,"write error");
             return (SOX_EOF);
         }
         /* update lengths and samplePtr */
@@ -201,12 +201,12 @@
     wav->gsmhandle=gsm_create();
     if (!wav->gsmhandle)
     {
-        sox_fail_errno(ft,SOX_EOF,"cannot create GSM object");
+        lsx_fail_errno(ft,SOX_EOF,"cannot create GSM object");
         return (SOX_EOF);
     }
         
     if(gsm_option(wav->gsmhandle,GSM_OPT_WAV49,&valueP) == -1){
-        sox_fail_errno(ft,SOX_EOF,"error setting gsm_option for WAV49 format. Recompile gsm library with -DWAV49 option and relink sox");
+        lsx_fail_errno(ft,SOX_EOF,"error setting gsm_option for WAV49 format. Recompile gsm library with -DWAV49 option and relink sox");
         return (SOX_EOF);
     }
 
@@ -239,7 +239,7 @@
   /* read and decode loop, possibly leaving some samples in wav->gsmsample */
     while (done < len) {
         wav->gsmindex=0;
-        bytes = sox_readbuf(ft, frame, 65);   
+        bytes = lsx_readbuf(ft, frame, 65);   
         if (bytes <=0)
             return done;
         if (bytes<65) {
@@ -249,13 +249,13 @@
         /* decode the long 33 byte half */
         if(gsm_decode(wav->gsmhandle,frame, wav->gsmsample)<0)
         {
-            sox_fail_errno(ft,SOX_EOF,"error during gsm decode");
+            lsx_fail_errno(ft,SOX_EOF,"error during gsm decode");
             return 0;
         }
         /* decode the short 32 byte half */
         if(gsm_decode(wav->gsmhandle,frame+33, wav->gsmsample+160)<0)
         {
-            sox_fail_errno(ft,SOX_EOF,"error during gsm decode");
+            lsx_fail_errno(ft,SOX_EOF,"error during gsm decode");
             return 0;
         }
 
@@ -280,9 +280,9 @@
     gsm_encode(wav->gsmhandle, wav->gsmsample, frame);
     /*encode the odd half long (33 byte) frame */
     gsm_encode(wav->gsmhandle, wav->gsmsample+160, frame+32);
-    if (sox_writebuf(ft, frame, 65) != 65)
+    if (lsx_writebuf(ft, frame, 65) != 65)
     {
-        sox_fail_errno(ft,SOX_EOF,"write error");
+        lsx_fail_errno(ft,SOX_EOF,"write error");
         return (SOX_EOF);
     }
     wav->gsmbytecount += 65;
@@ -326,8 +326,8 @@
 
     /* Add a pad byte if amount of written bytes is not even. */
     if (wav->gsmbytecount && wav->gsmbytecount % 2){
-        if(sox_writeb(ft, 0))
-            sox_fail_errno(ft,SOX_EOF,"write error");
+        if(lsx_writeb(ft, 0))
+            lsx_fail_errno(ft,SOX_EOF,"write error");
         else
             wav->gsmbytecount += 1;
     }
@@ -343,16 +343,16 @@
     char magic[5];
     for (;;)
     {
-        if (sox_reads(ft, magic, 4) == SOX_EOF)
+        if (lsx_reads(ft, magic, 4) == SOX_EOF)
         {
-            sox_fail_errno(ft, SOX_EHDR, "WAVE file has missing %s chunk", 
+            lsx_fail_errno(ft, SOX_EHDR, "WAVE file has missing %s chunk", 
                           Label);
             return SOX_EOF;
         }
         sox_debug("WAV Chunk %s", magic);
-        if (sox_readdw(ft, len) == SOX_EOF)
+        if (lsx_readdw(ft, len) == SOX_EOF)
         {
-            sox_fail_errno(ft, SOX_EHDR, "WAVE file %s chunk is too short", 
+            lsx_fail_errno(ft, SOX_EHDR, "WAVE file %s chunk is too short", 
                           magic);
             return SOX_EOF;
         }
@@ -361,9 +361,9 @@
             break; /* Found the given chunk */
 
         /* skip to next chunk */
-        if (*len == 0 || sox_seeki(ft, (sox_ssize_t)(*len), SEEK_CUR) != SOX_SUCCESS)
+        if (*len == 0 || lsx_seeki(ft, (sox_ssize_t)(*len), SEEK_CUR) != SOX_SUCCESS)
         {
-            sox_fail_errno(ft,SOX_EHDR, 
+            lsx_fail_errno(ft,SOX_EHDR, 
                           "WAV chunk appears to have invalid size %d.", *len);
             return SOX_EOF;
         }
@@ -374,7 +374,7 @@
 
 static int wavfail(sox_format_t * ft, const char *format)
 {
-    sox_fail_errno(ft, SOX_EHDR, "Unhandled WAV file encoding (%s).\nTry overriding the encoding: e.g. for an MP3 WAV, `-t mp3'", format);
+    lsx_fail_errno(ft, SOX_EHDR, "Unhandled WAV file encoding (%s).\nTry overriding the encoding: e.g. for an MP3 WAV, `-t mp3'", format);
     return SOX_EOF;
 }
 
@@ -409,10 +409,10 @@
     ft->sox_errno = SOX_SUCCESS;
     wav->ignoreSize = 0;
 
-    if (sox_reads(ft, magic, 4) == SOX_EOF || (strncmp("RIFF", magic, 4) != 0 &&
+    if (lsx_reads(ft, magic, 4) == SOX_EOF || (strncmp("RIFF", magic, 4) != 0 &&
                                              strncmp("RIFX", magic, 4) != 0))
     {
-        sox_fail_errno(ft,SOX_EHDR,"WAVE: RIFF header not found");
+        lsx_fail_errno(ft,SOX_EHDR,"WAVE: RIFF header not found");
         return SOX_EOF;
     }
 
@@ -420,18 +420,15 @@
     if (strncmp("RIFX", magic, 4) == 0) 
     {
         sox_debug("Found RIFX header");
-        ft->encoding.reverse_bytes = SOX_IS_LITTLEENDIAN;
+        ft->encoding.reverse_bytes = MACHINE_IS_LITTLEENDIAN;
     }
-    else
-    {
-        ft->encoding.reverse_bytes = SOX_IS_BIGENDIAN;
-    }
+    else ft->encoding.reverse_bytes = MACHINE_IS_BIGENDIAN;
 
-    sox_readdw(ft, &dwRiffLength);
+    lsx_readdw(ft, &dwRiffLength);
 
-    if (sox_reads(ft, magic, 4) == SOX_EOF || strncmp("WAVE", magic, 4))
+    if (lsx_reads(ft, magic, 4) == SOX_EOF || strncmp("WAVE", magic, 4))
     {
-        sox_fail_errno(ft,SOX_EHDR,"WAVE header not found");
+        lsx_fail_errno(ft,SOX_EHDR,"WAVE header not found");
         return SOX_EOF;
     }
 
@@ -438,7 +435,7 @@
     /* Now look for the format chunk */
     if (findChunk(ft, "fmt ", &len) == SOX_EOF)
     {
-        sox_fail_errno(ft,SOX_EHDR,"WAVE chunk fmt not found");
+        lsx_fail_errno(ft,SOX_EHDR,"WAVE chunk fmt not found");
         return SOX_EOF;
     }
     wFmtSize = len;
@@ -445,16 +442,16 @@
     
     if (wFmtSize < 16)
     {
-        sox_fail_errno(ft,SOX_EHDR,"WAVE file fmt chunk is too short");
+        lsx_fail_errno(ft,SOX_EHDR,"WAVE file fmt chunk is too short");
         return SOX_EOF;
     }
 
-    sox_readw(ft, &(wav->formatTag));
-    sox_readw(ft, &wChannels);
-    sox_readdw(ft, &dwSamplesPerSecond);
-    sox_readdw(ft, &dwAvgBytesPerSec);   /* Average bytes/second */
-    sox_readw(ft, &(wav->blockAlign));   /* Block align */
-    sox_readw(ft, &wBitsPerSample);      /* bits per sample per channel */
+    lsx_readw(ft, &(wav->formatTag));
+    lsx_readw(ft, &wChannels);
+    lsx_readdw(ft, &dwSamplesPerSecond);
+    lsx_readdw(ft, &dwAvgBytesPerSec);   /* Average bytes/second */
+    lsx_readw(ft, &(wav->blockAlign));   /* Block align */
+    lsx_readw(ft, &wBitsPerSample);      /* bits per sample per channel */
     len -= 16;
 
     if (wav->formatTag == WAVE_FORMAT_EXTENSIBLE)
@@ -468,24 +465,24 @@
 
       if (wFmtSize < 18)
       {
-        sox_fail_errno(ft,SOX_EHDR,"WAVE file fmt chunk is too short");
+        lsx_fail_errno(ft,SOX_EHDR,"WAVE file fmt chunk is too short");
         return SOX_EOF;
       }
-      sox_readw(ft, &extensionSize);
+      lsx_readw(ft, &extensionSize);
       len -= 2;
       if (extensionSize < 22)
       {
-        sox_fail_errno(ft,SOX_EHDR,"WAVE file fmt chunk is too short");
+        lsx_fail_errno(ft,SOX_EHDR,"WAVE file fmt chunk is too short");
         return SOX_EOF;
       }
-      sox_readw(ft, &numberOfValidBits);
-      sox_readdw(ft, &speakerPositionMask);
-      sox_readw(ft, &subFormatTag);
-      for (i = 0; i < 14; ++i) sox_readb(ft, &dummyByte);
+      lsx_readw(ft, &numberOfValidBits);
+      lsx_readdw(ft, &speakerPositionMask);
+      lsx_readw(ft, &subFormatTag);
+      for (i = 0; i < 14; ++i) lsx_readb(ft, &dummyByte);
       len -= 22;
       if (numberOfValidBits != wBitsPerSample)
       {
-        sox_fail_errno(ft,SOX_EHDR,"WAVE file fmt with padded samples is not supported yet");
+        lsx_fail_errno(ft,SOX_EHDR,"WAVE file fmt with padded samples is not supported yet");
         return SOX_EOF;
       }
       wav->formatTag = subFormatTag;
@@ -494,7 +491,7 @@
     switch (wav->formatTag)
     {
     case WAVE_FORMAT_UNKNOWN:
-        sox_fail_errno(ft,SOX_EHDR,"WAVE file is in unsupported Microsoft Official Unknown format.");
+        lsx_fail_errno(ft,SOX_EHDR,"WAVE file is in unsupported Microsoft Official Unknown format.");
         return SOX_EOF;
         
     case WAVE_FORMAT_PCM:
@@ -570,7 +567,7 @@
     case WAVE_FORMAT_G722_ADPCM:
         return wavfail(ft, "G.722 ADPCM");
     default:
-        sox_fail_errno(ft, SOX_EHDR, "Unknown WAV file encoding (type %x)", wav->formatTag);
+        lsx_fail_errno(ft, SOX_EHDR, "Unknown WAV file encoding (type %x)", wav->formatTag);
         return SOX_EOF;
     }
 
@@ -597,7 +594,7 @@
         wav->formatTag != WAVE_FORMAT_ALAW &&
         wav->formatTag != WAVE_FORMAT_MULAW) {
         if (len >= 2) {
-            sox_readw(ft, &wExtSize);
+            lsx_readw(ft, &wExtSize);
             len -= 2;
         } else {
             sox_warn("wave header missing FmtExt chunk");
@@ -606,7 +603,7 @@
 
     if (wExtSize > len)
     {
-        sox_fail_errno(ft,SOX_EOF,"wave header error: wExtSize inconsistent with wFmtLen");
+        lsx_fail_errno(ft,SOX_EOF,"wave header error: wExtSize inconsistent with wFmtLen");
         return SOX_EOF;
     }
 
@@ -615,7 +612,7 @@
     case WAVE_FORMAT_ADPCM:
         if (wExtSize < 4)
         {
-            sox_fail_errno(ft,SOX_EOF,"format[%s]: expects wExtSize >= %d",
+            lsx_fail_errno(ft,SOX_EOF,"format[%s]: expects wExtSize >= %d",
                         wav_format_str(wav->formatTag), 4);
             return SOX_EOF;
         }
@@ -622,22 +619,22 @@
 
         if (wBitsPerSample != 4)
         {
-            sox_fail_errno(ft,SOX_EOF,"Can only handle 4-bit MS ADPCM in wav files");
+            lsx_fail_errno(ft,SOX_EOF,"Can only handle 4-bit MS ADPCM in wav files");
             return SOX_EOF;
         }
 
-        sox_readw(ft, &(wav->samplesPerBlock));
+        lsx_readw(ft, &(wav->samplesPerBlock));
         bytesPerBlock = AdpcmBytesPerBlock(ft->signal.channels, wav->samplesPerBlock);
         if (bytesPerBlock > wav->blockAlign)
         {
-            sox_fail_errno(ft,SOX_EOF,"format[%s]: samplesPerBlock(%d) incompatible with blockAlign(%d)",
+            lsx_fail_errno(ft,SOX_EOF,"format[%s]: samplesPerBlock(%d) incompatible with blockAlign(%d)",
                 wav_format_str(wav->formatTag), wav->samplesPerBlock, wav->blockAlign);
             return SOX_EOF;
         }
 
-        sox_readw(ft, &(wav->nCoefs));
+        lsx_readw(ft, &(wav->nCoefs));
         if (wav->nCoefs < 7 || wav->nCoefs > 0x100) {
-            sox_fail_errno(ft,SOX_EOF,"ADPCM file nCoefs (%.4hx) makes no sense", wav->nCoefs);
+            lsx_fail_errno(ft,SOX_EOF,"ADPCM file nCoefs (%.4hx) makes no sense", wav->nCoefs);
             return SOX_EOF;
         }
         wav->packet = (unsigned char *)xmalloc(wav->blockAlign);
@@ -646,7 +643,7 @@
 
         if (wExtSize < 4 + 4*wav->nCoefs)
         {
-            sox_fail_errno(ft,SOX_EOF,"wave header error: wExtSize(%d) too small for nCoefs(%d)", wExtSize, wav->nCoefs);
+            lsx_fail_errno(ft,SOX_EOF,"wave header error: wExtSize(%d) too small for nCoefs(%d)", wExtSize, wav->nCoefs);
             return SOX_EOF;
         }
 
@@ -657,7 +654,7 @@
         {
             int i, errct=0;
             for (i=0; len>=2 && i < 2*wav->nCoefs; i++) {
-                sox_readw(ft, (unsigned short *)&(wav->iCoefs[i]));
+                lsx_readw(ft, (unsigned short *)&(wav->iCoefs[i]));
                 len -= 2;
                 if (i<14) errct += (wav->iCoefs[i] != iCoef[i/2][i%2]);
                 /* sox_debug("iCoefs[%2d] %4d",i,wav->iCoefs[i]); */
@@ -671,7 +668,7 @@
     case WAVE_FORMAT_IMA_ADPCM:
         if (wExtSize < 2)
         {
-            sox_fail_errno(ft,SOX_EOF,"format[%s]: expects wExtSize >= %d",
+            lsx_fail_errno(ft,SOX_EOF,"format[%s]: expects wExtSize >= %d",
                     wav_format_str(wav->formatTag), 2);
             return SOX_EOF;
         }
@@ -678,15 +675,15 @@
 
         if (wBitsPerSample != 4)
         {
-            sox_fail_errno(ft,SOX_EOF,"Can only handle 4-bit IMA ADPCM in wav files");
+            lsx_fail_errno(ft,SOX_EOF,"Can only handle 4-bit IMA ADPCM in wav files");
             return SOX_EOF;
         }
 
-        sox_readw(ft, &(wav->samplesPerBlock));
+        lsx_readw(ft, &(wav->samplesPerBlock));
         bytesPerBlock = ImaBytesPerBlock(ft->signal.channels, wav->samplesPerBlock);
         if (bytesPerBlock > wav->blockAlign || wav->samplesPerBlock%8 != 1)
         {
-            sox_fail_errno(ft,SOX_EOF,"format[%s]: samplesPerBlock(%d) incompatible with blockAlign(%d)",
+            lsx_fail_errno(ft,SOX_EOF,"format[%s]: samplesPerBlock(%d) incompatible with blockAlign(%d)",
                 wav_format_str(wav->formatTag), wav->samplesPerBlock, wav->blockAlign);
             return SOX_EOF;
         }
@@ -703,21 +700,21 @@
     case WAVE_FORMAT_GSM610:
         if (wExtSize < 2)
         {
-            sox_fail_errno(ft,SOX_EOF,"format[%s]: expects wExtSize >= %d",
+            lsx_fail_errno(ft,SOX_EOF,"format[%s]: expects wExtSize >= %d",
                     wav_format_str(wav->formatTag), 2);
             return SOX_EOF;
         }
-        sox_readw(ft, &wav->samplesPerBlock);
+        lsx_readw(ft, &wav->samplesPerBlock);
         bytesPerBlock = 65;
         if (wav->blockAlign != 65)
         {
-            sox_fail_errno(ft,SOX_EOF,"format[%s]: expects blockAlign(%d) = %d",
+            lsx_fail_errno(ft,SOX_EOF,"format[%s]: expects blockAlign(%d) = %d",
                     wav_format_str(wav->formatTag), wav->blockAlign, 65);
             return SOX_EOF;
         }
         if (wav->samplesPerBlock != 320)
         {
-            sox_fail_errno(ft,SOX_EOF,"format[%s]: expects samplesPerBlock(%d) = %d",
+            lsx_fail_errno(ft,SOX_EOF,"format[%s]: expects samplesPerBlock(%d) = %d",
                     wav_format_str(wav->formatTag), wav->samplesPerBlock, 320);
             return SOX_EOF;
         }
@@ -750,12 +747,12 @@
       break;
         
     default:
-      sox_fail_errno(ft,SOX_EFMT,"Sorry, don't understand .wav size");
+      lsx_fail_errno(ft,SOX_EFMT,"Sorry, don't understand .wav size");
       return SOX_EOF;
     }
 
     /* Skip anything left over from fmt chunk */
-    sox_seeki(ft, (sox_ssize_t)len, SEEK_CUR);
+    lsx_seeki(ft, (sox_ssize_t)len, SEEK_CUR);
 
     /* for non-PCM formats, there's a 'fact' chunk before
      * the upcoming 'data' chunk */
@@ -763,13 +760,13 @@
     /* Now look for the wave data chunk */
     if (findChunk(ft, "data", &len) == SOX_EOF)
     {
-        sox_fail_errno(ft, SOX_EOF, "Could not find data chunk.");
+        lsx_fail_errno(ft, SOX_EOF, "Could not find data chunk.");
         return SOX_EOF;
     }
     dwDataLength = len;
 
     /* Data starts here */
-    wav->dataStart = sox_tell(ft);
+    wav->dataStart = lsx_tell(ft);
 
     switch (wav->formatTag)
     {
@@ -843,15 +840,15 @@
          * doubt any machine writing Cool Edit Chunks writes them at an odd 
          * offset */
         len = (len + 1) & ~1u;
-        if (sox_seeki(ft, (sox_ssize_t)len, SEEK_CUR) == SOX_SUCCESS &&
+        if (lsx_seeki(ft, (sox_ssize_t)len, SEEK_CUR) == SOX_SUCCESS &&
             findChunk(ft, "LIST", &len) != SOX_EOF)
         {
             wav->comment = (char*)xmalloc(256);
             /* Initialize comment to a NULL string */
             wav->comment[0] = 0;
-            while(!sox_eof(ft))
+            while(!lsx_eof(ft))
             {
-                if (sox_reads(ft,magic,4) == SOX_EOF)
+                if (lsx_reads(ft,magic,4) == SOX_EOF)
                     break;
 
                 /* First look for type fields for LIST Chunk and
@@ -871,7 +868,7 @@
                 }
                 else
                 {
-                    if (sox_readdw(ft,&len) == SOX_EOF)
+                    if (lsx_readdw(ft,&len) == SOX_EOF)
                         break;
                     if (strncmp(magic,"ICRD",4) == 0)
                     {
@@ -881,7 +878,7 @@
                             sox_warn("Possible buffer overflow hack attack (ICRD)!");
                             break;
                         }
-                        sox_reads(ft,text,len);
+                        lsx_reads(ft,text,len);
                         if (strlen(wav->comment) + strlen(text) < 254)
                         {
                             if (wav->comment[0] != 0)
@@ -890,7 +887,7 @@
                             strcat(wav->comment,text);
                         }
                         if (strlen(text) < len)
-                           sox_seeki(ft, (sox_ssize_t)(len - strlen(text)), SEEK_CUR); 
+                           lsx_seeki(ft, (sox_ssize_t)(len - strlen(text)), SEEK_CUR); 
                     } 
                     else if (strncmp(magic,"ISFT",4) == 0)
                     {
@@ -900,7 +897,7 @@
                             sox_warn("Possible buffer overflow hack attack (ISFT)!");
                             break;
                         }
-                        sox_reads(ft,text,len);
+                        lsx_reads(ft,text,len);
                         if (strlen(wav->comment) + strlen(text) < 254)
                         {
                             if (wav->comment[0] != 0)
@@ -909,36 +906,36 @@
                             strcat(wav->comment,text);
                         }
                         if (strlen(text) < len)
-                           sox_seeki(ft, (sox_ssize_t)(len - strlen(text)), SEEK_CUR); 
+                           lsx_seeki(ft, (sox_ssize_t)(len - strlen(text)), SEEK_CUR); 
                     } 
                     else if (strncmp(magic,"cue ",4) == 0)
                     {
                         sox_debug("Chunk cue ");
-                        sox_seeki(ft,(sox_ssize_t)(len-4),SEEK_CUR);
-                        sox_readdw(ft,&dwLoopPos);
+                        lsx_seeki(ft,(sox_ssize_t)(len-4),SEEK_CUR);
+                        lsx_readdw(ft,&dwLoopPos);
                         ft->loops[0].start = dwLoopPos;
                     } 
                     else if (strncmp(magic,"ltxt",4) == 0)
                     {
                         sox_debug("Chunk ltxt");
-                        sox_readdw(ft,&dwLoopPos);
+                        lsx_readdw(ft,&dwLoopPos);
                         ft->loops[0].length = dwLoopPos - ft->loops[0].start;
                         if (len > 4)
-                           sox_seeki(ft, (sox_ssize_t)(len - 4), SEEK_CUR); 
+                           lsx_seeki(ft, (sox_ssize_t)(len - 4), SEEK_CUR); 
                     } 
                     else 
                     {
                         sox_debug("Attempting to seek beyond unsupported chunk '%c%c%c%c' of length %d bytes", magic[0], magic[1], magic[2], magic[3], len);
                         len = (len + 1) & ~1u;
-                        sox_seeki(ft, (sox_ssize_t)len, SEEK_CUR);
+                        lsx_seeki(ft, (sox_ssize_t)len, SEEK_CUR);
                     }
                 }
             }
         }
-        sox_clearerr(ft);
-        sox_seeki(ft,(sox_ssize_t)wav->dataStart,SEEK_SET);
+        lsx_clearerr(ft);
+        lsx_seeki(ft,(sox_ssize_t)wav->dataStart,SEEK_SET);
     }   
-    return sox_rawstartread(ft);
+    return lsx_rawstartread(ft);
 }
 
 
@@ -1023,7 +1020,7 @@
             if (!wav->ignoreSize && len > wav->numSamples*ft->signal.channels) 
                 len = (wav->numSamples*ft->signal.channels);
 
-            done = sox_rawread(ft, buf, len);
+            done = lsx_rawread(ft, buf, len);
             /* If software thinks there are more samples but I/O */
             /* says otherwise, let the user know about this.     */
             if (done == 0 && wav->numSamples != 0)
@@ -1082,7 +1079,7 @@
         ft->encoding.encoding != SOX_ENCODING_IMA_ADPCM &&
         ft->encoding.encoding != SOX_ENCODING_GSM)
     {
-        rc = sox_rawstartwrite(ft);
+        rc = lsx_rawstartwrite(ft);
         if (rc)
             return rc;
     }
@@ -1247,7 +1244,7 @@
         case SOX_ENCODING_IMA_ADPCM:
             if (wChannels>16)
             {
-                sox_fail_errno(ft,SOX_EOF,"Channels(%d) must be <= 16",wChannels);
+                lsx_fail_errno(ft,SOX_EOF,"Channels(%d) must be <= 16",wChannels);
                 return SOX_EOF;
             }
             wFormatTag = WAVE_FORMAT_IMA_ADPCM;
@@ -1259,7 +1256,7 @@
         case SOX_ENCODING_MS_ADPCM:
             if (wChannels>16)
             {
-                sox_fail_errno(ft,SOX_EOF,"Channels(%d) must be <= 16",wChannels);
+                lsx_fail_errno(ft,SOX_EOF,"Channels(%d) must be <= 16",wChannels);
                 return SOX_EOF;
             }
             wFormatTag = WAVE_FORMAT_ADPCM;
@@ -1324,56 +1321,56 @@
     /* If user specified opposite swap than we think, assume they are
      * asking to write a RIFX file.
      */
-    if (ft->encoding.reverse_bytes == SOX_IS_LITTLEENDIAN)
+    if (ft->encoding.reverse_bytes == MACHINE_IS_LITTLEENDIAN)
     {
         if (!second_header)
             sox_report("Requested to swap bytes so writing RIFX header");
-        sox_writes(ft, "RIFX");
+        lsx_writes(ft, "RIFX");
     }
     else
-        sox_writes(ft, "RIFF");
-    sox_writedw(ft, wRiffLength);
-    sox_writes(ft, "WAVE");
-    sox_writes(ft, "fmt ");
-    sox_writedw(ft, wFmtSize);
-    sox_writew(ft, isExtensible ? WAVE_FORMAT_EXTENSIBLE : wFormatTag);
-    sox_writew(ft, wChannels);
-    sox_writedw(ft, dwSamplesPerSecond);
-    sox_writedw(ft, dwAvgBytesPerSec);
-    sox_writew(ft, wBlockAlign);
-    sox_writew(ft, wBitsPerSample); /* end info common to all fmts */
+        lsx_writes(ft, "RIFF");
+    lsx_writedw(ft, wRiffLength);
+    lsx_writes(ft, "WAVE");
+    lsx_writes(ft, "fmt ");
+    lsx_writedw(ft, wFmtSize);
+    lsx_writew(ft, isExtensible ? WAVE_FORMAT_EXTENSIBLE : wFormatTag);
+    lsx_writew(ft, wChannels);
+    lsx_writedw(ft, dwSamplesPerSecond);
+    lsx_writedw(ft, dwAvgBytesPerSec);
+    lsx_writew(ft, wBlockAlign);
+    lsx_writew(ft, wBitsPerSample); /* end info common to all fmts */
 
     if (isExtensible) {
       static unsigned char const guids[][14] = {
         "\x00\x00\x00\x00\x10\x00\x80\x00\x00\xAA\x00\x38\x9B\x71",  /* wav */
         "\x00\x00\x21\x07\xd3\x11\x86\x44\xc8\xc1\xca\x00\x00\x00"}; /* amb */
-      sox_writew(ft, 22);
-      sox_writew(ft, wBitsPerSample); /* No padding in container */
-      sox_writedw(ft, 0);             /* Speaker mapping not specified */
-      sox_writew(ft, wFormatTag);
-      sox_writebuf(ft, guids[!strcmp(ft->filetype, "amb")], 14);
+      lsx_writew(ft, 22);
+      lsx_writew(ft, wBitsPerSample); /* No padding in container */
+      lsx_writedw(ft, 0);             /* Speaker mapping not specified */
+      lsx_writew(ft, wFormatTag);
+      lsx_writebuf(ft, guids[!strcmp(ft->filetype, "amb")], 14);
     }
     else 
     /* if not PCM, we need to write out wExtSize even if wExtSize=0 */
     if (wFormatTag != WAVE_FORMAT_PCM)
-        sox_writew(ft,wExtSize);
+        lsx_writew(ft,wExtSize);
 
     switch (wFormatTag)
     {
         int i;
         case WAVE_FORMAT_IMA_ADPCM:
-        sox_writew(ft, wSamplesPerBlock);
+        lsx_writew(ft, wSamplesPerBlock);
         break;
         case WAVE_FORMAT_ADPCM:
-        sox_writew(ft, wSamplesPerBlock);
-        sox_writew(ft, 7); /* nCoefs */
+        lsx_writew(ft, wSamplesPerBlock);
+        lsx_writew(ft, 7); /* nCoefs */
         for (i=0; i<7; i++) {
-            sox_writew(ft, (uint16_t)(iCoef[i][0]));
-            sox_writew(ft, (uint16_t)(iCoef[i][1]));
+            lsx_writew(ft, (uint16_t)(iCoef[i][0]));
+            lsx_writew(ft, (uint16_t)(iCoef[i][1]));
         }
         break;
         case WAVE_FORMAT_GSM610:
-        sox_writew(ft, wSamplesPerBlock);
+        lsx_writew(ft, wSamplesPerBlock);
         break;
         default:
         break;
@@ -1381,13 +1378,13 @@
 
     /* if not PCM, write the 'fact' chunk */
     if (isExtensible || wFormatTag != WAVE_FORMAT_PCM){
-        sox_writes(ft, "fact");
-        sox_writedw(ft,dwFactSize); 
-        sox_writedw(ft,dwSamplesWritten);
+        lsx_writes(ft, "fact");
+        lsx_writedw(ft,dwFactSize); 
+        lsx_writedw(ft,dwSamplesWritten);
     }
 
-    sox_writes(ft, "data");
-    sox_writedw(ft, dwDataLength);               /* data chunk size */
+    lsx_writes(ft, "data");
+    lsx_writedw(ft, dwDataLength);               /* data chunk size */
 
     if (!second_header) {
         sox_debug("Writing Wave file: %s format, %d channel%s, %d samp/sec",
@@ -1445,7 +1442,7 @@
             break;
 
         default:
-            len = sox_rawwrite(ft, buf, len);
+            len = lsx_rawwrite(ft, buf, len);
             wav->numSamples += (len/ft->signal.channels);
             return len;
         }
@@ -1481,9 +1478,9 @@
         if (!ft->seekable)
           return SOX_EOF;
 
-        if (sox_seeki(ft, 0, SEEK_SET) != 0)
+        if (lsx_seeki(ft, 0, SEEK_SET) != 0)
         {
-                sox_fail_errno(ft,SOX_EOF,"Can't rewind output file to rewrite .wav header.");
+                lsx_fail_errno(ft,SOX_EOF,"Can't rewind output file to rewrite .wav header.");
                 return SOX_EOF;
         }
 
@@ -1551,7 +1548,7 @@
     {
         case WAVE_FORMAT_IMA_ADPCM:
         case WAVE_FORMAT_ADPCM:
-            sox_fail_errno(ft,SOX_ENOTSUP,"ADPCM not supported");
+            lsx_fail_errno(ft,SOX_ENOTSUP,"ADPCM not supported");
             break;
 
         case WAVE_FORMAT_GSM610:
@@ -1564,7 +1561,7 @@
                          wav->blockAlign * ft->signal.channels / 2;
                 gsmoff -= gsmoff % (wav->blockAlign * ft->signal.channels);
 
-                ft->sox_errno = sox_seeki(ft, (sox_ssize_t)(gsmoff + wav->dataStart), SEEK_SET);
+                ft->sox_errno = lsx_seeki(ft, (sox_ssize_t)(gsmoff + wav->dataStart), SEEK_SET);
                 if (ft->sox_errno != SOX_SUCCESS)
                     return SOX_EOF;
 
@@ -1590,7 +1587,7 @@
                 new_offset += (channel_block - alignment);
             new_offset += wav->dataStart;
 
-            ft->sox_errno = sox_seeki(ft, new_offset, SEEK_SET);
+            ft->sox_errno = lsx_seeki(ft, new_offset, SEEK_SET);
 
             if( ft->sox_errno == SOX_SUCCESS )
                 wav->numSamples = (ft->length / ft->signal.channels) -
--- a/src/wve.c
+++ b/src/wve.c
@@ -29,21 +29,21 @@
   char buf[sizeof(ID1)];
   uint32_t num_samples;
 
-  if (sox_readchars(ft, buf, sizeof(buf)) || sox_readdw(ft, &num_samples) ||
-      sox_skipbytes(ft, sizeof(ID2)))
+  if (lsx_readchars(ft, buf, sizeof(buf)) || lsx_readdw(ft, &num_samples) ||
+      lsx_skipbytes(ft, sizeof(ID2)))
     return SOX_EOF;
   if (memcmp(ID1, buf, sizeof(buf))) {
-    sox_fail_errno(ft, SOX_EHDR, "wve: can't find Psion identifier");
+    lsx_fail_errno(ft, SOX_EHDR, "wve: can't find Psion identifier");
     return SOX_EOF;
   }
-  return sox_check_read_params(ft, 1, 8000., SOX_ENCODING_ALAW, 8, (off_t)num_samples);
+  return lsx_check_read_params(ft, 1, 8000., SOX_ENCODING_ALAW, 8, (off_t)num_samples);
 }
 
 static int write_header(sox_format_t * ft)
 {
-  return sox_writechars(ft, ID1, sizeof(ID1))
-      || sox_writedw(ft, ft->olength? ft->olength:ft->length)
-      || sox_writechars(ft, ID2, sizeof(ID2))? SOX_EOF:SOX_SUCCESS;
+  return lsx_writechars(ft, ID1, sizeof(ID1))
+      || lsx_writedw(ft, ft->olength? ft->olength:ft->length)
+      || lsx_writechars(ft, ID2, sizeof(ID2))? SOX_EOF:SOX_SUCCESS;
 }
 
 SOX_FORMAT_HANDLER(wve)
@@ -55,9 +55,9 @@
     SOX_LIB_VERSION_CODE,
     "Psion 3 audio format",
     names, SOX_FILE_BIG_END | SOX_FILE_MONO | SOX_FILE_REWIND,
-    start_read, sox_rawread, NULL,
-    write_header, sox_rawwrite, NULL,
-    sox_rawseek, write_encodings, write_rates
+    start_read, lsx_rawread, NULL,
+    write_header, lsx_rawwrite, NULL,
+    lsx_rawseek, write_encodings, write_rates
   };
   return &handler;
 }
--- a/src/xa.c
+++ b/src/xa.c
@@ -91,23 +91,23 @@
     char *magic = xa->header.magic;
 
     /* Check for the magic value */
-    if (sox_readbuf(ft, xa->header.magic, 4) != 4 ||
+    if (lsx_readbuf(ft, xa->header.magic, 4) != 4 ||
         (memcmp("XA\0\0", xa->header.magic, 4) != 0 &&
          memcmp("XAI\0", xa->header.magic, 4) != 0 &&
          memcmp("XAJ\0", xa->header.magic, 4) != 0))
     {
-        sox_fail_errno(ft, SOX_EHDR, "XA: Header not found");
+        lsx_fail_errno(ft, SOX_EHDR, "XA: Header not found");
         return SOX_EOF;
     }
     
     /* Read the rest of the header */
-    if (sox_readdw(ft, &xa->header.outSize) != SOX_SUCCESS) return SOX_EOF;
-    if (sox_readw(ft, &xa->header.tag) != SOX_SUCCESS) return SOX_EOF;
-    if (sox_readw(ft, &xa->header.channels) != SOX_SUCCESS) return SOX_EOF;
-    if (sox_readdw(ft, &xa->header.sampleRate) != SOX_SUCCESS) return SOX_EOF;
-    if (sox_readdw(ft, &xa->header.avgByteRate) != SOX_SUCCESS) return SOX_EOF;
-    if (sox_readw(ft, &xa->header.align) != SOX_SUCCESS) return SOX_EOF;
-    if (sox_readw(ft, &xa->header.bits) != SOX_SUCCESS) return SOX_EOF;
+    if (lsx_readdw(ft, &xa->header.outSize) != SOX_SUCCESS) return SOX_EOF;
+    if (lsx_readw(ft, &xa->header.tag) != SOX_SUCCESS) return SOX_EOF;
+    if (lsx_readw(ft, &xa->header.channels) != SOX_SUCCESS) return SOX_EOF;
+    if (lsx_readdw(ft, &xa->header.sampleRate) != SOX_SUCCESS) return SOX_EOF;
+    if (lsx_readdw(ft, &xa->header.avgByteRate) != SOX_SUCCESS) return SOX_EOF;
+    if (lsx_readw(ft, &xa->header.align) != SOX_SUCCESS) return SOX_EOF;
+    if (lsx_readw(ft, &xa->header.bits) != SOX_SUCCESS) return SOX_EOF;
 
     /* Output the data from the header */
     sox_debug("XA Header:");
@@ -148,7 +148,7 @@
     
     /* Check for supported formats */
     if (ft->encoding.bits_per_sample != 16) {
-        sox_fail_errno(ft, SOX_EFMT, "%d-bit sample resolution not supported.",
+        lsx_fail_errno(ft, SOX_EFMT, "%d-bit sample resolution not supported.",
             ft->encoding.bits_per_sample);
         return SOX_EOF;
     }
@@ -202,17 +202,17 @@
     while (done < len) {
         if (xa->bufPos >= xa->blockSize) {
             /* Read the next block */
-            bytes = sox_readbuf(ft, xa->buf, xa->blockSize);
+            bytes = lsx_readbuf(ft, xa->buf, xa->blockSize);
             if (bytes < xa->blockSize) {
-                if (sox_eof(ft)) {
+                if (lsx_eof(ft)) {
                     if (done > 0) {
                         return done;
                     }
-                    sox_fail_errno(ft,SOX_EOF,"Premature EOF on .xa input file");
+                    lsx_fail_errno(ft,SOX_EOF,"Premature EOF on .xa input file");
                     return 0;
                 } else {
                     /* error */
-                    sox_fail_errno(ft,SOX_EOF,"read error on input stream");
+                    lsx_fail_errno(ft,SOX_EOF,"read error on input stream");
                     return 0;
                 }
             }