Enable utf8 I/O stuff when compiling with MinGW.
[platform/upstream/flac.git] / src / flac / main.c
index 9a59c7b..62e54a4 100644 (file)
@@ -1,5 +1,5 @@
 /* flac - Command-line FLAC encoder/decoder
- * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
+ * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008,2009  Josh Coalson
  *
  * This program is free software; you can redistribute it and/or
  * modify it under the terms of the GNU General Public License
@@ -11,9 +11,9 @@
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  */
 
 #if HAVE_CONFIG_H
 #include <unistd.h> /* for unlink() */
 #endif
 #include "FLAC/all.h"
+#include "share/alloc.h"
 #include "share/grabbag.h"
+#include "share/compat.h"
+#include "share/safe_str.h"
 #include "analyze.h"
 #include "decode.h"
 #include "encode.h"
@@ -42,7 +45,7 @@
 #include "utils.h"
 #include "vorbiscomment.h"
 
-#if defined _MSC_VER || defined __MINGW32__ || defined __EMX__
+#if defined _MSC_VER || defined __MINGW32__
 #define FLAC__STRCASECMP stricmp
 #else
 #define FLAC__STRCASECMP strcasecmp
@@ -56,8 +59,6 @@
 #  include "share/getopt.h"
 #endif
 
-typedef enum { RAW, WAV, AIF, FLAC, OGGFLAC } FileFormat;
-
 static int do_it(void);
 
 static FLAC__bool init_options(void);
@@ -85,11 +86,6 @@ static const char *get_outfilename(const char *infilename, const char *suffix);
 static void die(const char *message);
 static int conditional_fclose(FILE *f);
 static char *local_strdup(const char *source);
-#ifdef _MSC_VER
-/* There's no strtoll() in MSVC6 so we just write a specialized one */
-static FLAC__int64 local__strtoll(const char *src, char **endptr);
-#endif
-
 
 /*
  * share__getopt format struct; note that for long options with no
@@ -99,23 +95,25 @@ static struct share__option long_options_[] = {
        /*
         * general options
         */
-       { "help"              , share__no_argument, 0, 'h' },
-       { "explain"           , share__no_argument, 0, 'H' },
-       { "version"           , share__no_argument, 0, 'v' },
-       { "decode"            , share__no_argument, 0, 'd' },
-       { "analyze"           , share__no_argument, 0, 'a' },
-       { "test"              , share__no_argument, 0, 't' },
-       { "stdout"            , share__no_argument, 0, 'c' },
-       { "silent"            , share__no_argument, 0, 's' },
-       { "totally-silent"    , share__no_argument, 0, 0 },
-       { "warnings-as-errors", share__no_argument, 0, 'w' },
-       { "force"             , share__no_argument, 0, 'f' },
-       { "delete-input-file" , share__no_argument, 0, 0 },
-       { "output-prefix"     , share__required_argument, 0, 0 },
-       { "output-name"       , share__required_argument, 0, 'o' },
-       { "skip"              , share__required_argument, 0, 0 },
-       { "until"             , share__required_argument, 0, 0 },
-       { "channel-map"       , share__required_argument, 0, 0 }, /* undocumented */
+       { "help"                  , share__no_argument, 0, 'h' },
+       { "explain"               , share__no_argument, 0, 'H' },
+       { "version"               , share__no_argument, 0, 'v' },
+       { "decode"                , share__no_argument, 0, 'd' },
+       { "analyze"               , share__no_argument, 0, 'a' },
+       { "test"                  , share__no_argument, 0, 't' },
+       { "stdout"                , share__no_argument, 0, 'c' },
+       { "silent"                , share__no_argument, 0, 's' },
+       { "totally-silent"        , share__no_argument, 0, 0 },
+       { "warnings-as-errors"    , share__no_argument, 0, 'w' },
+       { "force"                 , share__no_argument, 0, 'f' },
+       { "delete-input-file"     , share__no_argument, 0, 0 },
+       { "preserve-modtime"      , share__no_argument, 0, 0 },
+       { "keep-foreign-metadata" , share__no_argument, 0, 0 },
+       { "output-prefix"         , share__required_argument, 0, 0 },
+       { "output-name"           , share__required_argument, 0, 'o' },
+       { "skip"                  , share__required_argument, 0, 0 },
+       { "until"                 , share__required_argument, 0, 0 },
+       { "channel-map"           , share__required_argument, 0, 0 }, /* undocumented */
 
        /*
         * decoding options
@@ -145,11 +143,14 @@ static struct share__option long_options_[] = {
        { "best"                      , share__no_argument, 0, '8' },
        { "fast"                      , share__no_argument, 0, '0' },
        { "verify"                    , share__no_argument, 0, 'V' },
-       { "force-aiff-format"         , share__no_argument, 0, 0 },
        { "force-raw-format"          , share__no_argument, 0, 0 },
+       { "force-aiff-format"         , share__no_argument, 0, 0 },
+       { "force-rf64-format"         , share__no_argument, 0, 0 },
+       { "force-wave64-format"       , share__no_argument, 0, 0 },
        { "lax"                       , share__no_argument, 0, 0 },
        { "replay-gain"               , share__no_argument, 0, 0 },
-       { "sector-align"              , share__no_argument, 0, 0 },
+       { "ignore-chunk-sizes"        , share__no_argument, 0, 0 },
+       { "sector-align"              , share__no_argument, 0, 0 }, /* DEPRECATED */
        { "seekpoint"                 , share__required_argument, 0, 'S' },
        { "padding"                   , share__required_argument, 0, 'P' },
 #if FLAC__HAS_OGG
@@ -181,13 +182,17 @@ static struct share__option long_options_[] = {
        /*
         * negatives
         */
+       { "no-preserve-modtime"       , share__no_argument, 0, 0 },
        { "no-decode-through-errors"  , share__no_argument, 0, 0 },
        { "no-silent"                 , share__no_argument, 0, 0 },
        { "no-force"                  , share__no_argument, 0, 0 },
        { "no-seektable"              , share__no_argument, 0, 0 },
        { "no-delete-input-file"      , share__no_argument, 0, 0 },
+       { "no-keep-foreign-metadata"  , share__no_argument, 0, 0 },
        { "no-replay-gain"            , share__no_argument, 0, 0 },
-       { "no-sector-align"           , share__no_argument, 0, 0 },
+       { "no-ignore-chunk-sizes"     , share__no_argument, 0, 0 },
+       { "no-sector-align"           , share__no_argument, 0, 0 }, /* DEPRECATED */
+       { "no-utf8-convert"           , share__no_argument, 0, 0 },
        { "no-lax"                    , share__no_argument, 0, 0 },
 #if FLAC__HAS_OGG
        { "no-ogg"                    , share__no_argument, 0, 0 },
@@ -207,6 +212,7 @@ static struct share__option long_options_[] = {
        { "disable-constant-subframes", share__no_argument, 0, 0 },
        { "disable-fixed-subframes"   , share__no_argument, 0, 0 },
        { "disable-verbatim-subframes", share__no_argument, 0, 0 },
+       { "no-md5-sum"                , share__no_argument, 0, 0 },
 
        {0, 0, 0, 0}
 };
@@ -233,11 +239,17 @@ static struct {
        FLAC__bool has_serial_number; /* true iff --serial-number was used */
        long serial_number; /* this is the Ogg serial number and is unused for native FLAC */
        FLAC__bool force_to_stdout;
-       FLAC__bool force_aiff_format;
        FLAC__bool force_raw_format;
+       FLAC__bool force_aiff_format;
+       FLAC__bool force_rf64_format;
+       FLAC__bool force_wave64_format;
        FLAC__bool delete_input;
+       FLAC__bool preserve_modtime;
+       FLAC__bool keep_foreign_metadata;
        FLAC__bool replay_gain;
+       FLAC__bool ignore_chunk_sizes;
        FLAC__bool sector_align;
+       FLAC__bool utf8_convert; /* true by default, to convert tag strings from locale to utf-8, false if --no-utf8-convert used */
        const char *cmdline_forced_outfilename;
        const char *output_prefix;
        analysis_options aopts;
@@ -252,7 +264,7 @@ static struct {
        int format_channels;
        int format_bps;
        int format_sample_rate;
-       off_t format_input_size;
+       FLAC__off_t format_input_size;
        char requested_seek_points[5000]; /* bad MAGIC NUMBER but buffer overflow is checked */
        int num_requested_seek_points; /* -1 => no -S options were given, 0 => -S- was given */
        const char *cuesheet_filename;
@@ -270,6 +282,7 @@ static struct {
                FLAC__bool disable_constant_subframes;
                FLAC__bool disable_fixed_subframes;
                FLAC__bool disable_verbatim_subframes;
+               FLAC__bool do_md5;
        } debug;
 } option_values;
 
@@ -278,7 +291,7 @@ static struct {
  * miscellaneous globals
  */
 
-static FLAC__int32 align_reservoir_0[588], align_reservoir_1[588]; /* for carrying over samples from --sector-align */
+static FLAC__int32 align_reservoir_0[588], align_reservoir_1[588]; /* for carrying over samples from --sector-align */ /* DEPRECATED */
 static FLAC__int32 *align_reservoir[2] = { align_reservoir_0, align_reservoir_1 };
 static unsigned align_reservoir_samples = 0; /* 0 .. 587 */
 
@@ -291,6 +304,12 @@ int main(int argc, char *argv[])
        _response(&argc, &argv);
        _wildcard(&argc, &argv);
 #endif
+#ifdef _WIN32
+       if (get_utf8_argv(&argc, &argv) != 0) {
+               fprintf(stderr, "ERROR: failed to convert command line parameters to UTF-8\n");
+               return 1;
+       }
+#endif
 
        srand((unsigned)time(0));
        setlocale(LC_ALL, "");
@@ -366,8 +385,8 @@ int do_it(void)
                        if(!FLAC__format_sample_rate_is_valid(option_values.format_sample_rate))
                                return usage_error("ERROR: invalid sample rate '%u', must be > 0 and <= %u\n", option_values.format_sample_rate, FLAC__MAX_SAMPLE_RATE);
                }
-               if(option_values.force_raw_format && option_values.force_aiff_format)
-                       return usage_error("ERROR: only one of --force-raw-format and --force-aiff-format allowed\n");
+               if((option_values.force_raw_format?1:0) + (option_values.force_aiff_format?1:0) + (option_values.force_rf64_format?1:0) + (option_values.force_wave64_format?1:0) > 1)
+                       return usage_error("ERROR: only one of --force-raw-format/--force-aiff-format/--force-rf64-format/--force-wave64-format allowed\n");
                if(option_values.mode_decode) {
                        if(!option_values.force_raw_format) {
                                if(option_values.format_is_big_endian >= 0)
@@ -383,6 +402,18 @@ int do_it(void)
                                return usage_error("ERROR: --sample-rate not allowed with --decode\n");
                }
 
+               if(option_values.ignore_chunk_sizes) {
+                       if(option_values.mode_decode)
+                               return usage_error("ERROR: --ignore-chunk-sizes only allowed for encoding\n");
+                       if(0 != option_values.sector_align)
+                               return usage_error("ERROR: --ignore-chunk-sizes not allowed with --sector-align\n");
+                       if(0 != option_values.until_specification)
+                               return usage_error("ERROR: --ignore-chunk-sizes not allowed with --until\n");
+                       if(0 != option_values.cue_specification)
+                               return usage_error("ERROR: --ignore-chunk-sizes not allowed with --cue\n");
+                       if(0 != option_values.cuesheet_filename)
+                               return usage_error("ERROR: --ignore-chunk-sizes not allowed with --cuesheet\n");
+               }
                if(option_values.sector_align) {
                        if(option_values.mode_decode)
                                return usage_error("ERROR: --sector-align only allowed for encoding\n");
@@ -413,7 +444,10 @@ int do_it(void)
                         * tags that we will set later, to avoid rewriting the
                         * whole file.
                         */
-                       if(option_values.padding <= 0) {
+                       if(
+                               (option_values.padding >= 0 && option_values.padding < (int)GRABBAG__REPLAYGAIN_MAX_TAG_SPACE_REQUIRED) ||
+                               (option_values.padding < 0 && FLAC_ENCODE__DEFAULT_PADDING < (int)GRABBAG__REPLAYGAIN_MAX_TAG_SPACE_REQUIRED)
+                       ) {
                                flac__utils_printf(stderr, 1, "NOTE: --replay-gain may leave a small PADDING block even with --no-padding\n");
                                option_values.padding = GRABBAG__REPLAYGAIN_MAX_TAG_SPACE_REQUIRED;
                        }
@@ -430,10 +464,20 @@ int do_it(void)
                if(!option_values.mode_decode && 0 != option_values.cuesheet_filename && option_values.num_files > 1) {
                        return usage_error("ERROR: --cuesheet cannot be used when encoding multiple files\n");
                }
+               if(option_values.keep_foreign_metadata) {
+                       /* we're not going to try and support the re-creation of broken WAVE files */
+                       if(option_values.ignore_chunk_sizes)
+                               return usage_error("ERROR: using --keep-foreign-metadata cannot be used with --ignore-chunk-sizes\n");
+                       if(option_values.test_only)
+                               return usage_error("ERROR: --keep-foreign-metadata is not allowed in test mode\n");
+                       if(option_values.analyze)
+                               return usage_error("ERROR: --keep-foreign-metadata is not allowed in analyis mode\n");
+                       flac__utils_printf(stderr, 1, "NOTE: --keep-foreign-metadata is a new feature; make sure to test the output file before deleting the original.\n");
+               }
        }
 
        flac__utils_printf(stderr, 2, "\n");
-       flac__utils_printf(stderr, 2, "flac %s, Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson\n", FLAC__VERSION_STRING);
+       flac__utils_printf(stderr, 2, "flac %s, Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008,2009  Josh Coalson\n", FLAC__VERSION_STRING);
        flac__utils_printf(stderr, 2, "flac comes with ABSOLUTELY NO WARRANTY.  This is free software, and you are\n");
        flac__utils_printf(stderr, 2, "welcome to redistribute it under certain conditions.  Type `flac' for details.\n\n");
 
@@ -458,6 +502,9 @@ int do_it(void)
        else { /* encode */
                FLAC__bool first = true;
 
+               if(option_values.ignore_chunk_sizes)
+                       flac__utils_printf(stderr, 1, "INFO: Make sure you know what you're doing when using --ignore-chunk-sizes.\n      Improper use can cause flac to encode non-audio data as audio.\n");
+
                if(option_values.num_files == 0) {
                        retval = encode_file("-", first, true);
                }
@@ -480,13 +527,7 @@ int do_it(void)
                                                flac__utils_printf(stderr, 1, "ERROR: filename too long: %s", option_values.filenames[i]);
                                                return 1;
                                        }
-                                       if(0 == strcmp(option_values.filenames[i], "-")) {
-                                               FLAC__ASSERT(0);
-                                               /* double protection */
-                                               flac__utils_printf(stderr, 1, "internal error\n");
-                                               return 2;
-                                       }
-                                       if(0 != (error = grabbag__replaygain_store_to_file_album(outfilename, album_gain, album_peak, /*preserve_modtime=*/true))) {
+                                       if(0 != (error = grabbag__replaygain_store_to_file_album(outfilename, album_gain, album_peak, option_values.preserve_modtime))) {
                                                flac__utils_printf(stderr, 1, "%s: ERROR writing ReplayGain album tags (%s)\n", outfilename, error);
                                                retval = 1;
                                        }
@@ -519,11 +560,17 @@ FLAC__bool init_options(void)
        option_values.has_serial_number = false;
        option_values.serial_number = 0;
        option_values.force_to_stdout = false;
-       option_values.force_aiff_format = false;
        option_values.force_raw_format = false;
+       option_values.force_aiff_format = false;
+       option_values.force_rf64_format = false;
+       option_values.force_wave64_format = false;
        option_values.delete_input = false;
+       option_values.preserve_modtime = true;
+       option_values.keep_foreign_metadata = false;
        option_values.replay_gain = false;
+       option_values.ignore_chunk_sizes = false;
        option_values.sector_align = false;
+       option_values.utf8_convert = true;
        option_values.cmdline_forced_outfilename = 0;
        option_values.output_prefix = 0;
        option_values.aopts.do_residual_text = false;
@@ -540,7 +587,7 @@ FLAC__bool init_options(void)
        option_values.format_channels = -1;
        option_values.format_bps = -1;
        option_values.format_sample_rate = -1;
-       option_values.format_input_size = (off_t)(-1);
+       option_values.format_input_size = (FLAC__off_t)(-1);
        option_values.requested_seek_points[0] = '\0';
        option_values.num_requested_seek_points = -1;
        option_values.cuesheet_filename = 0;
@@ -557,6 +604,7 @@ FLAC__bool init_options(void)
        option_values.debug.disable_constant_subframes = false;
        option_values.debug.disable_fixed_subframes = false;
        option_values.debug.disable_verbatim_subframes = false;
+       option_values.debug.do_md5 = true;
 
        return true;
 }
@@ -593,7 +641,7 @@ int parse_options(int argc, char *argv[])
 
        if(option_values.num_files > 0) {
                unsigned i = 0;
-               if(0 == (option_values.filenames = (char**)malloc(sizeof(char*) * option_values.num_files)))
+               if(0 == (option_values.filenames = malloc(sizeof(char*) * option_values.num_files)))
                        die("out of memory allocating space for file names list");
                while(share__optind < argc)
                        option_values.filenames[i++] = local_strdup(argv[share__optind++]);
@@ -605,8 +653,6 @@ int parse_options(int argc, char *argv[])
 int parse_option(int short_option, const char *long_option, const char *option_argument)
 {
        const char *violation;
-       char *p;
-       int i;
 
        if(short_option == 0) {
                FLAC__ASSERT(0 != long_option);
@@ -616,6 +662,12 @@ int parse_option(int short_option, const char *long_option, const char *option_a
                else if(0 == strcmp(long_option, "delete-input-file")) {
                        option_values.delete_input = true;
                }
+               else if(0 == strcmp(long_option, "preserve-modtime")) {
+                       option_values.preserve_modtime = true;
+               }
+               else if(0 == strcmp(long_option, "keep-foreign-metadata")) {
+                       option_values.keep_foreign_metadata = true;
+               }
                else if(0 == strcmp(long_option, "output-prefix")) {
                        FLAC__ASSERT(0 != option_argument);
                        option_values.output_prefix = option_argument;
@@ -632,17 +684,12 @@ int parse_option(int short_option, const char *long_option, const char *option_a
                        FLAC__ASSERT(0 != option_argument);
                        {
                                char *end;
-#ifdef _MSC_VER
-                               FLAC__int64 i;
-                               i = local__strtoll(option_argument, &end);
-#else
-                               long long i;
-                               i = strtoll(option_argument, &end, 10);
-#endif
+                               FLAC__int64 ix;
+                               ix = strtoll(option_argument, &end, 10);
                                if(0 == strlen(option_argument) || *end)
                                        return usage_error("ERROR: --%s must be a number\n", long_option);
-                               option_values.format_input_size = (off_t)i;
-                               if(option_values.format_input_size != i) /* check if off_t is smaller than long long */
+                               option_values.format_input_size = (FLAC__off_t)ix;
+                               if(option_values.format_input_size != ix) /* check if FLAC__off_t is smaller than long long */
                                        return usage_error("ERROR: --%s too large; this build of flac does not support filesizes over 2GB\n", long_option);
                                if(option_values.format_input_size <= 0)
                                        return usage_error("ERROR: --%s must be > 0\n", long_option);
@@ -697,17 +744,23 @@ int parse_option(int short_option, const char *long_option, const char *option_a
                }
                else if(0 == strcmp(long_option, "tag-from-file")) {
                        FLAC__ASSERT(0 != option_argument);
-                       if(!flac__vorbiscomment_add(option_values.vorbis_comment, option_argument, /*value_from_file=*/true, &violation))
+                       if(!flac__vorbiscomment_add(option_values.vorbis_comment, option_argument, /*value_from_file=*/true, /*raw=*/!option_values.utf8_convert, &violation))
                                return usage_error("ERROR: (--tag-from-file) %s\n", violation);
                }
                else if(0 == strcmp(long_option, "no-cued-seekpoints")) {
                        option_values.cued_seekpoints = false;
                }
+               else if(0 == strcmp(long_option, "force-raw-format")) {
+                       option_values.force_raw_format = true;
+               }
                else if(0 == strcmp(long_option, "force-aiff-format")) {
                        option_values.force_aiff_format = true;
                }
-               else if(0 == strcmp(long_option, "force-raw-format")) {
-                       option_values.force_raw_format = true;
+               else if(0 == strcmp(long_option, "force-rf64-format")) {
+                       option_values.force_rf64_format = true;
+               }
+               else if(0 == strcmp(long_option, "force-wave64-format")) {
+                       option_values.force_wave64_format = true;
                }
                else if(0 == strcmp(long_option, "lax")) {
                        option_values.lax = true;
@@ -715,7 +768,12 @@ int parse_option(int short_option, const char *long_option, const char *option_a
                else if(0 == strcmp(long_option, "replay-gain")) {
                        option_values.replay_gain = true;
                }
+               else if(0 == strcmp(long_option, "ignore-chunk-sizes")) {
+                       option_values.ignore_chunk_sizes = true;
+               }
                else if(0 == strcmp(long_option, "sector-align")) {
+                       flac__utils_printf(stderr, 1, "WARNING: --sector-align is DEPRECATED and may not exist in future versions of flac.\n");
+                       flac__utils_printf(stderr, 1, "         shntool provides similar functionality\n");
                        option_values.sector_align = true;
                }
 #if FLAC__HAS_OGG
@@ -766,6 +824,9 @@ int parse_option(int short_option, const char *long_option, const char *option_a
                /*
                 * negatives
                 */
+               else if(0 == strcmp(long_option, "no-preserve-modtime")) {
+                       option_values.preserve_modtime = false;
+               }
                else if(0 == strcmp(long_option, "no-decode-through-errors")) {
                        option_values.continue_through_decode_errors = false;
                }
@@ -782,12 +843,21 @@ int parse_option(int short_option, const char *long_option, const char *option_a
                else if(0 == strcmp(long_option, "no-delete-input-file")) {
                        option_values.delete_input = false;
                }
+               else if(0 == strcmp(long_option, "no-keep-foreign-metadata")) {
+                       option_values.keep_foreign_metadata = false;
+               }
                else if(0 == strcmp(long_option, "no-replay-gain")) {
                        option_values.replay_gain = false;
                }
+               else if(0 == strcmp(long_option, "no-ignore-chunk-sizes")) {
+                       option_values.ignore_chunk_sizes = false;
+               }
                else if(0 == strcmp(long_option, "no-sector-align")) {
                        option_values.sector_align = false;
                }
+               else if(0 == strcmp(long_option, "no-utf8-convert")) {
+                       option_values.utf8_convert = false;
+               }
                else if(0 == strcmp(long_option, "no-lax")) {
                        option_values.lax = false;
                }
@@ -834,6 +904,9 @@ int parse_option(int short_option, const char *long_option, const char *option_a
                else if(0 == strcmp(long_option, "disable-verbatim-subframes")) {
                        option_values.debug.disable_verbatim_subframes = true;
                }
+               else if(0 == strcmp(long_option, "no-md5-sum")) {
+                       option_values.debug.do_md5 = false;
+               }
        }
        else {
                switch(short_option) {
@@ -875,7 +948,7 @@ int parse_option(int short_option, const char *long_option, const char *option_a
                                break;
                        case 'T':
                                FLAC__ASSERT(0 != option_argument);
-                               if(!flac__vorbiscomment_add(option_values.vorbis_comment, option_argument, /*value_from_file=*/false, &violation))
+                               if(!flac__vorbiscomment_add(option_values.vorbis_comment, option_argument, /*value_from_file=*/false, /*raw=*/!option_values.utf8_convert, &violation))
                                        return usage_error("ERROR: (-T/--tag) %s\n", violation);
                                break;
                        case '0':
@@ -911,8 +984,8 @@ int parse_option(int short_option, const char *long_option, const char *option_a
                                                return usage_error("ERROR: too many seekpoints requested\n");
                                        }
                                        else {
-                                               strcat(option_values.requested_seek_points, option_argument);
-                                               strcat(option_values.requested_seek_points, ";");
+                                               size_t len = strlen(option_values.requested_seek_points);
+                                               flac_snprintf(option_values.requested_seek_points+len, sizeof(option_values.requested_seek_points) - len, "%s;", option_argument);
                                        }
                                }
                                break;
@@ -923,11 +996,14 @@ int parse_option(int short_option, const char *long_option, const char *option_a
                                        return usage_error("ERROR: argument to -%c must be >= 0; for no padding use -%c-\n", short_option, short_option);
                                break;
                        case 'b':
-                               FLAC__ASSERT(0 != option_argument);
-                               i = atoi(option_argument);
-                               if((i < (int)FLAC__MIN_BLOCK_SIZE || i > (int)FLAC__MAX_BLOCK_SIZE))
-                                       return usage_error("ERROR: invalid blocksize (-%c) '%d', must be >= %u and <= %u\n", short_option, i, FLAC__MIN_BLOCK_SIZE, FLAC__MAX_BLOCK_SIZE);
-                               add_compression_setting_unsigned(CST_BLOCKSIZE, (unsigned)i);
+                               {
+                                       unsigned i ;
+                                       FLAC__ASSERT(0 != option_argument);
+                                       i = atoi(option_argument);
+                                       if((i < (int)FLAC__MIN_BLOCK_SIZE || i > (int)FLAC__MAX_BLOCK_SIZE))
+                                               return usage_error("ERROR: invalid blocksize (-%c) '%d', must be >= %u and <= %u\n", short_option, i, FLAC__MIN_BLOCK_SIZE, FLAC__MAX_BLOCK_SIZE);
+                                       add_compression_setting_unsigned(CST_BLOCKSIZE, (unsigned)i);
+                               }
                                break;
                        case 'e':
                                add_compression_setting_bool(CST_DO_EXHAUSTIVE_MODEL_SEARCH, true);
@@ -936,11 +1012,14 @@ int parse_option(int short_option, const char *long_option, const char *option_a
                                add_compression_setting_bool(CST_DO_ESCAPE_CODING, true);
                                break;
                        case 'l':
-                               FLAC__ASSERT(0 != option_argument);
-                               i = atoi(option_argument);
-                               if((i < 0 || i > (int)FLAC__MAX_LPC_ORDER))
-                                       return usage_error("ERROR: invalid LPC order (-%c) '%d', must be >= %u and <= %u\n", short_option, i, 0, FLAC__MAX_LPC_ORDER);
-                               add_compression_setting_unsigned(CST_MAX_LPC_ORDER, (unsigned)i);
+                               {
+                                       unsigned i ;
+                                       FLAC__ASSERT(0 != option_argument);
+                                       i = atoi(option_argument);
+                                       if(i > FLAC__MAX_LPC_ORDER)
+                                               return usage_error("ERROR: invalid LPC order (-%c) '%d', must be >= %u and <= %u\n", short_option, i, 0, FLAC__MAX_LPC_ORDER);
+                                       add_compression_setting_unsigned(CST_MAX_LPC_ORDER, i);
+                               }
                                break;
                        case 'A':
                                FLAC__ASSERT(0 != option_argument);
@@ -958,38 +1037,46 @@ int parse_option(int short_option, const char *long_option, const char *option_a
                                add_compression_setting_bool(CST_DO_QLP_COEFF_PREC_SEARCH, true);
                                break;
                        case 'q':
-                               FLAC__ASSERT(0 != option_argument);
-                               i = atoi(option_argument);
-                               if(i < 0 || (i > 0 && (i < (int)FLAC__MIN_QLP_COEFF_PRECISION || i > (int)FLAC__MAX_QLP_COEFF_PRECISION)))
-                                       return usage_error("ERROR: invalid value '%d' for qlp coeff precision (-%c), must be 0 or between %u and %u, inclusive\n", i, short_option, FLAC__MIN_QLP_COEFF_PRECISION, FLAC__MAX_QLP_COEFF_PRECISION);
-                               add_compression_setting_unsigned(CST_QLP_COEFF_PRECISION, (unsigned)i);
-                               break;
-                       case 'r':
-                               FLAC__ASSERT(0 != option_argument);
-                               p = strchr(option_argument, ',');
-                               if(0 == p) {
-                                       add_compression_setting_unsigned(CST_MIN_RESIDUAL_PARTITION_ORDER, 0);
+                               {
+                                       unsigned i ;
+                                       FLAC__ASSERT(0 != option_argument);
                                        i = atoi(option_argument);
-                                       if(i < 0)
-                                               return usage_error("ERROR: invalid value '%d' for residual partition order (-%c), must be between 0 and %u, inclusive\n", i, short_option, FLAC__MAX_RICE_PARTITION_ORDER);
-                                       add_compression_setting_unsigned(CST_MAX_RESIDUAL_PARTITION_ORDER, (unsigned)i);
+                                       if((i > 0 && (i < FLAC__MIN_QLP_COEFF_PRECISION || i > FLAC__MAX_QLP_COEFF_PRECISION)))
+                                               return usage_error("ERROR: invalid value '%d' for qlp coeff precision (-%c), must be 0 or between %u and %u, inclusive\n", i, short_option, FLAC__MIN_QLP_COEFF_PRECISION, FLAC__MAX_QLP_COEFF_PRECISION);
+                                       add_compression_setting_unsigned(CST_QLP_COEFF_PRECISION, i);
                                }
-                               else {
-                                       i = atoi(option_argument);
-                                       if(i < 0)
-                                               return usage_error("ERROR: invalid value '%d' for min residual partition order (-%c), must be between 0 and %u, inclusive\n", i, short_option, FLAC__MAX_RICE_PARTITION_ORDER);
-                                       add_compression_setting_unsigned(CST_MIN_RESIDUAL_PARTITION_ORDER, (unsigned)i);
-                                       i = atoi(++p);
-                                       if(i < 0)
-                                               return usage_error("ERROR: invalid value '%d' for max residual partition order (-%c), must be between 0 and %u, inclusive\n", i, short_option, FLAC__MAX_RICE_PARTITION_ORDER);
-                                       add_compression_setting_unsigned(CST_MAX_RESIDUAL_PARTITION_ORDER, (unsigned)i);
+                               break;
+                       case 'r':
+                               {
+                                       unsigned i;
+                                       char * p;
+                                       FLAC__ASSERT(0 != option_argument);
+                                       p = strchr(option_argument, ',');
+                                       if(0 == p) {
+                                               add_compression_setting_unsigned(CST_MIN_RESIDUAL_PARTITION_ORDER, 0);
+                                               i = atoi(option_argument);
+                                               if(i > FLAC__MAX_RICE_PARTITION_ORDER)
+                                                       return usage_error("ERROR: invalid value '%d' for residual partition order (-%c), must be between 0 and %u, inclusive\n", i, short_option, FLAC__MAX_RICE_PARTITION_ORDER);
+                                               add_compression_setting_unsigned(CST_MAX_RESIDUAL_PARTITION_ORDER, i);
+                                       }
+                                       else {
+                                               i = atoi(option_argument);
+                                               if(i > FLAC__MAX_RICE_PARTITION_ORDER)
+                                                       return usage_error("ERROR: invalid value '%d' for min residual partition order (-%c), must be between 0 and %u, inclusive\n", i, short_option, FLAC__MAX_RICE_PARTITION_ORDER);
+                                               add_compression_setting_unsigned(CST_MIN_RESIDUAL_PARTITION_ORDER, i);
+                                               i = atoi(++p);
+                                               if(i > FLAC__MAX_RICE_PARTITION_ORDER)
+                                                       return usage_error("ERROR: invalid value '%d' for max residual partition order (-%c), must be between 0 and %u, inclusive\n", i, short_option, FLAC__MAX_RICE_PARTITION_ORDER);
+                                               add_compression_setting_unsigned(CST_MAX_RESIDUAL_PARTITION_ORDER, i);
+                                       }
                                }
                                break;
                        case 'R':
-                               i = atoi(option_argument);
-                               if(i < 0)
-                                       return usage_error("ERROR: invalid value '%d' for Rice parameter search distance (-%c), must be >= 0\n", i, short_option);
-                               add_compression_setting_unsigned(CST_RICE_PARAMETER_SEARCH_DIST, (unsigned)i);
+                               {
+                                       unsigned i;
+                                       i = atoi(option_argument);
+                                       add_compression_setting_unsigned(CST_RICE_PARAMETER_SEARCH_DIST, i);
+                               }
                                break;
                        default:
                                FLAC__ASSERT(0);
@@ -1070,7 +1157,7 @@ static void usage_header(void)
 {
        printf("===============================================================================\n");
        printf("flac - Command-line FLAC encoder/decoder version %s\n", FLAC__VERSION_STRING);
-       printf("Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson\n");
+       printf("Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008,2009  Josh Coalson\n");
        printf("\n");
        printf("This program is free software; you can redistribute it and/or\n");
        printf("modify it under the terms of the GNU General Public License\n");
@@ -1082,9 +1169,9 @@ static void usage_header(void)
        printf("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n");
        printf("GNU General Public License for more details.\n");
        printf("\n");
-       printf("You should have received a copy of the GNU General Public License\n");
-       printf("along with this program; if not, write to the Free Software\n");
-       printf("Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n");
+       printf("You should have received a copy of the GNU General Public License along\n");
+       printf("with this program; if not, write to the Free Software Foundation, Inc.,\n");
+       printf("51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n");
        printf("===============================================================================\n");
 }
 
@@ -1097,6 +1184,9 @@ static void usage_summary(void)
        printf("  Testing: flac -t [<general-options>] [FLACFILE [...]]\n");
        printf("Analyzing: flac -a [<general-options>] [<analysis-options>] [FLACFILE [...]]\n");
        printf("\n");
+       printf("Be sure to read the list of known bugs at:\n");
+       printf("http://flac.sourceforge.net/documentation_bugs.html\n");
+       printf("\n");
 }
 
 void short_usage(void)
@@ -1106,6 +1196,9 @@ void short_usage(void)
        printf("This is the short help; for all options use 'flac --help'; for even more\n");
        printf("instructions use 'flac --explain'\n");
        printf("\n");
+       printf("Be sure to read the list of known bugs at:\n");
+       printf("http://flac.sourceforge.net/documentation_bugs.html\n");
+       printf("\n");
        printf("To encode:\n");
        printf("  flac [-#] [INPUTFILE [...]]\n");
        printf("\n");
@@ -1132,11 +1225,14 @@ void show_help(void)
        printf("  -c, --stdout                 Write output to stdout\n");
        printf("  -s, --silent                 Do not write runtime encode/decode statistics\n");
        printf("      --totally-silent         Do not print anything, including errors\n");
+       printf("      --no-utf8-convert        Do not convert tags from local charset to UTF-8\n");
        printf("  -w, --warnings-as-errors     Treat all warnings as errors\n");
        printf("  -f, --force                  Force overwriting of output files\n");
        printf("  -o, --output-name=FILENAME   Force the output file name\n");
        printf("      --output-prefix=STRING   Prepend STRING to output names\n");
        printf("      --delete-input-file      Deletes after a successful encode/decode\n");
+       printf("      --preserve-modtime       Output files keep timestamp of input (default)\n");
+       printf("      --keep-foreign-metadata  Save/restore WAVE or AIFF non-audio chunks\n");
        printf("      --skip={#|mm:ss.ss}      Skip the given initial samples for each input\n");
        printf("      --until={#|[+|-]mm:ss.ss}  Stop at the given sample for each input file\n");
 #if FLAC__HAS_OGG
@@ -1152,7 +1248,8 @@ void show_help(void)
        printf("encoding options:\n");
        printf("  -V, --verify                 Verify a correct encoding\n");
        printf("      --lax                    Allow encoder to generate non-Subset files\n");
-       printf("      --sector-align           Align multiple files on sector boundaries\n");
+       printf("      --ignore-chunk-sizes     Ignore data chunk sizes in WAVE/AIFF files\n");
+       printf("      --sector-align (DEPRECATED) Align multiple files on sector boundaries\n");
        printf("      --replay-gain            Calculate ReplayGain & store in FLAC tags\n");
        printf("      --cuesheet=FILENAME      Import cuesheet and store in CUESHEET block\n");
        printf("      --picture=SPECIFICATION  Import picture and store in PICTURE block\n");
@@ -1185,12 +1282,17 @@ void show_help(void)
        printf("      --sample-rate=#          Sample rate in Hz\n");
        printf("      --sign={signed|unsigned} Sign of samples\n");
        printf("      --input-size=#           Size of the raw input in bytes\n");
-       printf("      --force-aiff-format      Force decoding to AIFF format\n");
        printf("      --force-raw-format       Treat input or output as raw samples\n");
+       printf("      --force-aiff-format      Force decoding to AIFF format\n");
+       printf("      --force-rf64-format      Force decoding to RF64 format\n");
+       printf("      --force-wave64-format    Force decoding to Wave64 format\n");
        printf("negative options:\n");
        printf("      --no-adaptive-mid-side\n");
+       printf("      --no-cued-seekpoints\n");
        printf("      --no-decode-through-errors\n");
        printf("      --no-delete-input-file\n");
+       printf("      --no-preserve-modtime\n");
+       printf("      --no-keep-foreign-metadata\n");
        printf("      --no-exhaustive-model-search\n");
        printf("      --no-lax\n");
        printf("      --no-mid-side\n");
@@ -1202,6 +1304,7 @@ void show_help(void)
        printf("      --no-replay-gain\n");
        printf("      --no-residual-gnuplot\n");
        printf("      --no-residual-text\n");
+       printf("      --no-ignore-chunk-sizes\n");
        printf("      --no-sector-align\n");
        printf("      --no-seektable\n");
        printf("      --no-silent\n");
@@ -1215,8 +1318,8 @@ void show_explain(void)
        usage_header();
        usage_summary();
        printf("For encoding:\n");
-       printf("  The input file(s) may be a PCM RIFF WAVE file, AIFF (or uncompressed AIFF-C)\n");
-       printf("  file, or raw samples.\n");
+       printf("  The input file(s) may be a PCM WAVE or RF64 file, AIFF (or uncompressed\n");
+       printf("  AIFF-C) file, or raw samples.\n");
        printf("  The output file(s) will be in native FLAC or Ogg FLAC format\n");
        printf("For decoding, the reverse is true.\n");
        printf("\n");
@@ -1246,6 +1349,10 @@ void show_explain(void)
        printf("      --totally-silent         Do not print anything of any kind, including\n");
        printf("                               warnings or errors.  The exit code will be the\n");
        printf("                               only way to determine successful completion.\n");
+       printf("      --no-utf8-convert        Do not convert tags from local charset to UTF-8.\n");
+       printf("                               This is useful for scripts, and setting tags in\n");
+       printf("                               situations where the locale is wrong.  This\n");
+       printf("                               option must appear before any tag options!\n");
        printf("  -w, --warnings-as-errors     Treat all warnings as errors\n");
        printf("  -f, --force                  Force overwriting of output files\n");
        printf("  -o, --output-name=FILENAME   Force the output file name; usually flac just\n");
@@ -1261,6 +1368,18 @@ void show_explain(void)
        printf("                               successful encode or decode.  If there was an\n");
        printf("                               error (including a verify error) the input file\n");
        printf("                               is left intact.\n");
+       printf("      --preserve-modtime       Output files have their timestamps/permissions\n");
+       printf("                               set to match those of their inputs (this is\n");
+       printf("                               default).  Use --no-preserve-modtime to make\n");
+       printf("                               output files have the current time and default\n");
+       printf("                               permissions.\n");
+       printf("      --keep-foreign-metadata  If encoding, save WAVE or AIFF non-audio chunks\n");
+       printf("                               in FLAC metadata.  If decoding, restore any saved\n");
+       printf("                               non-audio chunks from FLAC metadata when writing\n");
+       printf("                               the decoded file.  Foreign metadata cannot be\n");
+       printf("                               transcoded, e.g. WAVE chunks saved in a FLAC file\n");
+       printf("                               cannot be restored when decoding to AIFF.  Input\n");
+       printf("                               and output must be regular files, not stdin/out.\n");
        printf("      --skip={#|mm:ss.ss}      Skip the first # samples of each input file; can\n");
        printf("                               be used both for encoding and decoding.  The\n");
        printf("                               alternative form mm:ss.ss can be used to specify\n");
@@ -1278,12 +1397,12 @@ void show_explain(void)
        printf("      --ogg                    When encoding, generate Ogg FLAC output instead\n");
        printf("                               of native FLAC.  Ogg FLAC streams are FLAC\n");
        printf("                               streams wrapped in an Ogg transport layer.  The\n");
-       printf("                               resulting file should have an '.ogg' extension\n");
+       printf("                               resulting file should have an '.oga' extension\n");
        printf("                               and will still be decodable by flac.  When\n");
        printf("                               decoding, force the input to be treated as\n");
        printf("                               Ogg FLAC.  This is useful when piping input\n");
        printf("                               from stdin or when the filename does not end in\n");
-       printf("                               '.ogg'.\n");
+       printf("                               '.oga' or '.ogg'.\n");
        printf("      --serial-number          Serial number to use for the FLAC stream.  When\n");
        printf("                               encoding and no serial number is given, flac\n");
        printf("                               uses a random one.  If encoding to multiple files\n");
@@ -1324,8 +1443,15 @@ void show_explain(void)
        printf("                               output in parallel and comparing to the\n");
        printf("                               original\n");
        printf("      --lax                    Allow encoder to generate non-Subset files\n");
+#if 0 /*@@@ currently undocumented */
+       printf("      --ignore-chunk-sizes     Ignore data chunk sizes in WAVE/AIFF files;\n");
+       printf("                               useful when piping data from programs which\n");
+       printf("                               generate bogus data chunk sizes.\n");
+#endif
        printf("      --sector-align           Align encoding of multiple CD format WAVE files\n");
-       printf("                               on sector boundaries.\n");
+       printf("                               on sector boundaries.  This option is DEPRECATED\n");
+       printf("                               and may not exist in future versions of flac.\n");
+       printf("                               shntool offers similar functionality.\n");
        printf("      --replay-gain            Calculate ReplayGain values and store them as\n");
        printf("                               FLAC tags.  Title gains/peaks will be computed\n");
        printf("                               for each file, and an album gain/peak will be\n");
@@ -1482,23 +1608,36 @@ void show_explain(void)
        printf("      --input-size=#           Size of the raw input in bytes.  If you are\n");
        printf("                               encoding raw samples from stdin, you must set\n");
        printf("                               this option in order to be able to use --skip,\n");
-       printf("                               --until, --cue-sheet, or other options that need\n");
+       printf("                               --until, --cuesheet, or other options that need\n");
        printf("                               to know the size of the input beforehand.  If\n");
        printf("                               the size given is greater than what is found in\n");
        printf("                               the input stream, the encoder will complain\n");
        printf("                               about an unexpected end-of-file.  If the size\n");
        printf("                               given is less, samples will be truncated.\n");
+       printf("      --force-raw-format       Force input (when encoding) or output (when\n");
+       printf("                               decoding) to be treated as raw samples\n");
        printf("      --force-aiff-format      Force the decoder to output AIFF format.  This\n");
        printf("                               option is not needed if the output filename (as\n");
        printf("                               set by -o) ends with .aif or .aiff; this option\n");
        printf("                               has no effect when encoding since input AIFF is\n");
        printf("                               auto-detected.\n");
-       printf("      --force-raw-format       Force input (when encoding) or output (when\n");
-       printf("                               decoding) to be treated as raw samples\n");
+       printf("      --force-rf64-format      Force the decoder to output RF64 format.  This\n");
+       printf("                               option is not needed if the output filename (as\n");
+       printf("                               set by -o) ends with .rf64; this option\n");
+       printf("                               has no effect when encoding since input RF64 is\n");
+       printf("                               auto-detected.\n");
+       printf("      --force-wave64-format    Force the decoder to output Wave64 format.  This\n");
+       printf("                               option is not needed if the output filename (as\n");
+       printf("                               set by -o) ends with .w64; this option\n");
+       printf("                               has no effect when encoding since input Wave64 is\n");
+       printf("                               auto-detected.\n");
        printf("negative options:\n");
        printf("      --no-adaptive-mid-side\n");
+       printf("      --no-cued-seekpoints\n");
        printf("      --no-decode-through-errors\n");
        printf("      --no-delete-input-file\n");
+       printf("      --no-preserve-modtime\n");
+       printf("      --no-keep-foreign-metadata\n");
        printf("      --no-exhaustive-model-search\n");
        printf("      --no-lax\n");
        printf("      --no-mid-side\n");
@@ -1509,6 +1648,9 @@ void show_explain(void)
        printf("      --no-qlp-coeff-prec-search\n");
        printf("      --no-residual-gnuplot\n");
        printf("      --no-residual-text\n");
+#if 0 /*@@@ currently undocumented */
+       printf("      --no-ignore-chunk-sizes\n");
+#endif
        printf("      --no-sector-align\n");
        printf("      --no-seektable\n");
        printf("      --no-silent\n");
@@ -1520,8 +1662,8 @@ void show_explain(void)
 void format_mistake(const char *infilename, FileFormat wrong, FileFormat right)
 {
        /* WATCHOUT: indexed by FileFormat */
-       static const char * const ff[] = { "raw", "WAVE", "AIFF", "FLAC", "Ogg FLAC" };
-       flac__utils_printf(stderr, 1, "WARNING: %s is not a %s file; treating as a %s file\n", infilename, ff[wrong], ff[right]);
+       static const char * const ff[] = { " raw", " WAVE", "n RF64", "n AIFF", "n AIFF-C", " FLAC", "n Ogg FLAC" };
+       flac__utils_printf(stderr, 1, "WARNING: %s is not a%s file; treating as a%s file\n", infilename, ff[wrong], ff[right]);
 }
 
 int encode_file(const char *infilename, FLAC__bool is_first_file, FLAC__bool is_last_file)
@@ -1529,11 +1671,10 @@ int encode_file(const char *infilename, FLAC__bool is_first_file, FLAC__bool is_
        FILE *encode_infile;
        FLAC__byte lookahead[12];
        unsigned lookahead_length = 0;
-       FileFormat fmt = RAW;
-       FLAC__bool is_aifc = false;
+       FileFormat input_format = FORMAT_RAW;
        int retval;
-       off_t infilesize;
-       encode_options_t common_options;
+       FLAC__off_t infilesize;
+       encode_options_t encode_options;
        const char *outfilename = get_encoded_outfilename(infilename); /* the final name of the encoded file */
        /* internal_outfilename is the file we will actually write to; it will be a temporary name if infilename==outfilename */
        char *internal_outfilename = 0; /* NULL implies 'use outfilename' */
@@ -1544,12 +1685,12 @@ int encode_file(const char *infilename, FLAC__bool is_first_file, FLAC__bool is_
        }
 
        if(0 == strcmp(infilename, "-")) {
-               infilesize = (off_t)(-1);
+               infilesize = (FLAC__off_t)(-1);
                encode_infile = grabbag__file_get_binary_stdin();
        }
        else {
                infilesize = grabbag__file_get_filesize(infilename);
-               if(0 == (encode_infile = fopen(infilename, "rb"))) {
+               if(0 == (encode_infile = flac_fopen(infilename, "rb"))) {
                        flac__utils_printf(stderr, 1, "ERROR: can't open input file %s: %s\n", infilename, strerror(errno));
                        return 1;
                }
@@ -1558,64 +1699,88 @@ int encode_file(const char *infilename, FLAC__bool is_first_file, FLAC__bool is_
        if(!option_values.force_raw_format) {
                /* first set format based on name */
                if(strlen(infilename) >= 4 && 0 == FLAC__STRCASECMP(infilename+(strlen(infilename)-4), ".wav"))
-                       fmt= WAV;
+                       input_format = FORMAT_WAVE;
+               else if(strlen(infilename) >= 5 && 0 == FLAC__STRCASECMP(infilename+(strlen(infilename)-5), ".rf64"))
+                       input_format = FORMAT_RF64;
+               else if(strlen(infilename) >= 4 && 0 == FLAC__STRCASECMP(infilename+(strlen(infilename)-4), ".w64"))
+                       input_format = FORMAT_WAVE64;
                else if(strlen(infilename) >= 4 && 0 == FLAC__STRCASECMP(infilename+(strlen(infilename)-4), ".aif"))
-                       fmt= AIF;
+                       input_format = FORMAT_AIFF;
                else if(strlen(infilename) >= 5 && 0 == FLAC__STRCASECMP(infilename+(strlen(infilename)-5), ".aiff"))
-                       fmt= AIF;
+                       input_format = FORMAT_AIFF;
                else if(strlen(infilename) >= 5 && 0 == FLAC__STRCASECMP(infilename+(strlen(infilename)-5), ".flac"))
-                       fmt= FLAC;
+                       input_format = FORMAT_FLAC;
+               else if(strlen(infilename) >= 4 && 0 == FLAC__STRCASECMP(infilename+(strlen(infilename)-4), ".oga"))
+                       input_format = FORMAT_OGGFLAC;
                else if(strlen(infilename) >= 4 && 0 == FLAC__STRCASECMP(infilename+(strlen(infilename)-4), ".ogg"))
-                       fmt= OGGFLAC;
+                       input_format = FORMAT_OGGFLAC;
 
                /* attempt to guess the file type based on the first 12 bytes */
                if((lookahead_length = fread(lookahead, 1, 12, encode_infile)) < 12) {
-                       if(fmt != RAW) {
-                               format_mistake(infilename, fmt, RAW);
+                       /* all supported non-raw formats have at least 12 bytes of header to read */
+                       if(input_format != FORMAT_RAW) {
+                               format_mistake(infilename, input_format, FORMAT_RAW);
                                if(option_values.treat_warnings_as_errors) {
                                        conditional_fclose(encode_infile);
                                        return 1;
                                }
                        }
-                       fmt= RAW;
+                       /* force to raw */
+                       input_format = FORMAT_RAW;
                }
                else {
-                       if(!strncmp((const char *)lookahead, "ID3", 3)) {
+                       if(!memcmp(lookahead, "ID3", 3)) {
                                flac__utils_printf(stderr, 1, "ERROR: input file %s has an ID3v2 tag\n", infilename);
+                               conditional_fclose(encode_infile);
                                return 1;
                        }
-                       else if(!strncmp((const char *)lookahead, "RIFF", 4) && !strncmp((const char *)lookahead+8, "WAVE", 4))
-                               fmt= WAV;
-                       else if(!strncmp((const char *)lookahead, "FORM", 4) && !strncmp((const char *)lookahead+8, "AIFF", 4))
-                               fmt= AIF;
-                       else if(!strncmp((const char *)lookahead, "FORM", 4) && !strncmp((const char *)lookahead+8, "AIFC", 4)) {
-                               fmt= AIF;
-                               is_aifc = true;
-                       }
+                       else if(!memcmp(lookahead, "RIFF", 4) && !memcmp(lookahead+8, "WAVE", 4))
+                               input_format = FORMAT_WAVE;
+                       else if(!memcmp(lookahead, "RF64", 4) && !memcmp(lookahead+8, "WAVE", 4))
+                               input_format = FORMAT_RF64;
+                       else if(!memcmp(lookahead, "riff\x2E\x91\xCF\x11\xA5\xD6\x28\xDB", 12)) /* just check 1st 12 bytes of GUID */
+                               input_format = FORMAT_WAVE64;
+                       else if(!memcmp(lookahead, "FORM", 4) && !memcmp(lookahead+8, "AIFF", 4))
+                               input_format = FORMAT_AIFF;
+                       else if(!memcmp(lookahead, "FORM", 4) && !memcmp(lookahead+8, "AIFC", 4))
+                               input_format = FORMAT_AIFF_C;
                        else if(!memcmp(lookahead, FLAC__STREAM_SYNC_STRING, sizeof(FLAC__STREAM_SYNC_STRING)))
-                               fmt= FLAC;
-                       /* this could be made more accurate by looking at the first packet */
+                               input_format = FORMAT_FLAC;
+                       /*@@@ this could be made more accurate by looking at the first packet to make sure it's Ogg FLAC and not, say, Ogg Vorbis.  we do catch such problems later though. */
                        else if(!memcmp(lookahead, "OggS", 4))
-                               fmt= OGGFLAC;
+                               input_format = FORMAT_OGGFLAC;
                        else {
-                               if(fmt != RAW) {
-                                       format_mistake(infilename, fmt, RAW);
+                               /* didn't find header of any supported format */
+                               if(input_format != FORMAT_RAW) {
+                                       format_mistake(infilename, input_format, FORMAT_RAW);
                                        if(option_values.treat_warnings_as_errors) {
                                                conditional_fclose(encode_infile);
                                                return 1;
                                        }
                                }
-                               fmt= RAW;
+                               /* force to raw */
+                               input_format = FORMAT_RAW;
                        }
                }
        }
 
+       if(option_values.keep_foreign_metadata) {
+               if(encode_infile == stdin || option_values.force_to_stdout) {
+                       conditional_fclose(encode_infile);
+                       return usage_error("ERROR: --keep-foreign-metadata cannot be used when encoding from stdin or to stdout\n");
+               }
+               if(input_format != FORMAT_WAVE && input_format != FORMAT_WAVE64 && input_format != FORMAT_RF64 && input_format != FORMAT_AIFF && input_format != FORMAT_AIFF_C) {
+                       conditional_fclose(encode_infile);
+                       return usage_error("ERROR: --keep-foreign-metadata can only be used with WAVE, Wave64, RF64, or AIFF input\n");
+               }
+       }
+
        /*
         * Error if output file already exists (and -f not used).
         * Use grabbag__file_get_filesize() as a cheap way to check.
         */
-       if(!option_values.test_only && !option_values.force_file_overwrite && strcmp(outfilename, "-") && grabbag__file_get_filesize(outfilename) != (off_t)(-1)) {
-               if(fmt == FLAC) {
+       if(!option_values.test_only && !option_values.force_file_overwrite && strcmp(outfilename, "-") && grabbag__file_get_filesize(outfilename) != (FLAC__off_t)(-1)) {
+               if(input_format == FORMAT_FLAC) {
                        /* need more detailed error message when re-flac'ing to avoid confusing the user */
                        flac__utils_printf(stderr, 1,
                                "ERROR: output file %s already exists.\n\n"
@@ -1626,7 +1791,7 @@ int encode_file(const char *infilename, FLAC__bool is_first_file, FLAC__bool is_
                                outfilename
                        );
                }
-               else if(fmt == OGGFLAC) {
+               else if(input_format == FORMAT_OGGFLAC) {
                        /* need more detailed error message when re-flac'ing to avoid confusing the user */
                        flac__utils_printf(stderr, 1,
                                "ERROR: output file %s already exists.\n\n"
@@ -1644,7 +1809,7 @@ int encode_file(const char *infilename, FLAC__bool is_first_file, FLAC__bool is_
        }
 
        if(option_values.format_input_size >= 0) {
-               if (fmt != RAW || infilesize >= 0) {
+               if (input_format != FORMAT_RAW || infilesize >= 0) {
                        flac__utils_printf(stderr, 1, "ERROR: can only use --input-size when encoding raw samples from stdin\n");
                        conditional_fclose(encode_infile);
                        return 1;
@@ -1654,25 +1819,25 @@ int encode_file(const char *infilename, FLAC__bool is_first_file, FLAC__bool is_
                }
        }
 
-       if(option_values.sector_align && (fmt == FLAC || fmt == OGGFLAC)) {
+       if(option_values.sector_align && (input_format == FORMAT_FLAC || input_format == FORMAT_OGGFLAC)) {
                flac__utils_printf(stderr, 1, "ERROR: can't use --sector-align when the input file is FLAC or Ogg FLAC\n");
                conditional_fclose(encode_infile);
                return 1;
        }
-       if(option_values.sector_align && fmt == RAW && infilesize < 0) {
+       if(option_values.sector_align && input_format == FORMAT_RAW && infilesize < 0) {
                flac__utils_printf(stderr, 1, "ERROR: can't use --sector-align when the input size is unknown\n");
                conditional_fclose(encode_infile);
                return 1;
        }
 
-       if(fmt == RAW) {
+       if(input_format == FORMAT_RAW) {
                if(option_values.format_is_big_endian < 0 || option_values.format_is_unsigned_samples < 0 || option_values.format_channels < 0 || option_values.format_bps < 0 || option_values.format_sample_rate < 0) {
                        conditional_fclose(encode_infile);
                        return usage_error("ERROR: for encoding a raw file you must specify a value for --endian, --sign, --channels, --bps, and --sample-rate\n");
                }
        }
 
-       if(encode_infile == stdin || option_values.force_to_stdout) {
+       if(option_values.force_to_stdout) {
                if(option_values.replay_gain) {
                        conditional_fclose(encode_infile);
                        return usage_error("ERROR: --replay-gain cannot be used when encoding to stdout\n");
@@ -1683,96 +1848,114 @@ int encode_file(const char *infilename, FLAC__bool is_first_file, FLAC__bool is_
                return usage_error("ERROR: --replay-gain cannot be used when encoding to Ogg FLAC yet\n");
        }
 
-       if(!flac__utils_parse_skip_until_specification(option_values.skip_specification, &common_options.skip_specification) || common_options.skip_specification.is_relative) {
+       if(!flac__utils_parse_skip_until_specification(option_values.skip_specification, &encode_options.skip_specification) || encode_options.skip_specification.is_relative) {
                conditional_fclose(encode_infile);
                return usage_error("ERROR: invalid value for --skip\n");
        }
 
-       if(!flac__utils_parse_skip_until_specification(option_values.until_specification, &common_options.until_specification)) { /*@@@@ more checks: no + without --skip, no - unless known total_samples_to_{en,de}code */
+       if(!flac__utils_parse_skip_until_specification(option_values.until_specification, &encode_options.until_specification)) { /*@@@@ more checks: no + without --skip, no - unless known total_samples_to_{en,de}code */
                conditional_fclose(encode_infile);
                return usage_error("ERROR: invalid value for --until\n");
        }
        /* if there is no "--until" we want to default to "--until=-0" */
        if(0 == option_values.until_specification)
-               common_options.until_specification.is_relative = true;
+               encode_options.until_specification.is_relative = true;
 
-       common_options.verify = option_values.verify;
-       common_options.treat_warnings_as_errors = option_values.treat_warnings_as_errors;
+       encode_options.verify = option_values.verify;
+       encode_options.treat_warnings_as_errors = option_values.treat_warnings_as_errors;
 #if FLAC__HAS_OGG
-       common_options.use_ogg = option_values.use_ogg;
+       encode_options.use_ogg = option_values.use_ogg;
        /* set a random serial number if one has not yet been specified */
        if(!option_values.has_serial_number) {
                option_values.serial_number = rand();
                option_values.has_serial_number = true;
        }
-       common_options.serial_number = option_values.serial_number++;
+       encode_options.serial_number = option_values.serial_number++;
 #endif
-       common_options.lax = option_values.lax;
-       common_options.padding = option_values.padding;
-       common_options.num_compression_settings = option_values.num_compression_settings;
-       FLAC__ASSERT(sizeof(common_options.compression_settings) >= sizeof(option_values.compression_settings));
-       memcpy(common_options.compression_settings, option_values.compression_settings, sizeof(option_values.compression_settings));
-       common_options.requested_seek_points = option_values.requested_seek_points;
-       common_options.num_requested_seek_points = option_values.num_requested_seek_points;
-       common_options.cuesheet_filename = option_values.cuesheet_filename;
-       common_options.continue_through_decode_errors = option_values.continue_through_decode_errors;
-       common_options.cued_seekpoints = option_values.cued_seekpoints;
-       common_options.channel_map_none = option_values.channel_map_none;
-       common_options.is_first_file = is_first_file;
-       common_options.is_last_file = is_last_file;
-       common_options.align_reservoir = align_reservoir;
-       common_options.align_reservoir_samples = &align_reservoir_samples;
-       common_options.replay_gain = option_values.replay_gain;
-       common_options.sector_align = option_values.sector_align;
-       common_options.vorbis_comment = option_values.vorbis_comment;
-       FLAC__ASSERT(sizeof(common_options.pictures) >= sizeof(option_values.pictures));
-       memcpy(common_options.pictures, option_values.pictures, sizeof(option_values.pictures));
-       common_options.num_pictures = option_values.num_pictures;
-       common_options.debug.disable_constant_subframes = option_values.debug.disable_constant_subframes;
-       common_options.debug.disable_fixed_subframes = option_values.debug.disable_fixed_subframes;
-       common_options.debug.disable_verbatim_subframes = option_values.debug.disable_verbatim_subframes;
+       encode_options.lax = option_values.lax;
+       encode_options.padding = option_values.padding;
+       encode_options.num_compression_settings = option_values.num_compression_settings;
+       FLAC__ASSERT(sizeof(encode_options.compression_settings) >= sizeof(option_values.compression_settings));
+       memcpy(encode_options.compression_settings, option_values.compression_settings, sizeof(option_values.compression_settings));
+       encode_options.requested_seek_points = option_values.requested_seek_points;
+       encode_options.num_requested_seek_points = option_values.num_requested_seek_points;
+       encode_options.cuesheet_filename = option_values.cuesheet_filename;
+       encode_options.continue_through_decode_errors = option_values.continue_through_decode_errors;
+       encode_options.cued_seekpoints = option_values.cued_seekpoints;
+       encode_options.channel_map_none = option_values.channel_map_none;
+       encode_options.is_first_file = is_first_file;
+       encode_options.is_last_file = is_last_file;
+       encode_options.align_reservoir = align_reservoir;
+       encode_options.align_reservoir_samples = &align_reservoir_samples;
+       encode_options.replay_gain = option_values.replay_gain;
+       encode_options.ignore_chunk_sizes = option_values.ignore_chunk_sizes;
+       encode_options.sector_align = option_values.sector_align;
+       encode_options.vorbis_comment = option_values.vorbis_comment;
+       FLAC__ASSERT(sizeof(encode_options.pictures) >= sizeof(option_values.pictures));
+       memcpy(encode_options.pictures, option_values.pictures, sizeof(option_values.pictures));
+       encode_options.num_pictures = option_values.num_pictures;
+       encode_options.format = input_format;
+       encode_options.debug.disable_constant_subframes = option_values.debug.disable_constant_subframes;
+       encode_options.debug.disable_fixed_subframes = option_values.debug.disable_fixed_subframes;
+       encode_options.debug.disable_verbatim_subframes = option_values.debug.disable_verbatim_subframes;
+       encode_options.debug.do_md5 = option_values.debug.do_md5;
 
        /* if infilename and outfilename point to the same file, we need to write to a temporary file */
        if(encode_infile != stdin && grabbag__file_are_same(infilename, outfilename)) {
                static const char *tmp_suffix = ".tmp,fl-ac+en'c";
+               size_t dest_len = strlen(outfilename) + strlen(tmp_suffix) + 1;
                /*@@@@ still a remote possibility that a file with this filename exists */
-               if(0 == (internal_outfilename = malloc(strlen(outfilename)+strlen(tmp_suffix)+1))) {
+               if(0 == (internal_outfilename = safe_malloc_(dest_len))) {
                        flac__utils_printf(stderr, 1, "ERROR allocating memory for tempfile name\n");
                        conditional_fclose(encode_infile);
                        return 1;
                }
-               strcpy(internal_outfilename, outfilename);
-               strcat(internal_outfilename, tmp_suffix);
+               safe_strncpy(internal_outfilename, outfilename, dest_len);
+               safe_strncat(internal_outfilename, tmp_suffix, dest_len);
        }
 
-       if(fmt == RAW) {
-               raw_encode_options_t options;
-
-               options.common = common_options;
-               options.is_big_endian = option_values.format_is_big_endian;
-               options.is_unsigned_samples = option_values.format_is_unsigned_samples;
-               options.channels = option_values.format_channels;
-               options.bps = option_values.format_bps;
-               options.sample_rate = option_values.format_sample_rate;
+       if(input_format == FORMAT_RAW) {
+               encode_options.format_options.raw.is_big_endian = option_values.format_is_big_endian;
+               encode_options.format_options.raw.is_unsigned_samples = option_values.format_is_unsigned_samples;
+               encode_options.format_options.raw.channels = option_values.format_channels;
+               encode_options.format_options.raw.bps = option_values.format_bps;
+               encode_options.format_options.raw.sample_rate = option_values.format_sample_rate;
 
-               retval = flac__encode_raw(encode_infile, infilesize, infilename, internal_outfilename? internal_outfilename : outfilename, lookahead, lookahead_length, options);
+               retval = flac__encode_file(encode_infile, infilesize, infilename, internal_outfilename? internal_outfilename : outfilename, lookahead, lookahead_length, encode_options);
+       }
+       else if(input_format == FORMAT_FLAC || input_format == FORMAT_OGGFLAC) {
+               retval = flac__encode_file(encode_infile, infilesize, infilename, internal_outfilename? internal_outfilename : outfilename, lookahead, lookahead_length, encode_options);
        }
-       else if(fmt == FLAC || fmt == OGGFLAC) {
-               flac_encode_options_t options;
+       else if(input_format == FORMAT_WAVE || input_format == FORMAT_WAVE64 || input_format == FORMAT_RF64 || input_format == FORMAT_AIFF || input_format == FORMAT_AIFF_C) {
+               encode_options.format_options.iff.foreign_metadata = 0;
+
+               /* initialize foreign metadata if requested */
+               if(option_values.keep_foreign_metadata) {
+                       encode_options.format_options.iff.foreign_metadata =
+                               flac__foreign_metadata_new(
+                                       input_format==FORMAT_WAVE || input_format==FORMAT_RF64?
+                                               FOREIGN_BLOCK_TYPE__RIFF :
+                                       input_format==FORMAT_WAVE64?
+                                               FOREIGN_BLOCK_TYPE__WAVE64 :
+                                               FOREIGN_BLOCK_TYPE__AIFF
+                               );
+                       if(0 == encode_options.format_options.iff.foreign_metadata) {
+                               flac__utils_printf(stderr, 1, "ERROR: creating foreign metadata object\n");
+                               conditional_fclose(encode_infile);
+                               if(internal_outfilename != 0)
+                                       free(internal_outfilename);
+                               return 1;
+                       }
+               }
 
-               options.common = common_options;
+               retval = flac__encode_file(encode_infile, infilesize, infilename, internal_outfilename? internal_outfilename : outfilename, lookahead, lookahead_length, encode_options);
 
-               retval = flac__encode_flac(encode_infile, infilesize, infilename, internal_outfilename? internal_outfilename : outfilename, lookahead, lookahead_length, options, fmt==OGGFLAC);
+               if(encode_options.format_options.iff.foreign_metadata)
+                       flac__foreign_metadata_delete(encode_options.format_options.iff.foreign_metadata);
        }
        else {
-               wav_encode_options_t options;
-
-               options.common = common_options;
-
-               if(fmt == AIF)
-                       retval = flac__encode_aif(encode_infile, infilesize, infilename, internal_outfilename? internal_outfilename : outfilename, lookahead, lookahead_length, options, is_aifc);
-               else
-                       retval = flac__encode_wav(encode_infile, infilesize, infilename, internal_outfilename? internal_outfilename : outfilename, lookahead, lookahead_length, options);
+               FLAC__ASSERT(0);
+               retval = 1; /* double protection */
        }
 
        if(retval == 0) {
@@ -1782,27 +1965,28 @@ int encode_file(const char *infilename, FLAC__bool is_first_file, FLAC__bool is_
                                const char *error;
                                grabbag__replaygain_get_title(&title_gain, &title_peak);
                                if(
-                                       0 != (error = grabbag__replaygain_store_to_file_reference(internal_outfilename? internal_outfilename : outfilename, /*preserve_modtime=*/true)) ||
-                                       0 != (error = grabbag__replaygain_store_to_file_title(internal_outfilename? internal_outfilename : outfilename, title_gain, title_peak, /*preserve_modtime=*/true))
+                                       0 != (error = grabbag__replaygain_store_to_file_reference(internal_outfilename? internal_outfilename : outfilename, option_values.preserve_modtime)) ||
+                                       0 != (error = grabbag__replaygain_store_to_file_title(internal_outfilename? internal_outfilename : outfilename, title_gain, title_peak, option_values.preserve_modtime))
                                ) {
                                        flac__utils_printf(stderr, 1, "%s: ERROR writing ReplayGain reference/title tags (%s)\n", outfilename, error);
+                                       retval = 1;
                                }
                        }
-                       if(strcmp(infilename, "-"))
+                       if(option_values.preserve_modtime && strcmp(infilename, "-"))
                                grabbag__file_copy_metadata(infilename, internal_outfilename? internal_outfilename : outfilename);
                }
        }
 
        /* rename temporary file if necessary */
        if(retval == 0 && internal_outfilename != 0) {
-               if(rename(internal_outfilename, outfilename) < 0) {
+               if(flac_rename(internal_outfilename, outfilename) < 0) {
 #if defined _MSC_VER || defined __MINGW32__ || defined __EMX__
-                       /* on some flavors of windows, rename() will fail if the destination already exists, so we unlink and try again */
-                       if(unlink(outfilename) < 0) {
+                       /* on some flavors of windows, flac_rename() will fail if the destination already exists, so we unlink and try again */
+                       if(flac_unlink(outfilename) < 0) {
                                flac__utils_printf(stderr, 1, "ERROR: moving new FLAC file %s back on top of original FLAC file %s, keeping both\n", internal_outfilename, outfilename);
                                retval = 1;
                        }
-                       else if(rename(internal_outfilename, outfilename) < 0) {
+                       else if(flac_rename(internal_outfilename, outfilename) < 0) {
                                flac__utils_printf(stderr, 1, "ERROR: moving new FLAC file %s back on top of original FLAC file %s, you must do it\n", internal_outfilename, outfilename);
                                retval = 1;
                        }
@@ -1815,7 +1999,7 @@ int encode_file(const char *infilename, FLAC__bool is_first_file, FLAC__bool is_
 
        /* handle --delete-input-file, but don't want to delete if piping from stdin, or if input filename and output filename are the same */
        if(retval == 0 && option_values.delete_input && strcmp(infilename, "-") && internal_outfilename == 0)
-               unlink(infilename);
+               flac_unlink(infilename);
 
        if(internal_outfilename != 0)
                free(internal_outfilename);
@@ -1827,7 +2011,8 @@ int decode_file(const char *infilename)
 {
        int retval;
        FLAC__bool treat_as_ogg = false;
-       decode_options_t common_options;
+       FileFormat output_format = FORMAT_WAVE;
+       decode_options_t decode_options;
        const char *outfilename = get_decoded_outfilename(infilename);
 
        if(0 == outfilename) {
@@ -1839,18 +2024,48 @@ int decode_file(const char *infilename)
         * Error if output file already exists (and -f not used).
         * Use grabbag__file_get_filesize() as a cheap way to check.
         */
-       if(!option_values.test_only && !option_values.force_file_overwrite && strcmp(outfilename, "-") && grabbag__file_get_filesize(outfilename) != (off_t)(-1)) {
+       if(!option_values.test_only && !option_values.force_file_overwrite && strcmp(outfilename, "-") && grabbag__file_get_filesize(outfilename) != (FLAC__off_t)(-1)) {
                flac__utils_printf(stderr, 1, "ERROR: output file %s already exists, use -f to override\n", outfilename);
                return 1;
        }
 
+       if(option_values.force_raw_format)
+               output_format = FORMAT_RAW;
+       else if(
+               option_values.force_aiff_format ||
+               (strlen(outfilename) >= 4 && 0 == FLAC__STRCASECMP(outfilename+(strlen(outfilename)-4), ".aif")) ||
+               (strlen(outfilename) >= 5 && 0 == FLAC__STRCASECMP(outfilename+(strlen(outfilename)-5), ".aiff"))
+       )
+               output_format = FORMAT_AIFF;
+       else if(
+               option_values.force_rf64_format ||
+               (strlen(outfilename) >= 5 && 0 == FLAC__STRCASECMP(outfilename+(strlen(outfilename)-5), ".rf64"))
+       )
+               output_format = FORMAT_RF64;
+       else if(
+               option_values.force_wave64_format ||
+               (strlen(outfilename) >= 4 && 0 == FLAC__STRCASECMP(outfilename+(strlen(outfilename)-4), ".w64"))
+       )
+               output_format = FORMAT_WAVE64;
+       else
+               output_format = FORMAT_WAVE;
+
        if(!option_values.test_only && !option_values.analyze) {
-               if(option_values.force_raw_format && (option_values.format_is_big_endian < 0 || option_values.format_is_unsigned_samples < 0))
+               if(output_format == FORMAT_RAW && (option_values.format_is_big_endian < 0 || option_values.format_is_unsigned_samples < 0))
                        return usage_error("ERROR: for decoding to a raw file you must specify a value for --endian and --sign\n");
        }
 
+       if(option_values.keep_foreign_metadata) {
+               if(0 == strcmp(infilename, "-") || 0 == strcmp(outfilename, "-"))
+                       return usage_error("ERROR: --keep-foreign-metadata cannot be used when decoding from stdin or to stdout\n");
+               if(output_format != FORMAT_WAVE && output_format != FORMAT_WAVE64 && output_format != FORMAT_RF64 && output_format != FORMAT_AIFF && output_format != FORMAT_AIFF_C)
+                       return usage_error("ERROR: --keep-foreign-metadata can only be used with WAVE, Wave64, RF64, or AIFF output\n");
+       }
+
        if(option_values.use_ogg)
                treat_as_ogg = true;
+       else if(strlen(infilename) >= 4 && 0 == FLAC__STRCASECMP(infilename+(strlen(infilename)-4), ".oga"))
+               treat_as_ogg = true;
        else if(strlen(infilename) >= 4 && 0 == FLAC__STRCASECMP(infilename+(strlen(infilename)-4), ".ogg"))
                treat_as_ogg = true;
        else
@@ -1863,62 +2078,70 @@ int decode_file(const char *infilename)
        }
 #endif
 
-       if(!flac__utils_parse_skip_until_specification(option_values.skip_specification, &common_options.skip_specification) || common_options.skip_specification.is_relative)
+       if(!flac__utils_parse_skip_until_specification(option_values.skip_specification, &decode_options.skip_specification) || decode_options.skip_specification.is_relative)
                return usage_error("ERROR: invalid value for --skip\n");
 
-       if(!flac__utils_parse_skip_until_specification(option_values.until_specification, &common_options.until_specification)) /*@@@ more checks: no + without --skip, no - unless known total_samples_to_{en,de}code */
+       if(!flac__utils_parse_skip_until_specification(option_values.until_specification, &decode_options.until_specification)) /*@@@ more checks: no + without --skip, no - unless known total_samples_to_{en,de}code */
                return usage_error("ERROR: invalid value for --until\n");
        /* if there is no "--until" we want to default to "--until=-0" */
        if(0 == option_values.until_specification)
-               common_options.until_specification.is_relative = true;
+               decode_options.until_specification.is_relative = true;
 
        if(option_values.cue_specification) {
-               if(!flac__utils_parse_cue_specification(option_values.cue_specification, &common_options.cue_specification))
+               if(!flac__utils_parse_cue_specification(option_values.cue_specification, &decode_options.cue_specification))
                        return usage_error("ERROR: invalid value for --cue\n");
-               common_options.has_cue_specification = true;
+               decode_options.has_cue_specification = true;
        }
        else
-               common_options.has_cue_specification = false;
+               decode_options.has_cue_specification = false;
 
-       common_options.treat_warnings_as_errors = option_values.treat_warnings_as_errors;
-       common_options.continue_through_decode_errors = option_values.continue_through_decode_errors;
-       common_options.replaygain_synthesis_spec = option_values.replaygain_synthesis_spec;
+       decode_options.treat_warnings_as_errors = option_values.treat_warnings_as_errors;
+       decode_options.continue_through_decode_errors = option_values.continue_through_decode_errors;
+       decode_options.replaygain_synthesis_spec = option_values.replaygain_synthesis_spec;
 #if FLAC__HAS_OGG
-       common_options.is_ogg = treat_as_ogg;
-       common_options.use_first_serial_number = !option_values.has_serial_number;
-       common_options.serial_number = option_values.serial_number;
+       decode_options.is_ogg = treat_as_ogg;
+       decode_options.use_first_serial_number = !option_values.has_serial_number;
+       decode_options.serial_number = option_values.serial_number;
 #endif
-       common_options.channel_map_none = option_values.channel_map_none;
-
-       if(!option_values.force_raw_format) {
-               wav_decode_options_t options;
+       decode_options.channel_map_none = option_values.channel_map_none;
+       decode_options.format = output_format;
 
-               options.common = common_options;
+       if(output_format == FORMAT_RAW) {
+               decode_options.format_options.raw.is_big_endian = option_values.format_is_big_endian;
+               decode_options.format_options.raw.is_unsigned_samples = option_values.format_is_unsigned_samples;
 
-               if(
-                       option_values.force_aiff_format ||
-                       (strlen(outfilename) >= 4 && 0 == FLAC__STRCASECMP(outfilename+(strlen(outfilename)-4), ".aif")) ||
-                       (strlen(outfilename) >= 5 && 0 == FLAC__STRCASECMP(outfilename+(strlen(outfilename)-5), ".aiff"))
-               )
-                       retval = flac__decode_aiff(infilename, option_values.test_only? 0 : outfilename, option_values.analyze, option_values.aopts, options);
-               else
-                       retval = flac__decode_wav(infilename, option_values.test_only? 0 : outfilename, option_values.analyze, option_values.aopts, options);
+               retval = flac__decode_file(infilename, option_values.test_only? 0 : outfilename, option_values.analyze, option_values.aopts, decode_options);
        }
        else {
-               raw_decode_options_t options;
+               decode_options.format_options.iff.foreign_metadata = 0;
+
+               /* initialize foreign metadata if requested */
+               if(option_values.keep_foreign_metadata) {
+                       decode_options.format_options.iff.foreign_metadata =
+                               flac__foreign_metadata_new(
+                                       output_format==FORMAT_WAVE || output_format==FORMAT_RF64?
+                                               FOREIGN_BLOCK_TYPE__RIFF :
+                                       output_format==FORMAT_WAVE64?
+                                               FOREIGN_BLOCK_TYPE__WAVE64 :
+                                               FOREIGN_BLOCK_TYPE__AIFF
+                               );
+                       if(0 == decode_options.format_options.iff.foreign_metadata) {
+                               flac__utils_printf(stderr, 1, "ERROR: creating foreign metadata object\n");
+                               return 1;
+                       }
+               }
 
-               options.common = common_options;
-               options.is_big_endian = option_values.format_is_big_endian;
-               options.is_unsigned_samples = option_values.format_is_unsigned_samples;
+               retval = flac__decode_file(infilename, option_values.test_only? 0 : outfilename, option_values.analyze, option_values.aopts, decode_options);
 
-               retval = flac__decode_raw(infilename, option_values.test_only? 0 : outfilename, option_values.analyze, option_values.aopts, options);
+               if(decode_options.format_options.iff.foreign_metadata)
+                       flac__foreign_metadata_delete(decode_options.format_options.iff.foreign_metadata);
        }
 
        if(retval == 0 && strcmp(infilename, "-")) {
-               if(strcmp(outfilename, "-"))
+               if(option_values.preserve_modtime && strcmp(outfilename, "-"))
                        grabbag__file_copy_metadata(infilename, outfilename);
                if(option_values.delete_input && !option_values.test_only && !option_values.analyze)
-                       unlink(infilename);
+                       flac_unlink(infilename);
        }
 
        return retval;
@@ -1926,7 +2149,7 @@ int decode_file(const char *infilename)
 
 const char *get_encoded_outfilename(const char *infilename)
 {
-       const char *suffix = (option_values.use_ogg? ".ogg" : ".flac");
+       const char *suffix = (option_values.use_ogg? ".oga" : ".flac");
        return get_outfilename(infilename, suffix);
 }
 
@@ -1942,6 +2165,12 @@ const char *get_decoded_outfilename(const char *infilename)
        else if(option_values.force_aiff_format) {
                suffix = ".aiff";
        }
+       else if(option_values.force_rf64_format) {
+               suffix = ".rf64";
+       }
+       else if(option_values.force_wave64_format) {
+               suffix = ".w64";
+       }
        else {
                suffix = ".wav";
        }
@@ -1954,7 +2183,7 @@ const char *get_outfilename(const char *infilename, const char *suffix)
                static char buffer[4096]; /* @@@ bad MAGIC NUMBER */
 
                if(0 == strcmp(infilename, "-") || option_values.force_to_stdout) {
-                       strcpy(buffer, "-");
+                       safe_strncpy(buffer, "-", sizeof(buffer));
                }
                else {
                        char *p;
@@ -2002,29 +2231,3 @@ char *local_strdup(const char *source)
                die("out of memory during strdup()");
        return ret;
 }
-
-#ifdef _MSC_VER
-/* There's no strtoll() in MSVC6 so we just write a specialized one */
-FLAC__int64 local__strtoll(const char *src, char **endptr)
-{
-       FLAC__bool neg = false;
-       FLAC__int64 ret = 0;
-       int c;
-       FLAC__ASSERT(0 != src);
-       if(*src == '-') {
-               neg = true;
-               src++;
-       }
-       while(0 != (c = *src)) {
-               c -= '0';
-               if(c >= 0 && c <= 9)
-                       ret = (ret * 10) + c;
-               else
-                       break;
-               src++;
-       }
-       if(endptr)
-               *endptr = (char*)src;
-       return neg? -ret : ret;
-}
-#endif