remove empty dir
[ghc-hetmet.git] / ghc / rts / RtsFlags.c
index f8b8e99..0f83b33 100644 (file)
@@ -1,5 +1,5 @@
+
 /* -----------------------------------------------------------------------------
- * $Id: RtsFlags.c,v 1.36 2001/01/24 15:41:30 simonmar Exp $
  *
  * (c) The AQUA Project, Glasgow University, 1994-1997
  * (c) The GHC Team, 1998-1999
 //@node Includes, Constants
 //@subsection Includes
 
+#include "PosixSource.h"
 #include "Rts.h"
 #include "RtsFlags.h"
 #include "RtsUtils.h"
 #include "BlockAlloc.h"
-#include "Itimer.h"            /* CS_MIN_MILLISECS */
+#include "Timer.h"             /* CS_MIN_MILLISECS */
 #include "Profiling.h"
 
-#if defined(PROFILING) 
-#include "Itimer.h"
-#endif
-
 #ifdef HAVE_CTYPE_H
 #include <ctype.h>
 #endif
 
-extern struct RTS_FLAGS RtsFlags;
+#include <stdlib.h>
+#include <string.h>
+
+// Flag Structure
+RTS_FLAGS RtsFlags;
 
 /*
  * Split argument lists
  */
-int     prog_argc; /* an "int" so as to match normal "argc" */
+int     prog_argc = 0;    /* an "int" so as to match normal "argc" */
 char  **prog_argv = NULL;
-int     rts_argc;  /* ditto */
+char   *prog_name = NULL; /* 'basename' of prog_argv[0] */
+int     rts_argc = 0;  /* ditto */
 char   *rts_argv[MAX_RTS_ARGS];
 
 //@node Constants, Static function decls, Includes
@@ -55,41 +57,9 @@ char   *rts_argv[MAX_RTS_ARGS];
 #define RTS 1
 #define PGM 0
 
-char *debug_opts_strs[] = {
-  "DEBUG (-D1): scheduler\n",
-  "DEBUG (-D2): evaluator\n",
-  "DEBUG (-D4): codegen\n",
-  "DEBUG (-D8): weak\n",
-  "DEBUG (-D16): gccafs\n",
-  "DEBUG (-D32): gc\n",
-  "DEBUG (-D64): block\n",
-  "DEBUG (-D128): sanity\n",
-  "DEBUG (-D256): stable\n",
-  "DEBUG (-D512): prof\n",
-  "DEBUG (-D1024): gran\n",
-  "DEBUG (-D2048): par\n",
-  "DEBUG (-D4096): linker\n"
-};
-
-char *debug_opts_prefix[] = {
-  "_-", /* scheduler */
-  "_.", /* evaluator */
-  "_,", /* codegen */
-  "_;", /* weak */
-  "_~", /* gccafs */
-  "_@", /* gc */
-  "_#", /* block */
-  "_&", /* sanity */
-  "_:", /* stable */
-  "_!", /* prof */
-  "_=", /* gran */
-  "_=" /* par */
-  "_*" /* linker */
-};
-
 #if defined(GRAN)
 
-char *gran_debug_opts_strs[] = {
+static char *gran_debug_opts_strs[] = {
   "DEBUG (-bDe, -bD1): event_trace; printing event trace.\n",
   "DEBUG (-bDE, -bD2): event_stats; printing event statistics.\n",
   "DEBUG (-bDb, -bD4): bq; check blocking queues\n",
@@ -108,34 +78,15 @@ char *gran_debug_opts_strs[] = {
 };
 
 /* one character codes for the available debug options */
-char gran_debug_opts_flags[] = {
+static char gran_debug_opts_flags[] = {
   'e', 'E', 'b', 'G', 'q', 'f', 'r', 'F', 'u', 'S', ':', 'o', 'z', 'P', 't'
 };
 
-/* prefix strings printed with the debug messages of the corresponding type */
-char *gran_debug_opts_prefix[] = {
-  "", /* event_trace */ 
-  "", /* event_stats */
-  "##", /* bq */
-  "**", /* pack */
-  "^^", /* checkSparkQ */
-  "==", /* thunkStealing */
-  "^^", /* randomSteal */
-  "+-", /* findWork */
-  "", /* unused */
-  "++", /* pri */
-  "::", /* checkLight */
-  "##", /* sortedQ */
-  "", /* blockOnFetch */
-  "", /* packBuffer */
-  "" /* blockOnFetch_sanity */
-};
-
 #elif defined(PAR)
 
-char *par_debug_opts_strs[] = {
+static char *par_debug_opts_strs[] = {
   "DEBUG (-qDv, -qD1): verbose; be generally verbose with parallel related stuff.\n",
-  "DEBUG (-qDt, -qD2): trace; trace messages.\n",
+  "DEBUG (-qDq, -qD2): bq; print blocking queues.\n",
   "DEBUG (-qDs, -qD4): schedule; scheduling of parallel threads.\n",
   "DEBUG (-qDe, -qD8): free; free messages.\n",
   "DEBUG (-qDr, -qD16): resume; resume messages.\n",
@@ -146,28 +97,13 @@ char *par_debug_opts_strs[] = {
   //"DEBUG (-qDo, -qD512): forward; forwarding messages to other PEs.\n",
   "DEBUG (-qDl, -qD256): tables; print internal LAGA etc tables.\n",
   "DEBUG (-qDo, -qD512): packet; packets and graph structures when packing.\n",
-  "DEBUG (-qDp, -qD1024): pack; packing and unpacking graphs.\n"
+  "DEBUG (-qDp, -qD1024): pack; packing and unpacking graphs.\n",
+  "DEBUG (-qDz, -qD2048): paranoia; ridiculously detailed output (excellent for filling a partition).\n"
 };
 
 /* one character codes for the available debug options */
-char par_debug_opts_flags[] = {
-  'v', 't', 's', 'e', 'r', 'w', 'F', 'f', 'l', 'o', 'p'  
-};
-
-/* prefix strings printed with the debug messages of the corresponding type */
-char *par_debug_opts_prefix[] = {
-  "  ", /* verbose */
-  "..", /* trace */
-  "--", /* schedule */
-  "!!", /* free */
-  "[]", /* resume */
-  ";;", /* weight */
-  "%%", /* fetch */
-  //",,", /* ack */
-  "$$", /* fish */
-  "", /* tables */
-  "**", /* packet */
-  "**" /* pack */
+static char par_debug_opts_flags[] = {
+  'v', 'q', 's', 'e', 'r', 'w', 'F', 'f', 'l', 'o', 'p', 'z'
 };
 
 #endif /* PAR */
@@ -179,12 +115,13 @@ char *par_debug_opts_prefix[] = {
    Static function decls
    -------------------------------------------------------------------------- */
 
-static FILE *          /* return NULL on error */
+static int             /* return NULL on error */
 open_stats_file (
     I_ arg,
     int argc, char *argv[],
     int rts_argc, char *rts_argv[],
-    const char *FILENAME_FMT);
+    const char *FILENAME_FMT,
+    FILE **file_ret);
 
 static I_ decode(const char *s);
 static void bad_option(const char *s);
@@ -199,10 +136,6 @@ static void process_par_option(int arg, int *rts_argc, char *rts_argv[], rtsBool
 static void set_par_debug_options(nat n);
 static void help_par_debug_options(nat n);
 #endif
-#if defined(DEBUG)
-static void set_debug_options(nat n);
-static void help_debug_options(nat n);
-#endif
 
 //@node Command-line option parsing routines, GranSim specific options, Static function decls
 //@subsection Command-line option parsing routines
@@ -216,42 +149,83 @@ void initRtsFlagsDefaults(void)
     RtsFlags.GcFlags.statsFile         = NULL;
     RtsFlags.GcFlags.giveStats         = NO_GC_STATS;
 
-    RtsFlags.GcFlags.maxStkSize                = (1024 * 1024) / sizeof(W_);
+    RtsFlags.GcFlags.maxStkSize                = (8 * 1024 * 1024) / sizeof(W_);
     RtsFlags.GcFlags.initialStkSize    = 1024 / sizeof(W_);
 
-    RtsFlags.GcFlags.minAllocAreaSize   = (256 * 1024)        / BLOCK_SIZE;
+    RtsFlags.GcFlags.minAllocAreaSize   = (512 * 1024)        / BLOCK_SIZE;
     RtsFlags.GcFlags.minOldGenSize      = (1024 * 1024)       / BLOCK_SIZE;
-    RtsFlags.GcFlags.maxHeapSize       = (64  * 1024 * 1024) / BLOCK_SIZE;
+    RtsFlags.GcFlags.maxHeapSize       = 0;    /* off by default */
     RtsFlags.GcFlags.heapSizeSuggestion        = 0;    /* none */
     RtsFlags.GcFlags.pcFreeHeap                = 3;    /* 3% */
     RtsFlags.GcFlags.oldGenFactor       = 2;
+#if defined(PAR)
+    /* A hack currently needed for GUM -- HWL */
+    RtsFlags.GcFlags.generations        = 1;
+    RtsFlags.GcFlags.steps              = 2;
+    RtsFlags.GcFlags.squeezeUpdFrames  = rtsFalse;
+#else
     RtsFlags.GcFlags.generations        = 2;
     RtsFlags.GcFlags.steps              = 2;
-
     RtsFlags.GcFlags.squeezeUpdFrames  = rtsTrue;
+#endif
+    RtsFlags.GcFlags.compact            = rtsFalse;
+    RtsFlags.GcFlags.compactThreshold   = 30.0;
 #ifdef RTS_GTK_FRONTPANEL
     RtsFlags.GcFlags.frontpanel         = rtsFalse;
 #endif
+    RtsFlags.GcFlags.idleGCDelayTicks   = 300 / TICK_MILLISECS; /* ticks */
+
+#ifdef DEBUG
+    RtsFlags.DebugFlags.scheduler      = rtsFalse;
+    RtsFlags.DebugFlags.interpreter    = rtsFalse;
+    RtsFlags.DebugFlags.codegen                = rtsFalse;
+    RtsFlags.DebugFlags.weak           = rtsFalse;
+    RtsFlags.DebugFlags.gccafs         = rtsFalse;
+    RtsFlags.DebugFlags.gc             = rtsFalse;
+    RtsFlags.DebugFlags.block_alloc    = rtsFalse;
+    RtsFlags.DebugFlags.sanity         = rtsFalse;
+    RtsFlags.DebugFlags.stable         = rtsFalse;
+    RtsFlags.DebugFlags.stm             = rtsFalse;
+    RtsFlags.DebugFlags.prof           = rtsFalse;
+    RtsFlags.DebugFlags.gran           = rtsFalse;
+    RtsFlags.DebugFlags.par            = rtsFalse;
+    RtsFlags.DebugFlags.linker         = rtsFalse;
+    RtsFlags.DebugFlags.squeeze                = rtsFalse;
+#endif
 
 #if defined(PROFILING) || defined(PAR)
     RtsFlags.CcFlags.doCostCentres     = 0;
 #endif /* PROFILING or PAR */
 
 #ifdef PROFILING
-    RtsFlags.ProfFlags.doHeapProfile = rtsFalse;
+    RtsFlags.ProfFlags.doHeapProfile      = rtsFalse;
+    RtsFlags.ProfFlags.profileInterval    = 100;
+    RtsFlags.ProfFlags.includeTSOs        = rtsFalse;
     RtsFlags.ProfFlags.showCCSOnException = rtsFalse;
+    RtsFlags.ProfFlags.maxRetainerSetSize = 8;
+    RtsFlags.ProfFlags.modSelector        = NULL;
+    RtsFlags.ProfFlags.descrSelector      = NULL;
+    RtsFlags.ProfFlags.typeSelector       = NULL;
+    RtsFlags.ProfFlags.ccSelector         = NULL;
+    RtsFlags.ProfFlags.ccsSelector        = NULL;
+    RtsFlags.ProfFlags.retainerSelector   = NULL;
+    RtsFlags.ProfFlags.bioSelector        = NULL;
+
 #elif defined(DEBUG)
-    RtsFlags.ProfFlags.doHeapProfile = rtsFalse;
+    RtsFlags.ProfFlags.doHeapProfile      = rtsFalse;
 #endif
 
     RtsFlags.ConcFlags.ctxtSwitchTime  = CS_MIN_MILLISECS;  /* In milliseconds */
 
-#ifdef SMP
+#ifdef THREADED_RTS
     RtsFlags.ParFlags.nNodes           = 1;
+    RtsFlags.ParFlags.migrate           = rtsTrue;
+    RtsFlags.ParFlags.wakeupMigrate     = rtsFalse;
 #endif
 
 #ifdef PAR
     RtsFlags.ParFlags.ParStats.Full      = rtsFalse;
+    RtsFlags.ParFlags.ParStats.Suppressed = rtsFalse;
     RtsFlags.ParFlags.ParStats.Binary    = rtsFalse;
     RtsFlags.ParFlags.ParStats.Sparks    = rtsFalse;
     RtsFlags.ParFlags.ParStats.Heap      = rtsFalse;
@@ -259,20 +233,26 @@ void initRtsFlagsDefaults(void)
     RtsFlags.ParFlags.ParStats.Global     = rtsFalse;
 
     RtsFlags.ParFlags.outputDisabled   = rtsFalse;
+#ifdef DIST
+    RtsFlags.ParFlags.doFairScheduling  = rtsTrue;  /* fair sched by def */
+#else
+    RtsFlags.ParFlags.doFairScheduling  = rtsFalse;  /* unfair sched by def */
+#endif
     RtsFlags.ParFlags.packBufferSize   = 1024;
-
+    RtsFlags.ParFlags.thunksToPack      = 1; /* 0 ... infinity; */
+    RtsFlags.ParFlags.globalising       = 1; /* 0 ... everything */
     RtsFlags.ParFlags.maxThreads        = 1024;
     RtsFlags.ParFlags.maxFishes        = MAX_FISHES;
     RtsFlags.ParFlags.fishDelay         = FISH_DELAY;
 #endif
 
-#if defined(PAR) || defined(SMP)
+#if defined(PAR) || defined(THREADED_RTS)
     RtsFlags.ParFlags.maxLocalSparks   = 4096;
-#endif /* PAR || SMP */
+#endif /* PAR || THREADED_RTS */
 
 #if defined(GRAN)
     /* ToDo: check defaults for GranSim and GUM */
-    RtsFlags.GcFlags.maxStkSize                = (1024 * 1024) / sizeof(W_);
+    RtsFlags.GcFlags.maxStkSize                = (8 * 1024 * 1024) / sizeof(W_);
     RtsFlags.GcFlags.initialStkSize    = 1024 / sizeof(W_);
 
     RtsFlags.GranFlags.maxThreads      = 65536; // refers to mandatory threads
@@ -358,15 +338,21 @@ usage_text[] = {
 "",
 "  -?       Prints this message and exits; the program is not executed",
 "",
-"  -K<size> Sets the maximum stack size (default 1M)  Egs: -K32k   -K512k",
-"  -k<size> Sets the initial thread stack size (default 1k)  Egs: -K4k   -K2m",
+"  -K<size> Sets the maximum stack size (default 8M)  Egs: -K32k   -K512k",
+"  -k<size> Sets the initial thread stack size (default 1k)  Egs: -k4k   -k2m",
 "",
 "  -A<size> Sets the minimum allocation area size (default 256k) Egs: -A1m -A10k",
-"  -M<size> Sets the maximum heap size (default 64M)  Egs: -M256k -M1G",
+"  -M<size> Sets the maximum heap size (default unlimited)  Egs: -M256k -M1G",
 "  -H<size> Sets the minimum heap size (default 0M)   Egs: -H24m  -H1G",
-"  -m<n>%   Minimum % of heap which must be available (default 3%)",
+"  -m<n>    Minimum % of heap which must be available (default 3%)",
 "  -G<n>    Number of generations (default: 2)",
 "  -T<n>    Number of steps in younger generations (default: 2)",
+"  -c<n>    Auto-enable compaction of the oldest generation when live data is",
+"           at least <n>% of the maximum heap size set with -M (default: 30%)",
+"  -c       Enable compaction for all major collections",
+#if defined(THREADED_RTS)
+"  -I<sec>  Perform full GC after <sec> idle time (default: 0.3, 0 == off)",
+#endif
 "",
 "  -t<file> One-line GC statistics  (default file: <program>.stat)",
 "  -s<file> Summary  GC statistics  (with -Sstderr going to stderr)",
@@ -381,15 +367,34 @@ usage_text[] = {
 #if defined(PROFILING) || defined(PAR)
 "",
 "  -px      Time/allocation profile (XML)  (output file <program>.prof)",
-"  -p<sort> Time/allocation profile        (output file <program>.prof)",
-"             sort: T = time (default), A = alloc, C = cost centre label",
-"  -P<sort> More detailed Time/Allocation profile"
+"  -p       Time/allocation profile        (output file <program>.prof)",
+"  -P       More detailed Time/Allocation profile",
+"  -Pa      Give information about *all* cost centres",
+
 # if defined(PROFILING)
 "",
-"  -hx            Heap residency profile (XML)  (output file <program>.prof)",
-"  -h<break-down> Heap residency profile (text) (output file <program>.prof)",
-"     break-down: C = cost centre stack (default), M = module",
-"                 D = closure description, Y = type description",
+"  -hx            Heap residency profile (XML)   (output file <program>.prof)",
+"  -h<break-down> Heap residency profile (hp2ps) (output file <program>.hp)",
+"     break-down: c = cost centre stack (default)",
+"                 m = module",
+"                 d = closure description",
+"                 y = type description",
+"                 r = retainer",
+"                 b = biography (LAG,DRAG,VOID,USE)",
+"  A subset of closures may be selected thusly:",
+"    -hc<cc>,...  specific cost centre(s) (top of stack only)",
+"    -hC<cc>,...  specific cost centre(s) (anywhere in stack)",
+"    -hm<mod>...  all cost centres from the specified modules(s)",
+"    -hd<des>,... closures with specified closure descriptions",
+"    -hy<typ>...  closures with specified type descriptions",
+"    -hr<cc>...   closures with specified retainers",
+"    -hb<bio>...  closures with specified biographies (lag,drag,void,use)",
+"",
+"  -R<size>       Set the maximum retainer set size (default: 8)",
+"",
+"  -i<sec>        Time between heap samples (seconds, default: 0.1)",
+"",
+"  -xt            Include threads (TSOs) in a heap profile",
 "",
 "  -xc      Show current cost centre stack on raising an exception",
 # endif
@@ -413,10 +418,31 @@ usage_text[] = {
 "  -C<secs>  Context-switch interval in seconds",
 "                (0 or no argument means switch as often as possible)",
 "                the default is .02 sec; resolution is .02 sec",
-#if defined(SMP)
+"",
+#if defined(DEBUG)
+"  -Ds  DEBUG: scheduler",
+"  -Di  DEBUG: interpreter",
+"  -Dc  DEBUG: codegen",
+"  -Dw  DEBUG: weak",
+"  -DG  DEBUG: gccafs",
+"  -Dg  DEBUG: gc",
+"  -Db  DEBUG: block",
+"  -DS  DEBUG: sanity",
+"  -Dt  DEBUG: stable",
+"  -Dp  DEBUG: prof",
+"  -Dr  DEBUG: gran",
+"  -DP  DEBUG: par",
+"  -Dl  DEBUG: linker",
+"  -Dm  DEBUG: stm",
+"  -Dz  DEBUG: stack squezing",
+"",
+#endif /* DEBUG */
+#if defined(THREADED_RTS)
 "  -N<n>     Use <n> OS threads (default: 1)",
+"  -qm       Don't automatically migrate threads between CPUs",
+"  -qw       Migrate a thread to the current CPU when it is woken up",
 #endif
-#if defined(SMP) || defined(PAR)
+#if defined(THREADED_RTS) || defined(PAR)
 "  -e<size>  Size of spark pools (default 100)",
 #endif
 #if defined(PAR)
@@ -426,7 +452,7 @@ usage_text[] = {
 "  -qd       Turn on PVM-ish debugging",
 "  -qO       Disable output for performance measurement",
 #endif
-#if defined(SMP) || defined(PAR)
+#if defined(THREADED_RTS) || defined(PAR)
 "  -e<n>     Maximum number of outstanding local sparks (default: 4096)",
 #endif
 #if defined(PAR)
@@ -437,42 +463,94 @@ usage_text[] = {
 "  -b...     All GranSim options start with -b; see GranSim User's Guide for details",
 #endif
 "",
+"RTS options may also be specified using the GHCRTS environment variable.",
+"",
 "Other RTS options may be available for programs compiled a different way.",
 "The GHC User's Guide has full details.",
 "",
 0
 };
 
-static __inline__ rtsBool
+STATIC_INLINE rtsBool
 strequal(const char *a, const char * b)
 {
     return(strcmp(a, b) == 0);
 }
 
+static void
+splitRtsFlags(char *s, int *rts_argc, char *rts_argv[])
+{
+    char *c1, *c2;
+
+    c1 = s;
+    do {
+       while (isspace(*c1)) { c1++; };
+       c2 = c1;
+       while (!isspace(*c2) && *c2 != '\0') { c2++; };
+       
+       if (c1 == c2) { break; }
+       
+       if (*rts_argc < MAX_RTS_ARGS-1) {
+           s = stgMallocBytes(c2-c1+1, "RtsFlags.c:splitRtsFlags()");
+           strncpy(s, c1, c2-c1);
+           s[c2-c1] = '\0';
+           rts_argv[(*rts_argc)++] = s;
+       } else {
+           barf("too many RTS arguments (max %d)", MAX_RTS_ARGS-1);
+       }
+       
+       c1 = c2;
+    } while (*c1 != '\0');
+}
+    
 void
 setupRtsFlags(int *argc, char *argv[], int *rts_argc, char *rts_argv[])
 {
     rtsBool error = rtsFalse;
     I_ mode;
     I_ arg, total_arg;
-    char *last_slash;
-
-    /* Remove directory from argv[0] -- default files in current directory */
-
-    if ((last_slash = (char *) strrchr(argv[0], '/')) != NULL)
-       strcpy(argv[0], last_slash+1);
-
-    /* Split arguments (argv) into PGM (argv) and RTS (rts_argv) parts */
-    /*   argv[0] must be PGM argument -- leave in argv                 */
 
+    setProgName (argv);
     total_arg = *argc;
     arg = 1;
 
     *argc = 1;
     *rts_argc = 0;
 
-    for (mode = PGM; arg < total_arg && ! strequal("--RTS", argv[arg]); arg++) {
-       if (strequal("+RTS", argv[arg])) {
+    // process arguments from the ghc_rts_opts global variable first.
+    // (arguments from the GHCRTS environment variable and the command
+    // line override these).
+    {
+       if (ghc_rts_opts != NULL) {
+           splitRtsFlags(ghc_rts_opts, rts_argc, rts_argv);
+       }
+    }
+
+    // process arguments from the GHCRTS environment variable next
+    // (arguments from the command line override these).
+    {
+       char *ghc_rts = getenv("GHCRTS");
+
+       if (ghc_rts != NULL) {
+           splitRtsFlags(ghc_rts, rts_argc, rts_argv);
+       }
+    }
+
+    // Split arguments (argv) into PGM (argv) and RTS (rts_argv) parts
+    //   argv[0] must be PGM argument -- leave in argv
+
+    for (mode = PGM; arg < total_arg; arg++) {
+       // The '--RTS' argument disables all future +RTS ... -RTS processing.
+       if (strequal("--RTS", argv[arg])) {
+           arg++;
+           break;
+       }
+       // The '--' argument is passed through to the program, but
+       // disables all further +RTS ... -RTS processing.
+       else if (strequal("--", argv[arg])) {
+           break;
+       }
+       else if (strequal("+RTS", argv[arg])) {
            mode = RTS;
        }
        else if (strequal("-RTS", argv[arg])) {
@@ -488,21 +566,18 @@ setupRtsFlags(int *argc, char *argv[], int *rts_argc, char *rts_argv[])
          barf("too many RTS arguments (max %d)", MAX_RTS_ARGS-1);
        }
     }
-    if (arg < total_arg) {
-       /* arg must be --RTS; process remaining program arguments */
-       while (++arg < total_arg) {
-           argv[(*argc)++] = argv[arg];
-       }
+    // process remaining program arguments
+    for (; arg < total_arg; arg++) {
+       argv[(*argc)++] = argv[arg];
     }
     argv[*argc] = (char *) 0;
     rts_argv[*rts_argc] = (char *) 0;
 
-    /* Process RTS (rts_argv) part: mainly to determine statsfile */
-
+    // Process RTS (rts_argv) part: mainly to determine statsfile
     for (arg = 0; arg < *rts_argc; arg++) {
        if (rts_argv[arg][0] != '-') {
            fflush(stdout);
-           prog_belch("unexpected RTS argument: %s", rts_argv[arg]);
+           errorBelch("unexpected RTS argument: %s", rts_argv[arg]);
            error = rtsTrue;
 
         } else {
@@ -520,7 +595,7 @@ setupRtsFlags(int *argc, char *argv[], int *rts_argc, char *rts_argv[])
 # define TICKY_BUILD_ONLY(x) x
 #else
 # define TICKY_BUILD_ONLY(x) \
-prog_belch("GHC not built for: ticky-ticky stats"); \
+errorBelch("not built for: ticky-ticky stats"); \
 error = rtsTrue;
 #endif
 
@@ -528,7 +603,7 @@ error = rtsTrue;
 # define COST_CENTRE_USING_BUILD_ONLY(x) x
 #else
 # define COST_CENTRE_USING_BUILD_ONLY(x) \
-prog_belch("GHC not built for: -prof or -parallel"); \
+errorBelch("not built for: -prof or -parallel"); \
 error = rtsTrue;
 #endif
 
@@ -536,31 +611,31 @@ error = rtsTrue;
 # define PROFILING_BUILD_ONLY(x)   x
 #else
 # define PROFILING_BUILD_ONLY(x) \
-prog_belch("GHC not built for: -prof"); \
+errorBelch("not built for: -prof"); \
 error = rtsTrue;
 #endif
 
-#ifdef SMP
-# define SMP_BUILD_ONLY(x)      x
+#ifdef PAR
+# define PAR_BUILD_ONLY(x)      x
 #else
-# define SMP_BUILD_ONLY(x) \
-prog_belch("GHC not built for: -parallel"); \
+# define PAR_BUILD_ONLY(x) \
+errorBelch("not built for: -parallel"); \
 error = rtsTrue;
 #endif
 
-#ifdef PAR
-# define PAR_BUILD_ONLY(x)      x
+#ifdef THREADED_RTS
+# define THREADED_BUILD_ONLY(x)      x
 #else
-# define PAR_BUILD_ONLY(x) \
-prog_belch("GHC not built for: -parallel"); \
+# define THREADED_BUILD_ONLY(x) \
+errorBelch("not built for: -smp"); \
 error = rtsTrue;
 #endif
 
-#if defined(SMP) || defined(PAR)
-# define PAR_OR_SMP_BUILD_ONLY(x)      x
+#if defined(THREADED_RTS) || defined(PAR)
+# define PAR_OR_THREADED_BUILD_ONLY(x)      x
 #else
-# define PAR_OR_SMP_BUILD_ONLY(x) \
-prog_belch("GHC not built for: -parallel or -smp"); \
+# define PAR_OR_THREADED_BUILD_ONLY(x) \
+errorBelch("not built for: -parallel or -smp"); \
 error = rtsTrue;
 #endif
 
@@ -568,7 +643,7 @@ error = rtsTrue;
 # define GRAN_BUILD_ONLY(x)     x
 #else
 # define GRAN_BUILD_ONLY(x) \
-prog_belch("GHC not built for: -gransim"); \
+errorBelch("not built for: -gransim"); \
 error = rtsTrue;
 #endif
 
@@ -589,6 +664,15 @@ error = rtsTrue;
                RtsFlags.GcFlags.ringBell = rtsTrue;
                break;
 
+             case 'c':
+                 if (rts_argv[arg][2] != '\0') {
+                     RtsFlags.GcFlags.compactThreshold =
+                         atof(rts_argv[arg]+2);
+                 } else {
+                     RtsFlags.GcFlags.compact = rtsTrue;
+                 }
+                 break;
+
              case 'F':
                RtsFlags.GcFlags.oldGenFactor = atof(rts_argv[arg]+2);
              
@@ -598,12 +682,65 @@ error = rtsTrue;
              
 #ifdef DEBUG
              case 'D':
-               if (isdigit(rts_argv[arg][2])) {/* Set all debugging options in one */
-               /* hack warning: interpret the flags as a binary number */
-                 nat n = decode(rts_argv[arg]+2);
-                 set_debug_options(n);
-               }
-               break;
+             { 
+                 char *c;
+
+                 for (c  = rts_argv[arg] + 2; *c != '\0'; c++) {
+                     switch (*c) {
+                     case 's':
+                         RtsFlags.DebugFlags.scheduler = rtsTrue;
+                         break;
+                     case 'i':
+                         RtsFlags.DebugFlags.interpreter = rtsTrue;
+                         break;
+                     case 'c':
+                         RtsFlags.DebugFlags.codegen = rtsTrue;
+                         break;
+                     case 'w':
+                         RtsFlags.DebugFlags.weak = rtsTrue;
+                         break;
+                     case 'G':
+                         RtsFlags.DebugFlags.gccafs = rtsTrue;
+                         break;
+                     case 'g':
+                         RtsFlags.DebugFlags.gc = rtsTrue;
+                         break;
+                     case 'b':
+                         RtsFlags.DebugFlags.block_alloc = rtsTrue;
+                         break;
+                     case 'S':
+                         RtsFlags.DebugFlags.sanity = rtsTrue;
+                         break;
+                     case 't':
+                         RtsFlags.DebugFlags.stable = rtsTrue;
+                         break;
+                     case 'p':
+                         RtsFlags.DebugFlags.prof = rtsTrue;
+                         break;
+                     case 'r':
+                         RtsFlags.DebugFlags.gran = rtsTrue;
+                         break;
+                     case 'P':
+                         RtsFlags.DebugFlags.par = rtsTrue;
+                         break;
+                     case 'l':
+                         RtsFlags.DebugFlags.linker = rtsTrue;
+                         break;
+                     case 'a':
+                         RtsFlags.DebugFlags.apply = rtsTrue;
+                         break;
+                     case 'm':
+                         RtsFlags.DebugFlags.stm = rtsTrue;
+                         break;
+                     case 'z':
+                         RtsFlags.DebugFlags.squeeze = rtsTrue;
+                         break;
+                     default:
+                         bad_option( rts_argv[arg] );
+                     }
+                 }
+                 break;
+             }
 #endif
 
              case 'K':
@@ -669,6 +806,23 @@ error = rtsTrue;
                  break;
 #endif
 
+             case 'I': /* idle GC delay */
+               if (rts_argv[arg][2] == '\0') {
+                 /* use default */
+               } else {
+                   I_ cst; /* tmp */
+
+                   /* Convert to ticks */
+                   cst = (I_) ((atof(rts_argv[arg]+2) * 1000));
+                   if (cst > 0 && cst < TICK_MILLISECS) {
+                       cst = TICK_MILLISECS;
+                   } else {
+                       cst = cst / TICK_MILLISECS;
+                   }
+                   RtsFlags.GcFlags.idleGCDelayTicks = cst;
+               }
+               break;
+
              case 'S':
                  RtsFlags.GcFlags.giveStats = VERBOSE_GC_STATS;
                  goto stats;
@@ -683,15 +837,17 @@ error = rtsTrue;
 
            stats:
 #ifdef PAR
-                 /* Opening all those files would almost certainly fail... */
-                 RtsFlags.ParFlags.ParStats.Full = rtsTrue;
-                 RtsFlags.GcFlags.statsFile = stderr; /* temporary; ToDo: rm */
+               /* Opening all those files would almost certainly fail... */
+               // RtsFlags.ParFlags.ParStats.Full = rtsTrue;
+               RtsFlags.GcFlags.statsFile = NULL; /* temporary; ToDo: rm */
 #else
-                 RtsFlags.GcFlags.statsFile
-                     = open_stats_file(arg, *argc, argv,
-                                       *rts_argc, rts_argv, STAT_FILENAME_FMT);
-                 
-                 if (RtsFlags.GcFlags.statsFile == NULL) error = rtsTrue;
+               { 
+                   int r;
+                   r = open_stats_file(arg, *argc, argv,
+                                       *rts_argc, rts_argv, STAT_FILENAME_FMT,
+                                       &RtsFlags.GcFlags.statsFile);
+                   if (r == -1) { error = rtsTrue; }
+               }
 #endif
                  break;
 
@@ -702,21 +858,32 @@ error = rtsTrue;
              /* =========== PROFILING ========================== */
 
              case 'P': /* detailed cost centre profiling (time/alloc) */
-               COST_CENTRE_USING_BUILD_ONLY(
-               RtsFlags.CcFlags.doCostCentres = COST_CENTRES_VERBOSE;
-               )
              case 'p': /* cost centre profiling (time/alloc) */
                COST_CENTRE_USING_BUILD_ONLY(
                switch (rts_argv[arg][2]) {
                  case 'x':
                    RtsFlags.CcFlags.doCostCentres = COST_CENTRES_XML;
                    break;
-                 default:
-                   RtsFlags.CcFlags.doCostCentres = COST_CENTRES_SUMMARY;
+                 case 'a':
+                   RtsFlags.CcFlags.doCostCentres = COST_CENTRES_ALL;
                    break;
+                 default:
+                     if (rts_argv[arg][1] == 'P') {
+                         RtsFlags.CcFlags.doCostCentres =
+                             COST_CENTRES_VERBOSE;
+                     } else {
+                         RtsFlags.CcFlags.doCostCentres =
+                             COST_CENTRES_SUMMARY;
+                     }
+                     break;
                }
                ) break;
 
+             case 'R':
+                 PROFILING_BUILD_ONLY(
+                     RtsFlags.ProfFlags.maxRetainerSetSize = atof(rts_argv[arg]+2);
+                 ) break;
+
              case 'h': /* serial heap profile */
 #if !defined(PROFILING) && defined(DEBUG)
                switch (rts_argv[arg][2]) {
@@ -728,32 +895,134 @@ error = rtsTrue;
                    RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_CLOSURE_TYPE;
                    break;
                  default:
-                   prog_belch("invalid heap profile option: %s",rts_argv[arg]);
+                   errorBelch("invalid heap profile option: %s",rts_argv[arg]);
                    error = rtsTrue;
                }
 #else
                PROFILING_BUILD_ONLY(
                switch (rts_argv[arg][2]) {
-                 case '\0':
-                 case CCchar:
-                   RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_CCS;
-                   break;
-                 case MODchar:
-                   RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_MOD;
-                   break;
-                 case DESCRchar:
-                   RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_DESCR;
-                   break;
-                 case TYPEchar:
-                   RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_TYPE;
+               case '\0':
+               case 'C':
+               case 'c':
+               case 'M':
+               case 'm':
+               case 'D':
+               case 'd':
+               case 'Y':
+               case 'y':
+               case 'R':
+               case 'r':
+               case 'B':
+               case 'b':
+                   if (rts_argv[arg][2] != '\0' && rts_argv[arg][3] != '\0') {
+                       {
+                           char *left  = strchr(rts_argv[arg], '{');
+                           char *right = strrchr(rts_argv[arg], '}');
+
+                           // curly braces are optional, for
+                           // backwards compat.
+                           if (left)
+                               left = left+1;
+                           else
+                               left = rts_argv[arg] + 3;
+
+                           if (!right)
+                               right = rts_argv[arg] + strlen(rts_argv[arg]);
+
+                           *right = '\0';
+
+                           switch (rts_argv[arg][2]) {
+                           case 'c': // cost centre label select
+                               RtsFlags.ProfFlags.ccSelector = left;
+                               break;
+                           case 'C':
+                               RtsFlags.ProfFlags.ccsSelector = left;
+                               break;
+                           case 'M':
+                           case 'm': // cost centre module select
+                               RtsFlags.ProfFlags.modSelector = left;
+                               break;
+                           case 'D':
+                           case 'd': // closure descr select 
+                               RtsFlags.ProfFlags.descrSelector = left;
+                               break;
+                           case 'Y':
+                           case 'y': // closure type select
+                               RtsFlags.ProfFlags.typeSelector = left;
+                               break;
+                           case 'R':
+                           case 'r': // retainer select
+                               RtsFlags.ProfFlags.retainerSelector = left;
+                               break;
+                           case 'B':
+                           case 'b': // biography select
+                               RtsFlags.ProfFlags.bioSelector = left;
+                               break;
+                           }
+                       }
+                       break;
+                   }
+
+                   if (RtsFlags.ProfFlags.doHeapProfile != 0) {
+                       errorBelch("multiple heap profile options");
+                       error = rtsTrue;
+                       break;
+                   }
+
+                   switch (rts_argv[arg][2]) {
+                   case '\0':
+                   case 'C':
+                   case 'c':
+                       RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_CCS;
+                       break;
+                   case 'M':
+                   case 'm':
+                         RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_MOD;
+                         break;
+                   case 'D':
+                   case 'd':
+                         RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_DESCR;
+                         break;
+                   case 'Y':
+                   case 'y':
+                         RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_TYPE;
+                         break;
+                   case 'R':
+                   case 'r':
+                         RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_RETAINER;
+                         break;
+                   case 'B':
+                   case 'b':
+                         RtsFlags.ProfFlags.doHeapProfile = HEAP_BY_LDV;
+                         break;
+                   }
                    break;
-                 default:
-                   prog_belch("invalid heap profile option: %s",rts_argv[arg]);
+                     
+               default:
+                   errorBelch("invalid heap profile option: %s",rts_argv[arg]);
                    error = rtsTrue;
                }
                ) 
+#endif /* PROFILING */
+               break;
+
+#if defined(PROFILING) 
+             case 'i': /* heap sample interval */
+               if (rts_argv[arg][2] == '\0') {
+                 /* use default */
+               } else {
+                   I_ cst; /* tmp */
+
+                   /* Convert to milliseconds */
+                   cst = (I_) ((atof(rts_argv[arg]+2) * 1000));
+                   cst = (cst / CS_MIN_MILLISECS) * CS_MIN_MILLISECS;
+                   if (cst != 0 && cst < CS_MIN_MILLISECS)
+                       cst = CS_MIN_MILLISECS;
+
+                   RtsFlags.ProfFlags.profileInterval = cst;
+               }
+               break;
 #endif
-               break;
 
              /* =========== CONCURRENT ========================= */
              case 'C': /* context switch interval */
@@ -772,42 +1041,63 @@ error = rtsTrue;
                }
                break;
 
-#ifdef SMP
+#ifdef THREADED_RTS
              case 'N':
-               SMP_BUILD_ONLY(
+               THREADED_BUILD_ONLY(
                if (rts_argv[arg][2] != '\0') {
                    RtsFlags.ParFlags.nNodes
                      = strtol(rts_argv[arg]+2, (char **) NULL, 10);
                    if (RtsFlags.ParFlags.nNodes <= 0) {
-                     prog_belch("bad value for -N");
+                     errorBelch("bad value for -N");
                      error = rtsTrue;
                    }
                }
                ) break;
+
+           case 'q':
+                   switch (rts_argv[arg][2]) {
+                   case '\0':
+                       errorBelch("incomplete RTS option: %s",rts_argv[arg]);
+                       error = rtsTrue;
+                       break;
+                   case 'm':
+                       RtsFlags.ParFlags.migrate = rtsFalse;
+                       break;
+                   case 'w':
+                       RtsFlags.ParFlags.wakeupMigrate = rtsTrue;
+                       break;
+                   default:
+                       errorBelch("unknown RTS option: %s",rts_argv[arg]);
+                       error = rtsTrue;
+                       break;
+                   }
+                   break;
 #endif
              /* =========== PARALLEL =========================== */
              case 'e':
-               PAR_OR_SMP_BUILD_ONLY(
+               PAR_OR_THREADED_BUILD_ONLY(
                if (rts_argv[arg][2] != '\0') {
                    RtsFlags.ParFlags.maxLocalSparks
                      = strtol(rts_argv[arg]+2, (char **) NULL, 10);
                    if (RtsFlags.ParFlags.maxLocalSparks <= 0) {
-                     prog_belch("bad value for -e");
+                     errorBelch("bad value for -e");
                      error = rtsTrue;
                    }
                }
                ) break;
 
+#ifdef PAR
              case 'q':
                PAR_BUILD_ONLY(
-               process_par_option(arg, rts_argc, rts_argv, &error);
+                 process_par_option(arg, rts_argc, rts_argv, &error);
                ) break;
+#endif
 
              /* =========== GRAN =============================== */
 
              case 'b':
                GRAN_BUILD_ONLY(
-               process_gran_option(arg, rts_argc, rts_argv, &error);
+                 process_gran_option(arg, rts_argc, rts_argv, &error);
                ) break;
 
              /* =========== TICKY ============================== */
@@ -816,11 +1106,14 @@ error = rtsTrue;
                TICKY_BUILD_ONLY(
 
                RtsFlags.TickyFlags.showTickyStats = rtsTrue;
-               RtsFlags.TickyFlags.tickyFile
-                 = open_stats_file(arg, *argc, argv,
-                       *rts_argc, rts_argv, TICKY_FILENAME_FMT);
 
-               if (RtsFlags.TickyFlags.tickyFile == NULL) error = rtsTrue;
+               { 
+                   int r;
+                   r = open_stats_file(arg, *argc, argv,
+                                       *rts_argc, rts_argv, TICKY_FILENAME_FMT,
+                                       &RtsFlags.TickyFlags.tickyFile);
+                   if (r == -1) { error = rtsTrue; }
+               }
                ) break;
 
              /* =========== EXTENDED OPTIONS =================== */
@@ -828,19 +1121,26 @@ error = rtsTrue;
               case 'x': /* Extend the argument space */
                 switch(rts_argv[arg][2]) {
                   case '\0':
-                   prog_belch("incomplete RTS option: %s",rts_argv[arg]);
+                   errorBelch("incomplete RTS option: %s",rts_argv[arg]);
                    error = rtsTrue;
                    break;
 
                   case 'c': /* Debugging tool: show current cost centre on an exception */
                     PROFILING_BUILD_ONLY(
-                    RtsFlags.ProfFlags.showCCSOnException = rtsTrue;
-                    ) break;
+                       RtsFlags.ProfFlags.showCCSOnException = rtsTrue;
+                       );
+                   break;
+
+               case 't':  /* Include memory used by TSOs in a heap profile */
+                   PROFILING_BUILD_ONLY(
+                       RtsFlags.ProfFlags.includeTSOs = rtsTrue;
+                       );
+                   break;
 
                   /* The option prefix '-xx' is reserved for future extension.  KSW 1999-11. */
 
                  default:
-                   prog_belch("unknown RTS option: %s",rts_argv[arg]);
+                   errorBelch("unknown RTS option: %s",rts_argv[arg]);
                    error = rtsTrue;
                    break;
                 }
@@ -848,7 +1148,7 @@ error = rtsTrue;
 
              /* =========== OH DEAR ============================ */
              default:
-               prog_belch("unknown RTS option: %s",rts_argv[arg]);
+               errorBelch("unknown RTS option: %s",rts_argv[arg]);
                error = rtsTrue;
                break;
            }
@@ -859,7 +1159,7 @@ error = rtsTrue;
 
         fflush(stdout);
        for (p = usage_text; *p; p++)
-           belch("%s", *p);
+           errorBelch("%s", *p);
        stg_exit(EXIT_FAILURE);
     }
 }
@@ -872,7 +1172,7 @@ error = rtsTrue;
 static void
 enable_GranSimLight(void) {
 
-    fprintf(stderr,"GrAnSim Light enabled (infinite number of processors;  0 communication costs)\n");
+    debugBelch("GrAnSim Light enabled (infinite number of processors;  0 communication costs)\n");
     RtsFlags.GranFlags.Light=rtsTrue;
     RtsFlags.GranFlags.Costs.latency = 
        RtsFlags.GranFlags.Costs.fetchtime = 
@@ -1132,7 +1432,7 @@ process_gran_option(int arg, int *rts_argc, char *rts_argv[], rtsBool *error)
            RtsFlags.GranFlags.Costs.pri_spark_overhead = decode(rts_argv[arg]+3);
          else
            RtsFlags.GranFlags.Costs.pri_spark_overhead = PRI_SPARK_OVERHEAD;
-         fprintf(stderr,"Overhead for pri spark: %d (per elem).\n",
+         debugBelch("Overhead for pri spark: %d (per elem).\n",
                         RtsFlags.GranFlags.Costs.pri_spark_overhead);
          break;
 
@@ -1141,7 +1441,7 @@ process_gran_option(int arg, int *rts_argc, char *rts_argv[], rtsBool *error)
            RtsFlags.GranFlags.Costs.pri_sched_overhead = decode(rts_argv[arg]+3);
          else
            RtsFlags.GranFlags.Costs.pri_sched_overhead = PRI_SCHED_OVERHEAD;
-         fprintf(stderr,"Overhead for pri sched: %d (per elem).\n",
+         debugBelch("Overhead for pri sched: %d (per elem).\n",
                       RtsFlags.GranFlags.Costs.pri_sched_overhead);
          break;
 
@@ -1155,8 +1455,7 @@ process_gran_option(int arg, int *rts_argc, char *rts_argv[], rtsBool *error)
              } else if (RtsFlags.GranFlags.proc > MAX_PROC || 
                         RtsFlags.GranFlags.proc < 1)
                {
-                 fprintf(stderr,"setupRtsFlags: no more than %u processors
-allowed\n", 
+                 debugBelch("setupRtsFlags: no more than %u processors allowed\n",
                          MAX_PROC);
                  *error = rtsTrue;
                }
@@ -1186,22 +1485,22 @@ allowed\n",
          break;
 
         case 'G':
-         fprintf(stderr,"Bulk fetching enabled.\n");
+         debugBelch("Bulk fetching enabled.\n");
          RtsFlags.GranFlags.DoBulkFetching=rtsTrue;
          break;
          
         case 'M':
-         fprintf(stderr,"Thread migration enabled.\n");
+         debugBelch("Thread migration enabled.\n");
          RtsFlags.GranFlags.DoThreadMigration=rtsTrue;
          break;
 
         case 'R':
-         fprintf(stderr,"Fair Scheduling enabled.\n");
+         debugBelch("Fair Scheduling enabled.\n");
          RtsFlags.GranFlags.DoFairSchedule=rtsTrue;
          break;
          
         case 'I':
-         fprintf(stderr,"Priority Scheduling enabled.\n");
+         debugBelch("Priority Scheduling enabled.\n");
          RtsFlags.GranFlags.DoPriorityScheduling=rtsTrue;
          break;
 
@@ -1262,18 +1561,18 @@ allowed\n",
            arg0 = rts_argv[arg]+3;
            if ((tmp = strstr(arg0,","))==NULL) {
              RtsFlags.GranFlags.SparkPriority = decode(arg0);
-             fprintf(stderr,"SparkPriority: %u.\n",RtsFlags.GranFlags.SparkPriority);
+             debugBelch("SparkPriority: %u.\n",RtsFlags.GranFlags.SparkPriority);
            } else {
              *(tmp++) = '\0'; 
              RtsFlags.GranFlags.SparkPriority = decode(arg0);
              RtsFlags.GranFlags.SparkPriority2 = decode(tmp);
-             fprintf(stderr,"SparkPriority: %u.\n",
+             debugBelch("SparkPriority: %u.\n",
                      RtsFlags.GranFlags.SparkPriority);
-             fprintf(stderr,"SparkPriority2:%u.\n",
+             debugBelch("SparkPriority2:%u.\n",
                      RtsFlags.GranFlags.SparkPriority2);
              if (RtsFlags.GranFlags.SparkPriority2 < 
                  RtsFlags.GranFlags.SparkPriority) {
-               fprintf(stderr,"WARNING: 2nd pri < main pri (%u<%u); 2nd pri has no effect\n",
+               debugBelch("WARNING: 2nd pri < main pri (%u<%u); 2nd pri has no effect\n",
                        RtsFlags.GranFlags.SparkPriority2,
                        RtsFlags.GranFlags.SparkPriority);
              }
@@ -1281,7 +1580,7 @@ allowed\n",
          } else {
            /* plain pri spark is now invoked with -bX  
               RtsFlags.GranFlags.DoPrioritySparking = 1;
-              fprintf(stderr,"PrioritySparking.\n");
+              debugBelch("PrioritySparking.\n");
            */
          }
          break;
@@ -1292,13 +1591,13 @@ allowed\n",
          } else {
            RtsFlags.GranFlags.ThunksToPack = 1;
          }
-         fprintf(stderr,"Thunks To Pack in one packet: %u.\n",
+         debugBelch("Thunks To Pack in one packet: %u.\n",
                  RtsFlags.GranFlags.ThunksToPack);
          break;
                      
         case 'e':
          RtsFlags.GranFlags.RandomSteal = rtsFalse;
-         fprintf(stderr,"Deterministic mode (no random stealing)\n");
+         debugBelch("Deterministic mode (no random stealing)\n");
                      break;
 
          /* The following class of options contains eXperimental */
@@ -1312,7 +1611,7 @@ allowed\n",
          } else {
            RtsFlags.GranFlags.packBufferSize_internal = GRANSIM_DEFAULT_PACK_BUFFER_SIZE;
          }
-         fprintf(stderr,"Size of GranSim internal pack buffer: %u.\n",
+         debugBelch("Size of GranSim internal pack buffer: %u.\n",
                  RtsFlags.GranFlags.packBufferSize_internal);
          break;
                      
@@ -1321,7 +1620,7 @@ allowed\n",
            
            case '\0':
              RtsFlags.GranFlags.DoPrioritySparking = 1;
-             fprintf(stderr,"Priority Sparking with Normal Priorities.\n");
+             debugBelch("Priority Sparking with Normal Priorities.\n");
              RtsFlags.GranFlags.InversePriorities = rtsFalse; 
              RtsFlags.GranFlags.RandomPriorities = rtsFalse;
              RtsFlags.GranFlags.IgnorePriorities = rtsFalse;
@@ -1329,19 +1628,19 @@ allowed\n",
                        
            case 'I':
              RtsFlags.GranFlags.DoPrioritySparking = 1;
-             fprintf(stderr,"Priority Sparking with Inverse Priorities.\n");
+             debugBelch("Priority Sparking with Inverse Priorities.\n");
              RtsFlags.GranFlags.InversePriorities++; 
              break;
              
            case 'R': 
              RtsFlags.GranFlags.DoPrioritySparking = 1;
-             fprintf(stderr,"Priority Sparking with Random Priorities.\n");
+             debugBelch("Priority Sparking with Random Priorities.\n");
              RtsFlags.GranFlags.RandomPriorities++;
              break;
              
            case 'N':
              RtsFlags.GranFlags.DoPrioritySparking = 1;
-             fprintf(stderr,"Priority Sparking with No Priorities.\n");
+             debugBelch("Priority Sparking with No Priorities.\n");
              RtsFlags.GranFlags.IgnorePriorities++;
              break;
              
@@ -1429,10 +1728,10 @@ allowed\n",
            case 'Q':    /* Set pack buffer size (same as 'Q' in GUM) */
              if (rts_argv[arg][4] != '\0') {
                RtsFlags.GranFlags.packBufferSize = decode(rts_argv[arg]+4);
-               fprintf(stderr,"Pack buffer size: %d\n",
+               debugBelch("Pack buffer size: %d\n",
                        RtsFlags.GranFlags.packBufferSize);
              } else {
-               fprintf(stderr, "setupRtsFlags: missing size of PackBuffer (for -Q)\n");
+               debugBelch("setupRtsFlags: missing size of PackBuffer (for -Q)\n");
                *error = rtsTrue;
              }
              break;
@@ -1449,7 +1748,7 @@ allowed\n",
                    break;
                
                if (i==MAX_GRAN_DEBUG_OPTION+1) {
-                 fprintf(stderr, "Valid GranSim debug options are:\n");
+                 debugBelch("Valid GranSim debug options are:\n");
                  help_GranSim_debug_options(MAX_GRAN_DEBUG_MASK);
                  bad_option( rts_argv[arg] );
                } else { // flag found; now set it
@@ -1460,92 +1759,92 @@ allowed\n",
              
 #if 0
            case 'e':       /* event trace; also -bD1 */
-             fprintf(stderr,"DEBUG: event_trace; printing event trace.\n");
+             debugBelch("DEBUG: event_trace; printing event trace.\n");
              RtsFlags.GranFlags.Debug.event_trace = rtsTrue;
              /* RtsFlags.GranFlags.event_trace=rtsTrue; */
              break;
              
            case 'E':       /* event statistics; also -bD2 */
-             fprintf(stderr,"DEBUG: event_stats; printing event statistics.\n");
+             debugBelch("DEBUG: event_stats; printing event statistics.\n");
              RtsFlags.GranFlags.Debug.event_stats = rtsTrue;
              /* RtsFlags.GranFlags.Debug |= 0x20; print event statistics   */
              break;
              
            case 'f':       /* thunkStealing; also -bD4 */
-             fprintf(stderr,"DEBUG: thunkStealing; printing forwarding of FETCHNODES.\n");
+             debugBelch("DEBUG: thunkStealing; printing forwarding of FETCHNODES.\n");
              RtsFlags.GranFlags.Debug.thunkStealing = rtsTrue;
              /* RtsFlags.GranFlags.Debug |= 0x2;  print fwd messages */
              break;
 
            case 'z':       /* blockOnFetch; also -bD8 */
-             fprintf(stderr,"DEBUG: blockOnFetch; check for blocked on fetch.\n");
+             debugBelch("DEBUG: blockOnFetch; check for blocked on fetch.\n");
              RtsFlags.GranFlags.Debug.blockOnFetch = rtsTrue;
              /* RtsFlags.GranFlags.Debug |= 0x4; debug non-reschedule-on-fetch */
              break;
              
            case 't':       /* blockOnFetch_sanity; also -bD16 */  
-             fprintf(stderr,"DEBUG: blockOnFetch_sanity; check for TSO asleep on fetch.\n");
+             debugBelch("DEBUG: blockOnFetch_sanity; check for TSO asleep on fetch.\n");
              RtsFlags.GranFlags.Debug.blockOnFetch_sanity = rtsTrue;
              /* RtsFlags.GranFlags.Debug |= 0x10; debug TSO asleep for fetch  */
              break;
 
            case 'S':       /* priSpark; also -bD32 */
-             fprintf(stderr,"DEBUG: priSpark; priority sparking.\n");
+             debugBelch("DEBUG: priSpark; priority sparking.\n");
              RtsFlags.GranFlags.Debug.priSpark = rtsTrue;
              break;
 
            case 's':       /* priSched; also -bD64 */
-             fprintf(stderr,"DEBUG: priSched; priority scheduling.\n");
+             debugBelch("DEBUG: priSched; priority scheduling.\n");
              RtsFlags.GranFlags.Debug.priSched = rtsTrue;
              break;
 
            case 'F':       /* findWork; also -bD128 */
-             fprintf(stderr,"DEBUG: findWork; searching spark-pools (local & remote), thread queues for work.\n");
+             debugBelch("DEBUG: findWork; searching spark-pools (local & remote), thread queues for work.\n");
              RtsFlags.GranFlags.Debug.findWork = rtsTrue;
              break;
              
            case 'g':       /* globalBlock; also -bD256 */
-             fprintf(stderr,"DEBUG: globalBlock; blocking on remote closures (FETCHMEs etc in GUM).\n");
+             debugBelch("DEBUG: globalBlock; blocking on remote closures (FETCHMEs etc in GUM).\n");
              RtsFlags.GranFlags.Debug.globalBlock = rtsTrue;
              break;
              
            case 'G':       /* pack; also -bD512 */
-             fprintf(stderr,"DEBUG: pack; routines for (un-)packing graph structures.\n");
+             debugBelch("DEBUG: pack; routines for (un-)packing graph structures.\n");
              RtsFlags.GranFlags.Debug.pack = rtsTrue;
              break;
              
            case 'P':       /* packBuffer; also -bD1024 */
-             fprintf(stderr,"DEBUG: packBuffer; routines handling pack buffer (GranSim internal!).\n");
+             debugBelch("DEBUG: packBuffer; routines handling pack buffer (GranSim internal!).\n");
              RtsFlags.GranFlags.Debug.packBuffer = rtsTrue;
              break;
              
            case 'o':       /* sortedQ; also -bD2048 */
-             fprintf(stderr,"DEBUG: sortedQ; check whether spark/thread queues are sorted.\n");
+             debugBelch("DEBUG: sortedQ; check whether spark/thread queues are sorted.\n");
              RtsFlags.GranFlags.Debug.sortedQ = rtsTrue;
              break;
              
            case 'r':       /* randomSteal; also -bD4096 */
-             fprintf(stderr,"DEBUG: randomSteal; stealing sparks/threads from random PEs.\n");
+             debugBelch("DEBUG: randomSteal; stealing sparks/threads from random PEs.\n");
              RtsFlags.GranFlags.Debug.randomSteal = rtsTrue;
              break;
              
            case 'q':       /* checkSparkQ; also -bD8192 */
-             fprintf(stderr,"DEBUG: checkSparkQ; check consistency of the spark queues.\n");
+             debugBelch("DEBUG: checkSparkQ; check consistency of the spark queues.\n");
              RtsFlags.GranFlags.Debug.checkSparkQ = rtsTrue;
              break;
              
            case ':':       /* checkLight; also -bD16384 */
-             fprintf(stderr,"DEBUG: checkLight; check GranSim-Light setup.\n");
+             debugBelch("DEBUG: checkLight; check GranSim-Light setup.\n");
              RtsFlags.GranFlags.Debug.checkLight = rtsTrue;
              break;
              
            case 'b':       /* bq; also -bD32768 */
-             fprintf(stderr,"DEBUG: bq; check blocking queues\n");
+             debugBelch("DEBUG: bq; check blocking queues\n");
              RtsFlags.GranFlags.Debug.bq = rtsTrue;
              break;
              
            case 'd':       /* all options turned on */
-             fprintf(stderr,"DEBUG: all options turned on.\n");
+             debugBelch("DEBUG: all options turned on.\n");
              set_GranSim_debug_options(MAX_GRAN_DEBUG_MASK);
              /* RtsFlags.GranFlags.Debug |= 0x40; */
              break;
@@ -1574,7 +1873,7 @@ set_GranSim_debug_options(nat n) {
 
   for (i=0; i<=MAX_GRAN_DEBUG_OPTION; i++) 
     if ((n>>i)&1) {
-      fprintf(stderr, gran_debug_opts_strs[i]);
+      errorBelch(gran_debug_opts_strs[i]);
       switch (i) {
         case 0: RtsFlags.GranFlags.Debug.event_trace   = rtsTrue;  break;
         case 1: RtsFlags.GranFlags.Debug.event_stats   = rtsTrue;  break;
@@ -1606,7 +1905,7 @@ help_GranSim_debug_options(nat n) {
 
   for (i=0; i<=MAX_GRAN_DEBUG_OPTION; i++) 
     if ((n>>i)&1) 
-      fprintf(stderr, gran_debug_opts_strs[i]);
+      debugBelch(gran_debug_opts_strs[i]);
 }
 
 # elif defined(PAR)
@@ -1614,9 +1913,12 @@ help_GranSim_debug_options(nat n) {
 static void
 process_par_option(int arg, int *rts_argc, char *rts_argv[], rtsBool *error)
 {
-  if (rts_argv[arg][1] != 'q') /* All GUM options start with -q */
+
+  if (rts_argv[arg][1] != 'q') { /* All GUM options start with -q */
+    errorBelch("Warning: GUM option does not start with -q: %s", rts_argv[arg]);
     return;
-  
+  }
+
   /* Communication and task creation cost parameters */
   switch(rts_argv[arg][2]) {
   case 'e':  /* -qe<n>  ... allow <n> local sparks */
@@ -1625,12 +1927,12 @@ process_par_option(int arg, int *rts_argc, char *rts_argv[], rtsBool *error)
        = strtol(rts_argv[arg]+3, (char **) NULL, 10);
       
       if (RtsFlags.ParFlags.maxLocalSparks <= 0) {
-       belch("setupRtsFlags: bad value for -e\n");
+       errorBelch("setupRtsFlags: bad value for -e\n");
        *error = rtsTrue;
       }
     }
     IF_PAR_DEBUG(verbose,
-                belch("-qe<n>: max %d local sparks", 
+                errorBelch("-qe<n>: max %d local sparks", 
                       RtsFlags.ParFlags.maxLocalSparks));
     break;
   
@@ -1639,11 +1941,11 @@ process_par_option(int arg, int *rts_argc, char *rts_argv[], rtsBool *error)
       RtsFlags.ParFlags.maxThreads
        = strtol(rts_argv[arg]+3, (char **) NULL, 10);
     } else {
-      belch("setupRtsFlags: missing size for -qt\n");
+      errorBelch("missing size for -qt\n");
       *error = rtsTrue;
     }
     IF_PAR_DEBUG(verbose,
-                belch("-qt<n>: max %d threads", 
+                errorBelch("-qt<n>: max %d threads", 
                       RtsFlags.ParFlags.maxThreads));
     break;
 
@@ -1654,37 +1956,62 @@ process_par_option(int arg, int *rts_argc, char *rts_argv[], rtsBool *error)
       RtsFlags.ParFlags.maxFishes = MAX_FISHES;
     break;
     IF_PAR_DEBUG(verbose,
-                belch("-qf<n>: max %d fishes sent out at one time", 
+                errorBelch("-qf<n>: max %d fishes sent out at one time", 
                       RtsFlags.ParFlags.maxFishes));
     break;
   
-
-  case 'd':
+  case 'F':
     if (rts_argv[arg][3] != '\0') {
       RtsFlags.ParFlags.fishDelay
        = strtol(rts_argv[arg]+3, (char **) NULL, 10);
     } else {
-      belch("setupRtsFlags: missing fish delay time for -qd\n");
+      errorBelch("missing fish delay time for -qF\n");
       *error = rtsTrue;
     }
     IF_PAR_DEBUG(verbose,
-                belch("-qd<n>: fish delay time %d", 
+                errorBelch("-qF<n>: fish delay time %d us", 
                       RtsFlags.ParFlags.fishDelay));
     break;
 
   case 'O':
     RtsFlags.ParFlags.outputDisabled = rtsTrue;
     IF_PAR_DEBUG(verbose,
-                belch("-qO: output disabled"));
+                errorBelch("-qO: output disabled"));
     break;
   
+  case 'g': /* -qg<n> ... globalisation scheme */
+    if (rts_argv[arg][3] != '\0') {
+      RtsFlags.ParFlags.globalising = decode(rts_argv[arg]+3);
+    } else {
+      errorBelch("missing identifier for globalisation scheme (for -qg)\n");
+      *error = rtsTrue;
+    }
+    IF_PAR_DEBUG(verbose,
+                debugBelch("-qg<n>: globalisation scheme set to  %d", 
+                      RtsFlags.ParFlags.globalising));
+    break;
+
+  case 'h': /* -qh<n> ... max number of thunks (except root) in packet */
+    if (rts_argv[arg][3] != '\0') {
+      RtsFlags.ParFlags.thunksToPack = decode(rts_argv[arg]+3);
+    } else {
+      errorBelch("missing number of thunks per packet (for -qh)\n");
+      *error = rtsTrue;
+    }
+    IF_PAR_DEBUG(verbose,
+                debugBelch("-qh<n>: thunks per packet set to %d", 
+                      RtsFlags.ParFlags.thunksToPack));
+    break;
+
   case 'P': /* -qP for writing a log file */
-    RtsFlags.ParFlags.ParStats.Full = rtsTrue;
+    //RtsFlags.ParFlags.ParStats.Full = rtsFalse;
     /* same encoding as in GranSim after -bP */        
     switch(rts_argv[arg][3]) {
-    case '\0': break; // nothing special, just an ordinary profile
-      //case '0': RtsFlags.ParFlags.ParStats.Suppressed = rtsTrue;
-      //  break;
+    case '\0': RtsFlags.ParFlags.ParStats.Full = rtsTrue;
+      break; // nothing special, just an ordinary profile
+    case '0': RtsFlags.ParFlags.ParStats.Suppressed = rtsTrue;
+       RtsFlags.ParFlags.ParStats.Full = rtsFalse;
+      break;
     case 'b': RtsFlags.ParFlags.ParStats.Binary = rtsTrue;
       break;
     case 's': RtsFlags.ParFlags.ParStats.Sparks = rtsTrue;
@@ -1693,12 +2020,18 @@ process_par_option(int arg, int *rts_argc, char *rts_argv[], rtsBool *error)
       //  break;
     case 'n': RtsFlags.ParFlags.ParStats.NewLogfile = rtsTrue;
       break;
-    case 'g': RtsFlags.ParFlags.ParStats.Global = rtsTrue;
+    case 'g': 
+# if defined(PAR_TICKY)
+      RtsFlags.ParFlags.ParStats.Global = rtsTrue;
+# else 
+      errorBelch("-qPg is only possible for a PAR_TICKY RTS, which this is not");
+      stg_exit(EXIT_FAILURE);
+# endif
       break;
     default: barf("Unknown option -qP%c", rts_argv[arg][2]);
     }
     IF_PAR_DEBUG(verbose,
-                belch("(-qP) writing to log-file (RtsFlags.ParFlags.ParStats.Full=%s)",
+                debugBelch("(-qP) writing to log-file (RtsFlags.ParFlags.ParStats.Full=%s)",
                       (RtsFlags.ParFlags.ParStats.Full ? "rtsTrue" : "rtsFalse")));
     break;
   
@@ -1706,14 +2039,20 @@ process_par_option(int arg, int *rts_argc, char *rts_argv[], rtsBool *error)
     if (rts_argv[arg][3] != '\0') {
       RtsFlags.ParFlags.packBufferSize = decode(rts_argv[arg]+3);
     } else {
-      belch("setupRtsFlags: missing size of PackBuffer (for -Q)\n");
-      error = rtsTrue;
+      errorBelch("missing size of PackBuffer (for -qQ)\n");
+      *error = rtsTrue;
     }
     IF_PAR_DEBUG(verbose,
-                belch("-qQ<n>: pack buffer size set to %d", 
+                debugBelch("-qQ<n>: pack buffer size set to %d", 
                       RtsFlags.ParFlags.packBufferSize));
     break;
 
+  case 'R':
+    RtsFlags.ParFlags.doFairScheduling = rtsTrue;
+    IF_PAR_DEBUG(verbose,
+                debugBelch("-qR: fair-ish scheduling"));
+    break;
+  
 # if defined(DEBUG)  
   case 'w':
     if (rts_argv[arg][3] != '\0') {
@@ -1723,7 +2062,7 @@ process_par_option(int arg, int *rts_argc, char *rts_argv[], rtsBool *error)
       RtsFlags.ParFlags.wait = 1000;
     }
     IF_PAR_DEBUG(verbose,
-                belch("-qw<n>: length of wait loop after synchr before reduction: %d", 
+                debugBelch("-qw<n>: length of wait loop after synchr before reduction: %d", 
                       RtsFlags.ParFlags.wait));
     break;
 
@@ -1739,7 +2078,7 @@ process_par_option(int arg, int *rts_argc, char *rts_argv[], rtsBool *error)
          break;
        
       if (i==MAX_PAR_DEBUG_OPTION+1) {
-       fprintf(stderr, "Valid GUM debug options are:\n");
+       errorBelch("Valid GUM debug options are:\n");
        help_par_debug_options(MAX_PAR_DEBUG_MASK);
        bad_option( rts_argv[arg] );
       } else { // flag found; now set it
@@ -1749,7 +2088,8 @@ process_par_option(int arg, int *rts_argc, char *rts_argv[], rtsBool *error)
     break;
 # endif
   default:
-    belch("Unknown option -q%c", rts_argv[arg][2]);
+    errorBelch("Unknown option -q%c (%d opts in total)", 
+         rts_argv[arg][2], *rts_argc);
     break;
   } /* switch */
 }
@@ -1764,10 +2104,10 @@ set_par_debug_options(nat n) {
 
   for (i=0; i<=MAX_PAR_DEBUG_OPTION; i++) 
     if ((n>>i)&1) {
-      fprintf(stderr, par_debug_opts_strs[i]);
+      debugBelch(par_debug_opts_strs[i]);
       switch (i) {
         case 0: RtsFlags.ParFlags.Debug.verbose       = rtsTrue;  break;
-        case 1: RtsFlags.ParFlags.Debug.trace         = rtsTrue;  break;
+        case 1: RtsFlags.ParFlags.Debug.bq            = rtsTrue;  break;
         case 2: RtsFlags.ParFlags.Debug.schedule      = rtsTrue;  break;
         case 3: RtsFlags.ParFlags.Debug.free          = rtsTrue;  break;
         case 4: RtsFlags.ParFlags.Debug.resume        = rtsTrue;  break;
@@ -1777,8 +2117,10 @@ set_par_debug_options(nat n) {
         case 7: RtsFlags.ParFlags.Debug.fish          = rtsTrue;  break;
         case 8: RtsFlags.ParFlags.Debug.tables        = rtsTrue;  break;
         case 9: RtsFlags.ParFlags.Debug.packet        = rtsTrue;  break;
-        case 10: RtsFlags.ParFlags.Debug.pack          = rtsTrue;  break;
-        default: barf("set_par_debug_options: only %d debug options expected");
+        case 10: RtsFlags.ParFlags.Debug.pack         = rtsTrue;  break;
+        case 11: RtsFlags.ParFlags.Debug.paranoia     = rtsTrue;  break;
+        default: barf("set_par_debug_options: only %d debug options expected",
+                     MAX_PAR_DEBUG_OPTION);
       } /* switch */
     } /* if */
 }
@@ -1793,84 +2135,70 @@ help_par_debug_options(nat n) {
 
   for (i=0; i<=MAX_PAR_DEBUG_OPTION; i++) 
     if ((n>>i)&1) 
-      fprintf(stderr, par_debug_opts_strs[i]);
+      debugBelch(par_debug_opts_strs[i]);
 }
 
 #endif /* PAR */
 
-#ifdef DEBUG
-static void
-set_debug_options(nat n) {
-  nat i;
-
-  for (i=0; i<=MAX_DEBUG_OPTION; i++) 
-    if ((n>>i)&1) {
-      fprintf(stderr, debug_opts_strs[i]);
-      switch (i) {
-        case 0:  RtsFlags.DebugFlags.scheduler   = rtsTrue; break;
-        case 1:  RtsFlags.DebugFlags.evaluator   = rtsTrue; break;
-        case 2:  RtsFlags.DebugFlags.codegen     = rtsTrue; break;
-        case 3:  RtsFlags.DebugFlags.weak        = rtsTrue; break;
-        case 4:  RtsFlags.DebugFlags.gccafs      = rtsTrue; break;
-        case 5:  RtsFlags.DebugFlags.gc          = rtsTrue; break;
-        case 6:  RtsFlags.DebugFlags.block_alloc = rtsTrue; break;
-        case 7:  RtsFlags.DebugFlags.sanity      = rtsTrue; break;
-        case 8:  RtsFlags.DebugFlags.stable      = rtsTrue; break;
-        case 9:  RtsFlags.DebugFlags.prof        = rtsTrue; break;
-        case 10: RtsFlags.DebugFlags.gran        = rtsTrue; break;
-        case 11: RtsFlags.DebugFlags.par         = rtsTrue; break;
-        case 12: RtsFlags.DebugFlags.linker      = rtsTrue; break;
-      } /* switch */
-    } /* if */
-}
+//@node Aux fcts,  , GranSim specific options
+//@subsection Aux fcts
 
 static void
-help_debug_options(nat n) {
-  nat i;
-
-  for (i=0; i<=MAX_DEBUG_OPTION; i++) 
-    if ((n>>i)&1) 
-      fprintf(stderr, debug_opts_strs[i]);
+stats_fprintf(FILE *f, char *s, ...)
+{
+    va_list ap;
+    va_start(ap,s);
+    if (f == NULL) {
+       vdebugBelch(s, ap);
+    } else {
+       vfprintf(f, s, ap);
+    }
+    va_end(ap);
 }
-#endif /* DEBUG */
-
-//@node Aux fcts,  , GranSim specific options
-//@subsection Aux fcts
 
-static FILE *          /* return NULL on error */
+static int             /* return -1 on error */
 open_stats_file (
     I_ arg,
     int argc, char *argv[],
     int rts_argc, char *rts_argv[],
-    const char *FILENAME_FMT)
+    const char *FILENAME_FMT,
+    FILE **file_ret)
 {
     FILE *f = NULL;
 
-    if (strequal(rts_argv[arg]+2, "stderr")) /* use real stderr */
-       f = stderr;
-    else if (rts_argv[arg][2] != '\0')     /* stats file specified */
-       f = fopen(rts_argv[arg]+2,"w");
-    else {
-       char stats_filename[STATS_FILENAME_MAXLEN]; /* default <program>.<ext> */
-       sprintf(stats_filename, FILENAME_FMT, argv[0]);
-       f = fopen(stats_filename,"w");
-    }
-    if (f == NULL) {
-       fprintf(stderr, "Can't open stats file %s\n", rts_argv[arg]+2);
+    if (strequal(rts_argv[arg]+2, "stderr")) { /* use debugBelch */
+        f = NULL; /* NULL means use debugBelch */
     } else {
+       if (rts_argv[arg][2] != '\0') {  /* stats file specified */
+           f = fopen(rts_argv[arg]+2,"w");
+       } else {
+           char stats_filename[STATS_FILENAME_MAXLEN]; /* default <program>.<ext> */
+           sprintf(stats_filename, FILENAME_FMT, argv[0]);
+           f = fopen(stats_filename,"w");
+       }
+       if (f == NULL) {
+           errorBelch("Can't open stats file %s\n", rts_argv[arg]+2);
+           return -1;
+       }
+    }
+    *file_ret = f;
+
+    {
        /* Write argv and rtsv into start of stats file */
-       I_ count;
-       for(count = 0; count < argc; count++)
-           fprintf(f, "%s ", argv[count]);
-       fprintf(f, "+RTS ");
+       int count;
+       for(count = 0; count < argc; count++) {
+           stats_fprintf(f, "%s ", argv[count]);
+       }
+       stats_fprintf(f, "+RTS ");
        for(count = 0; count < rts_argc; count++)
-           fprintf(f, "%s ", rts_argv[count]);
-       fprintf(f, "\n");
+           stats_fprintf(f, "%s ", rts_argv[count]);
+       stats_fprintf(f, "\n");
     }
-
-    return(f);
+    return 0;
 }
 
+
+
 static I_
 decode(const char *s)
 {
@@ -1898,6 +2226,56 @@ decode(const char *s)
 static void
 bad_option(const char *s)
 {
-  prog_belch("bad RTS option: %s", s);
+  errorBelch("bad RTS option: %s", s);
   stg_exit(EXIT_FAILURE);
 }
+
+/* -----------------------------------------------------------------------------
+   Getting/Setting the program's arguments.
+
+   These are used by System.Environment, and parts of the RTS.
+   -------------------------------------------------------------------------- */
+
+void
+setProgName(char *argv[])
+{
+    /* Remove directory from argv[0] -- default files in current directory */
+#if !defined(mingw32_HOST_OS)
+    char *last_slash;
+    if ( (last_slash = (char *) strrchr(argv[0], '/')) != NULL ) {
+       prog_name = last_slash+1;
+   } else {
+       prog_name = argv[0];
+   }
+#else
+    char* last_slash = argv[0] + (strlen(argv[0]) - 1);
+    while ( last_slash > argv[0] ) {
+       if ( *last_slash == '/' || *last_slash == '\\' ) {
+           prog_name = last_slash+1;
+           return;
+       }
+       last_slash--;
+    }
+    prog_name = argv[0];
+#endif
+}
+
+void
+getProgArgv(int *argc, char **argv[])
+{
+    if (argc) { *argc = prog_argc; }
+    if (argv) { *argv = prog_argv; }
+}
+
+void
+setProgArgv(int argc, char *argv[])
+{
+   /* Usually this is done by startupHaskell, so we don't need to call this. 
+      However, sometimes Hugs wants to change the arguments which Haskell
+      getArgs >>= ... will be fed.  So you can do that by calling here
+      _after_ calling startupHaskell.
+   */
+   prog_argc = argc;
+   prog_argv = argv;
+   setProgName(prog_argv);
+}