Merge tag 'upstream/1.0.31' into tizen
[platform/upstream/libsndfile.git] / src / aiff.c
index 0113ba6..763b493 100644 (file)
@@ -1,5 +1,5 @@
 /*
-** Copyright (C) 1999-2011 Erik de Castro Lopo <erikd@mega-nerd.com>
+** Copyright (C) 1999-2018 Erik de Castro Lopo <erikd@mega-nerd.com>
 ** Copyright (C) 2005 David Viens <davidv@plogue.com>
 **
 ** This program is free software; you can redistribute it and/or modify
@@ -123,34 +123,34 @@ enum
 } ;
 
 typedef struct
-{      unsigned int    size ;
-       short                   numChannels ;
-       unsigned int    numSampleFrames ;
-       short                   sampleSize ;
-       unsigned char   sampleRate [10] ;
-       unsigned int    encoding ;
+{      uint32_t        size ;
+       int16_t         numChannels ;
+       uint32_t        numSampleFrames ;
+       int16_t         sampleSize ;
+       uint8_t         sampleRate [10] ;
+       uint32_t        encoding ;
        char                    zero_bytes [2] ;
 } COMM_CHUNK ;
 
 typedef struct
-{      unsigned int    offset ;
-       unsigned int    blocksize ;
+{      uint32_t        offset ;
+       uint32_t        blocksize ;
 } SSND_CHUNK ;
 
 typedef struct
-{      short                   playMode ;
-       unsigned short  beginLoop ;
-       unsigned short  endLoop ;
+{      int16_t         playMode ;
+       uint16_t        beginLoop ;
+       uint16_t        endLoop ;
 } INST_LOOP ;
 
 typedef struct
-{      char            baseNote ;              /* all notes are MIDI note numbers */
-       char            detune ;                /* cents off, only -50 to +50 are significant */
-       char            lowNote ;
-       char            highNote ;
-       char            lowVelocity ;   /* 1 to 127 */
-       char            highVelocity ;  /* 1 to 127 */
-       short           gain ;                  /* in dB, 0 is normal */
+{      int8_t          baseNote ;              /* all notes are MIDI note numbers */
+       int8_t          detune ;                /* cents off, only -50 to +50 are significant */
+       int8_t          lowNote ;
+       int8_t          highNote ;
+       int8_t          lowVelocity ;   /* 1 to 127 */
+       int8_t          highVelocity ;  /* 1 to 127 */
+       int16_t         gain ;                  /* in dB, 0 is normal */
        INST_LOOP       sustain_loop ;
        INST_LOOP       release_loop ;
 } INST_CHUNK ;
@@ -170,27 +170,25 @@ enum
 
 
 typedef struct
-{      unsigned int    version ;
-       unsigned int    numBeats ;
-       unsigned short  rootNote ;
-       unsigned short  scaleType ;
-       unsigned short  sigNumerator ;
-       unsigned short  sigDenominator ;
-       unsigned short  loopType ;
+{      uint32_t        version ;
+       uint32_t        numBeats ;
+       uint16_t        rootNote ;
+       uint16_t        scaleType ;
+       uint16_t        sigNumerator ;
+       uint16_t        sigDenominator ;
+       uint16_t        loopType ;
 } basc_CHUNK ;
 
 typedef struct
-{      unsigned short  markerID ;
-       unsigned int    position ;
+{      uint16_t        markerID ;
+       uint32_t        position ;
 } MARK_ID_POS ;
 
 typedef struct
-{      PRIV_CHUNK4 chunk4 ;
-
-       sf_count_t      comm_offset ;
+{      sf_count_t      comm_offset ;
        sf_count_t      ssnd_offset ;
 
-       int chanmap_tag ;
+       int32_t         chanmap_tag ;
 
        MARK_ID_POS *markstr ;
 } AIFF_PRIVATE ;
@@ -201,8 +199,8 @@ typedef struct
 
 static int     aiff_close (SF_PRIVATE *psf) ;
 
-static int     tenbytefloat2int (unsigned char *bytes) ;
-static void uint2tenbytefloat (unsigned int num, unsigned char *bytes) ;
+static int     tenbytefloat2int (uint8_t *bytes) ;
+static void uint2tenbytefloat (uint32_t num, uint8_t *bytes) ;
 
 static int     aiff_read_comm_chunk (SF_PRIVATE *psf, COMM_CHUNK *comm_fmt) ;
 
@@ -214,15 +212,20 @@ static void       aiff_write_strings (SF_PRIVATE *psf, int location) ;
 
 static int     aiff_command (SF_PRIVATE *psf, int command, void *data, int datasize) ;
 
-static const char *get_loop_mode_str (short mode) ;
+static const char *get_loop_mode_str (int16_t mode) ;
 
-static short get_loop_mode (short mode) ;
+static int16_t get_loop_mode (int16_t mode) ;
 
 static int aiff_read_basc_chunk (SF_PRIVATE * psf, int) ;
 
 static int aiff_read_chanmap (SF_PRIVATE * psf, unsigned dword) ;
 
-static unsigned int marker_to_position (const MARK_ID_POS *m, unsigned short n, int marksize) ;
+static uint32_t marker_to_position (const MARK_ID_POS *m, uint16_t n, int marksize) ;
+
+static int aiff_set_chunk (SF_PRIVATE *psf, const SF_CHUNK_INFO * chunk_info) ;
+static SF_CHUNK_ITERATOR * aiff_next_chunk_iterator (SF_PRIVATE *psf, SF_CHUNK_ITERATOR * iterator) ;
+static int aiff_get_chunk_size (SF_PRIVATE *psf, const SF_CHUNK_ITERATOR * iterator, SF_CHUNK_INFO * chunk_info) ;
+static int aiff_get_chunk_data (SF_PRIVATE *psf, const SF_CHUNK_ITERATOR * iterator, SF_CHUNK_INFO * chunk_info) ;
 
 /*------------------------------------------------------------------------------
 ** Public function.
@@ -240,9 +243,16 @@ aiff_open (SF_PRIVATE *psf)
        if ((psf->container_data = calloc (1, sizeof (AIFF_PRIVATE))) == NULL)
                return SFE_MALLOC_FAILED ;
 
+       psf->container_close = aiff_close ;
+
        if (psf->file.mode == SFM_READ || (psf->file.mode == SFM_RDWR && psf->filelength > 0))
        {       if ((error = aiff_read_header (psf, &comm_fmt)))
                        return error ;
+
+               psf->next_chunk_iterator = aiff_next_chunk_iterator ;
+               psf->get_chunk_size = aiff_get_chunk_size ;
+               psf->get_chunk_data = aiff_get_chunk_data ;
+
                psf_fseek (psf, psf->dataoffset, SEEK_SET) ;
                } ;
 
@@ -266,15 +276,15 @@ aiff_open (SF_PRIVATE *psf)
                        psf->sf.frames = 0 ;
                        } ;
 
-               psf->str_flags = SF_STR_ALLOW_START | SF_STR_ALLOW_END ;
+               psf->strings.flags = SF_STR_ALLOW_START | SF_STR_ALLOW_END ;
 
                if ((error = aiff_write_header (psf, SF_FALSE)))
                        return error ;
 
-               psf->write_header = aiff_write_header ;
+               psf->write_header       = aiff_write_header ;
+               psf->set_chunk          = aiff_set_chunk ;
                } ;
 
-       psf->container_close = aiff_close ;
        psf->command = aiff_command ;
 
        switch (SF_CODEC (psf->sf.format))
@@ -310,15 +320,20 @@ aiff_open (SF_PRIVATE *psf)
                                break ;
 
                case SF_FORMAT_DWVW_12 :
-                               error = dwvw_init (psf, 12) ;
+                               if (psf->sf.frames > comm_fmt.numSampleFrames)
+                                       psf->sf.frames = comm_fmt.numSampleFrames ;
                                break ;
 
                case SF_FORMAT_DWVW_16 :
                                error = dwvw_init (psf, 16) ;
+                               if (psf->sf.frames > comm_fmt.numSampleFrames)
+                                       psf->sf.frames = comm_fmt.numSampleFrames ;
                                break ;
 
                case SF_FORMAT_DWVW_24 :
                                error = dwvw_init (psf, 24) ;
+                               if (psf->sf.frames > comm_fmt.numSampleFrames)
+                                       psf->sf.frames = comm_fmt.numSampleFrames ;
                                break ;
 
                case SF_FORMAT_DWVW_N :
@@ -328,7 +343,8 @@ aiff_open (SF_PRIVATE *psf)
                                        } ;
                                if (comm_fmt.sampleSize >= 8 && comm_fmt.sampleSize < 24)
                                {       error = dwvw_init (psf, comm_fmt.sampleSize) ;
-                                       psf->sf.frames = comm_fmt.numSampleFrames ;
+                                       if (psf->sf.frames > comm_fmt.numSampleFrames)
+                                               psf->sf.frames = comm_fmt.numSampleFrames ;
                                        break ;
                                        } ;
                                psf_log_printf (psf, "AIFC/DWVW : Bad bitwidth %d\n", comm_fmt.sampleSize) ;
@@ -344,13 +360,15 @@ aiff_open (SF_PRIVATE *psf)
                                break ;
                /* Lite remove end */
 
-               case SF_FORMAT_GSM610 :
-                               error = gsm610_init (psf) ;
-                               break ;
-
                default : return SFE_UNIMPLEMENTED ;
                } ;
 
+       if (psf->file.mode != SFM_WRITE && psf->sf.frames - comm_fmt.numSampleFrames != 0)
+       {       psf_log_printf (psf,
+                       "*** Frame count read from 'COMM' chunk (%u) not equal to frame count\n"
+                       "*** calculated from length of 'SSND' chunk (%u).\n",
+                       comm_fmt.numSampleFrames, (uint32_t) psf->sf.frames) ;
+               } ;
 
        return error ;
 } /* aiff_open */
@@ -360,24 +378,25 @@ aiff_open (SF_PRIVATE *psf)
 */
 
 /* This function ought to check size */
-static unsigned int
-marker_to_position (const MARK_ID_POS *m, unsigned short n, int marksize)
+static uint32_t
+marker_to_position (const MARK_ID_POS *m, uint16_t n, int marksize)
 {      int i ;
 
-    for (i = 0 ; i < marksize ; i++)
+       for (i = 0 ; i < marksize ; i++)
                if (m [i].markerID == n)
                        return m [i].position ;
-    return 0 ;
+       return 0 ;
 } /* marker_to_position */
 
 static int
 aiff_read_header (SF_PRIVATE *psf, COMM_CHUNK *comm_fmt)
 {      SSND_CHUNK      ssnd_fmt ;
        AIFF_PRIVATE *paiff ;
-       unsigned        marker, dword, FORMsize, SSNDsize, bytesread ;
+       BUF_UNION       ubuf ;
+       uint32_t        chunk_size = 0, FORMsize, SSNDsize, bytesread, mark_count = 0 ;
        int                     k, found_chunk = 0, done = 0, error = 0 ;
        char            *cptr ;
-       int                     instr_found = 0, mark_found = 0, mark_count = 0 ;
+       int                     instr_found = 0, mark_found = 0 ;
 
        if (psf->filelength > SF_PLATFORM_S64 (0xffffffff))
                psf_log_printf (psf, "Warning : filelength > 0xffffffff. This is bad!!!!\n") ;
@@ -401,54 +420,62 @@ aiff_read_header (SF_PRIVATE *psf, COMM_CHUNK *comm_fmt)
        **      one and then check for the mandatory chunks at the end.
        */
        while (! done)
-       {       psf_binheader_readf (psf, "m", &marker) ;
+       {       unsigned        marker ;
+               size_t jump = chunk_size & 1 ;
+
+               marker = chunk_size = 0 ;
+               psf_binheader_readf (psf, "Ejm4", jump, &marker, &chunk_size) ;
+               if (marker == 0)
+               {       sf_count_t pos = psf_ftell (psf) ;
+                       psf_log_printf (psf, "Have 0 marker at position %D (0x%x).\n", pos, pos) ;
+                       break ;
+                       } ;
 
                if (psf->file.mode == SFM_RDWR && (found_chunk & HAVE_SSND))
                        return SFE_AIFF_RW_SSND_NOT_LAST ;
 
+               psf_store_read_chunk_u32 (&psf->rchunks, marker, psf_ftell (psf), chunk_size) ;
+
                switch (marker)
                {       case FORM_MARKER :
                                        if (found_chunk)
                                                return SFE_AIFF_NO_FORM ;
 
-                                       psf_binheader_readf (psf, "E4", &FORMsize) ;
-                                       pchk4_store (&paiff->chunk4, marker, psf->headindex - 8, FORMsize) ;
+                                       FORMsize = chunk_size ;
+
+                                       found_chunk |= HAVE_FORM ;
+                                       psf_binheader_readf (psf, "m", &marker) ;
+                                       switch (marker)
+                                       {       case AIFC_MARKER :
+                                               case AIFF_MARKER :
+                                                       found_chunk |= (marker == AIFC_MARKER) ? (HAVE_AIFC | HAVE_AIFF) : HAVE_AIFF ;
+                                                       break ;
+                                               default :
+                                                       break ;
+                                               } ;
 
                                        if (psf->fileoffset > 0 && psf->filelength > FORMsize + 8)
                                        {       /* Set file length. */
                                                psf->filelength = FORMsize + 8 ;
-                                               psf_log_printf (psf, "FORM : %u\n", FORMsize) ;
+                                               psf_log_printf (psf, "FORM : %u\n %M\n", FORMsize, marker) ;
                                                }
-                                       else if (FORMsize != psf->filelength - 2 * SIGNED_SIZEOF (dword))
-                                       {       dword = psf->filelength - 2 * sizeof (dword) ;
-                                               psf_log_printf (psf, "FORM : %u (should be %u)\n", FORMsize, dword) ;
-                                               FORMsize = dword ;
+                                       else if (FORMsize != psf->filelength - 2 * SIGNED_SIZEOF (chunk_size))
+                                       {       chunk_size = psf->filelength - 2 * sizeof (chunk_size) ;
+                                               psf_log_printf (psf, "FORM : %u (should be %u)\n %M\n", FORMsize, chunk_size, marker) ;
+                                               FORMsize = chunk_size ;
                                                }
                                        else
-                                               psf_log_printf (psf, "FORM : %u\n", FORMsize) ;
-                                       found_chunk |= HAVE_FORM ;
+                                               psf_log_printf (psf, "FORM : %u\n %M\n", FORMsize, marker) ;
+                                       /* Set this to 0, so we don't jump a byte when parsing the next marker. */
+                                       chunk_size = 0 ;
                                        break ;
 
-                       case AIFC_MARKER :
-                       case AIFF_MARKER :
-                                       if ((found_chunk & HAVE_FORM) == 0)
-                                               return SFE_AIFF_AIFF_NO_FORM ;
-                                       psf_log_printf (psf, " %M\n", marker) ;
-                                       found_chunk |= (marker == AIFC_MARKER) ? (HAVE_AIFC | HAVE_AIFF) : HAVE_AIFF ;
-                                       break ;
 
                        case COMM_MARKER :
-                                       paiff->comm_offset = psf_ftell (psf) - 4 ;
-                                       error = aiff_read_comm_chunk (psf, comm_fmt) ;
-                                       pchk4_store (&paiff->chunk4, marker, paiff->comm_offset, comm_fmt->size) ;
-
-
-                                       psf->sf.samplerate = tenbytefloat2int (comm_fmt->sampleRate) ;
-                                       psf->sf.frames = comm_fmt->numSampleFrames ;
-                                       psf->sf.channels = comm_fmt->numChannels ;
-                                       psf->bytewidth = BITWIDTH2BYTES (comm_fmt->sampleSize) ;
-
-                                       if (error)
+                                       paiff->comm_offset = psf_ftell (psf) - 8 ;
+                                       chunk_size += chunk_size & 1 ;
+                                       comm_fmt->size = chunk_size ;
+                                       if ((error = aiff_read_comm_chunk (psf, comm_fmt)) != 0)
                                                return error ;
 
                                        found_chunk |= HAVE_COMM ;
@@ -459,16 +486,18 @@ aiff_read_header (SF_PRIVATE *psf, COMM_CHUNK *comm_fmt)
                                        if ((found_chunk & (HAVE_FORM | HAVE_AIFF | HAVE_COMM)) != (HAVE_FORM | HAVE_AIFF | HAVE_COMM))
                                                return SFE_AIFF_PEAK_B4_COMM ;
 
-                                       psf_binheader_readf (psf, "E4", &dword) ;
-                                       pchk4_store (&paiff->chunk4, marker, psf->headindex - 8, dword) ;
-
-                                       psf_log_printf (psf, "%M : %d\n", marker, dword) ;
-                                       if (dword != AIFF_PEAK_CHUNK_SIZE (psf->sf.channels))
-                                       {       psf_binheader_readf (psf, "j", dword) ;
+                                       psf_log_printf (psf, "%M : %d\n", marker, chunk_size) ;
+                                       if (chunk_size != AIFF_PEAK_CHUNK_SIZE (psf->sf.channels))
+                                       {       psf_binheader_readf (psf, "j", chunk_size) ;
                                                psf_log_printf (psf, "*** File PEAK chunk too big.\n") ;
                                                return SFE_WAV_BAD_PEAK ;
                                                } ;
 
+                                       if (psf->peak_info)
+                                       {       psf_log_printf (psf, "*** Found existing peak info, using last one.\n") ;
+                                               free (psf->peak_info) ;
+                                               psf->peak_info = NULL ;
+                                               } ;
                                        if ((psf->peak_info = peak_info_calloc (psf->sf.channels)) == NULL)
                                                return SFE_MALLOC_FAILED ;
 
@@ -483,18 +512,18 @@ aiff_read_header (SF_PRIVATE *psf, COMM_CHUNK *comm_fmt)
                                        psf_log_printf (psf, "  time stamp : %d\n", psf->peak_info->timestamp) ;
                                        psf_log_printf (psf, "    Ch   Position       Value\n") ;
 
-                                       cptr = psf->u.cbuf ;
-                                       for (dword = 0 ; dword < (unsigned) psf->sf.channels ; dword++)
+                                       cptr = ubuf.cbuf ;
+                                       for (k = 0 ; k < psf->sf.channels ; k++)
                                        {       float value ;
-                                               unsigned int position ;
+                                               uint32_t position ;
 
                                                psf_binheader_readf (psf, "Ef4", &value, &position) ;
-                                               psf->peak_info->peaks [dword].value = value ;
-                                               psf->peak_info->peaks [dword].position = position ;
+                                               psf->peak_info->peaks [k].value = value ;
+                                               psf->peak_info->peaks [k].position = position ;
 
-                                               snprintf (cptr, sizeof (psf->u.scbuf), "    %2d   %-12" PRId64 "   %g\n",
-                                                               dword, psf->peak_info->peaks [dword].position, psf->peak_info->peaks [dword].value) ;
-                                               cptr [sizeof (psf->u.scbuf) - 1] = 0 ;
+                                               snprintf (cptr, sizeof (ubuf.scbuf), "    %2d   %-12" PRId64 "   %g\n",
+                                                               k, psf->peak_info->peaks [k].position, psf->peak_info->peaks [k].value) ;
+                                               cptr [sizeof (ubuf.scbuf) - 1] = 0 ;
                                                psf_log_printf (psf, "%s", cptr) ;
                                                } ;
 
@@ -505,9 +534,9 @@ aiff_read_header (SF_PRIVATE *psf, COMM_CHUNK *comm_fmt)
                                        if ((found_chunk & HAVE_AIFC) && (found_chunk & HAVE_FVER) == 0)
                                                psf_log_printf (psf, "*** Valid AIFC files should have an FVER chunk.\n") ;
 
-                                       paiff->ssnd_offset = psf_ftell (psf) - 4 ;
-                                       psf_binheader_readf (psf, "E444", &SSNDsize, &(ssnd_fmt.offset), &(ssnd_fmt.blocksize)) ;
-                                       pchk4_store (&paiff->chunk4, marker, paiff->ssnd_offset, SSNDsize) ;
+                                       paiff->ssnd_offset = psf_ftell (psf) - 8 ;
+                                       SSNDsize = chunk_size ;
+                                       psf_binheader_readf (psf, "E44", &(ssnd_fmt.offset), &(ssnd_fmt.blocksize)) ;
 
                                        psf->datalength = SSNDsize - sizeof (ssnd_fmt) ;
                                        psf->dataoffset = psf_ftell (psf) ;
@@ -543,157 +572,148 @@ aiff_read_header (SF_PRIVATE *psf, COMM_CHUNK *comm_fmt)
                                                break ;
 
                                        /* Seek to end of SSND chunk. */
-                                       psf_fseek (psf, psf->dataoffset + psf->datalength + (SSNDsize & 1), SEEK_SET) ;
+                                       psf_fseek (psf, psf->dataoffset + psf->datalength, SEEK_SET) ;
                                        break ;
 
                        case c_MARKER :
-                                       psf_binheader_readf (psf, "E4", &dword) ;
-                                       pchk4_store (&paiff->chunk4, marker, psf_ftell (psf) - 8, dword) ;
-                                       if (dword == 0)
+                                       if (chunk_size == 0)
                                                break ;
-                                       if (dword >= SIGNED_SIZEOF (psf->u.scbuf))
-                                       {       psf_log_printf (psf, " %M : %d (too big)\n", marker, dword) ;
+                                       if (chunk_size >= SIGNED_SIZEOF (ubuf.scbuf))
+                                       {       psf_log_printf (psf, " %M : %d (too big)\n", marker, chunk_size) ;
                                                return SFE_INTERNAL ;
                                                } ;
 
-                                       cptr = psf->u.cbuf ;
-                                       psf_binheader_readf (psf, "b", cptr, dword + (dword & 1)) ;
-                                       cptr [dword] = 0 ;
+                                       cptr = ubuf.cbuf ;
+                                       psf_binheader_readf (psf, "b", cptr, chunk_size + (chunk_size & 1)) ;
+                                       cptr [chunk_size] = 0 ;
 
-                                       psf_sanitize_string (cptr, dword) ;
+                                       psf_sanitize_string (cptr, chunk_size) ;
 
                                        psf_log_printf (psf, " %M : %s\n", marker, cptr) ;
                                        psf_store_string (psf, SF_STR_COPYRIGHT, cptr) ;
+                                       chunk_size += chunk_size & 1 ;
                                        break ;
 
                        case AUTH_MARKER :
-                                       psf_binheader_readf (psf, "E4", &dword) ;
-                                       pchk4_store (&paiff->chunk4, marker, psf_ftell (psf) - 8, dword) ;
-                                       if (dword == 0)
+                                       if (chunk_size == 0)
                                                break ;
-                                       if (dword >= SIGNED_SIZEOF (psf->u.scbuf) - 1)
-                                       {       psf_log_printf (psf, " %M : %d (too big)\n", marker, dword) ;
+                                       if (chunk_size >= SIGNED_SIZEOF (ubuf.scbuf) - 1)
+                                       {       psf_log_printf (psf, " %M : %d (too big)\n", marker, chunk_size) ;
                                                return SFE_INTERNAL ;
                                                } ;
 
-                                       cptr = psf->u.cbuf ;
-                                       psf_binheader_readf (psf, "b", cptr, dword + (dword & 1)) ;
-                                       cptr [dword] = 0 ;
+                                       cptr = ubuf.cbuf ;
+                                       psf_binheader_readf (psf, "b", cptr, chunk_size + (chunk_size & 1)) ;
+                                       cptr [chunk_size] = 0 ;
                                        psf_log_printf (psf, " %M : %s\n", marker, cptr) ;
                                        psf_store_string (psf, SF_STR_ARTIST, cptr) ;
+                                       chunk_size += chunk_size & 1 ;
                                        break ;
 
                        case COMT_MARKER :
-                               {       unsigned short count, id, len ;
-                                       unsigned int timestamp ;
-
-                                       psf_binheader_readf (psf, "E42", &dword, &count) ;
-                                       pchk4_store (&paiff->chunk4, marker, psf_ftell (psf) - 8, dword) ;
-                                       psf_log_printf (psf, " %M : %d\n  count  : %d\n", marker, dword, count) ;
-                                       dword += (dword & 1) ;
-                                       if (dword == 0)
+                               {       uint16_t count, id, len ;
+                                       uint32_t timestamp, bytes ;
+
+                                       if (chunk_size == 0)
                                                break ;
-                                       dword -= 2 ;
+                                       bytes = chunk_size ;
+                                       bytes -= psf_binheader_readf (psf, "E2", &count) ;
+                                       psf_log_printf (psf, " %M : %d\n  count  : %d\n", marker, chunk_size, count) ;
 
                                        for (k = 0 ; k < count ; k++)
-                                       {       dword -= psf_binheader_readf (psf, "E422", &timestamp, &id, &len) ;
+                                       {       bytes -= psf_binheader_readf (psf, "E422", &timestamp, &id, &len) ;
                                                psf_log_printf (psf, "   time   : 0x%x\n   marker : %x\n   length : %d\n", timestamp, id, len) ;
 
-                                               if (len + 1 > SIGNED_SIZEOF (psf->u.scbuf))
+                                               if (len + 1 > SIGNED_SIZEOF (ubuf.scbuf))
                                                {       psf_log_printf (psf, "\nError : string length (%d) too big.\n", len) ;
                                                        return SFE_INTERNAL ;
                                                        } ;
 
-                                               cptr = psf->u.cbuf ;
-                                               dword -= psf_binheader_readf (psf, "b", cptr, len) ;
+                                               cptr = ubuf.cbuf ;
+                                               bytes -= psf_binheader_readf (psf, "b", cptr, len) ;
                                                cptr [len] = 0 ;
                                                psf_log_printf (psf, "   string : %s\n", cptr) ;
                                                } ;
 
-                                       if (dword > 0)
-                                               psf_binheader_readf (psf, "j", dword) ;
+                                       if (bytes > 0)
+                                               psf_binheader_readf (psf, "j", bytes) ;
                                        } ;
                                        break ;
 
                        case APPL_MARKER :
                                {       unsigned appl_marker ;
 
-                                       psf_binheader_readf (psf, "E4", &dword) ;
-                                       pchk4_store (&paiff->chunk4, marker, psf_ftell (psf) - 8, dword) ;
-                                       if (dword == 0)
+                                       if (chunk_size == 0)
                                                break ;
-                                       if (dword >= SIGNED_SIZEOF (psf->u.scbuf) - 1)
-                                       {       psf_log_printf (psf, " %M : %d (too big, skipping)\n", marker, dword) ;
-                                               psf_binheader_readf (psf, "j", dword + (dword & 1)) ;
+                                       if (chunk_size >= SIGNED_SIZEOF (ubuf.scbuf) - 1)
+                                       {       psf_log_printf (psf, " %M : %u (too big, skipping)\n", marker, chunk_size) ;
+                                               psf_binheader_readf (psf, "j", chunk_size + (chunk_size & 1)) ;
                                                break ;
                                                } ;
 
-                                       if (dword < 4)
-                                       {       psf_log_printf (psf, " %M : %d (too small, skipping)\n", marker, dword) ;
-                                               psf_binheader_readf (psf, "j", dword + (dword & 1)) ;
+                                       if (chunk_size < 4)
+                                       {       psf_log_printf (psf, " %M : %d (too small, skipping)\n", marker, chunk_size) ;
+                                               psf_binheader_readf (psf, "j", chunk_size + (chunk_size & 1)) ;
                                                break ;
                                                } ;
 
-                                       cptr = psf->u.cbuf ;
-                                       psf_binheader_readf (psf, "mb", &appl_marker, cptr, dword + (dword & 1) - 4) ;
-                                       cptr [dword] = 0 ;
+                                       cptr = ubuf.cbuf ;
+                                       psf_binheader_readf (psf, "mb", &appl_marker, cptr, chunk_size + (chunk_size & 1) - 4) ;
+                                       cptr [chunk_size] = 0 ;
 
-                                       for (k = 0 ; k < (int) dword ; k++)
+                                       for (k = 0 ; k < (int) chunk_size ; k++)
                                                if (! psf_isprint (cptr [k]))
                                                {       cptr [k] = 0 ;
                                                        break ;
                                                        } ;
 
-                                       psf_log_printf (psf, " %M : %d\n  AppSig : %M\n  Name   : %s\n", marker, dword, appl_marker, cptr) ;
+                                       psf_log_printf (psf, " %M : %d\n  AppSig : %M\n  Name   : %s\n", marker, chunk_size, appl_marker, cptr) ;
                                        psf_store_string (psf, SF_STR_SOFTWARE, cptr) ;
+                                       chunk_size += chunk_size & 1 ;
                                        } ;
                                        break ;
 
                        case NAME_MARKER :
-                                       psf_binheader_readf (psf, "E4", &dword) ;
-                                       pchk4_store (&paiff->chunk4, marker, psf_ftell (psf) - 8, dword) ;
-                                       if (dword == 0)
+                                       if (chunk_size == 0)
                                                break ;
-                                       if (dword >= SIGNED_SIZEOF (psf->u.scbuf) - 2)
-                                       {       psf_log_printf (psf, " %M : %d (too big)\n", marker, dword) ;
+                                       if (chunk_size >= SIGNED_SIZEOF (ubuf.scbuf) - 2)
+                                       {       psf_log_printf (psf, " %M : %d (too big)\n", marker, chunk_size) ;
                                                return SFE_INTERNAL ;
                                                } ;
 
-                                       cptr = psf->u.cbuf ;
-                                       psf_binheader_readf (psf, "b", cptr, dword + (dword & 1)) ;
-                                       cptr [dword] = 0 ;
+                                       cptr = ubuf.cbuf ;
+                                       psf_binheader_readf (psf, "b", cptr, chunk_size + (chunk_size & 1)) ;
+                                       cptr [chunk_size] = 0 ;
                                        psf_log_printf (psf, " %M : %s\n", marker, cptr) ;
                                        psf_store_string (psf, SF_STR_TITLE, cptr) ;
+                                       chunk_size += chunk_size & 1 ;
                                        break ;
 
                        case ANNO_MARKER :
-                                       psf_binheader_readf (psf, "E4", &dword) ;
-                                       pchk4_store (&paiff->chunk4, marker, psf_ftell (psf) - 8, dword) ;
-                                       if (dword == 0)
+                                       if (chunk_size == 0)
                                                break ;
-                                       if (dword >= SIGNED_SIZEOF (psf->u.scbuf) - 2)
-                                       {       psf_log_printf (psf, " %M : %d (too big)\n", marker, dword) ;
+                                       if (chunk_size >= SIGNED_SIZEOF (ubuf.scbuf) - 2)
+                                       {       psf_log_printf (psf, " %M : %d (too big)\n", marker, chunk_size) ;
                                                return SFE_INTERNAL ;
                                                } ;
 
-                                       cptr = psf->u.cbuf ;
-                                       psf_binheader_readf (psf, "b", cptr, dword + (dword & 1)) ;
-                                       cptr [dword] = 0 ;
+                                       cptr = ubuf.cbuf ;
+                                       psf_binheader_readf (psf, "b", cptr, chunk_size + (chunk_size & 1)) ;
+                                       cptr [chunk_size] = 0 ;
                                        psf_log_printf (psf, " %M : %s\n", marker, cptr) ;
                                        psf_store_string (psf, SF_STR_COMMENT, cptr) ;
+                                       chunk_size += chunk_size & 1 ;
                                        break ;
 
                        case INST_MARKER :
-                                       psf_binheader_readf (psf, "E4", &dword) ;
-                                       pchk4_store (&paiff->chunk4, marker, psf_ftell (psf) - 8, dword) ;
-                                       if (dword != SIZEOF_INST_CHUNK)
-                                       {       psf_log_printf (psf, " %M : %d (should be %d)\n", marker, dword, SIZEOF_INST_CHUNK) ;
-                                               psf_binheader_readf (psf, "j", dword) ;
+                                       if (chunk_size != SIZEOF_INST_CHUNK)
+                                       {       psf_log_printf (psf, " %M : %d (should be %d)\n", marker, chunk_size, SIZEOF_INST_CHUNK) ;
+                                               psf_binheader_readf (psf, "j", chunk_size) ;
                                                break ;
                                                } ;
-                                       psf_log_printf (psf, " %M : %d\n", marker, dword) ;
-                                       {       unsigned char bytes [6] ;
-                                               short gain ;
+                                       psf_log_printf (psf, " %M : %d\n", marker, chunk_size) ;
+                                       {       uint8_t bytes [6] ;
+                                               int16_t gain ;
 
                                                if (psf->instrument == NULL && (psf->instrument = psf_instrument_alloc ()) == NULL)
                                                        return SFE_MALLOC_FAILED ;
@@ -713,9 +733,9 @@ aiff_read_header (SF_PRIVATE *psf, COMM_CHUNK *comm_fmt)
                                                psf->instrument->gain = gain ;
                                                psf_log_printf (psf, "  Gain (dB) : %d\n", gain) ;
                                                } ;
-                                       {       short   mode ; /* 0 - no loop, 1 - forward looping, 2 - backward looping */
+                                       {       int16_t mode ; /* 0 - no loop, 1 - forward looping, 2 - backward looping */
                                                const char      *loop_mode ;
-                                               unsigned short begin, end ;
+                                               uint16_t begin, end ;
 
                                                psf_binheader_readf (psf, "E222", &mode, &begin, &end) ;
                                                loop_mode = get_loop_mode_str (mode) ;
@@ -752,24 +772,20 @@ aiff_read_header (SF_PRIVATE *psf, COMM_CHUNK *comm_fmt)
                                        break ;
 
                        case basc_MARKER :
-                                       psf_binheader_readf (psf, "E4", &dword) ;
-                                       pchk4_store (&paiff->chunk4, marker, psf_ftell (psf) - 8, dword) ;
-                                       psf_log_printf (psf, " basc : %u\n", dword) ;
+                                       psf_log_printf (psf, " basc : %u\n", chunk_size) ;
 
-                                       if ((error = aiff_read_basc_chunk (psf, dword)))
+                                       if ((error = aiff_read_basc_chunk (psf, chunk_size)))
                                                return error ;
                                        break ;
 
                        case MARK_MARKER :
-                                       psf_binheader_readf (psf, "E4", &dword) ;
-                                       pchk4_store (&paiff->chunk4, marker, psf_ftell (psf) - 8, dword) ;
-                                       psf_log_printf (psf, " %M : %d\n", marker, dword) ;
-                                       {       unsigned short mark_id, n = 0 ;
-                                               unsigned int position ;
+                                       psf_log_printf (psf, " %M : %d\n", marker, chunk_size) ;
+                                       {       uint16_t mark_id, n = 0 ;
+                                               uint32_t position ;
 
                                                bytesread = psf_binheader_readf (psf, "E2", &n) ;
                                                mark_count = n ;
-                                               psf_log_printf (psf, "  Count : %d\n", mark_count) ;
+                                               psf_log_printf (psf, "  Count : %u\n", mark_count) ;
                                                if (paiff->markstr != NULL)
                                                {       psf_log_printf (psf, "*** Second MARK chunk found. Throwing away the first.\n") ;
                                                        free (paiff->markstr) ;
@@ -778,31 +794,53 @@ aiff_read_header (SF_PRIVATE *psf, COMM_CHUNK *comm_fmt)
                                                if (paiff->markstr == NULL)
                                                        return SFE_MALLOC_FAILED ;
 
-                                               for (n = 0 ; n < mark_count && bytesread < dword ; n++)
-                                               {       unsigned int pstr_len ;
-                                                       unsigned char ch ;
+                                               if (mark_count > 2500) /* 2500 is close to the largest number of cues possible because of block sizes */
+                                               {       psf_log_printf (psf, "  More than 2500 markers, skipping!\n") ;
+                                                       psf_binheader_readf (psf, "j", chunk_size - bytesread) ;
+                                                       break ;
+                                               } ;
+
+                                               if (psf->cues)
+                                               {       free (psf->cues) ;
+                                                       psf->cues = NULL ;
+                                                       } ;
+                                               if ((psf->cues = psf_cues_alloc (mark_count)) == NULL)
+                                                       return SFE_MALLOC_FAILED ;
+
+                                               for (n = 0 ; n < mark_count && bytesread < chunk_size ; n++)
+                                               {       uint32_t pstr_len ;
+                                                       uint8_t ch ;
 
                                                        bytesread += psf_binheader_readf (psf, "E241", &mark_id, &position, &ch) ;
                                                        psf_log_printf (psf, "   Mark ID  : %u\n   Position : %u\n", mark_id, position) ;
 
+                                                       psf->cues->cue_points [n].indx = mark_id ;
+                                                       psf->cues->cue_points [n].position = 0 ;
+                                                       psf->cues->cue_points [n].fcc_chunk = MAKE_MARKER ('d', 'a', 't', 'a') ; /* always data */
+                                                       psf->cues->cue_points [n].chunk_start = 0 ;
+                                                       psf->cues->cue_points [n].block_start = 0 ;
+                                                       psf->cues->cue_points [n].sample_offset = position ;
+
                                                        pstr_len = (ch & 1) ? ch : ch + 1 ;
 
-                                                       if (pstr_len < sizeof (psf->u.scbuf) - 1)
-                                                       {       bytesread += psf_binheader_readf (psf, "b", psf->u.scbuf, pstr_len) ;
-                                                               psf->u.scbuf [pstr_len] = 0 ;
+                                                       if (pstr_len < sizeof (ubuf.scbuf) - 1)
+                                                       {       bytesread += psf_binheader_readf (psf, "b", ubuf.scbuf, pstr_len) ;
+                                                               ubuf.scbuf [pstr_len] = 0 ;
                                                                }
                                                        else
-                                                       {       unsigned int read_len = pstr_len - (sizeof (psf->u.scbuf) - 1) ;
-                                                               bytesread += psf_binheader_readf (psf, "bj", psf->u.scbuf, read_len, pstr_len - read_len) ;
-                                                               psf->u.scbuf [sizeof (psf->u.scbuf) - 1] = 0 ;
+                                                       {       uint32_t read_len = pstr_len - (sizeof (ubuf.scbuf) - 1) ;
+                                                               bytesread += psf_binheader_readf (psf, "bj", ubuf.scbuf, read_len, pstr_len - read_len) ;
+                                                               ubuf.scbuf [sizeof (ubuf.scbuf) - 1] = 0 ;
                                                                }
 
-                                                       psf_log_printf (psf, "   Name     : %s\n", psf->u.scbuf) ;
+                                                       psf_log_printf (psf, "   Name     : %s\n", ubuf.scbuf) ;
+
+                                                       psf_strlcpy (psf->cues->cue_points [n].name, sizeof (psf->cues->cue_points [n].name), ubuf.cbuf) ;
 
                                                        paiff->markstr [n].markerID = mark_id ;
                                                        paiff->markstr [n].position = position ;
                                                        /*
-                                                       **      TODO if psf->u.scbuf is equal to
+                                                       **      TODO if ubuf.scbuf is equal to
                                                        **      either Beg_loop, Beg loop or beg loop and spam
                                                        **      if (psf->instrument == NULL && (psf->instrument = psf_instrument_alloc ()) == NULL)
                                                        **              return SFE_MALLOC_FAILED ;
@@ -810,85 +848,115 @@ aiff_read_header (SF_PRIVATE *psf, COMM_CHUNK *comm_fmt)
                                                        } ;
                                                } ;
                                        mark_found++ ;
-                                       psf_binheader_readf (psf, "j", dword - bytesread) ;
+                                       psf_binheader_readf (psf, "j", chunk_size - bytesread) ;
                                        break ;
 
                        case FVER_MARKER :
                                        found_chunk |= HAVE_FVER ;
-                                       /* Fall through to next case. */
+                                       /* Falls through. */
 
                        case SFX_MARKER :
-                                       psf_binheader_readf (psf, "E4", &dword) ;
-                                       pchk4_store (&paiff->chunk4, marker, psf_ftell (psf) - 8, dword) ;
-                                       psf_log_printf (psf, " %M : %d\n", marker, dword) ;
-
-                                       psf_binheader_readf (psf, "j", dword) ;
+                                       psf_log_printf (psf, " %M : %d\n", marker, chunk_size) ;
+                                       psf_binheader_readf (psf, "j", chunk_size) ;
                                        break ;
 
                        case NONE_MARKER :
                                        /* Fix for broken AIFC files with incorrect COMM chunk length. */
-                                       {       unsigned char byte ;
-                                               psf_binheader_readf (psf, "1", &byte) ;
-                                               dword = byte ;
-                                               psf_binheader_readf (psf, "j", dword) ;
-                                       }
+                                       chunk_size = (chunk_size >> 24) - 3 ;
+                                       psf_log_printf (psf, " %M : %d\n", marker, chunk_size) ;
+                                       psf_binheader_readf (psf, "j", make_size_t (chunk_size)) ;
                                        break ;
 
                        case CHAN_MARKER :
-                                       psf_binheader_readf (psf, "E4", &dword) ;
-                                       pchk4_store (&paiff->chunk4, marker, psf_ftell (psf) - 8, dword) ;
-
-                                       if (dword < 12)
-                                       {       psf_log_printf (psf, " %M : %d (should be >= 12)\n", marker, dword) ;
-                                               psf_binheader_readf (psf, "j", dword) ;
+                                       if (chunk_size < 12)
+                                       {       psf_log_printf (psf, " %M : %d (should be >= 12)\n", marker, chunk_size) ;
+                                               psf_binheader_readf (psf, "j", chunk_size) ;
                                                break ;
                                                }
 
-                                       psf_log_printf (psf, " %M : %d\n", marker, dword) ;
+                                       psf_log_printf (psf, " %M : %d\n", marker, chunk_size) ;
 
-                                       if ((error = aiff_read_chanmap (psf, dword)))
+                                       if ((error = aiff_read_chanmap (psf, chunk_size)))
                                                return error ;
                                        break ;
 
                        default :
+                                       if (chunk_size >= 0xffff0000)
+                                       {       done = SF_TRUE ;
+                                               psf_log_printf (psf, "*** Unknown chunk marker (%X) at position %D with length %u. Exiting parser.\n", marker, psf_ftell (psf) - 8, chunk_size) ;
+                                               break ;
+                                               } ;
+
                                        if (psf_isprint ((marker >> 24) & 0xFF) && psf_isprint ((marker >> 16) & 0xFF)
                                                && psf_isprint ((marker >> 8) & 0xFF) && psf_isprint (marker & 0xFF))
-                                       {       psf_binheader_readf (psf, "E4", &dword) ;
-                                               psf_log_printf (psf, " %M : %d (unknown marker)\n", marker, dword) ;
+                                       {       psf_log_printf (psf, " %M : %u (unknown marker)\n", marker, chunk_size) ;
 
-                                               psf_binheader_readf (psf, "j", dword) ;
+                                               psf_binheader_readf (psf, "j", chunk_size) ;
                                                break ;
                                                } ;
-                                       if ((dword = psf_ftell (psf)) & 0x03)
-                                       {       psf_log_printf (psf, "  Unknown chunk marker %X at position %d. Resyncing.\n", marker, dword - 4) ;
 
+                                       if (psf_ftell (psf) & 0x03)
+                                       {       psf_log_printf (psf, "  Unknown chunk marker at position %D. Resynching.\n", psf_ftell (psf) - 8) ;
                                                psf_binheader_readf (psf, "j", -3) ;
                                                break ;
                                                } ;
                                        psf_log_printf (psf, "*** Unknown chunk marker %X at position %D. Exiting parser.\n", marker, psf_ftell (psf)) ;
-                                       done = 1 ;
+                                       done = SF_TRUE ;
                                        break ;
                        } ;     /* switch (marker) */
 
+               if (chunk_size >= psf->filelength)
+               {       psf_log_printf (psf, "*** Chunk size %u > file length %D. Exiting parser.\n", chunk_size, psf->filelength) ;
+                       break ;
+                       } ;
+
                if ((! psf->sf.seekable) && (found_chunk & HAVE_SSND))
                        break ;
 
-               if (psf_ftell (psf) >= psf->filelength - (2 * SIGNED_SIZEOF (dword)))
+               if (psf_ftell (psf) >= psf->filelength - (2 * SIGNED_SIZEOF (int32_t)))
                        break ;
                } ; /* while (1) */
 
        if (instr_found && mark_found)
-       {       int j ;
+       {       int ji, str_index ;
+               /* Next loop will convert markers to loop positions for internal handling */
+               for (ji = 0 ; ji < psf->instrument->loop_count ; ji ++)
+               {       if (ji < ARRAY_LEN (psf->instrument->loops))
+                       {       psf->instrument->loops [ji].start = marker_to_position (paiff->markstr, psf->instrument->loops [ji].start, mark_count) ;
+                               psf->instrument->loops [ji].end = marker_to_position (paiff->markstr, psf->instrument->loops [ji].end, mark_count) ;
+                               psf->instrument->loops [ji].mode = SF_LOOP_FORWARD ;
+                               } ;
+                       } ;
 
-               for (j = 0 ; j<psf->instrument->loop_count ; j ++)
-               {       if (j < ARRAY_LEN (psf->instrument->loops))
-                       {       psf->instrument->loops [j].start = marker_to_position (paiff->markstr, psf->instrument->loops [j].start, mark_count) ;
-                               psf->instrument->loops [j].end = marker_to_position (paiff->markstr, psf->instrument->loops [j].end, mark_count) ;
-                               psf->instrument->loops [j].mode = SF_LOOP_FORWARD ;
+               /* The markers that correspond to loop positions can now be removed from cues struct */
+               if (psf->cues->cue_count > (uint32_t) (psf->instrument->loop_count * 2))
+               {       uint32_t j ;
+
+                       for (j = 0 ; j < psf->cues->cue_count - (uint32_t) (psf->instrument->loop_count * 2) ; j ++)
+                       {       /* This simply copies the information in cues above loop positions and writes it at current count instead */
+                               psf->cues->cue_points [j].indx = psf->cues->cue_points [j + psf->instrument->loop_count * 2].indx ;
+                               psf->cues->cue_points [j].position = psf->cues->cue_points [j + psf->instrument->loop_count * 2].position ;
+                               psf->cues->cue_points [j].fcc_chunk = psf->cues->cue_points [j + psf->instrument->loop_count * 2].fcc_chunk ;
+                               psf->cues->cue_points [j].chunk_start = psf->cues->cue_points [j + psf->instrument->loop_count * 2].chunk_start ;
+                               psf->cues->cue_points [j].block_start = psf->cues->cue_points [j + psf->instrument->loop_count * 2].block_start ;
+                               psf->cues->cue_points [j].sample_offset = psf->cues->cue_points [j + psf->instrument->loop_count * 2].sample_offset ;
+                               for (str_index = 0 ; str_index < 256 ; str_index++)
+                                       psf->cues->cue_points [j].name [str_index] = psf->cues->cue_points [j + psf->instrument->loop_count * 2].name [str_index] ;
                                } ;
-                       } ;
+                       psf->cues->cue_count -= psf->instrument->loop_count * 2 ;
+                       } else
+                       {       /* All the cues were in fact loop positions so we can actually remove the cues altogether */
+                               free (psf->cues) ;
+                               psf->cues = NULL ;
+                               }
                } ;
 
+       if (psf->sf.channels < 1)
+               return SFE_CHANNEL_COUNT_ZERO ;
+
+       if (psf->sf.channels > SF_MAX_CHANNELS)
+               return SFE_CHANNEL_COUNT ;
+
        if (! (found_chunk & HAVE_FORM))
                return SFE_AIFF_NO_FORM ;
 
@@ -923,25 +991,22 @@ aiff_close (SF_PRIVATE *psf)
 
 static int
 aiff_read_comm_chunk (SF_PRIVATE *psf, COMM_CHUNK *comm_fmt)
-{      int error = 0, bytesread, subformat ;
-
-       psf->u.scbuf [0] = 0 ;
+{      BUF_UNION       ubuf ;
+       int subformat, samplerate ;
 
-       bytesread = psf_binheader_readf (psf, "E4", &(comm_fmt->size)) ;
+       ubuf.scbuf [0] = 0 ;
 
        /* The COMM chunk has an int aligned to an odd word boundary. Some
        ** procesors are not able to deal with this (ie bus fault) so we have
        ** to take special care.
        */
-       comm_fmt->size += comm_fmt->size & 1 ;
 
-       bytesread +=
        psf_binheader_readf (psf, "E242b", &(comm_fmt->numChannels), &(comm_fmt->numSampleFrames),
-                       &(comm_fmt->sampleSize), &(comm_fmt->sampleRate), SIGNED_SIZEOF (comm_fmt->sampleRate)) ;
+                               &(comm_fmt->sampleSize), &(comm_fmt->sampleRate), SIGNED_SIZEOF (comm_fmt->sampleRate)) ;
 
        if (comm_fmt->size > 0x10000 && (comm_fmt->size & 0xffff) == 0)
        {       psf_log_printf (psf, " COMM : %d (0x%x) *** should be ", comm_fmt->size, comm_fmt->size) ;
-               comm_fmt->size = ENDSWAP_INT (comm_fmt->size) ;
+               comm_fmt->size = ENDSWAP_32 (comm_fmt->size) ;
                psf_log_printf (psf, "%d (0x%x)\n", comm_fmt->size, comm_fmt->size) ;
                }
        else
@@ -950,22 +1015,30 @@ aiff_read_comm_chunk (SF_PRIVATE *psf, COMM_CHUNK *comm_fmt)
        if (comm_fmt->size == SIZEOF_AIFF_COMM)
                comm_fmt->encoding = NONE_MARKER ;
        else if (comm_fmt->size == SIZEOF_AIFC_COMM_MIN)
-               bytesread += psf_binheader_readf (psf, "Em", &(comm_fmt->encoding)) ;
+               psf_binheader_readf (psf, "Em", &(comm_fmt->encoding)) ;
        else if (comm_fmt->size >= SIZEOF_AIFC_COMM)
-       {       unsigned char encoding_len ;
+       {       uint8_t encoding_len ;
                unsigned read_len ;
 
-               bytesread += psf_binheader_readf (psf, "Em1", &(comm_fmt->encoding), &encoding_len) ;
+               psf_binheader_readf (psf, "Em1", &(comm_fmt->encoding), &encoding_len) ;
 
-               comm_fmt->size = SF_MIN (sizeof (psf->u.scbuf), make_size_t (comm_fmt->size)) ;
-               memset (psf->u.scbuf, 0, comm_fmt->size) ;
+               comm_fmt->size = SF_MIN (sizeof (ubuf.scbuf), make_size_t (comm_fmt->size)) ;
+               memset (ubuf.scbuf, 0, comm_fmt->size) ;
                read_len = comm_fmt->size - SIZEOF_AIFC_COMM + 1 ;
-               bytesread += psf_binheader_readf (psf, "b", psf->u.scbuf, read_len) ;
-               psf->u.scbuf [read_len + 1] = 0 ;
+               psf_binheader_readf (psf, "b", ubuf.scbuf, read_len) ;
+               ubuf.scbuf [read_len + 1] = 0 ;
                } ;
 
-       psf_log_printf (psf, "  Sample Rate : %d\n", tenbytefloat2int (comm_fmt->sampleRate)) ;
+       samplerate = tenbytefloat2int (comm_fmt->sampleRate) ;
+
+       psf_log_printf (psf, "  Sample Rate : %d\n", samplerate) ;
        psf_log_printf (psf, "  Frames      : %u%s\n", comm_fmt->numSampleFrames, (comm_fmt->numSampleFrames == 0 && psf->filelength > 104) ? " (Should not be 0)" : "") ;
+
+       if (comm_fmt->numChannels < 1 || comm_fmt->numChannels > SF_MAX_CHANNELS)
+       {       psf_log_printf (psf, "  Channels    : %d (should be >= 1 and < %d)\n", comm_fmt->numChannels, SF_MAX_CHANNELS) ;
+               return SFE_CHANNEL_COUNT_BAD ;
+               } ;
+
        psf_log_printf (psf, "  Channels    : %d\n", comm_fmt->numChannels) ;
 
        /* Found some broken 'fl32' files with comm.samplesize == 16. Fix it here. */
@@ -982,6 +1055,11 @@ aiff_read_comm_chunk (SF_PRIVATE *psf, COMM_CHUNK *comm_fmt)
 
        subformat = s_bitwidth_to_subformat (comm_fmt->sampleSize) ;
 
+       psf->sf.samplerate = samplerate ;
+       psf->sf.frames = comm_fmt->numSampleFrames ;
+       psf->sf.channels = comm_fmt->numChannels ;
+       psf->bytewidth = BITWIDTH2BYTES (comm_fmt->sampleSize) ;
+
        psf->endian = SF_ENDIAN_BIG ;
 
        switch (comm_fmt->encoding)
@@ -1046,7 +1124,6 @@ aiff_read_comm_chunk (SF_PRIVATE *psf, COMM_CHUNK *comm_fmt)
                                break ;
 
                case GSM_MARKER :
-                               psf->sf.format = SF_FORMAT_AIFF ;
                                psf->sf.format = (SF_FORMAT_AIFF | SF_FORMAT_GSM610) ;
                                break ;
 
@@ -1058,84 +1135,78 @@ aiff_read_comm_chunk (SF_PRIVATE *psf, COMM_CHUNK *comm_fmt)
 
                default :
                        psf_log_printf (psf, "AIFC : Unimplemented format : %M\n", comm_fmt->encoding) ;
-                       error = SFE_UNIMPLEMENTED ;
+                       return SFE_UNIMPLEMENTED ;
                } ;
 
-       if (! psf->u.scbuf [0])
+       if (! ubuf.scbuf [0])
                psf_log_printf (psf, "  Encoding    : %M\n", comm_fmt->encoding) ;
        else
-               psf_log_printf (psf, "  Encoding    : %M => %s\n", comm_fmt->encoding, psf->u.scbuf) ;
+               psf_log_printf (psf, "  Encoding    : %M => %s\n", comm_fmt->encoding, ubuf.scbuf) ;
 
-       return error ;
+       return 0 ;
 } /* aiff_read_comm_chunk */
 
 
 /*==========================================================================================
 */
 
-static int
-aiff_rewrite_header (SF_PRIVATE *psf, AIFF_PRIVATE * paiff)
+static void
+aiff_rewrite_header (SF_PRIVATE *psf)
 {
        /* Assuming here that the header has already been written and just
        ** needs to be corrected for new data length. That means that we
        ** only change the length fields of the FORM and SSND chunks ;
        ** everything else can be skipped over.
        */
-       int k, ch ;
-       int comm_size, comm_frames ;
+       int k, ch, comm_size, comm_frames ;
 
        psf_fseek (psf, 0, SEEK_SET) ;
-       psf_fread (psf->header, psf->dataoffset, 1, psf) ;
+       psf_fread (psf->header.ptr, psf->dataoffset, 1, psf) ;
 
-       psf->headindex = 0 ;
+       psf->header.indx = 0 ;
 
-       for (k = 0 ; k < paiff->chunk4.count ; k++)
-       {       switch (paiff->chunk4.l [k].chunk)
-               {       case FORM_MARKER :
-                               psf_binheader_writef (psf, "Etm8", FORM_MARKER, psf->filelength - 8) ;
-                               break ;
+       /* FORM chunk. */
+       psf_binheader_writef (psf, "Etm8", BHWm (FORM_MARKER), BHW8 (psf->filelength - 8)) ;
 
-                       case COMM_MARKER :
-                               psf->headindex = paiff->chunk4.l [k].offset ;
-                               comm_frames = psf->sf.frames ;
-                               comm_size = paiff->chunk4.l [k].len ;
-                               psf_binheader_writef (psf, "Em42t4", COMM_MARKER, comm_size, psf->sf.channels, comm_frames) ;
-                               break ;
+       /* COMM chunk. */
+       if ((k = psf_find_read_chunk_m32 (&psf->rchunks, COMM_MARKER)) >= 0)
+       {       psf->header.indx = psf->rchunks.chunks [k].offset - 8 ;
+               comm_frames = psf->sf.frames ;
+               comm_size = psf->rchunks.chunks [k].len ;
+               psf_binheader_writef (psf, "Em42t4", BHWm (COMM_MARKER), BHW4 (comm_size), BHW2 (psf->sf.channels), BHW4 (comm_frames)) ;
+               } ;
 
-                       case SSND_MARKER :
-                               psf->headindex = paiff->chunk4.l [k].offset ;
-                               psf_binheader_writef (psf, "Etm8", SSND_MARKER, psf->datalength + SIZEOF_SSND_CHUNK) ;
-                               break ;
+       /* PEAK chunk. */
+       if ((k = psf_find_read_chunk_m32 (&psf->rchunks, PEAK_MARKER)) >= 0)
+       {       psf->header.indx = psf->rchunks.chunks [k].offset - 8 ;
+               psf_binheader_writef (psf, "Em4", BHWm (PEAK_MARKER), BHW4 (AIFF_PEAK_CHUNK_SIZE (psf->sf.channels))) ;
+               psf_binheader_writef (psf, "E44", BHW4 (1), BHW4 (time (NULL))) ;
+               for (ch = 0 ; ch < psf->sf.channels ; ch++)
+                       psf_binheader_writef (psf, "Eft8", BHWf ((float) psf->peak_info->peaks [ch].value), BHW8 (psf->peak_info->peaks [ch].position)) ;
+               } ;
 
-                       case PEAK_MARKER :
-                               psf->headindex = paiff->chunk4.l [k].offset ;
-                               psf_binheader_writef (psf, "Em4", PEAK_MARKER, AIFF_PEAK_CHUNK_SIZE (psf->sf.channels)) ;
-                               psf_binheader_writef (psf, "E44", 1, time (NULL)) ;
-                               for (ch = 0 ; ch < psf->sf.channels ; ch++)
-                                       psf_binheader_writef (psf, "Eft8", (float) psf->peak_info->peaks [ch].value, psf->peak_info->peaks [ch].position) ;
-                               break ;
 
-                       default :
-                               /* There are a whole bunch of chunks we should just ignore. */
-                               break ;
-                       } ;
+       /* SSND chunk. */
+       if ((k = psf_find_read_chunk_m32 (&psf->rchunks, SSND_MARKER)) >= 0)
+       {       psf->header.indx = psf->rchunks.chunks [k].offset - 8 ;
+               psf_binheader_writef (psf, "Etm8", BHWm (SSND_MARKER), BHW8 (psf->datalength + SIZEOF_SSND_CHUNK)) ;
                } ;
 
        /* Header mangling complete so write it out. */
        psf_fseek (psf, 0, SEEK_SET) ;
-       psf_fwrite (psf->header, psf->headindex, 1, psf) ;
+       psf_fwrite (psf->header.ptr, psf->header.indx, 1, psf) ;
 
-       return ;
+       return ;
 } /* aiff_rewrite_header */
 
 static int
 aiff_write_header (SF_PRIVATE *psf, int calc_length)
 {      sf_count_t              current ;
        AIFF_PRIVATE    *paiff ;
-       unsigned char   comm_sample_rate [10], comm_zero_bytes [2] = { 0, 0 } ;
-       unsigned int    comm_type, comm_size, comm_encoding, comm_frames = 0 ;
+       uint8_t comm_sample_rate [10], comm_zero_bytes [2] = { 0, 0 } ;
+       uint32_t        comm_type, comm_size, comm_encoding, comm_frames = 0, uk ;
        int                             k, endian, has_data = SF_FALSE ;
-       short                   bit_width ;
+       int16_t                 bit_width ;
 
        if ((paiff = psf->container_data) == NULL)
                return SFE_INTERNAL ;
@@ -1156,11 +1227,11 @@ aiff_write_header (SF_PRIVATE *psf, int calc_length)
                        psf->sf.frames = psf->datalength / (psf->bytewidth * psf->sf.channels) ;
                } ;
 
-       if (psf->file.mode == SFM_RDWR && psf->dataoffset > 0 && paiff->chunk4.count > 0)
-       {       int err = aiff_rewrite_header (psf, paiff) ;
+       if (psf->file.mode == SFM_RDWR && psf->dataoffset > 0 && psf->rchunks.count > 0)
+       {       aiff_rewrite_header (psf) ;
                if (current > 0)
                        psf_fseek (psf, current, SEEK_SET) ;
-               return err ;
+               return 0 ;
                } ;
 
        endian = SF_ENDIAN (psf->sf.format) ;
@@ -1328,117 +1399,87 @@ aiff_write_header (SF_PRIVATE *psf, int calc_length)
                } ;
 
        /* Reset the current header length to zero. */
-       psf->header [0] = 0 ;
-       psf->headindex = 0 ;
+       psf->header.ptr [0] = 0 ;
+       psf->header.indx = 0 ;
        psf_fseek (psf, 0, SEEK_SET) ;
 
-       psf_binheader_writef (psf, "Etm8", FORM_MARKER, psf->filelength - 8) ;
+       psf_binheader_writef (psf, "Etm8", BHWm (FORM_MARKER), BHW8 (psf->filelength - 8)) ;
 
        /* Write AIFF/AIFC marker and COM chunk. */
        if (comm_type == AIFC_MARKER)
                /* AIFC must have an FVER chunk. */
-               psf_binheader_writef (psf, "Emm44", comm_type, FVER_MARKER, 4, 0xA2805140) ;
+               psf_binheader_writef (psf, "Emm44", BHWm (comm_type), BHWm (FVER_MARKER), BHW4 (4), BHW4 (0xA2805140)) ;
        else
-               psf_binheader_writef (psf, "Em", comm_type) ;
+               psf_binheader_writef (psf, "Em", BHWm (comm_type)) ;
 
-       paiff->comm_offset = psf->headindex - 8 ;
+       paiff->comm_offset = psf->header.indx - 8 ;
 
        memset (comm_sample_rate, 0, sizeof (comm_sample_rate)) ;
        uint2tenbytefloat (psf->sf.samplerate, comm_sample_rate) ;
 
-       psf_binheader_writef (psf, "Em42t42", COMM_MARKER, comm_size, psf->sf.channels, comm_frames, bit_width) ;
-       psf_binheader_writef (psf, "b", comm_sample_rate, sizeof (comm_sample_rate)) ;
+       psf_binheader_writef (psf, "Em42t42", BHWm (COMM_MARKER), BHW4 (comm_size), BHW2 (psf->sf.channels), BHW4 (comm_frames), BHW2 (bit_width)) ;
+       psf_binheader_writef (psf, "b", BHWv (comm_sample_rate), BHWz (sizeof (comm_sample_rate))) ;
 
        /* AIFC chunks have some extra data. */
        if (comm_type == AIFC_MARKER)
-               psf_binheader_writef (psf, "mb", comm_encoding, comm_zero_bytes, sizeof (comm_zero_bytes)) ;
+               psf_binheader_writef (psf, "mb", BHWm (comm_encoding), BHWv (comm_zero_bytes), BHWz (sizeof (comm_zero_bytes))) ;
 
        if (psf->channel_map && paiff->chanmap_tag)
-               psf_binheader_writef (psf, "Em4444", CHAN_MARKER, 12, paiff->chanmap_tag, 0, 0) ;
-
-       if (psf->instrument != NULL)
-       {       MARK_ID_POS     m [4] ;
-               INST_CHUNK ch ;
-               unsigned short ct = 0 ;
-
-               memset (m, 0, sizeof (m)) ;
-               memset (&ch, 0, sizeof (ch)) ;
-
-               ch.baseNote = psf->instrument->basenote ;
-               ch.detune = psf->instrument->detune ;
-               ch.lowNote = psf->instrument->key_lo ;
-               ch.highNote = psf->instrument->key_hi ;
-               ch.lowVelocity = psf->instrument->velocity_lo ;
-               ch.highVelocity = psf->instrument->velocity_hi ;
-               ch.gain = psf->instrument->gain ;
-               if (psf->instrument->loops [0].mode != SF_LOOP_NONE)
-               {       ch.sustain_loop.playMode = 1 ;
-                       ch.sustain_loop.beginLoop = ct ;
-                       m [0].markerID = ct++ ;
-                       m [0].position = psf->instrument->loops [0].start ;
-                       ch.sustain_loop.endLoop = ct ;
-                       m [1].markerID = ct++ ;
-                       m [1].position = psf->instrument->loops [0].end ;
-                       } ;
-               if (psf->instrument->loops [1].mode != SF_LOOP_NONE)
-               {       ch.release_loop.playMode = 1 ;
-                       ch.release_loop.beginLoop = ct ;
-                       m [2].markerID = ct++ ;
-                       m [2].position = psf->instrument->loops [1].start ;
-                       ch.release_loop.endLoop = ct ;
-                       m [3].markerID = ct++ ;
-                       m [3].position = psf->instrument->loops [1].end ;
-                       }
-               else
-               {       ch.release_loop.playMode = 0 ;
-                       ch.release_loop.beginLoop = 0 ;
-                       ch.release_loop.endLoop = 0 ;
+               psf_binheader_writef (psf, "Em4444", BHWm (CHAN_MARKER), BHW4 (12), BHW4 (paiff->chanmap_tag), BHW4 (0), BHW4 (0)) ;
+
+       /* Check if there's a INST chunk to write */
+       if (psf->instrument != NULL && psf->cues != NULL)
+       {       /* Huge chunk of code removed here because it had egregious errors that were
+               ** not detected by either the compiler or the tests. It was found when updating
+               ** the way psf_binheader_writef works.
+               */
+               }
+       else if (psf->instrument == NULL && psf->cues != NULL)
+       {       /* There are cues but no loops */
+               uint32_t idx ;
+               int totalStringLength = 0, stringLength ;
+
+               /* Here we count how many bytes will the pascal strings need */
+               for (idx = 0 ; idx < psf->cues->cue_count ; idx++)
+               {       stringLength = strlen (psf->cues->cue_points [idx].name) + 1 ; /* We'll count the first byte also of every pascal string */
+                       totalStringLength += stringLength + (stringLength % 2 == 0 ? 0 : 1) ;
                        } ;
 
-               psf_binheader_writef (psf, "Em4111111", INST_MARKER, SIZEOF_INST_CHUNK, ch.baseNote, ch.detune,
-                                               ch.lowNote, ch.highNote, ch.lowVelocity, ch.highVelocity) ;
-               psf_binheader_writef (psf, "2222222", ch.gain, ch.sustain_loop.playMode,
-                                               ch.sustain_loop.beginLoop, ch.sustain_loop.endLoop, ch.release_loop.playMode,
-                                               ch.release_loop.beginLoop, ch.release_loop.endLoop) ;
-
-               if (ct == 2)
-                       psf_binheader_writef (psf, "Em42241b241b",
-                                       MARK_MARKER, 2 + 2 * (2 + 4 + 1 + 9), 2,
-                                       m [0].markerID, m [0].position, 8, "beg loop", make_size_t (9),
-                                       m [1].markerID, m [1].position, 8, "end loop", make_size_t (9)) ;
-               else if (ct == 4)
-                       psf_binheader_writef (psf, "Em42 241b 241b 241b 241b",
-                                       MARK_MARKER, 2 + 4 * (2 + 4 + 1 + 9), 4,
-                                       m [0].markerID, m [0].position, 8, "beg loop", make_size_t (9),
-                                       m [1].markerID, m [1].position, 8, "end loop", make_size_t (9),
-                                       m [2].markerID, m [2].position, 8, "beg loop", make_size_t (9),
-                                       m [3].markerID, m [3].position, 8, "end loop", make_size_t (9)) ;
+               psf_binheader_writef (psf, "Em42",
+                       BHWm (MARK_MARKER), BHW4 (2 + psf->cues->cue_count * (2 + 4) + totalStringLength), BHW2 (psf->cues->cue_count)) ;
+
+               for (idx = 0 ; idx < psf->cues->cue_count ; idx++)
+                       psf_binheader_writef (psf, "E24p", BHW2 (psf->cues->cue_points [idx].indx), BHW4 (psf->cues->cue_points [idx].sample_offset), BHWp (psf->cues->cue_points [idx].name)) ;
                } ;
 
-       if (psf->str_flags & SF_STR_LOCATE_START)
+       if (psf->strings.flags & SF_STR_LOCATE_START)
                aiff_write_strings (psf, SF_STR_LOCATE_START) ;
 
        if (psf->peak_info != NULL && psf->peak_info->peak_loc == SF_PEAK_START)
-       {       psf_binheader_writef (psf, "Em4", PEAK_MARKER, AIFF_PEAK_CHUNK_SIZE (psf->sf.channels)) ;
-               psf_binheader_writef (psf, "E44", 1, time (NULL)) ;
+       {       psf_binheader_writef (psf, "Em4", BHWm (PEAK_MARKER), BHW4 (AIFF_PEAK_CHUNK_SIZE (psf->sf.channels))) ;
+               psf_binheader_writef (psf, "E44", BHW4 (1), BHW4 (time (NULL))) ;
                for (k = 0 ; k < psf->sf.channels ; k++)
-                       psf_binheader_writef (psf, "Eft8", (float) psf->peak_info->peaks [k].value, psf->peak_info->peaks [k].position) ;
+                       psf_binheader_writef (psf, "Eft8", BHWf ((float) psf->peak_info->peaks [k].value), BHW8 (psf->peak_info->peaks [k].position)) ;
                } ;
 
+       /* Write custom headers. */
+       for (uk = 0 ; uk < psf->wchunks.used ; uk++)
+               psf_binheader_writef (psf, "Em4b", BHWm (psf->wchunks.chunks [uk].mark32), BHW4 (psf->wchunks.chunks [uk].len), BHWv (psf->wchunks.chunks [uk].data), BHWz (psf->wchunks.chunks [uk].len)) ;
+
        /* Write SSND chunk. */
-       paiff->ssnd_offset = psf->headindex ;
-       psf_binheader_writef (psf, "Etm844", SSND_MARKER, psf->datalength + SIZEOF_SSND_CHUNK, 0, 0) ;
+       paiff->ssnd_offset = psf->header.indx ;
+       psf_binheader_writef (psf, "Etm844", BHWm (SSND_MARKER), BHW8 (psf->datalength + SIZEOF_SSND_CHUNK), BHW4 (0), BHW4 (0)) ;
 
        /* Header construction complete so write it out. */
-       psf_fwrite (psf->header, psf->headindex, 1, psf) ;
+       psf_fwrite (psf->header.ptr, psf->header.indx, 1, psf) ;
 
        if (psf->error)
                return psf->error ;
 
-       if (has_data && psf->dataoffset != psf->headindex)
+       if (has_data && psf->dataoffset != psf->header.indx)
                return psf->error = SFE_INTERNAL ;
 
-       psf->dataoffset = psf->headindex ;
+       psf->dataoffset = psf->header.indx ;
 
        if (! has_data)
                psf_fseek (psf, psf->dataoffset, SEEK_SET) ;
@@ -1453,30 +1494,30 @@ aiff_write_tailer (SF_PRIVATE *psf)
 {      int             k ;
 
        /* Reset the current header length to zero. */
-       psf->header [0] = 0 ;
-       psf->headindex = 0 ;
+       psf->header.ptr [0] = 0 ;
+       psf->header.indx = 0 ;
 
        psf->dataend = psf_fseek (psf, 0, SEEK_END) ;
 
        /* Make sure tailer data starts at even byte offset. Pad if necessary. */
        if (psf->dataend % 2 == 1)
-       {       psf_fwrite (psf->header, 1, 1, psf) ;
+       {       psf_fwrite (psf->header.ptr, 1, 1, psf) ;
                psf->dataend ++ ;
                } ;
 
        if (psf->peak_info != NULL && psf->peak_info->peak_loc == SF_PEAK_END)
-       {       psf_binheader_writef (psf, "Em4", PEAK_MARKER, AIFF_PEAK_CHUNK_SIZE (psf->sf.channels)) ;
-               psf_binheader_writef (psf, "E44", 1, time (NULL)) ;
+       {       psf_binheader_writef (psf, "Em4", BHWm (PEAK_MARKER), BHW4 (AIFF_PEAK_CHUNK_SIZE (psf->sf.channels))) ;
+               psf_binheader_writef (psf, "E44", BHW4 (1), BHW4 (time (NULL))) ;
                for (k = 0 ; k < psf->sf.channels ; k++)
-                       psf_binheader_writef (psf, "Eft8", (float) psf->peak_info->peaks [k].value, psf->peak_info->peaks [k].position) ;
+                       psf_binheader_writef (psf, "Eft8", BHWf ((float) psf->peak_info->peaks [k].value), BHW8 (psf->peak_info->peaks [k].position)) ;
                } ;
 
-       if (psf->str_flags & SF_STR_LOCATE_END)
+       if (psf->strings.flags & SF_STR_LOCATE_END)
                aiff_write_strings (psf, SF_STR_LOCATE_END) ;
 
        /* Write the tailer. */
-       if (psf->headindex > 0)
-               psf_fwrite (psf->header, psf->headindex, 1, psf) ;
+       if (psf->header.indx > 0)
+               psf_fwrite (psf->header.ptr, psf->header.indx, 1, psf) ;
 
        return 0 ;
 } /* aiff_write_tailer */
@@ -1486,37 +1527,37 @@ aiff_write_strings (SF_PRIVATE *psf, int location)
 {      int     k, slen ;
 
        for (k = 0 ; k < SF_MAX_STRINGS ; k++)
-       {       if (psf->strings [k].type == 0)
+       {       if (psf->strings.data [k].type == 0)
                        break ;
 
-               if (psf->strings [k].flags != location)
+               if (psf->strings.data [k].flags != location)
                        continue ;
 
-               switch (psf->strings [k].type)
+               switch (psf->strings.data [k].type)
                {       case SF_STR_SOFTWARE :
-                               slen = strlen (psf->strings [k].str) ;
-                               psf_binheader_writef (psf, "Em4mb", APPL_MARKER, slen + 4, m3ga_MARKER, psf->strings [k].str, make_size_t (slen + (slen & 1))) ;
+                               slen = strlen (psf->strings.storage + psf->strings.data [k].offset) ;
+                               psf_binheader_writef (psf, "Em4mb", BHWm (APPL_MARKER), BHW4 (slen + 4), BHWm (m3ga_MARKER), BHWv (psf->strings.storage + psf->strings.data [k].offset), BHWz (slen + (slen & 1))) ;
                                break ;
 
                        case SF_STR_TITLE :
-                               psf_binheader_writef (psf, "EmS", NAME_MARKER, psf->strings [k].str) ;
+                               psf_binheader_writef (psf, "EmS", BHWm (NAME_MARKER), BHWS (psf->strings.storage + psf->strings.data [k].offset)) ;
                                break ;
 
                        case SF_STR_COPYRIGHT :
-                               psf_binheader_writef (psf, "EmS", c_MARKER, psf->strings [k].str) ;
+                               psf_binheader_writef (psf, "EmS", BHWm (c_MARKER), BHWS (psf->strings.storage + psf->strings.data [k].offset)) ;
                                break ;
 
                        case SF_STR_ARTIST :
-                               psf_binheader_writef (psf, "EmS", AUTH_MARKER, psf->strings [k].str) ;
+                               psf_binheader_writef (psf, "EmS", BHWm (AUTH_MARKER), BHWS (psf->strings.storage + psf->strings.data [k].offset)) ;
                                break ;
 
                        case SF_STR_COMMENT :
-                               psf_binheader_writef (psf, "EmS", ANNO_MARKER, psf->strings [k].str) ;
+                               psf_binheader_writef (psf, "EmS", BHWm (ANNO_MARKER), BHWS (psf->strings.storage + psf->strings.data [k].offset)) ;
                                break ;
 
                        /*
                        case SF_STR_DATE :
-                               psf_binheader_writef (psf, "Ems", ICRD_MARKER, psf->strings [k].str) ;
+                               psf_binheader_writef (psf, "Ems", BHWm (ICRD_MARKER), BHWs (psf->strings.data [k].str)) ;
                                break ;
                        */
                        } ;
@@ -1541,13 +1582,11 @@ aiff_command (SF_PRIVATE * psf, int command, void * UNUSED (data), int UNUSED (d
                        break ;
        } ;
 
-
-
        return 0 ;
 } /* aiff_command */
 
 static const char*
-get_loop_mode_str (short mode)
+get_loop_mode_str (int16_t mode)
 {      switch (mode)
        {       case 0 : return "none" ;
                case 1 : return "forward" ;
@@ -1557,8 +1596,8 @@ get_loop_mode_str (short mode)
        return "*** unknown" ;
 } /* get_loop_mode_str */
 
-static short
-get_loop_mode (short mode)
+static int16_t
+get_loop_mode (int16_t mode)
 {      switch (mode)
        {       case 0 : return SF_LOOP_NONE ;
                case 1 : return SF_LOOP_FORWARD ;
@@ -1578,7 +1617,7 @@ get_loop_mode (short mode)
 */
 
 static int
-tenbytefloat2int (unsigned char *bytes)
+tenbytefloat2int (uint8_t *bytes)
 {      int val = 3 ;
 
        if (bytes [0] & 0x80)   /* Negative number. */
@@ -1603,8 +1642,8 @@ tenbytefloat2int (unsigned char *bytes)
 } /* tenbytefloat2int */
 
 static void
-uint2tenbytefloat (unsigned int num, unsigned char *bytes)
-{      unsigned int mask = 0x40000000 ;
+uint2tenbytefloat (uint32_t num, uint8_t *bytes)
+{      uint32_t mask = 0x40000000 ;
        int     count ;
 
        if (num <= 1)
@@ -1621,13 +1660,13 @@ uint2tenbytefloat (unsigned int num, unsigned char *bytes)
                return ;
                } ;
 
-       for (count = 0 ; count <= 32 ; count ++)
+       for (count = 0 ; count < 32 ; count ++)
        {       if (num & mask)
                        break ;
                mask >>= 1 ;
                } ;
 
-       num <<= count + 1 ;
+       num = count < 31 ? num << (count + 1) : 0 ;
        bytes [1] = 29 - count ;
        bytes [2] = (num >> 24) & 0xFF ;
        bytes [3] = (num >> 16) & 0xFF ;
@@ -1684,6 +1723,11 @@ aiff_read_basc_chunk (SF_PRIVATE * psf, int datasize)
 
        psf_log_printf (psf, "  Loop Type : 0x%x (%s)\n", bc.loopType, type_str) ;
 
+       if (psf->loop_info)
+       {       psf_log_printf (psf, "  Found existing loop info, using last one.\n") ;
+               free (psf->loop_info) ;
+               psf->loop_info = NULL ;
+               } ;
        if ((psf->loop_info = calloc (1, sizeof (SF_LOOP_INFO))) == NULL)
                return SFE_MALLOC_FAILED ;
 
@@ -1723,7 +1767,7 @@ aiff_read_chanmap (SF_PRIVATE * psf, unsigned dword)
                psf_binheader_readf (psf, "j", dword - bytesread) ;
 
        if (map_info->channel_map != NULL)
-       {       size_t chanmap_size = psf->sf.channels * sizeof (psf->channel_map [0]) ;
+       {       size_t chanmap_size = SF_MIN (psf->sf.channels, layout_tag & 0xffff) * sizeof (psf->channel_map [0]) ;
 
                free (psf->channel_map) ;
 
@@ -1736,3 +1780,49 @@ aiff_read_chanmap (SF_PRIVATE * psf, unsigned dword)
        return 0 ;
 } /* aiff_read_chanmap */
 
+/*==============================================================================
+*/
+
+static int
+aiff_set_chunk (SF_PRIVATE *psf, const SF_CHUNK_INFO * chunk_info)
+{      return psf_save_write_chunk (&psf->wchunks, chunk_info) ;
+} /* aiff_set_chunk */
+
+static SF_CHUNK_ITERATOR *
+aiff_next_chunk_iterator (SF_PRIVATE *psf, SF_CHUNK_ITERATOR * iterator)
+{      return psf_next_chunk_iterator (&psf->rchunks, iterator) ;
+} /* aiff_next_chunk_iterator */
+
+static int
+aiff_get_chunk_size (SF_PRIVATE *psf, const SF_CHUNK_ITERATOR * iterator, SF_CHUNK_INFO * chunk_info)
+{      int indx ;
+
+       if ((indx = psf_find_read_chunk_iterator (&psf->rchunks, iterator)) < 0)
+               return SFE_UNKNOWN_CHUNK ;
+
+       chunk_info->datalen = psf->rchunks.chunks [indx].len ;
+
+       return SFE_NO_ERROR ;
+} /* aiff_get_chunk_size */
+
+static int
+aiff_get_chunk_data (SF_PRIVATE *psf, const SF_CHUNK_ITERATOR * iterator, SF_CHUNK_INFO * chunk_info)
+{      sf_count_t pos ;
+       int indx ;
+
+       if ((indx = psf_find_read_chunk_iterator (&psf->rchunks, iterator)) < 0)
+               return SFE_UNKNOWN_CHUNK ;
+
+       if (chunk_info->data == NULL)
+               return SFE_BAD_CHUNK_DATA_PTR ;
+
+       chunk_info->id_size = psf->rchunks.chunks [indx].id_size ;
+       memcpy (chunk_info->id, psf->rchunks.chunks [indx].id, sizeof (chunk_info->id) / sizeof (*chunk_info->id)) ;
+
+       pos = psf_ftell (psf) ;
+       psf_fseek (psf, psf->rchunks.chunks [indx].offset, SEEK_SET) ;
+       psf_fread (chunk_info->data, SF_MIN (chunk_info->datalen, psf->rchunks.chunks [indx].len), 1, psf) ;
+       psf_fseek (psf, pos, SEEK_SET) ;
+
+       return SFE_NO_ERROR ;
+} /* aiff_get_chunk_data */