special version of sample formatting for common cases
[platform/upstream/flac.git] / src / flac / main.c
index ebab495..ae1937e 100644 (file)
@@ -1,5 +1,5 @@
 /* flac - Command-line FLAC encoder/decoder
- * Copyright (C) 2000,2001,2002,2003,2004  Josh Coalson
+ * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
  *
  * This program is free software; you can redistribute it and/or
  * modify it under the terms of the GNU General Public License
  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
  */
 
+#if HAVE_CONFIG_H
+#  include <config.h>
+#endif
+
 #include <ctype.h>
+#include <errno.h>
 #include <locale.h>
 #include <stdarg.h>
 #include <stdio.h>
 #include <string.h>
 #include <time.h>
 
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-
 #if !defined _MSC_VER && !defined __MINGW32__
 /* unlink is in stdio.h in VC++ */
 #include <unistd.h> /* for unlink() */
-#else
-#define strcasecmp stricmp
 #endif
 #include "FLAC/all.h"
 #include "share/grabbag.h"
 #include "utils.h"
 #include "vorbiscomment.h"
 
+#if defined _MSC_VER || defined __MINGW32__ || defined __EMX__
+#define FLAC__STRCASECMP stricmp
+#else
+#define FLAC__STRCASECMP strcasecmp
+#endif
+
 #if 0
 /*[JEC] was:#if HAVE_GETOPT_LONG*/
 /*[JEC] see flac/include/share/getopt.h as to why the change */
 #  include "share/getopt.h"
 #endif
 
-typedef enum { RAW, WAV, AIF } FileFormat;
+typedef enum { RAW, WAV, AIF, FLAC, OGGFLAC } FileFormat;
 
-static int do_it();
+static int do_it(void);
 
-static FLAC__bool init_options();
+static FLAC__bool init_options(void);
 static int parse_options(int argc, char *argv[]);
 static int parse_option(int short_option, const char *long_option, const char *option_argument);
-static void free_options();
+static void free_options(void);
+static void add_compression_setting_bool(compression_setting_type_t type, FLAC__bool value);
+static void add_compression_setting_string(compression_setting_type_t type, const char *value);
+static void add_compression_setting_unsigned(compression_setting_type_t type, unsigned value);
 
 static int usage_error(const char *message, ...);
-static void short_usage();
-static void show_version();
-static void show_help();
-static void show_explain();
-static void format_mistake(const char *infilename, const char *wrong, const char *right);
+static void short_usage(void);
+static void show_version(void);
+static void show_help(void);
+static void show_explain(void);
+static void format_mistake(const char *infilename, FileFormat wrong, FileFormat right);
 
 static int encode_file(const char *infilename, FLAC__bool is_first_file, FLAC__bool is_last_file);
 static int decode_file(const char *infilename);
@@ -75,7 +83,12 @@ static const char *get_decoded_outfilename(const char *infilename);
 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
 
 
 /*
@@ -86,21 +99,23 @@ 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 },
-       { "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 },
+       { "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 */
 
        /*
         * decoding options
@@ -114,7 +129,9 @@ static struct share__option long_options_[] = {
         */
        { "cuesheet"                  , share__required_argument, 0, 0 },
        { "no-cued-seekpoints"        , share__no_argument, 0, 0 },
+       { "picture"                   , share__required_argument, 0, 0 },
        { "tag"                       , share__required_argument, 0, 'T' },
+       { "tag-from-file"             , share__required_argument, 0, 0 },
        { "compression-level-0"       , share__no_argument, 0, '0' },
        { "compression-level-1"       , share__no_argument, 0, '1' },
        { "compression-level-2"       , share__no_argument, 0, '2' },
@@ -127,7 +144,6 @@ static struct share__option long_options_[] = {
        { "compression-level-9"       , share__no_argument, 0, '9' },
        { "best"                      , share__no_argument, 0, '8' },
        { "fast"                      , share__no_argument, 0, '0' },
-       { "super-secret-totally-impractical-compression-level", 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 },
@@ -136,13 +152,14 @@ static struct share__option long_options_[] = {
        { "sector-align"              , share__no_argument, 0, 0 },
        { "seekpoint"                 , share__required_argument, 0, 'S' },
        { "padding"                   , share__required_argument, 0, 'P' },
-#ifdef FLAC__HAS_OGG
+#if FLAC__HAS_OGG
        { "ogg"                       , share__no_argument, 0, 0 },
        { "serial-number"             , share__required_argument, 0, 0 },
 #endif
        { "blocksize"                 , share__required_argument, 0, 'b' },
        { "exhaustive-model-search"   , share__no_argument, 0, 'e' },
        { "max-lpc-order"             , share__required_argument, 0, 'l' },
+       { "apodization"               , share__required_argument, 0, 'A' },
        { "mid-side"                  , share__no_argument, 0, 'm' },
        { "adaptive-mid-side"         , share__no_argument, 0, 'M' },
        { "qlp-coeff-precision-search", share__no_argument, 0, 'p' },
@@ -172,7 +189,7 @@ static struct share__option long_options_[] = {
        { "no-replay-gain"            , share__no_argument, 0, 0 },
        { "no-sector-align"           , share__no_argument, 0, 0 },
        { "no-lax"                    , share__no_argument, 0, 0 },
-#ifdef FLAC__HAS_OGG
+#if FLAC__HAS_OGG
        { "no-ogg"                    , share__no_argument, 0, 0 },
 #endif
        { "no-exhaustive-model-search", share__no_argument, 0, 0 },
@@ -181,6 +198,7 @@ static struct share__option long_options_[] = {
        { "no-qlp-coeff-prec-search"  , share__no_argument, 0, 0 },
        { "no-padding"                , share__no_argument, 0, 0 },
        { "no-verify"                 , share__no_argument, 0, 0 },
+       { "no-warnings-as-errors"     , share__no_argument, 0, 0 },
        { "no-residual-gnuplot"       , share__no_argument, 0, 0 },
        { "no-residual-text"          , share__no_argument, 0, 0 },
        /*
@@ -204,6 +222,7 @@ static struct {
        FLAC__bool show_version;
        FLAC__bool mode_decode;
        FLAC__bool verify;
+       FLAC__bool treat_warnings_as_errors;
        FLAC__bool force_file_overwrite;
        FLAC__bool continue_through_decode_errors;
        replaygain_synthesis_spec_t replaygain_synthesis_spec;
@@ -213,11 +232,6 @@ static struct {
        FLAC__bool use_ogg;
        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 do_mid_side;
-       FLAC__bool loose_mid_side;
-       FLAC__bool do_exhaustive_model_search;
-       FLAC__bool do_escape_coding;
-       FLAC__bool do_qlp_coeff_prec_search;
        FLAC__bool force_to_stdout;
        FLAC__bool force_aiff_format;
        FLAC__bool force_raw_format;
@@ -227,9 +241,9 @@ static struct {
        const char *cmdline_forced_outfilename;
        const char *output_prefix;
        analysis_options aopts;
-       int padding;
-       unsigned max_lpc_order;
-       unsigned qlp_coeff_precision;
+       int padding; /* -1 => no -P options were given, 0 => -P- was given, else -P value */
+       size_t num_compression_settings;
+       compression_setting_t compression_settings[64]; /* bad MAGIC NUMBER but buffer overflow is checked */
        const char *skip_specification;
        const char *until_specification;
        const char *cue_specification;
@@ -238,20 +252,19 @@ static struct {
        int format_channels;
        int format_bps;
        int format_sample_rate;
-       long format_input_size;
-       int blocksize;
-       int min_residual_partition_order;
-       int max_residual_partition_order;
-       int rice_parameter_search_dist;
-       char requested_seek_points[50000]; /* bad MAGIC NUMBER but buffer overflow is checked */
+       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;
        FLAC__bool cued_seekpoints;
+       FLAC__bool channel_map_none; /* --channel-map=none specified, eventually will expand to take actual channel map */
 
        unsigned num_files;
        char **filenames;
 
        FLAC__StreamMetadata *vorbis_comment;
+       FLAC__StreamMetadata *pictures[64];
+       unsigned num_pictures;
 
        struct {
                FLAC__bool disable_constant_subframes;
@@ -274,6 +287,12 @@ int main(int argc, char *argv[])
 {
        int retval = 0;
 
+#ifdef __EMX__
+       _response(&argc, &argv);
+       _wildcard(&argc, &argv);
+#endif
+
+       srand((unsigned)time(0));
        setlocale(LC_ALL, "");
        if(!init_options()) {
                flac__utils_printf(stderr, 1, "ERROR: allocating memory\n");
@@ -289,7 +308,7 @@ int main(int argc, char *argv[])
        return retval;
 }
 
-int do_it()
+int do_it(void)
 {
        int retval = 0;
 
@@ -316,26 +335,6 @@ int do_it()
                 * tweak options; validate the values
                 */
                if(!option_values.mode_decode) {
-                       if(option_values.blocksize < 0) {
-                               if(option_values.max_lpc_order == 0)
-                                       option_values.blocksize = 1152;
-                               else
-                                       option_values.blocksize = 4608;
-                       }
-                       if(option_values.max_residual_partition_order < 0) {
-                               if(option_values.blocksize <= 1152)
-                                       option_values.max_residual_partition_order = 2;
-                               else if(option_values.blocksize <= 2304)
-                                       option_values.max_residual_partition_order = 3;
-                               else if(option_values.blocksize <= 4608)
-                                       option_values.max_residual_partition_order = 3;
-                               else
-                                       option_values.max_residual_partition_order = 4;
-                               option_values.min_residual_partition_order = option_values.max_residual_partition_order;
-                       }
-                       if(option_values.rice_parameter_search_dist < 0) {
-                               option_values.rice_parameter_search_dist = 0;
-                       }
                        if(0 != option_values.cue_specification)
                                return usage_error("ERROR: --cue is not allowed in test mode\n");
                }
@@ -347,14 +346,14 @@ int do_it()
                                        return usage_error("ERROR: --until is not allowed in test mode\n");
                                if(0 != option_values.cue_specification)
                                        return usage_error("ERROR: --cue is not allowed in test mode\n");
+                               if(0 != option_values.analyze)
+                                       return usage_error("ERROR: analysis mode (-a/--analyze) and test mode (-t/--test) cannot be used together\n");
                        }
                }
 
                if(0 != option_values.cue_specification && (0 != option_values.skip_specification || 0 != option_values.until_specification))
                        return usage_error("ERROR: --cue may not be combined with --skip or --until\n");
 
-               FLAC__ASSERT(option_values.blocksize >= 0 || option_values.mode_decode);
-
                if(option_values.format_channels >= 0) {
                        if(option_values.format_channels == 0 || (unsigned)option_values.format_channels > FLAC__MAX_CHANNELS)
                                return usage_error("ERROR: invalid number of channels '%u', must be > 0 and <= %u\n", option_values.format_channels, FLAC__MAX_CHANNELS);
@@ -383,12 +382,6 @@ int do_it()
                        if(option_values.format_sample_rate >= 0)
                                return usage_error("ERROR: --sample-rate not allowed with --decode\n");
                }
-               if(!option_values.mode_decode && ((unsigned)option_values.blocksize < FLAC__MIN_BLOCK_SIZE || (unsigned)option_values.blocksize > FLAC__MAX_BLOCK_SIZE)) {
-                       return usage_error("ERROR: invalid blocksize '%u', must be >= %u and <= %u\n", (unsigned)option_values.blocksize, FLAC__MIN_BLOCK_SIZE, FLAC__MAX_BLOCK_SIZE);
-               }
-               if(option_values.qlp_coeff_precision > 0 && option_values.qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION) {
-                       return usage_error("ERROR: invalid value '%u' for qlp coeff precision, must be 0 or >= %u\n", option_values.qlp_coeff_precision, FLAC__MIN_QLP_COEFF_PRECISION);
-               }
 
                if(option_values.sector_align) {
                        if(option_values.mode_decode)
@@ -420,7 +413,7 @@ int do_it()
                         * tags that we will set later, to avoid rewriting the
                         * whole file.
                         */
-                       if(option_values.padding < 0) {
+                       if(option_values.padding <= 0) {
                                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;
                        }
@@ -440,36 +433,10 @@ int do_it()
        }
 
        flac__utils_printf(stderr, 2, "\n");
-       flac__utils_printf(stderr, 2, "flac %s, Copyright (C) 2000,2001,2002,2003,2004 Josh Coalson\n", FLAC__VERSION_STRING);
+       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 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");
 
-       if(!option_values.mode_decode) {
-               char padopt[16];
-               if(option_values.padding < 0)
-                       strcpy(padopt, "-");
-               else
-                       sprintf(padopt, " %d", option_values.padding);
-               flac__utils_printf(stderr, 2,
-                       "options:%s%s%s%s -P%s -b %u%s -l %u%s%s%s -q %u -r %u,%u%s\n",
-                       option_values.delete_input?" --delete-input-file":"",
-                       option_values.sector_align?" --sector-align":"",
-                       option_values.use_ogg?" --ogg":"",
-                       option_values.lax?" --lax":"",
-                       padopt,
-                       (unsigned)option_values.blocksize,
-                       option_values.loose_mid_side?" -M":option_values.do_mid_side?" -m":"",
-                       option_values.max_lpc_order,
-                       option_values.do_exhaustive_model_search?" -e":"",
-                       option_values.do_escape_coding?" -E":"",
-                       option_values.do_qlp_coeff_prec_search?" -p":"",
-                       option_values.qlp_coeff_precision,
-                       (unsigned)option_values.min_residual_partition_order,
-                       (unsigned)option_values.max_residual_partition_order,
-                       option_values.verify? " -V":""
-               );
-       }
-
        if(option_values.mode_decode) {
                FLAC__bool first = true;
 
@@ -520,7 +487,7 @@ int do_it()
                                                return 2;
                                        }
                                        if(0 != (error = grabbag__replaygain_store_to_file_album(outfilename, album_gain, album_peak, /*preserve_modtime=*/true))) {
-                                               flac__utils_printf(stderr, 1, "%s: ERROR writing ReplayGain album tags\n", outfilename);
+                                               flac__utils_printf(stderr, 1, "%s: ERROR writing ReplayGain album tags (%s)\n", outfilename, error);
                                                retval = 1;
                                        }
                                }
@@ -531,12 +498,13 @@ int do_it()
        return retval;
 }
 
-FLAC__bool init_options()
+FLAC__bool init_options(void)
 {
        option_values.show_help = false;
        option_values.show_explain = false;
        option_values.mode_decode = false;
        option_values.verify = false;
+       option_values.treat_warnings_as_errors = false;
        option_values.force_file_overwrite = false;
        option_values.continue_through_decode_errors = false;
        option_values.replaygain_synthesis_spec.apply = false;
@@ -550,11 +518,6 @@ FLAC__bool init_options()
        option_values.use_ogg = false;
        option_values.has_serial_number = false;
        option_values.serial_number = 0;
-       option_values.do_mid_side = true;
-       option_values.loose_mid_side = false;
-       option_values.do_exhaustive_model_search = false;
-       option_values.do_escape_coding = false;
-       option_values.do_qlp_coeff_prec_search = false;
        option_values.force_to_stdout = false;
        option_values.force_aiff_format = false;
        option_values.force_raw_format = false;
@@ -565,9 +528,10 @@ FLAC__bool init_options()
        option_values.output_prefix = 0;
        option_values.aopts.do_residual_text = false;
        option_values.aopts.do_residual_gnuplot = false;
-       option_values.padding = 4096;
-       option_values.max_lpc_order = 8;
-       option_values.qlp_coeff_precision = 0;
+       option_values.padding = -1;
+       option_values.num_compression_settings = 1;
+       option_values.compression_settings[0].type = CST_COMPRESSION_LEVEL;
+       option_values.compression_settings[0].value.t_unsigned = 5;
        option_values.skip_specification = 0;
        option_values.until_specification = 0;
        option_values.cue_specification = 0;
@@ -576,21 +540,19 @@ FLAC__bool init_options()
        option_values.format_channels = -1;
        option_values.format_bps = -1;
        option_values.format_sample_rate = -1;
-       option_values.format_input_size = -1;
-       option_values.blocksize = -1;
-       option_values.min_residual_partition_order = -1;
-       option_values.max_residual_partition_order = -1;
-       option_values.rice_parameter_search_dist = -1;
+       option_values.format_input_size = (off_t)(-1);
        option_values.requested_seek_points[0] = '\0';
        option_values.num_requested_seek_points = -1;
        option_values.cuesheet_filename = 0;
        option_values.cued_seekpoints = true;
+       option_values.channel_map_none = false;;
 
        option_values.num_files = 0;
        option_values.filenames = 0;
 
        if(0 == (option_values.vorbis_comment = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT)))
                return false;
+       option_values.num_pictures = 0;
 
        option_values.debug.disable_constant_subframes = false;
        option_values.debug.disable_fixed_subframes = false;
@@ -604,7 +566,7 @@ int parse_options(int argc, char *argv[])
        int short_option;
        int option_index = 1;
        FLAC__bool had_error = false;
-       const char *short_opts = "0123456789ab:cdefFhHl:mMo:pP:q:r:sS:tT:vV";
+       const char *short_opts = "0123456789aA:b:cdefFhHl:mMo:pP:q:r:sS:tT:vVw";
 
        while ((short_option = share__getopt_long(argc, argv, short_opts, long_options_, &option_index)) != -1) {
                switch (short_option) {
@@ -631,7 +593,7 @@ int parse_options(int argc, char *argv[])
 
        if(option_values.num_files > 0) {
                unsigned i = 0;
-               if(0 == (option_values.filenames = malloc(sizeof(char *) * option_values.num_files)))
+               if(0 == (option_values.filenames = (char**)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++]);
@@ -642,7 +604,9 @@ 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);
@@ -666,7 +630,23 @@ int parse_option(int short_option, const char *long_option, const char *option_a
                }
                else if(0 == strcmp(long_option, "input-size")) {
                        FLAC__ASSERT(0 != option_argument);
-                       option_values.format_input_size = atol(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
+                               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 */
+                                       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);
+                       }
                }
                else if(0 == strcmp(long_option, "cue")) {
                        FLAC__ASSERT(0 != option_argument);
@@ -697,25 +677,32 @@ int parse_option(int short_option, const char *long_option, const char *option_a
                                }
                        }
                }
+               else if(0 == strcmp(long_option, "channel-map")) {
+                       if (0 == option_argument || strcmp(option_argument, "none"))
+                               return usage_error("ERROR: only --channel-map=none currently supported\n");
+                       option_values.channel_map_none = true;
+               }
                else if(0 == strcmp(long_option, "cuesheet")) {
                        FLAC__ASSERT(0 != option_argument);
                        option_values.cuesheet_filename = option_argument;
                }
+               else if(0 == strcmp(long_option, "picture")) {
+                       const unsigned max_pictures = sizeof(option_values.pictures)/sizeof(option_values.pictures[0]);
+                       FLAC__ASSERT(0 != option_argument);
+                       if(option_values.num_pictures >= max_pictures)
+                               return usage_error("ERROR: too many --picture arguments, only %u allowed\n", max_pictures);
+                       if(0 == (option_values.pictures[option_values.num_pictures] = grabbag__picture_parse_specification(option_argument, &violation)))
+                               return usage_error("ERROR: (--picture) %s\n", violation);
+                       option_values.num_pictures++;
+               }
+               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))
+                               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, "super-secret-totally-impractical-compression-level")) {
-                       option_values.lax = true;
-                       option_values.do_exhaustive_model_search = true;
-                       option_values.do_escape_coding = true;
-                       option_values.do_mid_side = true;
-                       option_values.loose_mid_side = false;
-                       option_values.do_qlp_coeff_prec_search = true;
-                       option_values.min_residual_partition_order = 0;
-                       option_values.max_residual_partition_order = 16;
-                       option_values.rice_parameter_search_dist = 0;
-                       option_values.max_lpc_order = 32;
-               }
                else if(0 == strcmp(long_option, "force-aiff-format")) {
                        option_values.force_aiff_format = true;
                }
@@ -731,7 +718,7 @@ int parse_option(int short_option, const char *long_option, const char *option_a
                else if(0 == strcmp(long_option, "sector-align")) {
                        option_values.sector_align = true;
                }
-#ifdef FLAC__HAS_OGG
+#if FLAC__HAS_OGG
                else if(0 == strcmp(long_option, "ogg")) {
                        option_values.use_ogg = true;
                }
@@ -804,29 +791,34 @@ int parse_option(int short_option, const char *long_option, const char *option_a
                else if(0 == strcmp(long_option, "no-lax")) {
                        option_values.lax = false;
                }
-#ifdef FLAC__HAS_OGG
+#if FLAC__HAS_OGG
                else if(0 == strcmp(long_option, "no-ogg")) {
                        option_values.use_ogg = false;
                }
 #endif
                else if(0 == strcmp(long_option, "no-exhaustive-model-search")) {
-                       option_values.do_exhaustive_model_search = false;
+                       add_compression_setting_bool(CST_DO_EXHAUSTIVE_MODEL_SEARCH, false);
                }
                else if(0 == strcmp(long_option, "no-mid-side")) {
-                       option_values.do_mid_side = option_values.loose_mid_side = false;
+                       add_compression_setting_bool(CST_DO_MID_SIDE, false);
+                       add_compression_setting_bool(CST_LOOSE_MID_SIDE, false);
                }
                else if(0 == strcmp(long_option, "no-adaptive-mid-side")) {
-                       option_values.loose_mid_side = option_values.do_mid_side = false;
+                       add_compression_setting_bool(CST_DO_MID_SIDE, false);
+                       add_compression_setting_bool(CST_LOOSE_MID_SIDE, false);
                }
                else if(0 == strcmp(long_option, "no-qlp-coeff-prec-search")) {
-                       option_values.do_qlp_coeff_prec_search = false;
+                       add_compression_setting_bool(CST_DO_QLP_COEFF_PREC_SEARCH, false);
                }
                else if(0 == strcmp(long_option, "no-padding")) {
-                       option_values.padding = -1;
+                       option_values.padding = 0;
                }
                else if(0 == strcmp(long_option, "no-verify")) {
                        option_values.verify = false;
                }
+               else if(0 == strcmp(long_option, "no-warnings-as-errors")) {
+                       option_values.treat_warnings_as_errors = false;
+               }
                else if(0 == strcmp(long_option, "no-residual-gnuplot")) {
                        option_values.aopts.do_residual_gnuplot = false;
                }
@@ -844,7 +836,6 @@ int parse_option(int short_option, const char *long_option, const char *option_a
                }
        }
        else {
-               const char *violation;
                switch(short_option) {
                        case 'h':
                                option_values.show_help = true;
@@ -884,170 +875,121 @@ 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, &violation))
+                               if(!flac__vorbiscomment_add(option_values.vorbis_comment, option_argument, /*value_from_file=*/false, &violation))
                                        return usage_error("ERROR: (-T/--tag) %s\n", violation);
                                break;
                        case '0':
-                               option_values.do_exhaustive_model_search = false;
-                               option_values.do_escape_coding = false;
-                               option_values.do_mid_side = false;
-                               option_values.loose_mid_side = false;
-                               option_values.qlp_coeff_precision = 0;
-                               option_values.min_residual_partition_order = option_values.max_residual_partition_order = 2;
-                               option_values.rice_parameter_search_dist = 0;
-                               option_values.max_lpc_order = 0;
-                               break;
                        case '1':
-                               option_values.do_exhaustive_model_search = false;
-                               option_values.do_escape_coding = false;
-                               option_values.do_mid_side = true;
-                               option_values.loose_mid_side = true;
-                               option_values.qlp_coeff_precision = 0;
-                               option_values.min_residual_partition_order = option_values.max_residual_partition_order = 2;
-                               option_values.rice_parameter_search_dist = 0;
-                               option_values.max_lpc_order = 0;
-                               break;
                        case '2':
-                               option_values.do_exhaustive_model_search = false;
-                               option_values.do_escape_coding = false;
-                               option_values.do_mid_side = true;
-                               option_values.loose_mid_side = false;
-                               option_values.qlp_coeff_precision = 0;
-                               option_values.min_residual_partition_order = 0;
-                               option_values.max_residual_partition_order = 3;
-                               option_values.rice_parameter_search_dist = 0;
-                               option_values.max_lpc_order = 0;
-                               break;
                        case '3':
-                               option_values.do_exhaustive_model_search = false;
-                               option_values.do_escape_coding = false;
-                               option_values.do_mid_side = false;
-                               option_values.loose_mid_side = false;
-                               option_values.qlp_coeff_precision = 0;
-                               option_values.min_residual_partition_order = option_values.max_residual_partition_order = 3;
-                               option_values.rice_parameter_search_dist = 0;
-                               option_values.max_lpc_order = 6;
-                               break;
                        case '4':
-                               option_values.do_exhaustive_model_search = false;
-                               option_values.do_escape_coding = false;
-                               option_values.do_mid_side = true;
-                               option_values.loose_mid_side = true;
-                               option_values.qlp_coeff_precision = 0;
-                               option_values.min_residual_partition_order = option_values.max_residual_partition_order = 3;
-                               option_values.rice_parameter_search_dist = 0;
-                               option_values.max_lpc_order = 8;
-                               break;
                        case '5':
-                               option_values.do_exhaustive_model_search = false;
-                               option_values.do_escape_coding = false;
-                               option_values.do_mid_side = true;
-                               option_values.loose_mid_side = false;
-                               option_values.qlp_coeff_precision = 0;
-                               option_values.min_residual_partition_order = option_values.max_residual_partition_order = 3;
-                               option_values.rice_parameter_search_dist = 0;
-                               option_values.max_lpc_order = 8;
-                               break;
                        case '6':
-                               option_values.do_exhaustive_model_search = false;
-                               option_values.do_escape_coding = false;
-                               option_values.do_mid_side = true;
-                               option_values.loose_mid_side = false;
-                               option_values.qlp_coeff_precision = 0;
-                               option_values.min_residual_partition_order = 0;
-                               option_values.max_residual_partition_order = 4;
-                               option_values.rice_parameter_search_dist = 0;
-                               option_values.max_lpc_order = 8;
-                               break;
                        case '7':
-                               option_values.do_exhaustive_model_search = true;
-                               option_values.do_escape_coding = false;
-                               option_values.do_mid_side = true;
-                               option_values.loose_mid_side = false;
-                               option_values.qlp_coeff_precision = 0;
-                               option_values.min_residual_partition_order = 0;
-                               option_values.max_residual_partition_order = 6;
-                               option_values.rice_parameter_search_dist = 0;
-                               option_values.max_lpc_order = 8;
-                               break;
                        case '8':
-                               option_values.do_exhaustive_model_search = true;
-                               option_values.do_escape_coding = false;
-                               option_values.do_mid_side = true;
-                               option_values.loose_mid_side = false;
-                               option_values.qlp_coeff_precision = 0;
-                               option_values.min_residual_partition_order = 0;
-                               option_values.max_residual_partition_order = 6;
-                               option_values.rice_parameter_search_dist = 0;
-                               option_values.max_lpc_order = 12;
+                               add_compression_setting_unsigned(CST_COMPRESSION_LEVEL, short_option-'0');
                                break;
                        case '9':
                                return usage_error("ERROR: compression level '9' is reserved\n");
                        case 'V':
                                option_values.verify = true;
                                break;
+                       case 'w':
+                               option_values.treat_warnings_as_errors = true;
+                               break;
                        case 'S':
                                FLAC__ASSERT(0 != option_argument);
-                               if(option_values.num_requested_seek_points < 0)
+                               if(0 == strcmp(option_argument, "-")) {
                                        option_values.num_requested_seek_points = 0;
-                               option_values.num_requested_seek_points++;
-                               if(strlen(option_values.requested_seek_points)+strlen(option_argument)+2 >= sizeof(option_values.requested_seek_points)) {
-                                       return usage_error("ERROR: too many seekpoints requested\n");
+                                       option_values.requested_seek_points[0] = '\0';
                                }
                                else {
-                                       strcat(option_values.requested_seek_points, option_argument);
-                                       strcat(option_values.requested_seek_points, ";");
+                                       if(option_values.num_requested_seek_points < 0)
+                                               option_values.num_requested_seek_points = 0;
+                                       option_values.num_requested_seek_points++;
+                                       if(strlen(option_values.requested_seek_points)+strlen(option_argument)+2 >= sizeof(option_values.requested_seek_points)) {
+                                               return usage_error("ERROR: too many seekpoints requested\n");
+                                       }
+                                       else {
+                                               strcat(option_values.requested_seek_points, option_argument);
+                                               strcat(option_values.requested_seek_points, ";");
+                                       }
                                }
                                break;
                        case 'P':
                                FLAC__ASSERT(0 != option_argument);
                                option_values.padding = atoi(option_argument);
                                if(option_values.padding < 0)
-                                       return usage_error("ERROR: argument to -P must be >= 0\n");
+                                       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);
-                               option_values.blocksize = atoi(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':
-                               option_values.do_exhaustive_model_search = true;
+                               add_compression_setting_bool(CST_DO_EXHAUSTIVE_MODEL_SEARCH, true);
                                break;
                        case 'E':
-                               option_values.do_escape_coding = true;
+                               add_compression_setting_bool(CST_DO_ESCAPE_CODING, true);
                                break;
                        case 'l':
                                FLAC__ASSERT(0 != option_argument);
-                               option_values.max_lpc_order = atoi(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);
+                               break;
+                       case 'A':
+                               FLAC__ASSERT(0 != option_argument);
+                               add_compression_setting_string(CST_APODIZATION, option_argument);
                                break;
                        case 'm':
-                               option_values.do_mid_side = true;
-                               option_values.loose_mid_side = false;
+                               add_compression_setting_bool(CST_DO_MID_SIDE, true);
+                               add_compression_setting_bool(CST_LOOSE_MID_SIDE, false);
                                break;
                        case 'M':
-                               option_values.loose_mid_side = option_values.do_mid_side = true;
+                               add_compression_setting_bool(CST_DO_MID_SIDE, true);
+                               add_compression_setting_bool(CST_LOOSE_MID_SIDE, true);
                                break;
                        case 'p':
-                               option_values.do_qlp_coeff_prec_search = true;
+                               add_compression_setting_bool(CST_DO_QLP_COEFF_PREC_SEARCH, true);
                                break;
                        case 'q':
                                FLAC__ASSERT(0 != option_argument);
-                               option_values.qlp_coeff_precision = atoi(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) {
-                                       option_values.min_residual_partition_order = 0;
-                                       option_values.max_residual_partition_order = atoi(option_argument);
+                                       add_compression_setting_unsigned(CST_MIN_RESIDUAL_PARTITION_ORDER, 0);
+                                       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);
                                }
                                else {
-                                       option_values.min_residual_partition_order = atoi(option_argument);
-                                       option_values.max_residual_partition_order = atoi(++p);
+                                       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':
-                               FLAC__ASSERT(0 != option_argument);
-                               option_values.rice_parameter_search_dist = atoi(option_argument);
+                               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);
                                break;
                        default:
                                FLAC__ASSERT(0);
@@ -1057,7 +999,7 @@ int parse_option(int short_option, const char *long_option, const char *option_a
        return 0;
 }
 
-void free_options()
+void free_options(void)
 {
        unsigned i;
        if(0 != option_values.filenames) {
@@ -1069,6 +1011,35 @@ void free_options()
        }
        if(0 != option_values.vorbis_comment)
                FLAC__metadata_object_delete(option_values.vorbis_comment);
+       for(i = 0; i < option_values.num_pictures; i++)
+               FLAC__metadata_object_delete(option_values.pictures[i]);
+}
+
+void add_compression_setting_bool(compression_setting_type_t type, FLAC__bool value)
+{
+       if(option_values.num_compression_settings >= sizeof(option_values.compression_settings)/sizeof(option_values.compression_settings[0]))
+               die("too many compression settings");
+       option_values.compression_settings[option_values.num_compression_settings].type = type;
+       option_values.compression_settings[option_values.num_compression_settings].value.t_bool = value;
+       option_values.num_compression_settings++;
+}
+
+void add_compression_setting_string(compression_setting_type_t type, const char *value)
+{
+       if(option_values.num_compression_settings >= sizeof(option_values.compression_settings)/sizeof(option_values.compression_settings[0]))
+               die("too many compression settings");
+       option_values.compression_settings[option_values.num_compression_settings].type = type;
+       option_values.compression_settings[option_values.num_compression_settings].value.t_string = value;
+       option_values.num_compression_settings++;
+}
+
+void add_compression_setting_unsigned(compression_setting_type_t type, unsigned value)
+{
+       if(option_values.num_compression_settings >= sizeof(option_values.compression_settings)/sizeof(option_values.compression_settings[0]))
+               die("too many compression settings");
+       option_values.compression_settings[option_values.num_compression_settings].type = type;
+       option_values.compression_settings[option_values.num_compression_settings].value.t_unsigned = value;
+       option_values.num_compression_settings++;
 }
 
 int usage_error(const char *message, ...)
@@ -1090,16 +1061,16 @@ int usage_error(const char *message, ...)
        return 1;
 }
 
-void show_version()
+void show_version(void)
 {
        printf("flac %s\n", FLAC__VERSION_STRING);
 }
 
-static void usage_header()
+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  Josh Coalson\n");
+       printf("Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  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");
@@ -1117,7 +1088,7 @@ static void usage_header()
        printf("===============================================================================\n");
 }
 
-static void usage_summary()
+static void usage_summary(void)
 {
        printf("Usage:\n");
        printf("\n");
@@ -1128,7 +1099,7 @@ static void usage_summary()
        printf("\n");
 }
 
-void short_usage()
+void short_usage(void)
 {
        usage_header();
        printf("\n");
@@ -1147,7 +1118,7 @@ void short_usage()
        printf("  flac -t [INPUTFILE [...]]\n");
 }
 
-void show_help()
+void show_help(void)
 {
        usage_header();
        usage_summary();
@@ -1161,13 +1132,14 @@ void show_help()
        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("  -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("      --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");
-#ifdef FLAC__HAS_OGG
+#if FLAC__HAS_OGG
        printf("      --ogg                    Use Ogg as transport layer\n");
        printf("      --serial-number          Serial number to use for the FLAC stream\n");
 #endif
@@ -1181,24 +1153,27 @@ void show_help()
        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("      --replay-gain            Calculate ReplayGain & store in Vorbis comments\n");
+       printf("      --replay-gain            Calculate ReplayGain & store in FLAC tags\n");
        printf("      --cuesheet=FILENAME      Import cuesheet and store in CUESHEET block\n");
-       printf("  -T, --tag=FIELD=VALUE        Add a Vorbis comment; may appear multiple times\n");
+       printf("      --picture=SPECIFICATION  Import picture and store in PICTURE block\n");
+       printf("  -T, --tag=FIELD=VALUE        Add a FLAC tag; may appear multiple times\n");
+       printf("      --tag-from-file=FIELD=FILENAME   Like --tag but gets value from file\n");
        printf("  -S, --seekpoint={#|X|#x|#s}  Add seek point(s)\n");
        printf("  -P, --padding=#              Write a PADDING block of length #\n");
-       printf("  -0, --compression-level-0, --fast  Synonymous with -l 0 -b 1152 -r 2,2\n");
-       printf("  -1, --compression-level-1          Synonymous with -l 0 -b 1152 -M -r 2,2\n");
+       printf("  -0, --compression-level-0, --fast  Synonymous with -l 0 -b 1152 -r 3\n");
+       printf("  -1, --compression-level-1          Synonymous with -l 0 -b 1152 -M -r 3\n");
        printf("  -2, --compression-level-2          Synonymous with -l 0 -b 1152 -m -r 3\n");
-       printf("  -3, --compression-level-3          Synonymous with -l 6 -b 4608 -r 3,3\n");
-       printf("  -4, --compression-level-4          Synonymous with -l 8 -b 4608 -M -r 3,3\n");
-       printf("  -5, --compression-level-5          Synonymous with -l 8 -b 4608 -m -r 3,3\n");
-       printf("  -6, --compression-level-6          Synonymous with -l 8 -b 4608 -m -r 4\n");
-       printf("  -7, --compression-level-7          Synonymous with -l 8 -b 4608 -m -e -r 6\n");
-       printf("  -8, --compression-level-8, --best  Synonymous with -l 12 -b 4608 -m -e -r 6\n");
+       printf("  -3, --compression-level-3          Synonymous with -l 6 -b 4096 -r 4\n");
+       printf("  -4, --compression-level-4          Synonymous with -l 8 -b 4096 -M -r 4\n");
+       printf("  -5, --compression-level-5          Synonymous with -l 8 -b 4096 -m -r 5\n");
+       printf("  -6, --compression-level-6          Synonymous with -l 8 -b 4096 -m -r 6\n");
+       printf("  -7, --compression-level-7          Synonymous with -l 8 -b 4096 -m -e -r 6\n");
+       printf("  -8, --compression-level-8, --best  Synonymous with -l 12 -b 4096 -m -e -r 6\n");
        printf("  -b, --blocksize=#                  Specify blocksize in samples\n");
        printf("  -m, --mid-side                     Try mid-side coding for each frame\n");
        printf("  -M, --adaptive-mid-side            Adaptive mid-side coding for all frames\n");
        printf("  -e, --exhaustive-model-search      Do exhaustive model search (expensive!)\n");
+       printf("  -A, --apodization=\"function\"       Window audio data with given the function\n");
        printf("  -l, --max-lpc-order=#              Max LPC order; 0 => only fixed predictors\n");
        printf("  -p, --qlp-coeff-precision-search   Exhaustively search LP coeff quantization\n");
        printf("  -q, --qlp-coeff-precision=#        Specify precision in bits\n");
@@ -1219,7 +1194,7 @@ void show_help()
        printf("      --no-exhaustive-model-search\n");
        printf("      --no-lax\n");
        printf("      --no-mid-side\n");
-#ifdef FLAC__HAS_OGG
+#if FLAC__HAS_OGG
        printf("      --no-ogg\n");
 #endif
        printf("      --no-padding\n");
@@ -1232,14 +1207,16 @@ void show_help()
        printf("      --no-silent\n");
        printf("      --no-force\n");
        printf("      --no-verify\n");
+       printf("      --no-warnings-as-errors\n");
 }
 
-void show_explain()
+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 file, or raw samples.\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 output file(s) will be in native FLAC or Ogg FLAC format\n");
        printf("For decoding, the reverse is true.\n");
        printf("\n");
@@ -1269,6 +1246,7 @@ void show_explain()
        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("  -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");
        printf("                               changes the extension.  May only be used when\n");
@@ -1296,7 +1274,7 @@ void show_explain()
        printf("                               relative to the --skip point.  If a `-' sign is\n");
        printf("                               at the beginning, the --until point is relative\n");
        printf("                               to end of the audio.\n");
-#ifdef FLAC__HAS_OGG
+#if FLAC__HAS_OGG
        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");
@@ -1308,9 +1286,10 @@ void show_explain()
        printf("                               '.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 '0'.  When decoding and no number is\n");
-       printf("                               given, flac uses the serial number of the first\n");
-       printf("                               page.\n");
+       printf("                               uses a random one.  If encoding to multiple files\n");
+       printf("                               the serial number is incremented for each file.\n");
+       printf("                               When decoding and no number is given, flac uses\n");
+       printf("                               the serial number of the first page.\n");
 #endif
        printf("analysis options:\n");
        printf("      --residual-text          Include residual signal in text output.  This\n");
@@ -1332,11 +1311,14 @@ void show_explain()
        printf("                               default is the beginning of the stream.  The\n");
        printf("                               optional second #.# is the track and index point\n");
        printf("                               at which decoding will end; the default is the\n");
-       printf("                               end of the stream.  If the seekpoint does not\n");
+       printf("                               end of the stream.  If the cuepoint does not\n");
        printf("                               exist, the closest one before it (for the start\n");
        printf("                               point) or after it (for the end point) will be\n");
        printf("                               used.  The cuepoints are merely translated into\n");
        printf("                               sample numbers then used as --skip and --until.\n");
+       printf("                               A CD track can always be cued by, for example,\n");
+       printf("                               --cue=9.1-10.1 for track 9, even if the CD has\n");
+       printf("                               no 10th track.\n");
        printf("encoding options:\n");
        printf("  -V, --verify                 Verify a correct encoding by decoding the\n");
        printf("                               output in parallel and comparing to the\n");
@@ -1344,8 +1326,8 @@ void show_explain()
        printf("      --lax                    Allow encoder to generate non-Subset files\n");
        printf("      --sector-align           Align encoding of multiple CD format WAVE files\n");
        printf("                               on sector boundaries.\n");
-       printf("      --replay-gain            Calculate ReplayGain values and store in Vorbis\n");
-       printf("                               comments.  Title gains/peaks will be computed\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");
        printf("                               computed for all files.  All input files must\n");
        printf("                               have the same resolution, sample rate, and\n");
@@ -1359,10 +1341,65 @@ void show_explain()
        printf("                               seekpoint will be added for each index point in\n");
        printf("                               the cuesheet to the SEEKTABLE unless\n");
        printf("                               --no-cued-seekpoints is specified.\n");
-       printf("  -T, --tag=FIELD=VALUE        Add a Vorbis comment.  Make sure to quote the\n");
+       printf("      --picture=SPECIFICATION  Import a picture and store it in a PICTURE block.\n");
+       printf("                               More than one --picture command can be specified.\n");
+       printf("                               The SPECIFICATION can either be a simple filename\n");
+       printf("                               for the picture file, or a complete specification\n");
+       printf("                               whose parts are separated by | characters.  Some\n");
+       printf("                               parts may be left empty to invoke default values.\n");
+       printf("                               Using a filename is shorthand for \"||||FILE\".\n");
+       printf("                               The SPECIFICATION format is:\n");
+       printf("         [TYPE]|[MIME-TYPE]|[DESCRIPTION]|[WIDTHxHEIGHTxDEPTH[/COLORS]]|FILE\n");
+       printf("           TYPE is optional; it is a number from one of:\n");
+       printf("              0: Other\n");
+       printf("              1: 32x32 pixels 'file icon' (PNG only)\n");
+       printf("              2: Other file icon\n");
+       printf("              3: Cover (front)\n");
+       printf("              4: Cover (back)\n");
+       printf("              5: Leaflet page\n");
+       printf("              6: Media (e.g. label side of CD)\n");
+       printf("              7: Lead artist/lead performer/soloist\n");
+       printf("              8: Artist/performer\n");
+       printf("              9: Conductor\n");
+       printf("             10: Band/Orchestra\n");
+       printf("             11: Composer\n");
+       printf("             12: Lyricist/text writer\n");
+       printf("             13: Recording Location\n");
+       printf("             14: During recording\n");
+       printf("             15: During performance\n");
+       printf("             16: Movie/video screen capture\n");
+       printf("             17: A bright coloured fish\n");
+       printf("             18: Illustration\n");
+       printf("             19: Band/artist logotype\n");
+       printf("             20: Publisher/Studio logotype\n");
+       printf("             The default is 3 (front cover).  There may only be one picture each\n");
+       printf("             of type 1 and 2 in a file.\n");
+       printf("           MIME-TYPE is optional; if left blank, it will be detected from the\n");
+       printf("             file.  For best compatibility with players, use pictures with MIME\n");
+       printf("             type image/jpeg or image/png.  The MIME type can also be --> to\n");
+       printf("             mean that FILE is actually a URL to an image, though this use is\n");
+       printf("             discouraged.\n");
+       printf("           DESCRIPTION is optional; the default is an empty string\n");
+       printf("           The next part specfies the resolution and color information.  If\n");
+       printf("             the MIME-TYPE is image/jpeg, image/png, or image/gif, you can\n");
+       printf("             usually leave this empty and they can be detected from the file.\n");
+       printf("             Otherwise, you must specify the width in pixels, height in pixels,\n");
+       printf("             and color depth in bits-per-pixel.  If the image has indexed colors\n");
+       printf("             you should also specify the number of colors used.\n");
+       printf("           FILE is the path to the picture file to be imported, or the URL if\n");
+       printf("             MIME type is -->\n");
+       printf("  -T, --tag=FIELD=VALUE        Add a FLAC tag.  Make sure to quote the\n");
        printf("                               comment if necessary.  This option may appear\n");
        printf("                               more than once to add several comments.  NOTE:\n");
        printf("                               all tags will be added to all encoded files.\n");
+       printf("      --tag-from-file=FIELD=FILENAME   Like --tag, except FILENAME is a file\n");
+       printf("                               whose contents will be read verbatim to set the\n");
+       printf("                               tag value.  The contents will be converted to\n");
+       printf("                               UTF-8 from the local charset.  This can be used\n");
+       printf("                               to store a cuesheet in a tag (e.g.\n");
+       printf("                               --tag-from-file=\"CUESHEET=image.cue\").  Do not\n");
+       printf("                               try to store binary data in tag fields!  Use\n");
+       printf("                               APPLICATION blocks for that.\n");
        printf("  -S, --seekpoint={#|X|#x|#s}  Include a point or points in a SEEKTABLE\n");
        printf("       #  : a specific sample number for a seek point\n");
        printf("       X  : a placeholder point (always goes at the end of the SEEKTABLE)\n");
@@ -1389,28 +1426,42 @@ void show_explain()
        printf("                               of the 4 metadata block header bytes.  You can\n");
        printf("                               force no PADDING block at all to be written with\n");
        printf("                               --no-padding.  The encoder writes a PADDING\n");
-       printf("                               block of 4096 bytes by default.\n");
+       printf("                               block of 8192 bytes by default, or 65536 bytes\n");
+       printf("                               if the input audio is more than 20 minutes long.\n");
        printf("  -b, --blocksize=#            Specify the blocksize in samples; the default is\n");
-       printf("                               1152 for -l 0, else 4608; must be one of 192,\n");
+       printf("                               1152 for -l 0, else 4096; must be one of 192,\n");
        printf("                               576, 1152, 2304, 4608, 256, 512, 1024, 2048,\n");
-       printf("                               4096, 8192, 16384, or 32768 (unless --lax is\n");
-       printf("                               used)\n");
-       printf("  -0, --compression-level-0, --fast  Synonymous with -l 0 -b 1152 -r 2,2\n");
-       printf("  -1, --compression-level-1          Synonymous with -l 0 -b 1152 -M -r 2,2\n");
+       printf("                               4096 (and 8192 or 16384 if the sample rate is\n");
+       printf("                               >48kHz) for Subset streams.\n");
+       printf("  -0, --compression-level-0, --fast  Synonymous with -l 0 -b 1152 -r 3\n");
+       printf("  -1, --compression-level-1          Synonymous with -l 0 -b 1152 -M -r 3\n");
        printf("  -2, --compression-level-2          Synonymous with -l 0 -b 1152 -m -r 3\n");
-       printf("  -3, --compression-level-3          Synonymous with -l 6 -b 4608 -r 3,3\n");
-       printf("  -4, --compression-level-4          Synonymous with -l 8 -b 4608 -M -r 3,3\n");
-       printf("  -5, --compression-level-5          Synonymous with -l 8 -b 4608 -m -r 3,3\n");
+       printf("  -3, --compression-level-3          Synonymous with -l 6 -b 4096 -r 4\n");
+       printf("  -4, --compression-level-4          Synonymous with -l 8 -b 4096 -M -r 4\n");
+       printf("  -5, --compression-level-5          Synonymous with -l 8 -b 4096 -m -r 5\n");
        printf("                                     -5 is the default setting\n");
-       printf("  -6, --compression-level-6          Synonymous with -l 8 -b 4608 -m -r 4\n");
-       printf("  -7, --compression-level-7          Synonymous with -l 8 -b 4608 -m -e -r 6\n");
-       printf("  -8, --compression-level-8, --best  Synonymous with -l 12 -b 4608 -m -e -r 6\n");
+       printf("  -6, --compression-level-6          Synonymous with -l 8 -b 4096 -m -r 6\n");
+       printf("  -7, --compression-level-7          Synonymous with -l 8 -b 4096 -m -e -r 6\n");
+       printf("  -8, --compression-level-8, --best  Synonymous with -l 12 -b 4096 -m -e -r 6\n");
        printf("  -m, --mid-side                     Try mid-side coding for each frame\n");
        printf("                                     (stereo only)\n");
        printf("  -M, --adaptive-mid-side            Adaptive mid-side coding for all frames\n");
        printf("                                     (stereo only)\n");
        printf("  -e, --exhaustive-model-search      Do exhaustive model search (expensive!)\n");
-       printf("  -l, --max-lpc-order=#              Max LPC order; 0 => only fixed predictors\n");
+       printf("  -A, --apodization=\"function\"       Window audio data with given the function.\n");
+       printf("                                     The functions are: bartlett, bartlett_hann,\n");
+       printf("                                     blackman, blackman_harris_4term_92db,\n");
+       printf("                                     connes, flattop, gauss(STDDEV), hamming,\n");
+       printf("                                     hann, kaiser_bessel, nuttall, rectangle,\n");
+       printf("                                     triangle, tukey(P), welch.  More than one\n");
+       printf("                                     may be specified but encoding time is a\n");
+       printf("                                     multiple of the number of functions since\n");
+       printf("                                     they are each tried in turn.  The encoder\n");
+       printf("                                     chooses suitable defaults in the absence\n");
+       printf("                                     of any -A options.\n");
+       printf("  -l, --max-lpc-order=#              Max LPC order; 0 => only fixed predictors.\n");
+       printf("                                     Must be <= 12 for Subset streams if sample\n");
+       printf("                                     rate is <=48kHz.\n");
        printf("  -p, --qlp-coeff-precision-search   Do exhaustive search of LP coefficient\n");
        printf("                                     quantization (expensive!); overrides -q;\n");
        printf("                                     does nothing if using -l 0\n");
@@ -1451,7 +1502,7 @@ void show_explain()
        printf("      --no-exhaustive-model-search\n");
        printf("      --no-lax\n");
        printf("      --no-mid-side\n");
-#ifdef FLAC__HAS_OGG
+#if FLAC__HAS_OGG
        printf("      --no-ogg\n");
 #endif
        printf("      --no-padding\n");
@@ -1463,11 +1514,14 @@ void show_explain()
        printf("      --no-silent\n");
        printf("      --no-force\n");
        printf("      --no-verify\n");
+       printf("      --no-warnings-as-errors\n");
 }
 
-void format_mistake(const char *infilename, const char *wrong, const char *right)
+void format_mistake(const char *infilename, FileFormat wrong, FileFormat right)
 {
-       flac__utils_printf(stderr, 1, "WARNING: %s is not a %s file; treating as a %s file\n", infilename, wrong, 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]);
 }
 
 int encode_file(const char *infilename, FLAC__bool is_first_file, FLAC__bool is_last_file)
@@ -1475,126 +1529,195 @@ 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;
+       FileFormat fmt = RAW;
+       FLAC__bool is_aifc = false;
        int retval;
-       long infilesize;
+       off_t infilesize;
        encode_options_t common_options;
-       const char *outfilename = get_encoded_outfilename(infilename);
+       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' */
 
        if(0 == outfilename) {
                flac__utils_printf(stderr, 1, "ERROR: filename too long: %s", infilename);
                return 1;
        }
 
-       /*
-        * 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 && grabbag__file_get_filesize(outfilename) != (off_t)(-1)) {
-               flac__utils_printf(stderr, 1, "ERROR: output file %s already exists, use -f to override\n", outfilename);
-               return 1;
-       }
-
        if(0 == strcmp(infilename, "-")) {
-               infilesize = -1;
+               infilesize = (off_t)(-1);
                encode_infile = grabbag__file_get_binary_stdin();
        }
        else {
                infilesize = grabbag__file_get_filesize(infilename);
                if(0 == (encode_infile = fopen(infilename, "rb"))) {
-                       flac__utils_printf(stderr, 1, "ERROR: can't open input file %s\n", infilename);
+                       flac__utils_printf(stderr, 1, "ERROR: can't open input file %s: %s\n", infilename, strerror(errno));
                        return 1;
                }
        }
 
        if(!option_values.force_raw_format) {
                /* first set format based on name */
-               if(strlen(infilename) >= 4 && 0 == strcasecmp(infilename+(strlen(infilename)-4), ".wav"))
+               if(strlen(infilename) >= 4 && 0 == FLAC__STRCASECMP(infilename+(strlen(infilename)-4), ".wav"))
                        fmt= WAV;
-               else if(strlen(infilename) >= 4 && 0 == strcasecmp(infilename+(strlen(infilename)-4), ".aif"))
+               else if(strlen(infilename) >= 4 && 0 == FLAC__STRCASECMP(infilename+(strlen(infilename)-4), ".aif"))
                        fmt= AIF;
-               else if(strlen(infilename) >= 5 && 0 == strcasecmp(infilename+(strlen(infilename)-5), ".aiff"))
+               else if(strlen(infilename) >= 5 && 0 == FLAC__STRCASECMP(infilename+(strlen(infilename)-5), ".aiff"))
                        fmt= AIF;
+               else if(strlen(infilename) >= 5 && 0 == FLAC__STRCASECMP(infilename+(strlen(infilename)-5), ".flac"))
+                       fmt= FLAC;
+               else if(strlen(infilename) >= 4 && 0 == FLAC__STRCASECMP(infilename+(strlen(infilename)-4), ".ogg"))
+                       fmt= 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 == AIF ? "AIFF" : "WAVE", "raw");
+                       if(fmt != RAW) {
+                               format_mistake(infilename, fmt, RAW);
+                               if(option_values.treat_warnings_as_errors) {
+                                       conditional_fclose(encode_infile);
+                                       return 1;
+                               }
+                       }
                        fmt= RAW;
                }
                else {
-                       if(!strncmp((const char *)lookahead, "RIFF", 4) && !strncmp((const char *)lookahead+8, "WAVE", 4))
+                       if(!strncmp((const char *)lookahead, "ID3", 3)) {
+                               flac__utils_printf(stderr, 1, "ERROR: input file %s has an ID3v2 tag\n", infilename);
+                               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, FLAC__STREAM_SYNC_STRING, sizeof(FLAC__STREAM_SYNC_STRING)))
+                               fmt= FLAC;
+                       /* this could be made more accurate by looking at the first packet */
+                       else if(!memcmp(lookahead, "OggS", 4))
+                               fmt= OGGFLAC;
                        else {
-                               if(fmt != RAW)
-                                       format_mistake(infilename, fmt == AIF ? "AIFF" : "WAVE", "raw");
+                               if(fmt != RAW) {
+                                       format_mistake(infilename, fmt, RAW);
+                                       if(option_values.treat_warnings_as_errors) {
+                                               conditional_fclose(encode_infile);
+                                               return 1;
+                                       }
+                               }
                                fmt= RAW;
                        }
                }
        }
 
-       if(option_values.format_input_size >= 0 && (fmt != RAW || infilesize >= 0)) {
-               flac__utils_printf(stderr, 1, "ERROR: can only use --input-size when encoding raw samples from stdin\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) {
+                       /* 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"
+                               "By default flac encodes files to FLAC format; if you meant to decode this file\n"
+                               "from FLAC to something else, use -d.  If you meant to re-encode this file from\n"
+                               "FLAC to FLAC again, use -f to force writing to the same file, or -o to specify\n"
+                               "a different output filename.\n",
+                               outfilename
+                       );
+               }
+               else if(fmt == 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"
+                               "By default 'flac -ogg' encodes files to Ogg FLAC format; if you meant to decode\n"
+                               "this file from Ogg FLAC to something else, use -d.  If you meant to re-encode\n"
+                               "this file from Ogg FLAC to Ogg FLAC again, use -f to force writing to the same\n"
+                               "file, or -o to specify a different output filename.\n",
+                               outfilename
+                       );
+               }
+               else
+                       flac__utils_printf(stderr, 1, "ERROR: output file %s already exists, use -f to override\n", outfilename);
+               conditional_fclose(encode_infile);
                return 1;
        }
-       else {
-               infilesize = option_values.format_input_size;
+
+       if(option_values.format_input_size >= 0) {
+               if (fmt != 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;
+               }
+               else {
+                       infilesize = option_values.format_input_size;
+               }
        }
 
+       if(option_values.sector_align && (fmt == FLAC || fmt == 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) {
-               flac__utils_printf(stderr, 1, "ERROR: can't --sector-align when the input size is unknown\n");
+               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(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)
+               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.replay_gain)
+               if(option_values.replay_gain) {
+                       conditional_fclose(encode_infile);
                        return usage_error("ERROR: --replay-gain cannot be used when encoding to stdout\n");
+               }
+       }
+       if(option_values.replay_gain && option_values.use_ogg) {
+               conditional_fclose(encode_infile);
+               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, &common_options.skip_specification) || common_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, &common_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;
 
        common_options.verify = option_values.verify;
-#ifdef FLAC__HAS_OGG
+       common_options.treat_warnings_as_errors = option_values.treat_warnings_as_errors;
+#if FLAC__HAS_OGG
        common_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) {
-               srand(time(0));
                option_values.serial_number = rand();
                option_values.has_serial_number = true;
        }
        common_options.serial_number = option_values.serial_number++;
 #endif
        common_options.lax = option_values.lax;
-       common_options.do_mid_side = option_values.do_mid_side;
-       common_options.loose_mid_side = option_values.loose_mid_side;
-       common_options.do_exhaustive_model_search = option_values.do_exhaustive_model_search;
-       common_options.do_escape_coding = option_values.do_escape_coding;
-       common_options.do_qlp_coeff_prec_search = option_values.do_qlp_coeff_prec_search;
-       common_options.min_residual_partition_order = option_values.min_residual_partition_order;
-       common_options.max_residual_partition_order = option_values.max_residual_partition_order;
-       common_options.rice_parameter_search_dist = option_values.rice_parameter_search_dist;
-       common_options.max_lpc_order = option_values.max_lpc_order;
-       common_options.blocksize = (unsigned)option_values.blocksize;
-       common_options.qlp_coeff_precision = option_values.qlp_coeff_precision;
        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;
@@ -1602,10 +1725,26 @@ int encode_file(const char *infilename, FLAC__bool is_first_file, FLAC__bool is_
        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;
 
+       /* 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";
+               /*@@@@ still a remote possibility that a file with this filename exists */
+               if(0 == (internal_outfilename = malloc(strlen(outfilename)+strlen(tmp_suffix)+1))) {
+                       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);
+       }
+
        if(fmt == RAW) {
                raw_encode_options_t options;
 
@@ -1616,7 +1755,14 @@ int encode_file(const char *infilename, FLAC__bool is_first_file, FLAC__bool is_
                options.bps = option_values.format_bps;
                options.sample_rate = option_values.format_sample_rate;
 
-               retval = flac__encode_raw(encode_infile, infilesize, infilename, outfilename, lookahead, lookahead_length, options);
+               retval = flac__encode_raw(encode_infile, infilesize, infilename, internal_outfilename? internal_outfilename : outfilename, lookahead, lookahead_length, options);
+       }
+       else if(fmt == FLAC || fmt == OGGFLAC) {
+               flac_encode_options_t options;
+
+               options.common = common_options;
+
+               retval = flac__encode_flac(encode_infile, infilesize, infilename, internal_outfilename? internal_outfilename : outfilename, lookahead, lookahead_length, options, fmt==OGGFLAC);
        }
        else {
                wav_encode_options_t options;
@@ -1624,27 +1770,56 @@ int encode_file(const char *infilename, FLAC__bool is_first_file, FLAC__bool is_
                options.common = common_options;
 
                if(fmt == AIF)
-                       retval = flac__encode_aif(encode_infile, infilesize, infilename, outfilename, lookahead, lookahead_length, options);
+                       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, outfilename, lookahead, lookahead_length, options);
+                       retval = flac__encode_wav(encode_infile, infilesize, infilename, internal_outfilename? internal_outfilename : outfilename, lookahead, lookahead_length, options);
        }
 
-       if(retval == 0 && strcmp(infilename, "-")) {
+       if(retval == 0) {
                if(strcmp(outfilename, "-")) {
                        if(option_values.replay_gain) {
                                float title_gain, title_peak;
                                const char *error;
                                grabbag__replaygain_get_title(&title_gain, &title_peak);
-                               if(0 != (error = grabbag__replaygain_store_to_file_title(outfilename, title_gain, title_peak, /*preserve_modtime=*/true))) {
-                                       flac__utils_printf(stderr, 1, "%s: ERROR writing ReplayGain title tags\n", outfilename);
+                               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))
+                               ) {
+                                       flac__utils_printf(stderr, 1, "%s: ERROR writing ReplayGain reference/title tags (%s)\n", outfilename, error);
                                }
                        }
-                       grabbag__file_copy_metadata(infilename, outfilename);
+                       if(strcmp(infilename, "-"))
+                               grabbag__file_copy_metadata(infilename, internal_outfilename? internal_outfilename : outfilename);
                }
-               if(option_values.delete_input)
-                       unlink(infilename);
        }
 
+       /* rename temporary file if necessary */
+       if(retval == 0 && internal_outfilename != 0) {
+               if(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) {
+                               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) {
+                               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;
+                       }
+#else
+                       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;
+#endif
+               }
+       }
+
+       /* 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);
+
+       if(internal_outfilename != 0)
+               free(internal_outfilename);
+
        return retval;
 }
 
@@ -1664,7 +1839,7 @@ 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 && 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) != (off_t)(-1)) {
                flac__utils_printf(stderr, 1, "ERROR: output file %s already exists, use -f to override\n", outfilename);
                return 1;
        }
@@ -1676,12 +1851,12 @@ int decode_file(const char *infilename)
 
        if(option_values.use_ogg)
                treat_as_ogg = true;
-       else if(strlen(infilename) >= 4 && 0 == strcasecmp(infilename+(strlen(infilename)-4), ".ogg"))
+       else if(strlen(infilename) >= 4 && 0 == FLAC__STRCASECMP(infilename+(strlen(infilename)-4), ".ogg"))
                treat_as_ogg = true;
        else
                treat_as_ogg = false;
 
-#ifndef FLAC__HAS_OGG
+#if !FLAC__HAS_OGG
        if(treat_as_ogg) {
                flac__utils_printf(stderr, 1, "%s: Ogg support has not been built into this copy of flac\n", infilename);
                return 1;
@@ -1705,13 +1880,15 @@ int decode_file(const char *infilename)
        else
                common_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;
-#ifdef FLAC__HAS_OGG
+#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;
 #endif
+       common_options.channel_map_none = option_values.channel_map_none;
 
        if(!option_values.force_raw_format) {
                wav_decode_options_t options;
@@ -1720,8 +1897,8 @@ int decode_file(const char *infilename)
 
                if(
                        option_values.force_aiff_format ||
-                       (strlen(outfilename) >= 4 && 0 == strcasecmp(outfilename+(strlen(outfilename)-4), ".aif")) ||
-                       (strlen(outfilename) >= 5 && 0 == strcasecmp(outfilename+(strlen(outfilename)-5), ".aiff"))
+                       (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
@@ -1785,19 +1962,13 @@ const char *get_outfilename(const char *infilename, const char *suffix)
                                return 0;
                        if (flac__strlcat(buffer, infilename, sizeof buffer) >= sizeof buffer)
                                return 0;
-                       if(0 == (p = strrchr(buffer, '.'))) {
+                       /* the . must come after any / to avoid problems with, e.g. "some.directory/extensionless-filename" */
+                       if(0 == (p = strrchr(buffer, '.')) || strchr(p, '/')) {
                                if (flac__strlcat(buffer, suffix, sizeof buffer) >= sizeof buffer)
                                        return 0;
                        }
                        else {
-                               if(0 == strcmp(p, suffix)) {
-                                       *p = '\0';
-                                       if (flac__strlcat(buffer, "_new", sizeof buffer) >= sizeof buffer)
-                                               return 0;
-                               }
-                               else {
-                                       *p = '\0';
-                               }
+                               *p = '\0';
                                if (flac__strlcat(buffer, suffix, sizeof buffer) >= sizeof buffer)
                                        return 0;
                        }
@@ -1815,6 +1986,14 @@ void die(const char *message)
        exit(1);
 }
 
+int conditional_fclose(FILE *f)
+{
+       if(f == 0 || f == stdin || f == stdout)
+               return 0;
+       else
+               return fclose(f);
+}
+
 char *local_strdup(const char *source)
 {
        char *ret;
@@ -1823,3 +2002,29 @@ 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