Don't allow shortcuts with Ctrl+Alt because on Windows they can be used as the AltGr...
[xonotic/darkplaces.git] / prvm_edict.c
index ffe917a..8633fdf 100644 (file)
@@ -23,35 +23,31 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 #include "progsvm.h"
 #include "csprogs.h"
 
-prvm_prog_t *prog;
-
-static prvm_prog_t prog_list[PRVM_MAXPROGS];
+prvm_prog_t prvm_prog_list[PRVM_PROG_MAX];
 
 int            prvm_type_size[8] = {1,sizeof(string_t)/4,1,3,1,1,sizeof(func_t)/4,sizeof(void *)/4};
 
 prvm_eval_t prvm_badvalue; // used only for error returns
 
-ddef_t *PRVM_ED_FieldAtOfs(int ofs);
-qboolean PRVM_ED_ParseEpair(prvm_edict_t *ent, ddef_t *key, const char *s, qboolean parsebackslash);
-
-cvar_t prvm_language = {CVAR_SAVE, "prvm_language", "", "when set, loads progs.dat.LANGUAGENAME.po for string translations; when set to dump, progs.dat.pot is written from the strings in the progs"};
+cvar_t prvm_language = {CVAR_SAVE, "prvm_language", "", "when set, loads PROGSFILE.LANGUAGENAME.po and common.LANGUAGENAME.po for string translations; when set to dump, PROGSFILE.pot is written from the strings in the progs"};
 // LordHavoc: prints every opcode as it executes - warning: this is significant spew
 cvar_t prvm_traceqc = {0, "prvm_traceqc", "0", "prints every QuakeC statement as it is executed (only for really thorough debugging!)"};
 // LordHavoc: counts usage of each QuakeC statement
 cvar_t prvm_statementprofiling = {0, "prvm_statementprofiling", "0", "counts how many times each QuakeC statement has been executed, these counts are displayed in prvm_printfunction output (if enabled)"};
 cvar_t prvm_timeprofiling = {0, "prvm_timeprofiling", "0", "counts how long each function has been executed, these counts are displayed in prvm_profile output (if enabled)"};
+cvar_t prvm_coverage = {0, "prvm_coverage", "0", "report and count coverage events (1: per-function, 2: coverage() builtin, 4: per-statement)"};
 cvar_t prvm_backtraceforwarnings = {0, "prvm_backtraceforwarnings", "0", "print a backtrace for warnings too"};
 cvar_t prvm_leaktest = {0, "prvm_leaktest", "0", "try to detect memory leaks in strings or entities"};
+cvar_t prvm_leaktest_follow_targetname = {0, "prvm_leaktest_follow_targetname", "0", "if set, target/targetname links are considered when leak testing; this should normally not be required, as entities created during startup - e.g. info_notnull - are never considered leaky"};
 cvar_t prvm_leaktest_ignore_classnames = {0, "prvm_leaktest_ignore_classnames", "", "classnames of entities to NOT leak check because they are found by find(world, classname, ...) but are actually spawned by QC code (NOT map entities)"};
 cvar_t prvm_errordump = {0, "prvm_errordump", "0", "write a savegame on crash to crash-server.dmp"};
+cvar_t prvm_breakpointdump = {0, "prvm_breakpointdump", "0", "write a savegame on breakpoint to breakpoint-server.dmp"};
 cvar_t prvm_reuseedicts_startuptime = {0, "prvm_reuseedicts_startuptime", "2", "allows immediate re-use of freed entity slots during start of new level (value in seconds)"};
 cvar_t prvm_reuseedicts_neverinsameframe = {0, "prvm_reuseedicts_neverinsameframe", "1", "never allows re-use of freed entity slots during same frame"};
 
 static double prvm_reuseedicts_always_allow = 0;
 qboolean prvm_runawaycheck = true;
 
-extern sizebuf_t vm_tempstringsbuf;
-
 //============================================================================
 // mempool handling
 
@@ -60,7 +56,7 @@ extern sizebuf_t vm_tempstringsbuf;
 PRVM_MEM_Alloc
 ===============
 */
-void PRVM_MEM_Alloc(void)
+static void PRVM_MEM_Alloc(prvm_prog_t *prog)
 {
        int i;
 
@@ -80,13 +76,13 @@ void PRVM_MEM_Alloc(void)
 
        // alloc edict fields
        prog->entityfieldsarea = prog->entityfields * prog->max_edicts;
-       prog->edictsfields = (vec_t *)Mem_Alloc(prog->progs_mempool, prog->entityfieldsarea * sizeof(vec_t));
+       prog->edictsfields = (prvm_vec_t *)Mem_Alloc(prog->progs_mempool, prog->entityfieldsarea * sizeof(prvm_vec_t));
 
        // set edict pointers
        for(i = 0; i < prog->max_edicts; i++)
        {
                prog->edicts[i].priv.required = (prvm_edict_private_t *)((unsigned char  *)prog->edictprivate + i * prog->edictprivate_size);
-               prog->edicts[i].fields.vp = prog->edictsfields + i * prog->entityfields;
+               prog->edicts[i].fields.fp = prog->edictsfields + i * prog->entityfields;
        }
 }
 
@@ -95,140 +91,132 @@ void PRVM_MEM_Alloc(void)
 PRVM_MEM_IncreaseEdicts
 ===============
 */
-void PRVM_MEM_IncreaseEdicts(void)
+void PRVM_MEM_IncreaseEdicts(prvm_prog_t *prog)
 {
        int             i;
 
        if(prog->max_edicts >= prog->limit_edicts)
                return;
 
-       PRVM_GCALL(begin_increase_edicts)();
+       prog->begin_increase_edicts(prog);
 
        // increase edicts
        prog->max_edicts = min(prog->max_edicts + 256, prog->limit_edicts);
 
        prog->entityfieldsarea = prog->entityfields * prog->max_edicts;
-       prog->edictsfields = (vec_t*)Mem_Realloc(prog->progs_mempool, (void *)prog->edictsfields, prog->entityfieldsarea * sizeof(vec_t));
+       prog->edictsfields = (prvm_vec_t*)Mem_Realloc(prog->progs_mempool, (void *)prog->edictsfields, prog->entityfieldsarea * sizeof(prvm_vec_t));
        prog->edictprivate = (void *)Mem_Realloc(prog->progs_mempool, (void *)prog->edictprivate, prog->max_edicts * prog->edictprivate_size);
 
        //set e and v pointers
        for(i = 0; i < prog->max_edicts; i++)
        {
                prog->edicts[i].priv.required  = (prvm_edict_private_t *)((unsigned char  *)prog->edictprivate + i * prog->edictprivate_size);
-               prog->edicts[i].fields.vp = prog->edictsfields + i * prog->entityfields;
+               prog->edicts[i].fields.fp = prog->edictsfields + i * prog->entityfields;
        }
 
-       PRVM_GCALL(end_increase_edicts)();
+       prog->end_increase_edicts(prog);
 }
 
 //============================================================================
 // normal prvm
 
-int PRVM_ED_FindFieldOffset(const char *field)
+int PRVM_ED_FindFieldOffset(prvm_prog_t *prog, const char *field)
 {
        ddef_t *d;
-       d = PRVM_ED_FindField(field);
+       d = PRVM_ED_FindField(prog, field);
        if (!d)
                return -1;
        return d->ofs;
 }
 
-int PRVM_ED_FindGlobalOffset(const char *global)
+int PRVM_ED_FindGlobalOffset(prvm_prog_t *prog, const char *global)
 {
        ddef_t *d;
-       d = PRVM_ED_FindGlobal(global);
+       d = PRVM_ED_FindGlobal(prog, global);
        if (!d)
                return -1;
        return d->ofs;
 }
 
-func_t PRVM_ED_FindFunctionOffset(const char *function)
+func_t PRVM_ED_FindFunctionOffset(prvm_prog_t *prog, const char *function)
 {
        mfunction_t *f;
-       f = PRVM_ED_FindFunction(function);
+       f = PRVM_ED_FindFunction(prog, function);
        if (!f)
                return 0;
        return (func_t)(f - prog->functions);
 }
 
-qboolean PRVM_ProgLoaded(int prognr)
-{
-       if(prognr < 0 || prognr >= PRVM_MAXPROGS)
-               return FALSE;
-
-       return (prog_list[prognr].loaded ? TRUE : FALSE);
-}
-
 /*
 =================
-PRVM_SetProgFromString
+PRVM_ProgFromString
 =================
 */
-// perhaps add a return value when the str doesnt exist
-qboolean PRVM_SetProgFromString(const char *str)
-{
-       int i = 0;
-       for(; i < PRVM_MAXPROGS ; i++)
-               if(prog_list[i].name && !strcmp(prog_list[i].name,str))
-               {
-                       if(prog_list[i].loaded)
-                       {
-                               prog = &prog_list[i];
-                               return TRUE;
-                       }
-                       else
-                       {
-                               Con_Printf("%s not loaded !\n",PRVM_NAME);
-                               return FALSE;
-                       }
-               }
-
-       Con_Printf("Invalid program name %s !\n", str);
-       return FALSE;
+prvm_prog_t *PRVM_ProgFromString(const char *str)
+{
+       if (!strcmp(str, "server"))
+               return SVVM_prog;
+       if (!strcmp(str, "client"))
+               return CLVM_prog;
+#ifdef CONFIG_MENU
+       if (!strcmp(str, "menu"))
+               return MVM_prog;
+#endif
+       return NULL;
 }
 
 /*
 =================
-PRVM_SetProg
+PRVM_FriendlyProgFromString
 =================
 */
-void PRVM_SetProg(int prognr)
+prvm_prog_t *PRVM_FriendlyProgFromString(const char *str)
 {
-       if(0 <= prognr && prognr < PRVM_MAXPROGS)
+       prvm_prog_t *prog = PRVM_ProgFromString(str);
+       if (!prog)
        {
-               if(prog_list[prognr].loaded)
-                       prog = &prog_list[prognr];
-               else
-                       PRVM_ERROR("%i not loaded !", prognr);
-               return;
+               Con_Printf("%s: unknown program name\n", str);
+               return NULL;
        }
-       PRVM_ERROR("Invalid program number %i", prognr);
+       if (!prog->loaded)
+       {
+               Con_Printf("%s: program is not loaded\n", str);
+               return NULL;
+       }
+       return prog;
 }
 
 /*
 =================
 PRVM_ED_ClearEdict
 
-Sets everything to NULL
+Sets everything to NULL.
+
+Nota bene: this also marks the entity as allocated if it has been previously
+freed and sets the allocation origin.
 =================
 */
-void PRVM_ED_ClearEdict (prvm_edict_t *e)
+void PRVM_ED_ClearEdict(prvm_prog_t *prog, prvm_edict_t *e)
 {
-       memset (e->fields.vp, 0, prog->entityfields * 4);
+       memset(e->fields.fp, 0, prog->entityfields * sizeof(prvm_vec_t));
        e->priv.required->free = false;
+       e->priv.required->freetime = realtime;
+       if(e->priv.required->allocation_origin)
+               Mem_Free((char *)e->priv.required->allocation_origin);
+       e->priv.required->allocation_origin = PRVM_AllocationOrigin(prog);
 
        // AK: Let the init_edict function determine if something needs to be initialized
-       PRVM_GCALL(init_edict)(e);
+       prog->init_edict(prog, e);
 }
 
-const char *PRVM_AllocationOrigin(void)
+const char *PRVM_AllocationOrigin(prvm_prog_t *prog)
 {
        char *buf = NULL;
        if(prog->leaktest_active)
        if(prog->depth > 0) // actually in QC code and not just parsing the entities block of a map/savegame
        {
-               buf = (char *)PRVM_Alloc(128);
-               PRVM_ShortStackTrace(buf, 128);
+               buf = (char *)PRVM_Alloc(256);
+               PRVM_ShortStackTrace(prog, buf, 256);
        }
        return buf;
 }
@@ -240,13 +228,13 @@ PRVM_ED_CanAlloc
 Returns if this particular edict could get allocated by PRVM_ED_Alloc
 =================
 */
-qboolean PRVM_ED_CanAlloc(prvm_edict_t *e)
+qboolean PRVM_ED_CanAlloc(prvm_prog_t *prog, prvm_edict_t *e)
 {
        if(!e->priv.required->free)
                return false;
        if(prvm_reuseedicts_always_allow == realtime)
                return true;
-       if(realtime <= e->priv.required->freetime && prvm_reuseedicts_neverinsameframe.integer)
+       if(realtime <= e->priv.required->freetime + 0.1 && prvm_reuseedicts_neverinsameframe.integer)
                return false; // never allow reuse in same frame (causes networking trouble)
        if(e->priv.required->freetime < prog->starttime + prvm_reuseedicts_startuptime.value)
                return true;
@@ -266,10 +254,10 @@ instead of being removed and recreated, which can cause interpolated
 angles and bad trails.
 =================
 */
-prvm_edict_t *PRVM_ED_Alloc (void)
+prvm_edict_t *PRVM_ED_Alloc(prvm_prog_t *prog)
 {
-       int                     i;
-       prvm_edict_t            *e;
+       int i;
+       prvm_edict_t *e;
 
        // the client qc dont need maxclients
        // thus it doesnt need to use svs.maxclients
@@ -279,26 +267,23 @@ prvm_edict_t *PRVM_ED_Alloc (void)
        for (i = prog->reserved_edicts + 1;i < prog->num_edicts;i++)
        {
                e = PRVM_EDICT_NUM(i);
-               if(PRVM_ED_CanAlloc(e))
+               if(PRVM_ED_CanAlloc(prog, e))
                {
-                       PRVM_ED_ClearEdict (e);
-                       e->priv.required->allocation_origin = PRVM_AllocationOrigin();
+                       PRVM_ED_ClearEdict (prog, e);
                        return e;
                }
        }
 
        if (i == prog->limit_edicts)
-               PRVM_ERROR ("%s: PRVM_ED_Alloc: no free edicts",PRVM_NAME);
+               prog->error_cmd("%s: PRVM_ED_Alloc: no free edicts", prog->name);
 
        prog->num_edicts++;
        if (prog->num_edicts >= prog->max_edicts)
-               PRVM_MEM_IncreaseEdicts();
+               PRVM_MEM_IncreaseEdicts(prog);
 
        e = PRVM_EDICT_NUM(i);
-       PRVM_ED_ClearEdict (e);
-
-       e->priv.required->allocation_origin = PRVM_AllocationOrigin();
 
+       PRVM_ED_ClearEdict(prog, e);
        return e;
 }
 
@@ -310,19 +295,19 @@ Marks the edict as free
 FIXME: walk all entities and NULL out references to this entity
 =================
 */
-void PRVM_ED_Free (prvm_edict_t *ed)
+void PRVM_ED_Free(prvm_prog_t *prog, prvm_edict_t *ed)
 {
        // dont delete the null entity (world) or reserved edicts
-       if(PRVM_NUM_FOR_EDICT(ed) <= prog->reserved_edicts )
+       if (ed - prog->edicts <= prog->reserved_edicts)
                return;
 
-       PRVM_GCALL(free_edict)(ed);
+       prog->free_edict(prog, ed);
 
        ed->priv.required->free = true;
        ed->priv.required->freetime = realtime;
        if(ed->priv.required->allocation_origin)
        {
-               PRVM_Free((char *)ed->priv.required->allocation_origin);
+               Mem_Free((char *)ed->priv.required->allocation_origin);
                ed->priv.required->allocation_origin = NULL;
        }
 }
@@ -334,7 +319,7 @@ void PRVM_ED_Free (prvm_edict_t *ed)
 PRVM_ED_GlobalAtOfs
 ============
 */
-ddef_t *PRVM_ED_GlobalAtOfs (int ofs)
+static ddef_t *PRVM_ED_GlobalAtOfs (prvm_prog_t *prog, int ofs)
 {
        ddef_t          *def;
        int                     i;
@@ -353,7 +338,7 @@ ddef_t *PRVM_ED_GlobalAtOfs (int ofs)
 PRVM_ED_FieldAtOfs
 ============
 */
-ddef_t *PRVM_ED_FieldAtOfs (int ofs)
+ddef_t *PRVM_ED_FieldAtOfs (prvm_prog_t *prog, int ofs)
 {
        ddef_t          *def;
        int                     i;
@@ -372,7 +357,7 @@ ddef_t *PRVM_ED_FieldAtOfs (int ofs)
 PRVM_ED_FindField
 ============
 */
-ddef_t *PRVM_ED_FindField (const char *name)
+ddef_t *PRVM_ED_FindField (prvm_prog_t *prog, const char *name)
 {
        ddef_t *def;
        int i;
@@ -380,7 +365,7 @@ ddef_t *PRVM_ED_FindField (const char *name)
        for (i = 0;i < prog->numfielddefs;i++)
        {
                def = &prog->fielddefs[i];
-               if (!strcmp(PRVM_GetString(def->s_name), name))
+               if (!strcmp(PRVM_GetString(prog, def->s_name), name))
                        return def;
        }
        return NULL;
@@ -391,7 +376,7 @@ ddef_t *PRVM_ED_FindField (const char *name)
 PRVM_ED_FindGlobal
 ============
 */
-ddef_t *PRVM_ED_FindGlobal (const char *name)
+ddef_t *PRVM_ED_FindGlobal (prvm_prog_t *prog, const char *name)
 {
        ddef_t *def;
        int i;
@@ -399,7 +384,7 @@ ddef_t *PRVM_ED_FindGlobal (const char *name)
        for (i = 0;i < prog->numglobaldefs;i++)
        {
                def = &prog->globaldefs[i];
-               if (!strcmp(PRVM_GetString(def->s_name), name))
+               if (!strcmp(PRVM_GetString(prog, def->s_name), name))
                        return def;
        }
        return NULL;
@@ -411,7 +396,7 @@ ddef_t *PRVM_ED_FindGlobal (const char *name)
 PRVM_ED_FindFunction
 ============
 */
-mfunction_t *PRVM_ED_FindFunction (const char *name)
+mfunction_t *PRVM_ED_FindFunction (prvm_prog_t *prog, const char *name)
 {
        mfunction_t             *func;
        int                             i;
@@ -419,7 +404,7 @@ mfunction_t *PRVM_ED_FindFunction (const char *name)
        for (i = 0;i < prog->numfunctions;i++)
        {
                func = &prog->functions[i];
-               if (!strcmp(PRVM_GetString(func->s_name), name))
+               if (!strcmp(PRVM_GetString(prog, func->s_name), name))
                        return func;
        }
        return NULL;
@@ -433,9 +418,8 @@ PRVM_ValueString
 Returns a string describing *data in a type specific manner
 =============
 */
-char *PRVM_ValueString (etype_t type, prvm_eval_t *val)
+static char *PRVM_ValueString (prvm_prog_t *prog, etype_t type, prvm_eval_t *val, char *line, size_t linelength)
 {
-       static char line[MAX_INPUTLINE];
        ddef_t *def;
        mfunction_t *f;
        int n;
@@ -445,39 +429,39 @@ char *PRVM_ValueString (etype_t type, prvm_eval_t *val)
        switch (type)
        {
        case ev_string:
-               strlcpy (line, PRVM_GetString (val->string), sizeof (line));
+               strlcpy (line, PRVM_GetString (prog, val->string), linelength);
                break;
        case ev_entity:
                n = val->edict;
                if (n < 0 || n >= prog->max_edicts)
-                       dpsnprintf (line, sizeof(line), "entity %i (invalid!)", n);
+                       dpsnprintf (line, linelength, "entity %i (invalid!)", n);
                else
-                       dpsnprintf (line, sizeof(line), "entity %i", n);
+                       dpsnprintf (line, linelength, "entity %i", n);
                break;
        case ev_function:
                f = prog->functions + val->function;
-               dpsnprintf (line, sizeof(line), "%s()", PRVM_GetString(f->s_name));
+               dpsnprintf (line, linelength, "%s()", PRVM_GetString(prog, f->s_name));
                break;
        case ev_field:
-               def = PRVM_ED_FieldAtOfs ( val->_int );
-               dpsnprintf (line, sizeof(line), ".%s", PRVM_GetString(def->s_name));
+               def = PRVM_ED_FieldAtOfs ( prog, val->_int );
+               dpsnprintf (line, linelength, ".%s", PRVM_GetString(prog, def->s_name));
                break;
        case ev_void:
-               dpsnprintf (line, sizeof(line), "void");
+               dpsnprintf (line, linelength, "void");
                break;
        case ev_float:
                // LordHavoc: changed from %5.1f to %10.4f
-               dpsnprintf (line, sizeof(line), "%10.4f", val->_float);
+               dpsnprintf (line, linelength, FLOAT_LOSSLESS_FORMAT, val->_float);
                break;
        case ev_vector:
                // LordHavoc: changed from %5.1f to %10.4f
-               dpsnprintf (line, sizeof(line), "'%10.4f %10.4f %10.4f'", val->vector[0], val->vector[1], val->vector[2]);
+               dpsnprintf (line, linelength, "'" VECTOR_LOSSLESS_FORMAT "'", val->vector[0], val->vector[1], val->vector[2]);
                break;
        case ev_pointer:
-               dpsnprintf (line, sizeof(line), "pointer");
+               dpsnprintf (line, linelength, "pointer");
                break;
        default:
-               dpsnprintf (line, sizeof(line), "bad type %i", (int) type);
+               dpsnprintf (line, linelength, "bad type %i", (int) type);
                break;
        }
 
@@ -492,9 +476,8 @@ Returns a string describing *data in a type specific manner
 Easier to parse than PR_ValueString
 =============
 */
-char *PRVM_UglyValueString (etype_t type, prvm_eval_t *val)
+char *PRVM_UglyValueString (prvm_prog_t *prog, etype_t type, prvm_eval_t *val, char *line, size_t linelength)
 {
-       static char line[MAX_INPUTLINE];
        int i;
        const char *s;
        ddef_t *def;
@@ -508,8 +491,8 @@ char *PRVM_UglyValueString (etype_t type, prvm_eval_t *val)
                // Parse the string a bit to turn special characters
                // (like newline, specifically) into escape codes,
                // this fixes saving games from various mods
-               s = PRVM_GetString (val->string);
-               for (i = 0;i < (int)sizeof(line) - 2 && *s;)
+               s = PRVM_GetString (prog, val->string);
+               for (i = 0;i < (int)linelength - 2 && *s;)
                {
                        if (*s == '\n')
                        {
@@ -538,27 +521,28 @@ char *PRVM_UglyValueString (etype_t type, prvm_eval_t *val)
                line[i] = '\0';
                break;
        case ev_entity:
-               dpsnprintf (line, sizeof (line), "%i", PRVM_NUM_FOR_EDICT(PRVM_PROG_TO_EDICT(val->edict)));
+               i = val->edict;
+               dpsnprintf (line, linelength, "%i", i);
                break;
        case ev_function:
                f = prog->functions + val->function;
-               strlcpy (line, PRVM_GetString (f->s_name), sizeof (line));
+               strlcpy (line, PRVM_GetString (prog, f->s_name), linelength);
                break;
        case ev_field:
-               def = PRVM_ED_FieldAtOfs ( val->_int );
-               dpsnprintf (line, sizeof (line), ".%s", PRVM_GetString(def->s_name));
+               def = PRVM_ED_FieldAtOfs ( prog, val->_int );
+               dpsnprintf (line, linelength, ".%s", PRVM_GetString(prog, def->s_name));
                break;
        case ev_void:
-               dpsnprintf (line, sizeof (line), "void");
+               dpsnprintf (line, linelength, "void");
                break;
        case ev_float:
-               dpsnprintf (line, sizeof (line), "%.9g", val->_float);
+               dpsnprintf (line, linelength, FLOAT_LOSSLESS_FORMAT, val->_float);
                break;
        case ev_vector:
-               dpsnprintf (line, sizeof (line), "%.9g %.9g %.9g", val->vector[0], val->vector[1], val->vector[2]);
+               dpsnprintf (line, linelength, VECTOR_LOSSLESS_FORMAT, val->vector[0], val->vector[1], val->vector[2]);
                break;
        default:
-               dpsnprintf (line, sizeof (line), "bad type %i", type);
+               dpsnprintf (line, linelength, "bad type %i", type);
                break;
        }
 
@@ -573,22 +557,22 @@ Returns a string with a description and the contents of a global,
 padded to 20 field width
 ============
 */
-char *PRVM_GlobalString (int ofs)
+char *PRVM_GlobalString (prvm_prog_t *prog, int ofs, char *line, size_t linelength)
 {
        char    *s;
        //size_t        i;
        ddef_t  *def;
-       void    *val;
-       static char     line[128];
+       prvm_eval_t     *val;
+       char valuebuf[MAX_INPUTLINE];
 
-       val = (void *)&prog->globals.generic[ofs];
-       def = PRVM_ED_GlobalAtOfs(ofs);
+       val = (prvm_eval_t *)&prog->globals.fp[ofs];
+       def = PRVM_ED_GlobalAtOfs(prog, ofs);
        if (!def)
-               dpsnprintf (line, sizeof(line), "GLOBAL%i", ofs);
+               dpsnprintf (line, linelength, "GLOBAL%i", ofs);
        else
        {
-               s = PRVM_ValueString ((etype_t)def->type, (prvm_eval_t *)val);
-               dpsnprintf (line, sizeof(line), "%s (=%s)", PRVM_GetString(def->s_name), s);
+               s = PRVM_ValueString (prog, (etype_t)def->type, val, valuebuf, sizeof(valuebuf));
+               dpsnprintf (line, linelength, "%s (=%s)", PRVM_GetString(prog, def->s_name), s);
        }
 
        //i = strlen(line);
@@ -599,17 +583,16 @@ char *PRVM_GlobalString (int ofs)
        return line;
 }
 
-char *PRVM_GlobalStringNoContents (int ofs)
+char *PRVM_GlobalStringNoContents (prvm_prog_t *prog, int ofs, char *line, size_t linelength)
 {
        //size_t        i;
        ddef_t  *def;
-       static char     line[128];
 
-       def = PRVM_ED_GlobalAtOfs(ofs);
+       def = PRVM_ED_GlobalAtOfs(prog, ofs);
        if (!def)
-               dpsnprintf (line, sizeof(line), "GLOBAL%i", ofs);
+               dpsnprintf (line, linelength, "GLOBAL%i", ofs);
        else
-               dpsnprintf (line, sizeof(line), "%s", PRVM_GetString(def->s_name));
+               dpsnprintf (line, linelength, "%s", PRVM_GetString(prog, def->s_name));
 
        //i = strlen(line);
        //for ( ; i<20 ; i++)
@@ -629,28 +612,29 @@ For debugging
 */
 // LordHavoc: optimized this to print out much more quickly (tempstring)
 // LordHavoc: changed to print out every 4096 characters (incase there are a lot of fields to print)
-void PRVM_ED_Print(prvm_edict_t *ed, const char *wildcard_fieldname)
+void PRVM_ED_Print(prvm_prog_t *prog, prvm_edict_t *ed, const char *wildcard_fieldname)
 {
        size_t  l;
        ddef_t  *d;
-       int             *v;
+       prvm_eval_t     *val;
        int             i, j;
        const char      *name;
        int             type;
        char    tempstring[MAX_INPUTLINE], tempstring2[260]; // temporary string buffers
+       char    valuebuf[MAX_INPUTLINE];
 
        if (ed->priv.required->free)
        {
-               Con_Printf("%s: FREE\n",PRVM_NAME);
+               Con_Printf("%s: FREE\n",prog->name);
                return;
        }
 
        tempstring[0] = 0;
-       dpsnprintf(tempstring, sizeof(tempstring), "\n%s EDICT %i:\n", PRVM_NAME, PRVM_NUM_FOR_EDICT(ed));
+       dpsnprintf(tempstring, sizeof(tempstring), "\n%s EDICT %i:\n", prog->name, PRVM_NUM_FOR_EDICT(ed));
        for (i = 1;i < prog->numfielddefs;i++)
        {
                d = &prog->fielddefs[i];
-               name = PRVM_GetString(d->s_name);
+               name = PRVM_GetString(prog, d->s_name);
                if(strlen(name) > 1 && name[strlen(name)-2] == '_' && (name[strlen(name)-1] == 'x' || name[strlen(name)-1] == 'y' || name[strlen(name)-1] == 'z'))
                        continue;       // skip _x, _y, _z vars
 
@@ -660,13 +644,13 @@ void PRVM_ED_Print(prvm_edict_t *ed, const char *wildcard_fieldname)
                                // Didn't match; skip
                                continue;
 
-               v = (int *)(ed->fields.vp + d->ofs);
+               val = (prvm_eval_t *)(ed->fields.fp + d->ofs);
 
        // if the value is still all 0, skip the field
                type = d->type & ~DEF_SAVEGLOBAL;
 
                for (j=0 ; j<prvm_type_size[type] ; j++)
-                       if (v[j])
+                       if (val->ivector[j])
                                break;
                if (j == prvm_type_size[type])
                        continue;
@@ -683,7 +667,7 @@ void PRVM_ED_Print(prvm_edict_t *ed, const char *wildcard_fieldname)
                        strlcat(tempstring, " ", sizeof(tempstring));
                strlcat(tempstring, " ", sizeof(tempstring));
 
-               name = PRVM_ValueString((etype_t)d->type, (prvm_eval_t *)v);
+               name = PRVM_ValueString(prog, (etype_t)d->type, val, valuebuf, sizeof(valuebuf));
                if (strlen(name) > sizeof(tempstring2)-4)
                {
                        memcpy (tempstring2, name, sizeof(tempstring2)-4);
@@ -711,13 +695,15 @@ For savegames
 =============
 */
 extern cvar_t developer_entityparsing;
-void PRVM_ED_Write (qfile_t *f, prvm_edict_t *ed)
+void PRVM_ED_Write (prvm_prog_t *prog, qfile_t *f, prvm_edict_t *ed)
 {
        ddef_t  *d;
-       int             *v;
+       prvm_eval_t     *val;
        int             i, j;
        const char      *name;
        int             type;
+       char vabuf[1024];
+       char valuebuf[MAX_INPUTLINE];
 
        FS_Print(f, "{\n");
 
@@ -730,7 +716,7 @@ void PRVM_ED_Write (qfile_t *f, prvm_edict_t *ed)
        for (i = 1;i < prog->numfielddefs;i++)
        {
                d = &prog->fielddefs[i];
-               name = PRVM_GetString(d->s_name);
+               name = PRVM_GetString(prog, d->s_name);
 
                if(developer_entityparsing.integer)
                        Con_Printf("PRVM_ED_Write: at entity %d field %s\n", PRVM_NUM_FOR_EDICT(ed), name);
@@ -739,28 +725,28 @@ void PRVM_ED_Write (qfile_t *f, prvm_edict_t *ed)
                if(strlen(name) > 1 && name[strlen(name)-2] == '_')
                        continue;       // skip _x, _y, _z vars, and ALSO other _? vars as some mods expect them to be never saved (TODO: a gameplayfix for using the "more precise" condition above?)
 
-               v = (int *)(ed->fields.vp + d->ofs);
+               val = (prvm_eval_t *)(ed->fields.fp + d->ofs);
 
        // if the value is still all 0, skip the field
                type = d->type & ~DEF_SAVEGLOBAL;
                for (j=0 ; j<prvm_type_size[type] ; j++)
-                       if (v[j])
+                       if (val->ivector[j])
                                break;
                if (j == prvm_type_size[type])
                        continue;
 
                FS_Printf(f,"\"%s\" ",name);
-               prog->statestring = va("PRVM_ED_Write, ent=%d, name=%s", i, name);
-               FS_Printf(f,"\"%s\"\n", PRVM_UglyValueString((etype_t)d->type, (prvm_eval_t *)v));
+               prog->statestring = va(vabuf, sizeof(vabuf), "PRVM_ED_Write, ent=%d, name=%s", i, name);
+               FS_Printf(f,"\"%s\"\n", PRVM_UglyValueString(prog, (etype_t)d->type, val, valuebuf, sizeof(valuebuf)));
                prog->statestring = NULL;
        }
 
        FS_Print(f, "}\n");
 }
 
-void PRVM_ED_PrintNum (int ent, const char *wildcard_fieldname)
+void PRVM_ED_PrintNum (prvm_prog_t *prog, int ent, const char *wildcard_fieldname)
 {
-       PRVM_ED_Print(PRVM_EDICT_NUM(ent), wildcard_fieldname);
+       PRVM_ED_Print(prog, PRVM_EDICT_NUM(ent), wildcard_fieldname);
 }
 
 /*
@@ -772,6 +758,7 @@ For debugging, prints all the entities in the current server
 */
 void PRVM_ED_PrintEdicts_f (void)
 {
+       prvm_prog_t *prog;
        int             i;
        const char *wildcard_fieldname;
 
@@ -781,8 +768,7 @@ void PRVM_ED_PrintEdicts_f (void)
                return;
        }
 
-       PRVM_Begin;
-       if(!PRVM_SetProgFromString(Cmd_Argv(1)))
+       if (!(prog = PRVM_FriendlyProgFromString(Cmd_Argv(1))))
                return;
 
        if( Cmd_Argc() == 3)
@@ -790,11 +776,9 @@ void PRVM_ED_PrintEdicts_f (void)
        else
                wildcard_fieldname = NULL;
 
-       Con_Printf("%s: %i entities\n", PRVM_NAME, prog->num_edicts);
+       Con_Printf("%s: %i entities\n", prog->name, prog->num_edicts);
        for (i=0 ; i<prog->num_edicts ; i++)
-               PRVM_ED_PrintNum (i, wildcard_fieldname);
-
-       PRVM_End;
+               PRVM_ED_PrintNum (prog, i, wildcard_fieldname);
 }
 
 /*
@@ -804,8 +788,9 @@ PRVM_ED_PrintEdict_f
 For debugging, prints a single edict
 =============
 */
-void PRVM_ED_PrintEdict_f (void)
+static void PRVM_ED_PrintEdict_f (void)
 {
+       prvm_prog_t *prog;
        int             i;
        const char      *wildcard_fieldname;
 
@@ -815,15 +800,13 @@ void PRVM_ED_PrintEdict_f (void)
                return;
        }
 
-       PRVM_Begin;
-       if(!PRVM_SetProgFromString(Cmd_Argv(1)))
+       if (!(prog = PRVM_FriendlyProgFromString(Cmd_Argv(1))))
                return;
 
        i = atoi (Cmd_Argv(2));
        if (i >= prog->num_edicts)
        {
                Con_Print("Bad edict number\n");
-               PRVM_End;
                return;
        }
        if( Cmd_Argc() == 4)
@@ -832,9 +815,7 @@ void PRVM_ED_PrintEdict_f (void)
        else
                // Use All
                wildcard_fieldname = NULL;
-       PRVM_ED_PrintNum (i, wildcard_fieldname);
-
-       PRVM_End;
+       PRVM_ED_PrintNum (prog, i, wildcard_fieldname);
 }
 
 /*
@@ -846,11 +827,9 @@ For debugging
 */
 // 2 possibilities : 1. just displaying the active edict count
 //                                      2. making a function pointer [x]
-void PRVM_ED_Count_f (void)
+static void PRVM_ED_Count_f (void)
 {
-       int             i;
-       prvm_edict_t    *ent;
-       int             active;
+       prvm_prog_t *prog;
 
        if(Cmd_Argc() != 2)
        {
@@ -858,28 +837,10 @@ void PRVM_ED_Count_f (void)
                return;
        }
 
-       PRVM_Begin;
-       if(!PRVM_SetProgFromString(Cmd_Argv(1)))
+       if (!(prog = PRVM_FriendlyProgFromString(Cmd_Argv(1))))
                return;
 
-       if(prog->count_edicts)
-               prog->count_edicts();
-       else
-       {
-               active = 0;
-               for (i=0 ; i<prog->num_edicts ; i++)
-               {
-                       ent = PRVM_EDICT_NUM(i);
-                       if (ent->priv.required->free)
-                               continue;
-                       active++;
-               }
-
-               Con_Printf("num_edicts:%3i\n", prog->num_edicts);
-               Con_Printf("active    :%3i\n", active);
-       }
-
-       PRVM_End;
+       prog->count_edicts(prog);
 }
 
 /*
@@ -896,12 +857,14 @@ FIXME: need to tag constants, doesn't really work
 PRVM_ED_WriteGlobals
 =============
 */
-void PRVM_ED_WriteGlobals (qfile_t *f)
+void PRVM_ED_WriteGlobals (prvm_prog_t *prog, qfile_t *f)
 {
        ddef_t          *def;
        int                     i;
        const char              *name;
        int                     type;
+       char vabuf[1024];
+       char valuebuf[MAX_INPUTLINE];
 
        FS_Print(f,"{\n");
        for (i = 0;i < prog->numglobaldefs;i++)
@@ -915,14 +878,14 @@ void PRVM_ED_WriteGlobals (qfile_t *f)
                if (type != ev_string && type != ev_float && type != ev_entity)
                        continue;
 
-               name = PRVM_GetString(def->s_name);
+               name = PRVM_GetString(prog, def->s_name);
 
                if(developer_entityparsing.integer)
                        Con_Printf("PRVM_ED_WriteGlobals: at global %s\n", name);
 
-               prog->statestring = va("PRVM_ED_WriteGlobals, name=%s", name);
+               prog->statestring = va(vabuf, sizeof(vabuf), "PRVM_ED_WriteGlobals, name=%s", name);
                FS_Printf(f,"\"%s\" ", name);
-               FS_Printf(f,"\"%s\"\n", PRVM_UglyValueString((etype_t)type, (prvm_eval_t *)&prog->globals.generic[def->ofs]));
+               FS_Printf(f,"\"%s\"\n", PRVM_UglyValueString(prog, (etype_t)type, (prvm_eval_t *)&prog->globals.fp[def->ofs], valuebuf, sizeof(valuebuf)));
                prog->statestring = NULL;
        }
        FS_Print(f,"}\n");
@@ -933,7 +896,7 @@ void PRVM_ED_WriteGlobals (qfile_t *f)
 PRVM_ED_ParseGlobals
 =============
 */
-void PRVM_ED_ParseGlobals (const char *data)
+void PRVM_ED_ParseGlobals (prvm_prog_t *prog, const char *data)
 {
        char keyname[MAX_INPUTLINE];
        ddef_t *key;
@@ -941,8 +904,8 @@ void PRVM_ED_ParseGlobals (const char *data)
        while (1)
        {
                // parse key
-               if (!COM_ParseToken_Simple(&data, false, false))
-                       PRVM_ERROR ("PRVM_ED_ParseGlobals: EOF without closing brace");
+               if (!COM_ParseToken_Simple(&data, false, false, true))
+                       prog->error_cmd("PRVM_ED_ParseGlobals: EOF without closing brace");
                if (com_token[0] == '}')
                        break;
 
@@ -952,24 +915,24 @@ void PRVM_ED_ParseGlobals (const char *data)
                strlcpy (keyname, com_token, sizeof(keyname));
 
                // parse value
-               if (!COM_ParseToken_Simple(&data, false, true))
-                       PRVM_ERROR ("PRVM_ED_ParseGlobals: EOF without closing brace");
+               if (!COM_ParseToken_Simple(&data, false, true, true))
+                       prog->error_cmd("PRVM_ED_ParseGlobals: EOF without closing brace");
 
                if (developer_entityparsing.integer)
                        Con_Printf(" \"%s\"\n", com_token);
 
                if (com_token[0] == '}')
-                       PRVM_ERROR ("PRVM_ED_ParseGlobals: closing brace without data");
+                       prog->error_cmd("PRVM_ED_ParseGlobals: closing brace without data");
 
-               key = PRVM_ED_FindGlobal (keyname);
+               key = PRVM_ED_FindGlobal (prog, keyname);
                if (!key)
                {
-                       Con_DPrintf("'%s' is not a global on %s\n", keyname, PRVM_NAME);
+                       Con_DPrintf("'%s' is not a global on %s\n", keyname, prog->name);
                        continue;
                }
 
-               if (!PRVM_ED_ParseEpair(NULL, key, com_token, true))
-                       PRVM_ERROR ("PRVM_ED_ParseGlobals: parse error");
+               if (!PRVM_ED_ParseEpair(prog, NULL, key, com_token, true))
+                       prog->error_cmd("PRVM_ED_ParseGlobals: parse error");
        }
 }
 
@@ -984,7 +947,7 @@ Can parse either fields or globals
 returns false if error
 =============
 */
-qboolean PRVM_ED_ParseEpair(prvm_edict_t *ent, ddef_t *key, const char *s, qboolean parsebackslash)
+qboolean PRVM_ED_ParseEpair(prvm_prog_t *prog, prvm_edict_t *ent, ddef_t *key, const char *s, qboolean parsebackslash)
 {
        int i, l;
        char *new_p;
@@ -993,14 +956,14 @@ qboolean PRVM_ED_ParseEpair(prvm_edict_t *ent, ddef_t *key, const char *s, qbool
        mfunction_t *func;
 
        if (ent)
-               val = (prvm_eval_t *)(ent->fields.vp + key->ofs);
+               val = (prvm_eval_t *)(ent->fields.fp + key->ofs);
        else
-               val = (prvm_eval_t *)(prog->globals.generic + key->ofs);
+               val = (prvm_eval_t *)(prog->globals.fp + key->ofs);
        switch (key->type & ~DEF_SAVEGLOBAL)
        {
        case ev_string:
                l = (int)strlen(s) + 1;
-               val->string = PRVM_AllocString(l, &new_p);
+               val->string = PRVM_AllocString(prog, l, &new_p);
                for (i = 0;i < l;i++)
                {
                        if (s[i] == '\\' && s[i+1] && parsebackslash)
@@ -1044,42 +1007,42 @@ qboolean PRVM_ED_ParseEpair(prvm_edict_t *ent, ddef_t *key, const char *s, qbool
                        s++;
                i = atoi(s);
                if (i >= prog->limit_edicts)
-                       Con_Printf("PRVM_ED_ParseEpair: ev_entity reference too large (edict %u >= MAX_EDICTS %u) on %s\n", (unsigned int)i, prog->limit_edicts, PRVM_NAME);
+                       Con_Printf("PRVM_ED_ParseEpair: ev_entity reference too large (edict %u >= MAX_EDICTS %u) on %s\n", (unsigned int)i, prog->limit_edicts, prog->name);
                while (i >= prog->max_edicts)
-                       PRVM_MEM_IncreaseEdicts();
+                       PRVM_MEM_IncreaseEdicts(prog);
                // if IncreaseEdicts was called the base pointer needs to be updated
                if (ent)
-                       val = (prvm_eval_t *)(ent->fields.vp + key->ofs);
+                       val = (prvm_eval_t *)(ent->fields.fp + key->ofs);
                val->edict = PRVM_EDICT_TO_PROG(PRVM_EDICT_NUM((int)i));
                break;
 
        case ev_field:
                if (*s != '.')
                {
-                       Con_DPrintf("PRVM_ED_ParseEpair: Bogus field name %s in %s\n", s, PRVM_NAME);
+                       Con_DPrintf("PRVM_ED_ParseEpair: Bogus field name %s in %s\n", s, prog->name);
                        return false;
                }
-               def = PRVM_ED_FindField(s + 1);
+               def = PRVM_ED_FindField(prog, s + 1);
                if (!def)
                {
-                       Con_DPrintf("PRVM_ED_ParseEpair: Can't find field %s in %s\n", s, PRVM_NAME);
+                       Con_DPrintf("PRVM_ED_ParseEpair: Can't find field %s in %s\n", s, prog->name);
                        return false;
                }
                val->_int = def->ofs;
                break;
 
        case ev_function:
-               func = PRVM_ED_FindFunction(s);
+               func = PRVM_ED_FindFunction(prog, s);
                if (!func)
                {
-                       Con_Printf("PRVM_ED_ParseEpair: Can't find function %s in %s\n", s, PRVM_NAME);
+                       Con_Printf("PRVM_ED_ParseEpair: Can't find function %s in %s\n", s, prog->name);
                        return false;
                }
                val->function = func - prog->functions;
                break;
 
        default:
-               Con_Printf("PRVM_ED_ParseEpair: Unknown key->type %i for key \"%s\" on %s\n", key->type, PRVM_GetString(key->s_name), PRVM_NAME);
+               Con_Printf("PRVM_ED_ParseEpair: Unknown key->type %i for key \"%s\" on %s\n", key->type, PRVM_GetString(prog, key->s_name), prog->name);
                return false;
        }
        return true;
@@ -1101,22 +1064,17 @@ All progs can support this extension; sg calls it in server QC, cg in client
 QC, mg in menu QC.
 =============
 */
-void PRVM_GameCommand(const char *whichprogs, const char *whichcmd)
+static void PRVM_GameCommand(const char *whichprogs, const char *whichcmd)
 {
+       prvm_prog_t *prog;
        if(Cmd_Argc() < 1)
        {
                Con_Printf("%s text...\n", whichcmd);
                return;
        }
 
-       PRVM_Begin;
-       if(!PRVM_SetProgFromString(whichprogs))
-       // note: this is not PRVM_SetProg because that one aborts "hard" using PRVM_Error
-       // also, it makes printing error messages easier!
-       {
-               Con_Printf("%s program not loaded.\n", whichprogs);
+       if (!(prog = PRVM_FriendlyProgFromString(whichprogs)))
                return;
-       }
 
        if(!PRVM_allfunction(GameCommand))
        {
@@ -1129,23 +1087,21 @@ void PRVM_GameCommand(const char *whichprogs, const char *whichcmd)
 
                s = Cmd_Args();
 
-               restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
-               PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(s ? s : "");
-               PRVM_ExecuteProgram (PRVM_allfunction(GameCommand), "QC function GameCommand is missing");
-               vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
+               restorevm_tempstringsbuf_cursize = prog->tempstringsbuf.cursize;
+               PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(prog, s ? s : "");
+               prog->ExecuteProgram(prog, PRVM_allfunction(GameCommand), "QC function GameCommand is missing");
+               prog->tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
        }
-
-       PRVM_End;
 }
-void PRVM_GameCommand_Server_f(void)
+static void PRVM_GameCommand_Server_f(void)
 {
        PRVM_GameCommand("server", "sv_cmd");
 }
-void PRVM_GameCommand_Client_f(void)
+static void PRVM_GameCommand_Client_f(void)
 {
        PRVM_GameCommand("client", "cl_cmd");
 }
-void PRVM_GameCommand_Menu_f(void)
+static void PRVM_GameCommand_Menu_f(void)
 {
        PRVM_GameCommand("menu", "menu_cmd");
 }
@@ -1157,12 +1113,14 @@ PRVM_ED_EdictGet_f
 Console command to load a field of a specified edict
 =============
 */
-void PRVM_ED_EdictGet_f(void)
+static void PRVM_ED_EdictGet_f(void)
 {
+       prvm_prog_t *prog;
        prvm_edict_t *ed;
        ddef_t *key;
        const char *s;
        prvm_eval_t *v;
+       char valuebuf[MAX_INPUTLINE];
 
        if(Cmd_Argc() != 4 && Cmd_Argc() != 5)
        {
@@ -1170,23 +1128,19 @@ void PRVM_ED_EdictGet_f(void)
                return;
        }
 
-       PRVM_Begin;
-       if(!PRVM_SetProgFromString(Cmd_Argv(1)))
-       {
-               Con_Printf("Wrong program name %s !\n", Cmd_Argv(1));
+       if (!(prog = PRVM_FriendlyProgFromString(Cmd_Argv(1))))
                return;
-       }
 
        ed = PRVM_EDICT_NUM(atoi(Cmd_Argv(2)));
 
-       if((key = PRVM_ED_FindField(Cmd_Argv(3))) == 0)
+       if((key = PRVM_ED_FindField(prog, Cmd_Argv(3))) == 0)
        {
                Con_Printf("Key %s not found !\n", Cmd_Argv(3));
                goto fail;
        }
 
-       v = (prvm_eval_t *)(ed->fields.vp + key->ofs);
-       s = PRVM_UglyValueString((etype_t)key->type, v);
+       v = (prvm_eval_t *)(ed->fields.fp + key->ofs);
+       s = PRVM_UglyValueString(prog, (etype_t)key->type, v, valuebuf, sizeof(valuebuf));
        if(Cmd_Argc() == 5)
        {
                cvar_t *cvar = Cvar_FindVar(Cmd_Argv(4));
@@ -1201,14 +1155,16 @@ void PRVM_ED_EdictGet_f(void)
                Con_Printf("%s\n", s);
 
 fail:
-       PRVM_End;
+       ;
 }
 
-void PRVM_ED_GlobalGet_f(void)
+static void PRVM_ED_GlobalGet_f(void)
 {
+       prvm_prog_t *prog;
        ddef_t *key;
        const char *s;
        prvm_eval_t *v;
+       char valuebuf[MAX_INPUTLINE];
 
        if(Cmd_Argc() != 3 && Cmd_Argc() != 4)
        {
@@ -1216,22 +1172,18 @@ void PRVM_ED_GlobalGet_f(void)
                return;
        }
 
-       PRVM_Begin;
-       if(!PRVM_SetProgFromString(Cmd_Argv(1)))
-       {
-               Con_Printf("Wrong program name %s !\n", Cmd_Argv(1));
+       if (!(prog = PRVM_FriendlyProgFromString(Cmd_Argv(1))))
                return;
-       }
 
-       key = PRVM_ED_FindGlobal(Cmd_Argv(2));
+       key = PRVM_ED_FindGlobal(prog, Cmd_Argv(2));
        if(!key)
        {
                Con_Printf( "No global '%s' in %s!\n", Cmd_Argv(2), Cmd_Argv(1) );
                goto fail;
        }
 
-       v = (prvm_eval_t *) &prog->globals.generic[key->ofs];
-       s = PRVM_UglyValueString((etype_t)key->type, v);
+       v = (prvm_eval_t *) &prog->globals.fp[key->ofs];
+       s = PRVM_UglyValueString(prog, (etype_t)key->type, v, valuebuf, sizeof(valuebuf));
        if(Cmd_Argc() == 4)
        {
                cvar_t *cvar = Cvar_FindVar(Cmd_Argv(3));
@@ -1246,7 +1198,7 @@ void PRVM_ED_GlobalGet_f(void)
                Con_Printf("%s\n", s);
 
 fail:
-       PRVM_End;
+       ;
 }
 
 /*
@@ -1256,8 +1208,9 @@ PRVM_ED_EdictSet_f
 Console command to set a field of a specified edict
 =============
 */
-void PRVM_ED_EdictSet_f(void)
+static void PRVM_ED_EdictSet_f(void)
 {
+       prvm_prog_t *prog;
        prvm_edict_t *ed;
        ddef_t *key;
 
@@ -1267,21 +1220,15 @@ void PRVM_ED_EdictSet_f(void)
                return;
        }
 
-       PRVM_Begin;
-       if(!PRVM_SetProgFromString(Cmd_Argv(1)))
-       {
-               Con_Printf("Wrong program name %s !\n", Cmd_Argv(1));
+       if (!(prog = PRVM_FriendlyProgFromString(Cmd_Argv(1))))
                return;
-       }
 
        ed = PRVM_EDICT_NUM(atoi(Cmd_Argv(2)));
 
-       if((key = PRVM_ED_FindField(Cmd_Argv(3))) == 0)
+       if((key = PRVM_ED_FindField(prog, Cmd_Argv(3))) == 0)
                Con_Printf("Key %s not found !\n", Cmd_Argv(3));
        else
-               PRVM_ED_ParseEpair(ed, key, Cmd_Argv(4), true);
-
-       PRVM_End;
+               PRVM_ED_ParseEpair(prog, ed, key, Cmd_Argv(4), true);
 }
 
 /*
@@ -1293,7 +1240,7 @@ ed should be a properly initialized empty edict.
 Used for initial level load and for savegames.
 ====================
 */
-const char *PRVM_ED_ParseEdict (const char *data, prvm_edict_t *ent)
+const char *PRVM_ED_ParseEdict (prvm_prog_t *prog, const char *data, prvm_edict_t *ent)
 {
        ddef_t *key;
        qboolean anglehack;
@@ -1307,8 +1254,8 @@ const char *PRVM_ED_ParseEdict (const char *data, prvm_edict_t *ent)
        while (1)
        {
        // parse key
-               if (!COM_ParseToken_Simple(&data, false, false))
-                       PRVM_ERROR ("PRVM_ED_ParseEdict: EOF without closing brace");
+               if (!COM_ParseToken_Simple(&data, false, false, true))
+                       prog->error_cmd("PRVM_ED_ParseEdict: EOF without closing brace");
                if (developer_entityparsing.integer)
                        Con_Printf("Key: \"%s\"", com_token);
                if (com_token[0] == '}')
@@ -1339,13 +1286,13 @@ const char *PRVM_ED_ParseEdict (const char *data, prvm_edict_t *ent)
                }
 
        // parse value
-               if (!COM_ParseToken_Simple(&data, false, false))
-                       PRVM_ERROR ("PRVM_ED_ParseEdict: EOF without closing brace");
+               if (!COM_ParseToken_Simple(&data, false, false, true))
+                       prog->error_cmd("PRVM_ED_ParseEdict: EOF without closing brace");
                if (developer_entityparsing.integer)
                        Con_Printf(" \"%s\"\n", com_token);
 
                if (com_token[0] == '}')
-                       PRVM_ERROR ("PRVM_ED_ParseEdict: closing brace without data");
+                       prog->error_cmd("PRVM_ED_ParseEdict: closing brace without data");
 
                init = true;
 
@@ -1358,10 +1305,10 @@ const char *PRVM_ED_ParseEdict (const char *data, prvm_edict_t *ent)
                if (keyname[0] == '_')
                        continue;
 
-               key = PRVM_ED_FindField (keyname);
+               key = PRVM_ED_FindField (prog, keyname);
                if (!key)
                {
-                       Con_DPrintf("%s: '%s' is not a field\n", PRVM_NAME, keyname);
+                       Con_DPrintf("%s: '%s' is not a field\n", prog->name, keyname);
                        continue;
                }
 
@@ -1372,12 +1319,14 @@ const char *PRVM_ED_ParseEdict (const char *data, prvm_edict_t *ent)
                        dpsnprintf (com_token, sizeof(com_token), "0 %s 0", temp);
                }
 
-               if (!PRVM_ED_ParseEpair(ent, key, com_token, strcmp(keyname, "wad") != 0))
-                       PRVM_ERROR ("PRVM_ED_ParseEdict: parse error");
+               if (!PRVM_ED_ParseEpair(prog, ent, key, com_token, strcmp(keyname, "wad") != 0))
+                       prog->error_cmd("PRVM_ED_ParseEdict: parse error");
        }
 
-       if (!init)
+       if (!init) {
                ent->priv.required->free = true;
+               ent->priv.required->freetime = realtime;
+       }
 
        return data;
 }
@@ -1398,12 +1347,13 @@ Used for both fresh maps and savegame loads.  A fresh map would also need
 to call PRVM_ED_CallSpawnFunctions () to let the objects initialize themselves.
 ================
 */
-void PRVM_ED_LoadFromFile (const char *data)
+void PRVM_ED_LoadFromFile (prvm_prog_t *prog, const char *data)
 {
        prvm_edict_t *ent;
        int parsed, inhibited, spawned, died;
        const char *funcname;
        mfunction_t *func;
+       char vabuf[1024];
 
        parsed = 0;
        inhibited = 0;
@@ -1416,10 +1366,10 @@ void PRVM_ED_LoadFromFile (const char *data)
        while (1)
        {
 // parse the opening brace
-               if (!COM_ParseToken_Simple(&data, false, false))
+               if (!COM_ParseToken_Simple(&data, false, false, true))
                        break;
                if (com_token[0] != '{')
-                       PRVM_ERROR ("PRVM_ED_LoadFromFile: %s: found %s when expecting {", PRVM_NAME, com_token);
+                       prog->error_cmd("PRVM_ED_LoadFromFile: %s: found %s when expecting {", prog->name, com_token);
 
                // CHANGED: this is not conform to PR_LoadFromFile
                if(prog->loadintoworld)
@@ -1428,19 +1378,19 @@ void PRVM_ED_LoadFromFile (const char *data)
                        ent = PRVM_EDICT_NUM(0);
                }
                else
-                       ent = PRVM_ED_Alloc();
+                       ent = PRVM_ED_Alloc(prog);
 
                // clear it
                if (ent != prog->edicts)        // hack
-                       memset (ent->fields.vp, 0, prog->entityfields * 4);
+                       memset (ent->fields.fp, 0, prog->entityfields * sizeof(prvm_vec_t));
 
-               data = PRVM_ED_ParseEdict (data, ent);
+               data = PRVM_ED_ParseEdict (prog, data, ent);
                parsed++;
 
                // remove the entity ?
-               if(prog->load_edict && !prog->load_edict(ent))
+               if(!prog->load_edict(prog, ent))
                {
-                       PRVM_ED_Free(ent);
+                       PRVM_ED_Free(prog, ent);
                        inhibited++;
                        continue;
                }
@@ -1448,8 +1398,9 @@ void PRVM_ED_LoadFromFile (const char *data)
                if (PRVM_serverfunction(SV_OnEntityPreSpawnFunction))
                {
                        // self = ent
+                       PRVM_serverglobalfloat(time) = sv.time;
                        PRVM_serverglobaledict(self) = PRVM_EDICT_TO_PROG(ent);
-                       PRVM_ExecuteProgram (PRVM_serverfunction(SV_OnEntityPreSpawnFunction), "QC function SV_OnEntityPreSpawnFunction is missing");
+                       prog->ExecuteProgram(prog, PRVM_serverfunction(SV_OnEntityPreSpawnFunction), "QC function SV_OnEntityPreSpawnFunction is missing");
                }
 
                if(ent->priv.required->free)
@@ -1466,17 +1417,17 @@ void PRVM_ED_LoadFromFile (const char *data)
                        if (!PRVM_alledictstring(ent, classname))
                        {
                                Con_Print("No classname for:\n");
-                               PRVM_ED_Print(ent, NULL);
-                               PRVM_ED_Free (ent);
+                               PRVM_ED_Print(prog, ent, NULL);
+                               PRVM_ED_Free (prog, ent);
                                continue;
                        }
 
                        // look for the spawn function
-                       funcname = PRVM_GetString(PRVM_alledictstring(ent, classname));
-                       func = PRVM_ED_FindFunction (va("spawnfunc_%s", funcname));
+                       funcname = PRVM_GetString(prog, PRVM_alledictstring(ent, classname));
+                       func = PRVM_ED_FindFunction (prog, va(vabuf, sizeof(vabuf), "spawnfunc_%s", funcname));
                        if(!func)
                                if(!PRVM_allglobalfloat(require_spawnfunc_prefix))
-                                       func = PRVM_ED_FindFunction (funcname);
+                                       func = PRVM_ED_FindFunction (prog, funcname);
 
                        if (!func)
                        {
@@ -1484,25 +1435,27 @@ void PRVM_ED_LoadFromFile (const char *data)
                                if (PRVM_serverfunction(SV_OnEntityNoSpawnFunction))
                                {
                                        // self = ent
+                                       PRVM_serverglobalfloat(time) = sv.time;
                                        PRVM_serverglobaledict(self) = PRVM_EDICT_TO_PROG(ent);
-                                       PRVM_ExecuteProgram (PRVM_serverfunction(SV_OnEntityNoSpawnFunction), "QC function SV_OnEntityNoSpawnFunction is missing");
+                                       prog->ExecuteProgram(prog, PRVM_serverfunction(SV_OnEntityNoSpawnFunction), "QC function SV_OnEntityNoSpawnFunction is missing");
                                }
                                else
                                {
                                        if (developer.integer > 0) // don't confuse non-developers with errors
                                        {
                                                Con_Print("No spawn function for:\n");
-                                               PRVM_ED_Print(ent, NULL);
+                                               PRVM_ED_Print(prog, ent, NULL);
                                        }
-                                       PRVM_ED_Free (ent);
+                                       PRVM_ED_Free (prog, ent);
                                        continue; // not included in "inhibited" count
                                }
                        }
                        else
                        {
                                // self = ent
+                               PRVM_serverglobalfloat(time) = sv.time;
                                PRVM_allglobaledict(self) = PRVM_EDICT_TO_PROG(ent);
-                               PRVM_ExecuteProgram (func - prog->functions, "");
+                               prog->ExecuteProgram(prog, func - prog->functions, "");
                        }
                }
 
@@ -1510,8 +1463,9 @@ void PRVM_ED_LoadFromFile (const char *data)
                if (PRVM_serverfunction(SV_OnEntityPostSpawnFunction))
                {
                        // self = ent
+                       PRVM_serverglobalfloat(time) = sv.time;
                        PRVM_serverglobaledict(self) = PRVM_EDICT_TO_PROG(ent);
-                       PRVM_ExecuteProgram (PRVM_serverfunction(SV_OnEntityPostSpawnFunction), "QC function SV_OnEntityPostSpawnFunction is missing");
+                       prog->ExecuteProgram(prog, PRVM_serverfunction(SV_OnEntityPostSpawnFunction), "QC function SV_OnEntityPostSpawnFunction is missing");
                }
 
                spawned++;
@@ -1519,12 +1473,12 @@ void PRVM_ED_LoadFromFile (const char *data)
                        died++;
        }
 
-       Con_DPrintf("%s: %i new entities parsed, %i new inhibited, %i (%i new) spawned (whereas %i removed self, %i stayed)\n", PRVM_NAME, parsed, inhibited, prog->num_edicts, spawned, died, spawned - died);
+       Con_DPrintf("%s: %i new entities parsed, %i new inhibited, %i (%i new) spawned (whereas %i removed self, %i stayed)\n", prog->name, parsed, inhibited, prog->num_edicts, spawned, died, spawned - died);
 
        prvm_reuseedicts_always_allow = 0;
 }
 
-void PRVM_FindOffsets(void)
+static void PRVM_FindOffsets(prvm_prog_t *prog)
 {
        // field and global searches use -1 for NULL
        memset(&prog->fieldoffsets, -1, sizeof(prog->fieldoffsets));
@@ -1564,9 +1518,9 @@ void PRVM_FindOffsets(void)
 #define PRVM_DECLARE_serverfunction(x)
 #define PRVM_DECLARE_clientfunction(x)
 #define PRVM_DECLARE_menufunction(x)
-#define PRVM_DECLARE_field(x) prog->fieldoffsets.x = PRVM_ED_FindFieldOffset(#x);
-#define PRVM_DECLARE_global(x) prog->globaloffsets.x = PRVM_ED_FindGlobalOffset(#x);
-#define PRVM_DECLARE_function(x) prog->funcoffsets.x = PRVM_ED_FindFunctionOffset(#x);
+#define PRVM_DECLARE_field(x) prog->fieldoffsets.x = PRVM_ED_FindFieldOffset(prog, #x);
+#define PRVM_DECLARE_global(x) prog->globaloffsets.x = PRVM_ED_FindGlobalOffset(prog, #x);
+#define PRVM_DECLARE_function(x) prog->funcoffsets.x = PRVM_ED_FindFunctionOffset(prog, #x);
 #include "prvm_offsets.h"
 #undef PRVM_DECLARE_serverglobalfloat
 #undef PRVM_DECLARE_serverglobalvector
@@ -1640,7 +1594,7 @@ typedef struct po_s
        po_string_t *hashtable[PO_HASHSIZE];
 }
 po_t;
-void PRVM_PO_UnparseString(char *out, const char *in, size_t outsize)
+static void PRVM_PO_UnparseString(char *out, const char *in, size_t outsize)
 {
        for(;;)
        {
@@ -1664,7 +1618,7 @@ void PRVM_PO_UnparseString(char *out, const char *in, size_t outsize)
                                                *out++ = '\\';
                                                *out++ = '0' + ((*in & 0700) >> 6);
                                                *out++ = '0' + ((*in & 0070) >> 3);
-                                               *out++ = '0' + ((*in & 0007));
+                                               *out++ = '0' +  (*in & 0007)      ;
                                                outsize -= 4;
                                        }
                                }
@@ -1681,7 +1635,7 @@ void PRVM_PO_UnparseString(char *out, const char *in, size_t outsize)
                ++in;
        }
 }
-void PRVM_PO_ParseString(char *out, const char *in, size_t outsize)
+static void PRVM_PO_ParseString(char *out, const char *in, size_t outsize)
 {
        for(;;)
        {
@@ -1740,9 +1694,9 @@ void PRVM_PO_ParseString(char *out, const char *in, size_t outsize)
                ++in;
        }
 }
-po_t *PRVM_PO_Load(const char *filename, mempool_t *pool)
+static po_t *PRVM_PO_Load(const char *filename, const char *filename2, mempool_t *pool)
 {
-       po_t *po;
+       po_t *po = NULL;
        const char *p, *q;
        int mode;
        char inbuf[MAX_INPUTLINE];
@@ -1750,96 +1704,109 @@ po_t *PRVM_PO_Load(const char *filename, mempool_t *pool)
        size_t decodedpos;
        int hashindex;
        po_string_t thisstr;
-       const char *buf = (const char *) FS_LoadFile(filename, pool, true, NULL);
-
-       if(!buf)
-               return NULL;
-
-       memset(&thisstr, 0, sizeof(thisstr)); // hush compiler warning
-
-       po = (po_t *)Mem_Alloc(pool, sizeof(*po));
-       memset(po, 0, sizeof(*po));
+       int i;
 
-       p = buf;
-       while(*p)
+       for (i = 0; i < 2; ++i)
        {
-               if(*p == '#')
-               {
-                       // skip to newline
-                       p = strchr(p, '\n');
-                       if(!p)
-                               break;
-                       ++p;
-                       continue;
-               }
-               if(*p == '\r' || *p == '\n')
-               {
-                       ++p;
+               const char *buf = (const char *)
+                       FS_LoadFile((i > 0 ? filename : filename2), pool, true, NULL);
+               // first read filename2, then read filename
+               // so that progs.dat.de.po wins over common.de.po
+               // and within file, last item wins
+
+               if(!buf)
                        continue;
-               }
-               if(!strncmp(p, "msgid \"", 7))
-               {
-                       mode = 0;
-                       p += 6;
-               }
-               else if(!strncmp(p, "msgstr \"", 8))
+
+               if (!po)
                {
-                       mode = 1;
-                       p += 7;
+                       po = (po_t *)Mem_Alloc(pool, sizeof(*po));
+                       memset(po, 0, sizeof(*po));
                }
-               else
+
+               memset(&thisstr, 0, sizeof(thisstr)); // hush compiler warning
+
+               p = buf;
+               while(*p)
                {
-                       p = strchr(p, '\n');
-                       if(!p)
-                               break;
-                       ++p;
-                       continue;
+                       if(*p == '#')
+                       {
+                               // skip to newline
+                               p = strchr(p, '\n');
+                               if(!p)
+                                       break;
+                               ++p;
+                               continue;
+                       }
+                       if(*p == '\r' || *p == '\n')
+                       {
+                               ++p;
+                               continue;
+                       }
+                       if(!strncmp(p, "msgid \"", 7))
+                       {
+                               mode = 0;
+                               p += 6;
+                       }
+                       else if(!strncmp(p, "msgstr \"", 8))
+                       {
+                               mode = 1;
+                               p += 7;
+                       }
+                       else
+                       {
+                               p = strchr(p, '\n');
+                               if(!p)
+                                       break;
+                               ++p;
+                               continue;
+                       }
+                       decodedpos = 0;
+                       while(*p == '"')
+                       {
+                               ++p;
+                               q = strchr(p, '\n');
+                               if(!q)
+                                       break;
+                               if(*(q-1) == '\r')
+                                       --q;
+                               if(*(q-1) != '"')
+                                       break;
+                               if((size_t)(q - p) >= (size_t) sizeof(inbuf))
+                                       break;
+                               strlcpy(inbuf, p, q - p); // not - 1, because this adds a NUL
+                               PRVM_PO_ParseString(decodedbuf + decodedpos, inbuf, sizeof(decodedbuf) - decodedpos);
+                               decodedpos += strlen(decodedbuf + decodedpos);
+                               if(*q == '\r')
+                                       ++q;
+                               if(*q == '\n')
+                                       ++q;
+                               p = q;
+                       }
+                       if(mode == 0)
+                       {
+                               if(thisstr.key)
+                                       Mem_Free(thisstr.key);
+                               thisstr.key = (char *)Mem_Alloc(pool, decodedpos + 1);
+                               memcpy(thisstr.key, decodedbuf, decodedpos + 1);
+                       }
+                       else if(decodedpos > 0 && thisstr.key) // skip empty translation results
+                       {
+                               thisstr.value = (char *)Mem_Alloc(pool, decodedpos + 1);
+                               memcpy(thisstr.value, decodedbuf, decodedpos + 1);
+                               hashindex = CRC_Block((const unsigned char *) thisstr.key, strlen(thisstr.key)) % PO_HASHSIZE;
+                               thisstr.nextonhashchain = po->hashtable[hashindex];
+                               po->hashtable[hashindex] = (po_string_t *)Mem_Alloc(pool, sizeof(thisstr));
+                               memcpy(po->hashtable[hashindex], &thisstr, sizeof(thisstr));
+                               memset(&thisstr, 0, sizeof(thisstr));
+                       }
                }
-               decodedpos = 0;
-               while(*p == '"')
-               {
-                       ++p;
-                       q = strchr(p, '\n');
-                       if(!q)
-                               break;
-                       if(*(q-1) == '\r')
-                               --q;
-                       if(*(q-1) != '"')
-                               break;
-                       if((size_t)(q - p) >= (size_t) sizeof(inbuf))
-                               break;
-                       strlcpy(inbuf, p, q - p); // not - 1, because this adds a NUL
-                       PRVM_PO_ParseString(decodedbuf + decodedpos, inbuf, sizeof(decodedbuf) - decodedpos);
-                       decodedpos += strlen(decodedbuf + decodedpos);
-                       if(*q == '\r')
-                               ++q;
-                       if(*q == '\n')
-                               ++q;
-                       p = q;
-               }
-               if(mode == 0)
-               {
-                       if(thisstr.key)
-                               Mem_Free(thisstr.key);
-                       thisstr.key = (char *)Mem_Alloc(pool, decodedpos + 1);
-                       memcpy(thisstr.key, decodedbuf, decodedpos + 1);
-               }
-               else if(decodedpos > 0 && thisstr.key) // skip empty translation results
-               {
-                       thisstr.value = (char *)Mem_Alloc(pool, decodedpos + 1);
-                       memcpy(thisstr.value, decodedbuf, decodedpos + 1);
-                       hashindex = CRC_Block((const unsigned char *) thisstr.key, strlen(thisstr.key)) % PO_HASHSIZE;
-                       thisstr.nextonhashchain = po->hashtable[hashindex];
-                       po->hashtable[hashindex] = (po_string_t *)Mem_Alloc(pool, sizeof(thisstr));
-                       memcpy(po->hashtable[hashindex], &thisstr, sizeof(thisstr));
-                       memset(&thisstr, 0, sizeof(thisstr));
-               }
-       }
-       
-       Mem_Free((char *) buf);
+               
+               Mem_Free((char *) buf);
+       }
+
        return po;
 }
-const char *PRVM_PO_Lookup(po_t *po, const char *str)
+static const char *PRVM_PO_Lookup(po_t *po, const char *str)
 {
        int hashindex = CRC_Block((const unsigned char *) str, strlen(str)) % PO_HASHSIZE;
        po_string_t *p = po->hashtable[hashindex];
@@ -1851,7 +1818,7 @@ const char *PRVM_PO_Lookup(po_t *po, const char *str)
        }
        return NULL;
 }
-void PRVM_PO_Destroy(po_t *po)
+static void PRVM_PO_Destroy(po_t *po)
 {
        int i;
        for(i = 0; i < PO_HASHSIZE; ++i)
@@ -1869,16 +1836,21 @@ void PRVM_PO_Destroy(po_t *po)
        Mem_Free(po);
 }
 
-void PRVM_LeakTest(void);
-void PRVM_ResetProg(void)
+void PRVM_LeakTest(prvm_prog_t *prog);
+void PRVM_Prog_Reset(prvm_prog_t *prog)
 {
-       PRVM_LeakTest();
-       PRVM_GCALL(reset_cmd)();
-       Mem_FreePool(&prog->progs_mempool);
-       if(prog->po)
-               PRVM_PO_Destroy((po_t *) prog->po);
+       if (prog->loaded)
+       {
+               PRVM_LeakTest(prog);
+               prog->reset_cmd(prog);
+               Mem_FreePool(&prog->progs_mempool);
+               if(prog->po)
+                       PRVM_PO_Destroy((po_t *) prog->po);
+       }
        memset(prog,0,sizeof(prvm_prog_t));
-       prog->starttime = Sys_DoubleTime();
+       prog->break_statement = -1;
+       prog->watch_global_type = ev_void;
+       prog->watch_field_type = ev_void;
 }
 
 /*
@@ -1886,7 +1858,7 @@ void PRVM_ResetProg(void)
 PRVM_LoadLNO
 ===============
 */
-void PRVM_LoadLNO( const char *progname ) {
+static void PRVM_LoadLNO( prvm_prog_t *prog, const char *progname ) {
        fs_offset_t filesize;
        unsigned char *lno;
        unsigned int *header;
@@ -1924,7 +1896,14 @@ void PRVM_LoadLNO( const char *progname ) {
                (unsigned int)LittleLong( header[ 5 ] ) == (unsigned int)prog->progs_numstatements )
        {
                prog->statement_linenums = (int *)Mem_Alloc(prog->progs_mempool, prog->progs_numstatements * sizeof( int ) );
-               memcpy( prog->statement_linenums, (int *) lno + 6, prog->progs_numstatements * sizeof( int ) );
+               memcpy( prog->statement_linenums, header + 6, prog->progs_numstatements * sizeof( int ) );
+
+               /* gmqcc suports columnums */
+               if ((unsigned int)filesize > ((6 + 2 * prog->progs_numstatements) * sizeof( int )))
+               {
+                       prog->statement_columnnums = (int *)Mem_Alloc(prog->progs_mempool, prog->progs_numstatements * sizeof( int ) );
+                       memcpy( prog->statement_columnnums, header + 6 + prog->progs_numstatements, prog->progs_numstatements * sizeof( int ) );
+               }
        }
        Mem_Free( lno );
 }
@@ -1934,14 +1913,15 @@ void PRVM_LoadLNO( const char *progname ) {
 PRVM_LoadProgs
 ===============
 */
-void PRVM_LoadProgs (const char * filename, int numrequiredfunc, const char **required_func, int numrequiredfields, prvm_required_field_t *required_field, int numrequiredglobals, prvm_required_field_t *required_global)
+static void PRVM_UpdateBreakpoints(prvm_prog_t *prog);
+void PRVM_Prog_Load(prvm_prog_t *prog, const char * filename, unsigned char * data, fs_offset_t size, int numrequiredfunc, const char **required_func, int numrequiredfields, prvm_required_field_t *required_field, int numrequiredglobals, prvm_required_field_t *required_global)
 {
        int i;
        dprograms_t *dprograms;
        dstatement_t *instatements;
        ddef_t *infielddefs;
        ddef_t *inglobaldefs;
-       float *inglobals;
+       int *inglobals;
        dfunction_t *infunctions;
        char *instrings;
        fs_offset_t filesize;
@@ -1950,16 +1930,38 @@ void PRVM_LoadProgs (const char * filename, int numrequiredfunc, const char **re
        int a;
        int b;
        int c;
+       union
+       {
+               unsigned int i;
+               float f;
+       }
+       u;
+       unsigned int d;
+       char vabuf[1024];
+       char vabuf2[1024];
+       cvar_t *cvar;
 
        if (prog->loaded)
-               PRVM_ERROR ("PRVM_LoadProgs: there is already a %s program loaded!", PRVM_NAME );
+               prog->error_cmd("PRVM_LoadProgs: there is already a %s program loaded!", prog->name );
 
-       dprograms = (dprograms_t *)FS_LoadFile (filename, prog->progs_mempool, false, &filesize);
+       Host_LockSession(); // all progs can use the session cvar
+       Crypto_LoadKeys(); // all progs might use the keys at init time
+
+       if (data)
+       {
+               dprograms = (dprograms_t *) data;
+               filesize = size;
+       }
+       else
+               dprograms = (dprograms_t *)FS_LoadFile (filename, prog->progs_mempool, false, &filesize);
        if (dprograms == NULL || filesize < (fs_offset_t)sizeof(dprograms_t))
-               PRVM_ERROR ("PRVM_LoadProgs: couldn't load %s for %s", filename, PRVM_NAME);
+               prog->error_cmd("PRVM_LoadProgs: couldn't load %s for %s", filename, prog->name);
        // TODO bounds check header fields (e.g. numstatements), they must never go behind end of file
 
-       Con_DPrintf("%s programs occupy %iK.\n", PRVM_NAME, (int)(filesize/1024));
+       prog->profiletime = Sys_DirtyTime();
+       prog->starttime = realtime;
+
+       Con_DPrintf("%s programs occupy %iK.\n", prog->name, (int)(filesize/1024));
 
        requiredglobalspace = 0;
        for (i = 0;i < numrequiredglobals;i++)
@@ -1971,7 +1973,7 @@ void PRVM_LoadProgs (const char * filename, int numrequiredfunc, const char **re
        prog->progs_version = LittleLong(dprograms->version);
        prog->progs_crc = LittleLong(dprograms->crc);
        if (prog->progs_version != PROG_VERSION)
-               PRVM_ERROR ("%s: %s has wrong version number (%i should be %i)", PRVM_NAME, filename, prog->progs_version, PROG_VERSION);
+               prog->error_cmd("%s: %s has wrong version number (%i should be %i)", prog->name, filename, prog->progs_version, PROG_VERSION);
        instatements = (dstatement_t *)((unsigned char *)dprograms + LittleLong(dprograms->ofs_statements));
        prog->progs_numstatements = LittleLong(dprograms->numstatements);
        inglobaldefs = (ddef_t *)((unsigned char *)dprograms + LittleLong(dprograms->ofs_globaldefs));
@@ -1982,7 +1984,7 @@ void PRVM_LoadProgs (const char * filename, int numrequiredfunc, const char **re
        prog->progs_numfunctions = LittleLong(dprograms->numfunctions);
        instrings = (char *)((unsigned char *)dprograms + LittleLong(dprograms->ofs_strings));
        prog->progs_numstrings = LittleLong(dprograms->numstrings);
-       inglobals = (float *)((unsigned char *)dprograms + LittleLong(dprograms->ofs_globals));
+       inglobals = (int *)((unsigned char *)dprograms + LittleLong(dprograms->ofs_globals));
        prog->progs_numglobals = LittleLong(dprograms->numglobals);
        prog->progs_entityfields = LittleLong(dprograms->entityfields);
 
@@ -1994,8 +1996,8 @@ void PRVM_LoadProgs (const char * filename, int numrequiredfunc, const char **re
        prog->numglobals = prog->progs_numglobals;
        prog->entityfields = prog->progs_entityfields;
 
-       if (LittleLong(dprograms->ofs_strings) + prog->progs_numstrings >= (int)filesize)
-               PRVM_ERROR ("%s: %s strings go past end of file", PRVM_NAME, filename);
+       if (LittleLong(dprograms->ofs_strings) + prog->progs_numstrings > (int)filesize)
+               prog->error_cmd("%s: %s strings go past end of file", prog->name, filename);
        prog->strings = (char *)Mem_Alloc(prog->progs_mempool, prog->progs_numstrings);
        memcpy(prog->strings, instrings, prog->progs_numstrings);
        prog->stringssize = prog->progs_numstrings;
@@ -2009,12 +2011,16 @@ void PRVM_LoadProgs (const char * filename, int numrequiredfunc, const char **re
 
        // we need to expand the globaldefs and fielddefs to include engine defs
        prog->globaldefs = (ddef_t *)Mem_Alloc(prog->progs_mempool, (prog->progs_numglobaldefs + numrequiredglobals) * sizeof(ddef_t));
-       prog->globals.generic = (float *)Mem_Alloc(prog->progs_mempool, (prog->progs_numglobals + requiredglobalspace) * sizeof(float));
+       prog->globals.fp = (prvm_vec_t *)Mem_Alloc(prog->progs_mempool, (prog->progs_numglobals + requiredglobalspace + 2) * sizeof(prvm_vec_t));
+               // + 2 is because of an otherwise occurring overrun in RETURN instruction
+               // when trying to return the last or second-last global
+               // (RETURN always returns a vector, there is no RETURN_F instruction)
        prog->fielddefs = (ddef_t *)Mem_Alloc(prog->progs_mempool, (prog->progs_numfielddefs + numrequiredfields) * sizeof(ddef_t));
        // we need to convert the statements to our memory format
        prog->statements = (mstatement_t *)Mem_Alloc(prog->progs_mempool, prog->progs_numstatements * sizeof(mstatement_t));
        // allocate space for profiling statement usage
        prog->statement_profile = (double *)Mem_Alloc(prog->progs_mempool, prog->progs_numstatements * sizeof(*prog->statement_profile));
+       prog->explicit_profile = (double *)Mem_Alloc(prog->progs_mempool, prog->progs_numstatements * sizeof(*prog->statement_profile));
        // functions need to be converted to the memory format
        prog->functions = (mfunction_t *)Mem_Alloc(prog->progs_mempool, sizeof(mfunction_t) * prog->progs_numfunctions);
 
@@ -2028,7 +2034,7 @@ void PRVM_LoadProgs (const char * filename, int numrequiredfunc, const char **re
                prog->functions[i].locals = LittleLong(infunctions[i].locals);
                memcpy(prog->functions[i].parm_size, infunctions[i].parm_size, sizeof(infunctions[i].parm_size));
                if(prog->functions[i].first_statement >= prog->numstatements)
-                       PRVM_ERROR("PRVM_LoadProgs: out of bounds function statement (function %d) in %s", i, PRVM_NAME);
+                       prog->error_cmd("PRVM_LoadProgs: out of bounds function statement (function %d) in %s", i, prog->name);
                // TODO bounds check parm_start, s_name, s_file, numparms, locals, parm_size
        }
 
@@ -2046,7 +2052,7 @@ void PRVM_LoadProgs (const char * filename, int numrequiredfunc, const char **re
        {
                prog->globaldefs[prog->numglobaldefs].type = required_global[i].type;
                prog->globaldefs[prog->numglobaldefs].ofs = prog->numglobals;
-               prog->globaldefs[prog->numglobaldefs].s_name = PRVM_SetEngineString(required_global[i].name);
+               prog->globaldefs[prog->numglobaldefs].s_name = PRVM_SetEngineString(prog, required_global[i].name);
                if (prog->globaldefs[prog->numglobaldefs].type == ev_vector)
                        prog->numglobals += 3;
                else
@@ -2059,7 +2065,7 @@ void PRVM_LoadProgs (const char * filename, int numrequiredfunc, const char **re
        {
                prog->fielddefs[i].type = LittleShort(infielddefs[i].type);
                if (prog->fielddefs[i].type & DEF_SAVEGLOBAL)
-                       PRVM_ERROR ("PRVM_LoadProgs: prog->fielddefs[i].type & DEF_SAVEGLOBAL in %s", PRVM_NAME);
+                       prog->error_cmd("PRVM_LoadProgs: prog->fielddefs[i].type & DEF_SAVEGLOBAL in %s", prog->name);
                prog->fielddefs[i].ofs = LittleShort(infielddefs[i].ofs);
                prog->fielddefs[i].s_name = LittleLong(infielddefs[i].s_name);
                // TODO bounds check ofs, s_name
@@ -2070,7 +2076,7 @@ void PRVM_LoadProgs (const char * filename, int numrequiredfunc, const char **re
        {
                prog->fielddefs[prog->numfielddefs].type = required_field[i].type;
                prog->fielddefs[prog->numfielddefs].ofs = prog->entityfields;
-               prog->fielddefs[prog->numfielddefs].s_name = PRVM_SetEngineString(required_field[i].name);
+               prog->fielddefs[prog->numfielddefs].s_name = PRVM_SetEngineString(prog, required_field[i].name);
                if (prog->fielddefs[prog->numfielddefs].type == ev_vector)
                        prog->entityfields += 3;
                else
@@ -2084,8 +2090,26 @@ void PRVM_LoadProgs (const char * filename, int numrequiredfunc, const char **re
 #define remapfield(index) (index)
 
        // copy globals
+       // FIXME: LordHavoc: this uses a crude way to identify integer constants, rather than checking for matching globaldefs and checking their type
        for (i = 0;i < prog->progs_numglobals;i++)
-               ((int *)prog->globals.generic)[remapglobal(i)] = LittleLong(((int *)inglobals)[i]);
+       {
+               u.i = LittleLong(inglobals[i]);
+               // most globals are 0, we only need to deal with the ones that are not
+               if (u.i)
+               {
+                       d = u.i & 0xFF800000;
+                       if ((d == 0xFF800000) || (d == 0))
+                       {
+                               // Looks like an integer (expand to int64)
+                               prog->globals.ip[remapglobal(i)] = u.i;
+                       }
+                       else
+                       {
+                               // Looks like a float (expand to double)
+                               prog->globals.fp[remapglobal(i)] = u.f;
+                       }
+               }
+       }
 
        // LordHavoc: TODO: support 32bit progs statement formats
        // copy, remap globals in statements, bounds check
@@ -2101,7 +2125,7 @@ void PRVM_LoadProgs (const char * filename, int numrequiredfunc, const char **re
                case OP_IFNOT:
                        b = (short)b;
                        if (a >= prog->progs_numglobals || b + i < 0 || b + i >= prog->progs_numstatements)
-                               PRVM_ERROR("PRVM_LoadProgs: out of bounds IF/IFNOT (statement %d) in %s", i, PRVM_NAME);
+                               prog->error_cmd("PRVM_LoadProgs: out of bounds IF/IFNOT (statement %d) in %s", i, prog->name);
                        prog->statements[i].op = op;
                        prog->statements[i].operand[0] = remapglobal(a);
                        prog->statements[i].operand[1] = -1;
@@ -2111,7 +2135,7 @@ void PRVM_LoadProgs (const char * filename, int numrequiredfunc, const char **re
                case OP_GOTO:
                        a = (short)a;
                        if (a + i < 0 || a + i >= prog->progs_numstatements)
-                               PRVM_ERROR("PRVM_LoadProgs: out of bounds GOTO (statement %d) in %s", i, PRVM_NAME);
+                               prog->error_cmd("PRVM_LoadProgs: out of bounds GOTO (statement %d) in %s", i, prog->name);
                        prog->statements[i].op = op;
                        prog->statements[i].operand[0] = -1;
                        prog->statements[i].operand[1] = -1;
@@ -2119,7 +2143,8 @@ void PRVM_LoadProgs (const char * filename, int numrequiredfunc, const char **re
                        prog->statements[i].jumpabsolute = i + a;
                        break;
                default:
-                       Con_DPrintf("PRVM_LoadProgs: unknown opcode %d at statement %d in %s\n", (int)op, i, PRVM_NAME);
+                       Con_DPrintf("PRVM_LoadProgs: unknown opcode %d at statement %d in %s\n", (int)op, i, prog->name);
+                       break;
                // global global global
                case OP_ADD_F:
                case OP_ADD_V:
@@ -2156,7 +2181,7 @@ void PRVM_LoadProgs (const char * filename, int numrequiredfunc, const char **re
                case OP_LOAD_FNC:
                case OP_LOAD_V:
                        if (a >= prog->progs_numglobals || b >= prog->progs_numglobals || c >= prog->progs_numglobals)
-                               PRVM_ERROR("PRVM_LoadProgs: out of bounds global index (statement %d)", i);
+                               prog->error_cmd("PRVM_LoadProgs: out of bounds global index (statement %d)", i);
                        prog->statements[i].op = op;
                        prog->statements[i].operand[0] = remapglobal(a);
                        prog->statements[i].operand[1] = remapglobal(b);
@@ -2170,7 +2195,7 @@ void PRVM_LoadProgs (const char * filename, int numrequiredfunc, const char **re
                case OP_NOT_FNC:
                case OP_NOT_ENT:
                        if (a >= prog->progs_numglobals || c >= prog->progs_numglobals)
-                               PRVM_ERROR("PRVM_LoadProgs: out of bounds global index (statement %d) in %s", i, PRVM_NAME);
+                               prog->error_cmd("PRVM_LoadProgs: out of bounds global index (statement %d) in %s", i, prog->name);
                        prog->statements[i].op = op;
                        prog->statements[i].operand[0] = remapglobal(a);
                        prog->statements[i].operand[1] = -1;
@@ -2192,7 +2217,7 @@ void PRVM_LoadProgs (const char * filename, int numrequiredfunc, const char **re
                case OP_STOREP_V:
                case OP_STORE_V:
                        if (a >= prog->progs_numglobals || b >= prog->progs_numglobals)
-                               PRVM_ERROR("PRVM_LoadProgs: out of bounds global index (statement %d) in %s", i, PRVM_NAME);
+                               prog->error_cmd("PRVM_LoadProgs: out of bounds global index (statement %d) in %s", i, prog->name);
                        prog->statements[i].op = op;
                        prog->statements[i].operand[0] = remapglobal(a);
                        prog->statements[i].operand[1] = remapglobal(b);
@@ -2201,6 +2226,11 @@ void PRVM_LoadProgs (const char * filename, int numrequiredfunc, const char **re
                        break;
                // 1 global
                case OP_CALL0:
+                       if ( a < prog->progs_numglobals)
+                               if ( prog->globals.ip[remapglobal(a)] >= 0 )
+                                       if ( prog->globals.ip[remapglobal(a)] < prog->progs_numfunctions )
+                                               if ( prog->functions[prog->globals.ip[remapglobal(a)]].first_statement == -642 )
+                                                       ++prog->numexplicitcoveragestatements;
                case OP_CALL1:
                case OP_CALL2:
                case OP_CALL3:
@@ -2212,7 +2242,7 @@ void PRVM_LoadProgs (const char * filename, int numrequiredfunc, const char **re
                case OP_DONE:
                case OP_RETURN:
                        if ( a >= prog->progs_numglobals)
-                               PRVM_ERROR("PRVM_LoadProgs: out of bounds global index (statement %d) in %s", i, PRVM_NAME);
+                               prog->error_cmd("PRVM_LoadProgs: out of bounds global index (statement %d) in %s", i, prog->name);
                        prog->statements[i].op = op;
                        prog->statements[i].operand[0] = remapglobal(a);
                        prog->statements[i].operand[1] = -1;
@@ -2223,7 +2253,7 @@ void PRVM_LoadProgs (const char * filename, int numrequiredfunc, const char **re
        }
        if(prog->numstatements < 1)
        {
-               PRVM_ERROR("PRVM_LoadProgs: empty program in %s", PRVM_NAME);
+               prog->error_cmd("PRVM_LoadProgs: empty program in %s", prog->name);
        }
        else switch(prog->statements[prog->numstatements - 1].op)
        {
@@ -2232,35 +2262,36 @@ void PRVM_LoadProgs (const char * filename, int numrequiredfunc, const char **re
                case OP_DONE:
                        break;
                default:
-                       PRVM_ERROR("PRVM_LoadProgs: program may fall off the edge (does not end with RETURN, GOTO or DONE) in %s", PRVM_NAME);
+                       prog->error_cmd("PRVM_LoadProgs: program may fall off the edge (does not end with RETURN, GOTO or DONE) in %s", prog->name);
                        break;
        }
 
        // we're done with the file now
-       Mem_Free(dprograms);
+       if(!data)
+               Mem_Free(dprograms);
        dprograms = NULL;
 
        // check required functions
        for(i=0 ; i < numrequiredfunc ; i++)
-               if(PRVM_ED_FindFunction(required_func[i]) == 0)
-                       PRVM_ERROR("%s: %s not found in %s",PRVM_NAME, required_func[i], filename);
+               if(PRVM_ED_FindFunction(prog, required_func[i]) == 0)
+                       prog->error_cmd("%s: %s not found in %s",prog->name, required_func[i], filename);
 
-       PRVM_LoadLNO(filename);
+       PRVM_LoadLNO(prog, filename);
 
-       PRVM_Init_Exec();
+       PRVM_Init_Exec(prog);
 
        if(*prvm_language.string)
        // in CSQC we really shouldn't be able to change how stuff works... sorry for now
        // later idea: include a list of authorized .po file checksums with the csprogs
        {
-               qboolean deftrans = !!strcmp(PRVM_NAME, "client");
-               const char *realfilename = (strcmp(PRVM_NAME, "client") ? filename : csqc_progname.string);
+               qboolean deftrans = prog == CLVM_prog;
+               const char *realfilename = (prog != CLVM_prog ? filename : csqc_progname.string);
                if(deftrans) // once we have dotranslate_ strings, ALWAYS use the opt-in method!
                {
                        for (i=0 ; i<prog->numglobaldefs ; i++)
                        {
                                const char *name;
-                               name = PRVM_GetString(prog->globaldefs[i].s_name);
+                               name = PRVM_GetString(prog, prog->globaldefs[i].s_name);
                                if((prog->globaldefs[i].type & ~DEF_SAVEGLOBAL) == ev_string)
                                if(name && !strncmp(name, "dotranslate_", 12))
                                {
@@ -2271,19 +2302,19 @@ void PRVM_LoadProgs (const char * filename, int numrequiredfunc, const char **re
                }
                if(!strcmp(prvm_language.string, "dump"))
                {
-                       qfile_t *f = FS_OpenRealFile(va("%s.pot", realfilename), "w", false);
+                       qfile_t *f = FS_OpenRealFile(va(vabuf, sizeof(vabuf), "%s.pot", realfilename), "w", false);
                        Con_Printf("Dumping to %s.pot\n", realfilename);
                        if(f)
                        {
                                for (i=0 ; i<prog->numglobaldefs ; i++)
                                {
                                        const char *name;
-                                       name = PRVM_GetString(prog->globaldefs[i].s_name);
+                                       name = PRVM_GetString(prog, prog->globaldefs[i].s_name);
                                        if(deftrans ? (!name || strncmp(name, "notranslate_", 12)) : (name && !strncmp(name, "dotranslate_", 12)))
                                        if((prog->globaldefs[i].type & ~DEF_SAVEGLOBAL) == ev_string)
                                        {
                                                prvm_eval_t *val = PRVM_GLOBALFIELDVALUE(prog->globaldefs[i].ofs);
-                                               const char *value = PRVM_GetString(val->string);
+                                               const char *value = PRVM_GetString(prog, val->string);
                                                if(*value)
                                                {
                                                        char buf[MAX_INPUTLINE];
@@ -2297,23 +2328,26 @@ void PRVM_LoadProgs (const char * filename, int numrequiredfunc, const char **re
                }
                else
                {
-                       po_t *po = PRVM_PO_Load(va("%s.%s.po", realfilename, prvm_language.string), prog->progs_mempool);
+                       po_t *po = PRVM_PO_Load(
+                                       va(vabuf, sizeof(vabuf), "%s.%s.po", realfilename, prvm_language.string),
+                                       va(vabuf2, sizeof(vabuf2), "common.%s.po", prvm_language.string),
+                                       prog->progs_mempool);
                        if(po)
                        {
                                for (i=0 ; i<prog->numglobaldefs ; i++)
                                {
                                        const char *name;
-                                       name = PRVM_GetString(prog->globaldefs[i].s_name);
+                                       name = PRVM_GetString(prog, prog->globaldefs[i].s_name);
                                        if(deftrans ? (!name || strncmp(name, "notranslate_", 12)) : (name && !strncmp(name, "dotranslate_", 12)))
                                        if((prog->globaldefs[i].type & ~DEF_SAVEGLOBAL) == ev_string)
                                        {
                                                prvm_eval_t *val = PRVM_GLOBALFIELDVALUE(prog->globaldefs[i].ofs);
-                                               const char *value = PRVM_GetString(val->string);
+                                               const char *value = PRVM_GetString(prog, val->string);
                                                if(*value)
                                                {
                                                        value = PRVM_PO_Lookup(po, value);
                                                        if(value)
-                                                               val->string = PRVM_SetEngineString(value);
+                                                               val->string = PRVM_SetEngineString(prog, value);
                                                }
                                        }
                                }
@@ -2321,10 +2355,13 @@ void PRVM_LoadProgs (const char * filename, int numrequiredfunc, const char **re
                }
        }
 
+       for (cvar = cvar_vars; cvar; cvar = cvar->next)
+               cvar->globaldefindex[prog - prvm_prog_list] = -1;
+
        for (i=0 ; i<prog->numglobaldefs ; i++)
        {
                const char *name;
-               name = PRVM_GetString(prog->globaldefs[i].s_name);
+               name = PRVM_GetString(prog, prog->globaldefs[i].s_name);
                //Con_Printf("found var %s\n", name);
                if(name
                        && !strncmp(name, "autocvar_", 9)
@@ -2332,13 +2369,13 @@ void PRVM_LoadProgs (const char * filename, int numrequiredfunc, const char **re
                )
                {
                        prvm_eval_t *val = PRVM_GLOBALFIELDVALUE(prog->globaldefs[i].ofs);
-                       cvar_t *cvar = Cvar_FindVar(name + 9);
-                       //Con_Printf("PRVM_LoadProgs: autocvar global %s in %s, processing...\n", name, PRVM_NAME);
+                       cvar = Cvar_FindVar(name + 9);
+                       //Con_Printf("PRVM_LoadProgs: autocvar global %s in %s, processing...\n", name, prog->name);
                        if(!cvar)
                        {
                                const char *value;
                                char buf[64];
-                               Con_DPrintf("PRVM_LoadProgs: no cvar for autocvar global %s in %s, creating...\n", name, PRVM_NAME);
+                               Con_DPrintf("PRVM_LoadProgs: no cvar for autocvar global %s in %s, creating...\n", name, prog->name);
                                switch(prog->globaldefs[i].type & ~DEF_SAVEGLOBAL)
                                {
                                        case ev_float:
@@ -2352,22 +2389,21 @@ void PRVM_LoadProgs (const char * filename, int numrequiredfunc, const char **re
                                                dpsnprintf(buf, sizeof(buf), "%.9g %.9g %.9g", val->vector[0], val->vector[1], val->vector[2]); value = buf;
                                                break;
                                        case ev_string:
-                                               value = PRVM_GetString(val->string);
+                                               value = PRVM_GetString(prog, val->string);
                                                break;
                                        default:
-                                               Con_Printf("PRVM_LoadProgs: invalid type of autocvar global %s in %s\n", name, PRVM_NAME);
+                                               Con_Printf("PRVM_LoadProgs: invalid type of autocvar global %s in %s\n", name, prog->name);
                                                goto fail;
                                }
                                cvar = Cvar_Get(name + 9, value, 0, NULL);
                                if((prog->globaldefs[i].type & ~DEF_SAVEGLOBAL) == ev_string)
                                {
-                                       val->string = PRVM_SetEngineString(cvar->string);
-                                       cvar->globaldefindex_stringno[prog - prog_list] = val->string;
+                                       val->string = PRVM_SetEngineString(prog, cvar->string);
+                                       cvar->globaldefindex_stringno[prog - prvm_prog_list] = val->string;
                                }
                                if(!cvar)
-                                       PRVM_ERROR("PRVM_LoadProgs: could not create cvar for autocvar global %s in %s", name, PRVM_NAME);
-                               cvar->globaldefindex_progid[prog - prog_list] = prog->id;
-                               cvar->globaldefindex[prog - prog_list] = i;
+                                       prog->error_cmd("PRVM_LoadProgs: could not create cvar for autocvar global %s in %s", name, prog->name);
+                               cvar->globaldefindex[prog - prvm_prog_list] = i;
                        }
                        else if((cvar->flags & CVAR_PRIVATE) == 0)
                        {
@@ -2396,18 +2432,17 @@ void PRVM_LoadProgs (const char * filename, int numrequiredfunc, const char **re
                                                }
                                                break;
                                        case ev_string:
-                                               val->string = PRVM_SetEngineString(cvar->string);
-                                               cvar->globaldefindex_stringno[prog - prog_list] = val->string;
+                                               val->string = PRVM_SetEngineString(prog, cvar->string);
+                                               cvar->globaldefindex_stringno[prog - prvm_prog_list] = val->string;
                                                break;
                                        default:
-                                               Con_Printf("PRVM_LoadProgs: invalid type of autocvar global %s in %s\n", name, PRVM_NAME);
+                                               Con_Printf("PRVM_LoadProgs: invalid type of autocvar global %s in %s\n", name, prog->name);
                                                goto fail;
                                }
-                               cvar->globaldefindex_progid[prog - prog_list] = prog->id;
-                               cvar->globaldefindex[prog - prog_list] = i;
+                               cvar->globaldefindex[prog - prvm_prog_list] = i;
                        }
                        else
-                               Con_Printf("PRVM_LoadProgs: private cvar for autocvar global %s in %s\n", name, PRVM_NAME);
+                               Con_Printf("PRVM_LoadProgs: private cvar for autocvar global %s in %s\n", name, prog->name);
                }
 fail:
                ;
@@ -2415,28 +2450,35 @@ fail:
 
        prog->loaded = TRUE;
 
+       PRVM_UpdateBreakpoints(prog);
+
        // set flags & ddef_ts in prog
 
        prog->flag = 0;
 
-       PRVM_FindOffsets();
+       PRVM_FindOffsets(prog);
 
-       PRVM_GCALL(init_cmd)();
+       prog->init_cmd(prog);
 
        // init mempools
-       PRVM_MEM_Alloc();
+       PRVM_MEM_Alloc(prog);
+
+       // Inittime is at least the time when this function finished. However,
+       // later events may bump it.
+       prog->inittime = realtime;
 }
 
 
-void PRVM_Fields_f (void)
+static void PRVM_Fields_f (void)
 {
+       prvm_prog_t *prog;
        int i, j, ednum, used, usedamount;
        int *counts;
        char tempstring[MAX_INPUTLINE], tempstring2[260];
        const char *name;
        prvm_edict_t *ed;
        ddef_t *d;
-       int *v;
+       prvm_eval_t *val;
 
        // TODO
        /*
@@ -2453,8 +2495,7 @@ void PRVM_Fields_f (void)
                return;
        }
 
-       PRVM_Begin;
-       if(!PRVM_SetProgFromString(Cmd_Argv(1)))
+       if (!(prog = PRVM_FriendlyProgFromString(Cmd_Argv(1))))
                return;
 
        counts = (int *)Mem_Alloc(tempmempool, prog->numfielddefs * sizeof(int));
@@ -2466,14 +2507,14 @@ void PRVM_Fields_f (void)
                for (i = 1;i < prog->numfielddefs;i++)
                {
                        d = &prog->fielddefs[i];
-                       name = PRVM_GetString(d->s_name);
+                       name = PRVM_GetString(prog, d->s_name);
                        if (name[strlen(name)-2] == '_')
                                continue;       // skip _x, _y, _z vars
-                       v = (int *)(ed->fields.vp + d->ofs);
+                       val = (prvm_eval_t *)(ed->fields.fp + d->ofs);
                        // if the value is still all 0, skip the field
                        for (j = 0;j < prvm_type_size[d->type & ~DEF_SAVEGLOBAL];j++)
                        {
-                               if (v[j])
+                               if (val->ivector[j])
                                {
                                        counts[i]++;
                                        break;
@@ -2487,7 +2528,7 @@ void PRVM_Fields_f (void)
        for (i = 0;i < prog->numfielddefs;i++)
        {
                d = &prog->fielddefs[i];
-               name = PRVM_GetString(d->s_name);
+               name = PRVM_GetString(prog, d->s_name);
                if (name[strlen(name)-2] == '_')
                        continue;       // skip _x, _y, _z vars
                switch(d->type & ~DEF_SAVEGLOBAL)
@@ -2546,13 +2587,12 @@ void PRVM_Fields_f (void)
                }
        }
        Mem_Free(counts);
-       Con_Printf("%s: %i entity fields (%i in use), totalling %i bytes per edict (%i in use), %i edicts allocated, %i bytes total spent on edict fields (%i needed)\n", PRVM_NAME, prog->entityfields, used, prog->entityfields * 4, usedamount * 4, prog->max_edicts, prog->entityfields * 4 * prog->max_edicts, usedamount * 4 * prog->max_edicts);
-
-       PRVM_End;
+       Con_Printf("%s: %i entity fields (%i in use), totalling %i bytes per edict (%i in use), %i edicts allocated, %i bytes total spent on edict fields (%i needed)\n", prog->name, prog->entityfields, used, prog->entityfields * 4, usedamount * 4, prog->max_edicts, prog->entityfields * 4 * prog->max_edicts, usedamount * 4 * prog->max_edicts);
 }
 
-void PRVM_Globals_f (void)
+static void PRVM_Globals_f (void)
 {
+       prvm_prog_t *prog;
        int i;
        const char *wildcard;
        int numculled;
@@ -2569,8 +2609,7 @@ void PRVM_Globals_f (void)
                return;
        }
 
-       PRVM_Begin;
-       if(!PRVM_SetProgFromString (Cmd_Argv (1)))
+       if (!(prog = PRVM_FriendlyProgFromString(Cmd_Argv(1))))
                return;
 
        if( Cmd_Argc() == 3)
@@ -2578,21 +2617,19 @@ void PRVM_Globals_f (void)
        else
                wildcard = NULL;
 
-       Con_Printf("%s :", PRVM_NAME);
+       Con_Printf("%s :", prog->name);
 
        for (i = 0;i < prog->numglobaldefs;i++)
        {
                if(wildcard)
-                       if( !matchpattern( PRVM_GetString(prog->globaldefs[i].s_name), wildcard, 1) )
+                       if( !matchpattern( PRVM_GetString(prog, prog->globaldefs[i].s_name), wildcard, 1) )
                        {
                                numculled++;
                                continue;
                        }
-               Con_Printf("%s\n", PRVM_GetString(prog->globaldefs[i].s_name));
+               Con_Printf("%s\n", PRVM_GetString(prog, prog->globaldefs[i].s_name));
        }
        Con_Printf("%i global variables, %i culled, totalling %i bytes\n", prog->numglobals, numculled, prog->numglobals * 4);
-
-       PRVM_End;
 }
 
 /*
@@ -2600,24 +2637,24 @@ void PRVM_Globals_f (void)
 PRVM_Global
 ===============
 */
-void PRVM_Global_f(void)
+static void PRVM_Global_f(void)
 {
+       prvm_prog_t *prog;
        ddef_t *global;
+       char valuebuf[MAX_INPUTLINE];
        if( Cmd_Argc() != 3 ) {
                Con_Printf( "prvm_global <program name> <global name>\n" );
                return;
        }
 
-       PRVM_Begin;
-       if( !PRVM_SetProgFromString( Cmd_Argv(1) ) )
+       if (!(prog = PRVM_FriendlyProgFromString(Cmd_Argv(1))))
                return;
 
-       global = PRVM_ED_FindGlobal( Cmd_Argv(2) );
+       global = PRVM_ED_FindGlobal( prog, Cmd_Argv(2) );
        if( !global )
                Con_Printf( "No global '%s' in %s!\n", Cmd_Argv(2), Cmd_Argv(1) );
        else
-               Con_Printf( "%s: %s\n", Cmd_Argv(2), PRVM_ValueString( (etype_t)global->type, PRVM_GLOBALFIELDVALUE(global->ofs) ) );
-       PRVM_End;
+               Con_Printf( "%s: %s\n", Cmd_Argv(2), PRVM_ValueString( prog, (etype_t)global->type, PRVM_GLOBALFIELDVALUE(global->ofs), valuebuf, sizeof(valuebuf) ) );
 }
 
 /*
@@ -2625,24 +2662,231 @@ void PRVM_Global_f(void)
 PRVM_GlobalSet
 ===============
 */
-void PRVM_GlobalSet_f(void)
+static void PRVM_GlobalSet_f(void)
 {
+       prvm_prog_t *prog;
        ddef_t *global;
        if( Cmd_Argc() != 4 ) {
                Con_Printf( "prvm_globalset <program name> <global name> <value>\n" );
                return;
        }
 
-       PRVM_Begin;
-       if( !PRVM_SetProgFromString( Cmd_Argv(1) ) )
+       if (!(prog = PRVM_FriendlyProgFromString(Cmd_Argv(1))))
                return;
 
-       global = PRVM_ED_FindGlobal( Cmd_Argv(2) );
+       global = PRVM_ED_FindGlobal( prog, Cmd_Argv(2) );
        if( !global )
                Con_Printf( "No global '%s' in %s!\n", Cmd_Argv(2), Cmd_Argv(1) );
        else
-               PRVM_ED_ParseEpair( NULL, global, Cmd_Argv(3), true );
-       PRVM_End;
+               PRVM_ED_ParseEpair( prog, NULL, global, Cmd_Argv(3), true );
+}
+
+/*
+======================
+Break- and Watchpoints
+======================
+*/
+typedef struct
+{
+       char break_statement[256];
+       char watch_global[256];
+       int watch_edict;
+       char watch_field[256];
+}
+debug_data_t;
+static debug_data_t debug_data[PRVM_PROG_MAX];
+
+void PRVM_Breakpoint(prvm_prog_t *prog, int stack_index, const char *text)
+{
+       char vabuf[1024];
+       Con_Printf("PRVM_Breakpoint: %s\n", text);
+       PRVM_PrintState(prog, stack_index);
+       if (prvm_breakpointdump.integer)
+               Host_Savegame_to(prog, va(vabuf, sizeof(vabuf), "breakpoint-%s.dmp", prog->name));
+}
+
+void PRVM_Watchpoint(prvm_prog_t *prog, int stack_index, const char *text, etype_t type, prvm_eval_t *o, prvm_eval_t *n)
+{
+       size_t sz = sizeof(prvm_vec_t) * ((type & ~DEF_SAVEGLOBAL) == ev_vector ? 3 : 1);
+       if (memcmp(o, n, sz))
+       {
+               char buf[1024];
+               char valuebuf_o[128];
+               char valuebuf_n[128];
+               PRVM_UglyValueString(prog, type, o, valuebuf_o, sizeof(valuebuf_o));
+               PRVM_UglyValueString(prog, type, n, valuebuf_n, sizeof(valuebuf_n));
+               dpsnprintf(buf, sizeof(buf), "%s: %s -> %s", text, valuebuf_o, valuebuf_n);
+               PRVM_Breakpoint(prog, stack_index, buf);
+               memcpy(o, n, sz);
+       }
+}
+
+static void PRVM_UpdateBreakpoints(prvm_prog_t *prog)
+{
+       debug_data_t *debug = &debug_data[prog - prvm_prog_list];
+       if (!prog->loaded)
+               return;
+       if (debug->break_statement[0])
+       {
+               if (debug->break_statement[0] >= '0' && debug->break_statement[0] <= '9')
+               {
+                       prog->break_statement = atoi(debug->break_statement);
+                       prog->break_stack_index = 0;
+               }
+               else
+               {
+                       mfunction_t *func;
+                       func = PRVM_ED_FindFunction (prog, debug->break_statement);
+                       if (!func)
+                       {
+                               Con_Printf("%s progs: no function or statement named %s to break on!\n", prog->name, debug->break_statement);
+                               prog->break_statement = -1;
+                       }
+                       else
+                       {
+                               prog->break_statement = func->first_statement;
+                               prog->break_stack_index = 1;
+                       }
+               }
+               if (prog->break_statement >= -1)
+                       Con_Printf("%s progs: breakpoint is at statement %d\n", prog->name, prog->break_statement);
+       }
+       else
+               prog->break_statement = -1;
+
+       if (debug->watch_global[0])
+       {
+               ddef_t *global = PRVM_ED_FindGlobal( prog, debug->watch_global );
+               if( !global )
+               {
+                       Con_Printf( "%s progs: no global named '%s' to watch!\n", prog->name, debug->watch_global );
+                       prog->watch_global_type = ev_void;
+               }
+               else
+               {
+                       size_t sz = sizeof(prvm_vec_t) * ((global->type  & ~DEF_SAVEGLOBAL) == ev_vector ? 3 : 1);
+                       prog->watch_global = global->ofs;
+                       prog->watch_global_type = (etype_t)global->type;
+                       memcpy(&prog->watch_global_value, PRVM_GLOBALFIELDVALUE(prog->watch_global), sz);
+               }
+               if (prog->watch_global_type != ev_void)
+                       Con_Printf("%s progs: global watchpoint is at global index %d\n", prog->name, prog->watch_global);
+       }
+       else
+               prog->watch_global_type = ev_void;
+
+       if (debug->watch_field[0])
+       {
+               ddef_t *field = PRVM_ED_FindField( prog, debug->watch_field );
+               if( !field )
+               {
+                       Con_Printf( "%s progs: no field named '%s' to watch!\n", prog->name, debug->watch_field );
+                       prog->watch_field_type = ev_void;
+               }
+               else
+               {
+                       size_t sz = sizeof(prvm_vec_t) * ((field->type & ~DEF_SAVEGLOBAL) == ev_vector ? 3 : 1);
+                       prog->watch_edict = debug->watch_edict;
+                       prog->watch_field = field->ofs;
+                       prog->watch_field_type = (etype_t)field->type;
+                       if (prog->watch_edict < prog->num_edicts)
+                               memcpy(&prog->watch_edictfield_value, PRVM_EDICTFIELDVALUE(PRVM_EDICT_NUM(prog->watch_edict), prog->watch_field), sz);
+                       else
+                               memset(&prog->watch_edictfield_value, 0, sz);
+               }
+               if (prog->watch_edict != ev_void)
+                       Con_Printf("%s progs: edict field watchpoint is at edict %d field index %d\n", prog->name, prog->watch_edict, prog->watch_field);
+       }
+       else
+               prog->watch_field_type = ev_void;
+}
+
+static void PRVM_Breakpoint_f(void)
+{
+       prvm_prog_t *prog;
+
+       if( Cmd_Argc() == 2 ) {
+               if (!(prog = PRVM_FriendlyProgFromString(Cmd_Argv(1))))
+                       return;
+               {
+                       debug_data_t *debug = &debug_data[prog - prvm_prog_list];
+                       debug->break_statement[0] = 0;
+               }
+               PRVM_UpdateBreakpoints(prog);
+               return;
+       }
+       if( Cmd_Argc() != 3 ) {
+               Con_Printf( "prvm_breakpoint <program name> <function name | statement>\n" );
+               return;
+       }
+
+       if (!(prog = PRVM_ProgFromString(Cmd_Argv(1))))
+               return;
+
+       {
+               debug_data_t *debug = &debug_data[prog - prvm_prog_list];
+               strlcpy(debug->break_statement, Cmd_Argv(2), sizeof(debug->break_statement));
+       }
+       PRVM_UpdateBreakpoints(prog);
+}
+
+static void PRVM_GlobalWatchpoint_f(void)
+{
+       prvm_prog_t *prog;
+
+       if( Cmd_Argc() == 2 ) {
+               if (!(prog = PRVM_FriendlyProgFromString(Cmd_Argv(1))))
+                       return;
+               {
+                       debug_data_t *debug = &debug_data[prog - prvm_prog_list];
+                       debug->watch_global[0] = 0;
+               }
+               PRVM_UpdateBreakpoints(prog);
+               return;
+       }
+       if( Cmd_Argc() != 3 ) {
+               Con_Printf( "prvm_globalwatchpoint <program name> <global name>\n" );
+               return;
+       }
+
+       if (!(prog = PRVM_ProgFromString(Cmd_Argv(1))))
+               return;
+
+       {
+               debug_data_t *debug = &debug_data[prog - prvm_prog_list];
+               strlcpy(debug->watch_global, Cmd_Argv(2), sizeof(debug->watch_global));
+       }
+       PRVM_UpdateBreakpoints(prog);
+}
+
+static void PRVM_EdictWatchpoint_f(void)
+{
+       prvm_prog_t *prog;
+
+       if( Cmd_Argc() == 2 ) {
+               if (!(prog = PRVM_FriendlyProgFromString(Cmd_Argv(1))))
+                       return;
+               {
+                       debug_data_t *debug = &debug_data[prog - prvm_prog_list];
+                       debug->watch_field[0] = 0;
+               }
+               PRVM_UpdateBreakpoints(prog);
+               return;
+       }
+       if( Cmd_Argc() != 4 ) {
+               Con_Printf( "prvm_edictwatchpoint <program name> <edict number> <field name>\n" );
+               return;
+       }
+
+       if (!(prog = PRVM_ProgFromString(Cmd_Argv(1))))
+               return;
+
+       {
+               debug_data_t *debug = &debug_data[prog - prvm_prog_list];
+               debug->watch_edict = atoi(Cmd_Argv(2));
+               strlcpy(debug->watch_field, Cmd_Argv(3), sizeof(debug->watch_field));
+       }
+       PRVM_UpdateBreakpoints(prog);
 }
 
 /*
@@ -2670,14 +2914,21 @@ void PRVM_Init (void)
        Cmd_AddCommand ("menu_cmd", PRVM_GameCommand_Menu_f, "calls the menu QC function GameCommand with the supplied string as argument");
        Cmd_AddCommand ("sv_cmd", PRVM_GameCommand_Server_f, "calls the server QC function GameCommand with the supplied string as argument");
 
+       Cmd_AddCommand ("prvm_breakpoint", PRVM_Breakpoint_f, "marks a statement or function as breakpoint (when this is executed, a stack trace is printed); to actually halt and investigate state, combine this with a gdb breakpoint on PRVM_Breakpoint, or with prvm_breakpointdump; run with just progs name to clear breakpoint");
+       Cmd_AddCommand ("prvm_globalwatchpoint", PRVM_GlobalWatchpoint_f, "marks a global as watchpoint (when this is executed, a stack trace is printed); to actually halt and investigate state, combine this with a gdb breakpoint on PRVM_Breakpoint, or with prvm_breakpointdump; run with just progs name to clear watchpoint");
+       Cmd_AddCommand ("prvm_edictwatchpoint", PRVM_EdictWatchpoint_f, "marks an entity field as watchpoint (when this is executed, a stack trace is printed); to actually halt and investigate state, combine this with a gdb breakpoint on PRVM_Breakpoint, or with prvm_breakpointdump; run with just progs name to clear watchpoint");
+
        Cvar_RegisterVariable (&prvm_language);
        Cvar_RegisterVariable (&prvm_traceqc);
        Cvar_RegisterVariable (&prvm_statementprofiling);
        Cvar_RegisterVariable (&prvm_timeprofiling);
+       Cvar_RegisterVariable (&prvm_coverage);
        Cvar_RegisterVariable (&prvm_backtraceforwarnings);
        Cvar_RegisterVariable (&prvm_leaktest);
+       Cvar_RegisterVariable (&prvm_leaktest_follow_targetname);
        Cvar_RegisterVariable (&prvm_leaktest_ignore_classnames);
        Cvar_RegisterVariable (&prvm_errordump);
+       Cvar_RegisterVariable (&prvm_breakpointdump);
        Cvar_RegisterVariable (&prvm_reuseedicts_startuptime);
        Cvar_RegisterVariable (&prvm_reuseedicts_neverinsameframe);
 
@@ -2692,68 +2943,27 @@ void PRVM_Init (void)
 PRVM_InitProg
 ===============
 */
-void PRVM_InitProg(int prognr)
+void PRVM_Prog_Init(prvm_prog_t *prog)
 {
-       static unsigned int progid = 0;
-
-       if(prognr < 0 || prognr >= PRVM_MAXPROGS)
-               Sys_Error("PRVM_InitProg: Invalid program number %i",prognr);
-
-       prog = &prog_list[prognr];
-
-       if(prog->loaded)
-               PRVM_ResetProg();
-
-       memset(prog, 0, sizeof(prvm_prog_t));
-       prog->starttime = Sys_DoubleTime();
-       prog->id = ++progid;
-
-       prog->error_cmd = Host_Error;
+       PRVM_Prog_Reset(prog);
        prog->leaktest_active = prvm_leaktest.integer != 0;
 }
 
-int PRVM_GetProgNr(void)
-{
-       return prog - prog_list;
-}
-
-void *_PRVM_Alloc(size_t buffersize, const char *filename, int fileline)
-{
-       return _Mem_Alloc(prog->progs_mempool, NULL, buffersize, 16, filename, fileline);
-}
-
-void _PRVM_Free(void *buffer, const char *filename, int fileline)
-{
-       _Mem_Free(buffer, filename, fileline);
-}
-
-void _PRVM_FreeAll(const char *filename, int fileline)
-{
-       prog->functions = NULL;
-       prog->strings = NULL;
-       prog->fielddefs = NULL;
-       prog->globaldefs = NULL;
-       prog->statements = NULL;
-       // FIXME: what about knownstrings?
-       _Mem_EmptyPool(prog->progs_mempool, filename, fileline);
-}
-
 // LordHavoc: turned PRVM_EDICT_NUM into a #define for speed reasons
-unsigned int PRVM_EDICT_NUM_ERROR(unsigned int n, const char *filename, int fileline)
+unsigned int PRVM_EDICT_NUM_ERROR(prvm_prog_t *prog, unsigned int n, const char *filename, int fileline)
 {
-       PRVM_ERROR ("PRVM_EDICT_NUM: %s: bad number %i (called at %s:%i)", PRVM_NAME, n, filename, fileline);
+       prog->error_cmd("PRVM_EDICT_NUM: %s: bad number %i (called at %s:%i)", prog->name, n, filename, fileline);
        return 0;
 }
 
-sizebuf_t vm_tempstringsbuf;
 #define PRVM_KNOWNSTRINGBASE 0x40000000
 
-const char *PRVM_GetString(int num)
+const char *PRVM_GetString(prvm_prog_t *prog, int num)
 {
        if (num < 0)
        {
                // invalid
-               VM_Warning("PRVM_GetString: Invalid string offset (%i < 0)\n", num);
+               VM_Warning(prog, "PRVM_GetString: Invalid string offset (%i < 0)\n", num);
                return "";
        }
        else if (num < prog->stringssize)
@@ -2761,15 +2971,15 @@ const char *PRVM_GetString(int num)
                // constant string from progs.dat
                return prog->strings + num;
        }
-       else if (num <= prog->stringssize + vm_tempstringsbuf.maxsize)
+       else if (num <= prog->stringssize + prog->tempstringsbuf.maxsize)
        {
                // tempstring returned by engine to QC (becomes invalid after returning to engine)
                num -= prog->stringssize;
-               if (num < vm_tempstringsbuf.cursize)
-                       return (char *)vm_tempstringsbuf.data + num;
+               if (num < prog->tempstringsbuf.cursize)
+                       return (char *)prog->tempstringsbuf.data + num;
                else
                {
-                       VM_Warning("PRVM_GetString: Invalid temp-string offset (%i >= %i vm_tempstringsbuf.cursize)\n", num, vm_tempstringsbuf.cursize);
+                       VM_Warning(prog, "PRVM_GetString: Invalid temp-string offset (%i >= %i prog->tempstringsbuf.cursize)\n", num, prog->tempstringsbuf.cursize);
                        return "";
                }
        }
@@ -2781,49 +2991,47 @@ const char *PRVM_GetString(int num)
                {
                        if (!prog->knownstrings[num])
                        {
-                               VM_Warning("PRVM_GetString: Invalid zone-string offset (%i has been freed)\n", num);
+                               VM_Warning(prog, "PRVM_GetString: Invalid zone-string offset (%i has been freed)\n", num);
                                return "";
                        }
                        return prog->knownstrings[num];
                }
                else
                {
-                       VM_Warning("PRVM_GetString: Invalid zone-string offset (%i >= %i)\n", num, prog->numknownstrings);
+                       VM_Warning(prog, "PRVM_GetString: Invalid zone-string offset (%i >= %i)\n", num, prog->numknownstrings);
                        return "";
                }
        }
        else
        {
                // invalid string offset
-               VM_Warning("PRVM_GetString: Invalid constant-string offset (%i >= %i prog->stringssize)\n", num, prog->stringssize);
+               VM_Warning(prog, "PRVM_GetString: Invalid constant-string offset (%i >= %i prog->stringssize)\n", num, prog->stringssize);
                return "";
        }
 }
 
-const char *PRVM_ChangeEngineString(int i, const char *s)
+const char *PRVM_ChangeEngineString(prvm_prog_t *prog, int i, const char *s)
 {
        const char *old;
        i = i - PRVM_KNOWNSTRINGBASE;
        if(i < 0 || i >= prog->numknownstrings)
-               PRVM_ERROR("PRVM_ChangeEngineString: s is not an engine string");
+               prog->error_cmd("PRVM_ChangeEngineString: s is not an engine string");
        old = prog->knownstrings[i];
        prog->knownstrings[i] = s;
        return old;
 }
 
-int PRVM_SetEngineString(const char *s)
+int PRVM_SetEngineString(prvm_prog_t *prog, const char *s)
 {
        int i;
        if (!s)
                return 0;
        if (s >= prog->strings && s <= prog->strings + prog->stringssize)
-               PRVM_ERROR("PRVM_SetEngineString: s in prog->strings area");
+               prog->error_cmd("PRVM_SetEngineString: s in prog->strings area");
        // if it's in the tempstrings area, use a reserved range
        // (otherwise we'd get millions of useless string offsets cluttering the database)
-       if (s >= (char *)vm_tempstringsbuf.data && s < (char *)vm_tempstringsbuf.data + vm_tempstringsbuf.maxsize)
-#if 1
-               return prog->stringssize + (s - (char *)vm_tempstringsbuf.data);
-#endif
+       if (s >= (char *)prog->tempstringsbuf.data && s < (char *)prog->tempstringsbuf.data + prog->tempstringsbuf.maxsize)
+               return prog->stringssize + (s - (char *)prog->tempstringsbuf.data);
        // see if it's a known string address
        for (i = 0;i < prog->numknownstrings;i++)
                if (prog->knownstrings[i] == s)
@@ -2873,7 +3081,7 @@ int PRVM_SetEngineString(const char *s)
 //  buffer)
 // the buffer size is automatically grown as needed
 
-int PRVM_SetTempString(const char *s)
+int PRVM_SetTempString(prvm_prog_t *prog, const char *s)
 {
        int size;
        char *t;
@@ -2881,36 +3089,42 @@ int PRVM_SetTempString(const char *s)
                return 0;
        size = (int)strlen(s) + 1;
        if (developer_insane.integer)
-               Con_DPrintf("PRVM_SetTempString: cursize %i, size %i\n", vm_tempstringsbuf.cursize, size);
-       if (vm_tempstringsbuf.maxsize < vm_tempstringsbuf.cursize + size)
-       {
-               sizebuf_t old = vm_tempstringsbuf;
-               if (vm_tempstringsbuf.cursize + size >= 1<<28)
-                       PRVM_ERROR("PRVM_SetTempString: ran out of tempstring memory!  (refusing to grow tempstring buffer over 256MB, cursize %i, size %i)\n", vm_tempstringsbuf.cursize, size);
-               vm_tempstringsbuf.maxsize = max(vm_tempstringsbuf.maxsize, 65536);
-               while (vm_tempstringsbuf.maxsize < vm_tempstringsbuf.cursize + size)
-                       vm_tempstringsbuf.maxsize *= 2;
-               if (vm_tempstringsbuf.maxsize != old.maxsize || vm_tempstringsbuf.data == NULL)
-               {
-                       Con_DPrintf("PRVM_SetTempString: enlarging tempstrings buffer (%iKB -> %iKB)\n", old.maxsize/1024, vm_tempstringsbuf.maxsize/1024);
-                       vm_tempstringsbuf.data = (unsigned char *) Mem_Alloc(sv_mempool, vm_tempstringsbuf.maxsize);
-                       if (old.cursize)
-                               memcpy(vm_tempstringsbuf.data, old.data, old.cursize);
+               Con_DPrintf("PRVM_SetTempString: cursize %i, size %i\n", prog->tempstringsbuf.cursize, size);
+       if (prog->tempstringsbuf.maxsize < prog->tempstringsbuf.cursize + size)
+       {
+               sizebuf_t old = prog->tempstringsbuf;
+               if (prog->tempstringsbuf.cursize + size >= 1<<28)
+                       prog->error_cmd("PRVM_SetTempString: ran out of tempstring memory!  (refusing to grow tempstring buffer over 256MB, cursize %i, size %i)\n", prog->tempstringsbuf.cursize, size);
+               prog->tempstringsbuf.maxsize = max(prog->tempstringsbuf.maxsize, 65536);
+               while (prog->tempstringsbuf.maxsize < prog->tempstringsbuf.cursize + size)
+                       prog->tempstringsbuf.maxsize *= 2;
+               if (prog->tempstringsbuf.maxsize != old.maxsize || prog->tempstringsbuf.data == NULL)
+               {
+                       Con_DPrintf("PRVM_SetTempString: enlarging tempstrings buffer (%iKB -> %iKB)\n", old.maxsize/1024, prog->tempstringsbuf.maxsize/1024);
+                       prog->tempstringsbuf.data = (unsigned char *) Mem_Alloc(prog->progs_mempool, prog->tempstringsbuf.maxsize);
                        if (old.data)
+                       {
+                               if (old.cursize)
+                                       memcpy(prog->tempstringsbuf.data, old.data, old.cursize);
                                Mem_Free(old.data);
+                       }
                }
        }
-       t = (char *)vm_tempstringsbuf.data + vm_tempstringsbuf.cursize;
+       t = (char *)prog->tempstringsbuf.data + prog->tempstringsbuf.cursize;
        memcpy(t, s, size);
-       vm_tempstringsbuf.cursize += size;
-       return PRVM_SetEngineString(t);
+       prog->tempstringsbuf.cursize += size;
+       return PRVM_SetEngineString(prog, t);
 }
 
-int PRVM_AllocString(size_t bufferlength, char **pointer)
+int PRVM_AllocString(prvm_prog_t *prog, size_t bufferlength, char **pointer)
 {
        int i;
        if (!bufferlength)
+       {
+               if (pointer)
+                       *pointer = NULL;
                return 0;
+       }
        for (i = prog->firstfreeknownstring;i < prog->numknownstrings;i++)
                if (!prog->knownstrings[i])
                        break;
@@ -2946,25 +3160,25 @@ int PRVM_AllocString(size_t bufferlength, char **pointer)
        prog->knownstrings[i] = (char *)PRVM_Alloc(bufferlength);
        prog->knownstrings_freeable[i] = true;
        if(prog->leaktest_active)
-               prog->knownstrings_origin[i] = PRVM_AllocationOrigin();
+               prog->knownstrings_origin[i] = PRVM_AllocationOrigin(prog);
        if (pointer)
                *pointer = (char *)(prog->knownstrings[i]);
        return PRVM_KNOWNSTRINGBASE + i;
 }
 
-void PRVM_FreeString(int num)
+void PRVM_FreeString(prvm_prog_t *prog, int num)
 {
        if (num == 0)
-               PRVM_ERROR("PRVM_FreeString: attempt to free a NULL string");
+               prog->error_cmd("PRVM_FreeString: attempt to free a NULL string");
        else if (num >= 0 && num < prog->stringssize)
-               PRVM_ERROR("PRVM_FreeString: attempt to free a constant string");
+               prog->error_cmd("PRVM_FreeString: attempt to free a constant string");
        else if (num >= PRVM_KNOWNSTRINGBASE && num < PRVM_KNOWNSTRINGBASE + prog->numknownstrings)
        {
                num = num - PRVM_KNOWNSTRINGBASE;
                if (!prog->knownstrings[num])
-                       PRVM_ERROR("PRVM_FreeString: attempt to free a non-existent or already freed string");
+                       prog->error_cmd("PRVM_FreeString: attempt to free a non-existent or already freed string");
                if (!prog->knownstrings_freeable[num])
-                       PRVM_ERROR("PRVM_FreeString: attempt to free a string owned by the engine");
+                       prog->error_cmd("PRVM_FreeString: attempt to free a string owned by the engine");
                PRVM_Free((char *)prog->knownstrings[num]);
                if(prog->leaktest_active)
                        if(prog->knownstrings_origin[num])
@@ -2974,10 +3188,10 @@ void PRVM_FreeString(int num)
                prog->firstfreeknownstring = min(prog->firstfreeknownstring, num);
        }
        else
-               PRVM_ERROR("PRVM_FreeString: invalid string offset %i", num);
+               prog->error_cmd("PRVM_FreeString: invalid string offset %i", num);
 }
 
-static qboolean PRVM_IsStringReferenced(string_t string)
+static qboolean PRVM_IsStringReferenced(prvm_prog_t *prog, string_t string)
 {
        int i, j;
 
@@ -3008,84 +3222,71 @@ static qboolean PRVM_IsStringReferenced(string_t string)
        return false;
 }
 
-static qboolean PRVM_IsEdictRelevant(prvm_edict_t *edict)
+static qboolean PRVM_IsEdictRelevant(prvm_prog_t *prog, prvm_edict_t *edict)
 {
+       char vabuf[1024];
+       char vabuf2[1024];
        if(PRVM_NUM_FOR_EDICT(edict) <= prog->reserved_edicts)
                return true; // world or clients
-       switch(prog - prog_list)
+       if (edict->priv.required->freetime <= prog->inittime)
+               return true; // created during startup
+       if (prog == SVVM_prog)
        {
-               case PRVM_SERVERPROG:
-                       {
-                               if(PRVM_serveredictfloat(edict, solid)) // can block other stuff, or is a trigger?
-                                       return true;
-                               if(PRVM_serveredictfloat(edict, modelindex)) // visible ent?
-                                       return true;
-                               if(PRVM_serveredictfloat(edict, effects)) // particle effect?
-                                       return true;
-                               if(PRVM_serveredictfunction(edict, think)) // has a think function?
-                                       if(PRVM_serveredictfloat(edict, nextthink) > 0) // that actually will eventually run?
-                                               return true;
-                               if(PRVM_serveredictfloat(edict, takedamage))
-                                       return true;
-                               if(*prvm_leaktest_ignore_classnames.string)
-                               {
-                                       if(strstr(va(" %s ", prvm_leaktest_ignore_classnames.string), va(" %s ", PRVM_GetString(PRVM_serveredictstring(edict, classname)))))
-                                               return true;
-                               }
-                       }
-                       break;
-               case PRVM_CLIENTPROG:
-                       {
-                               // TODO someone add more stuff here
-                               if(PRVM_clientedictfloat(edict, entnum)) // csqc networked
-                                       return true;
-                               if(PRVM_clientedictfloat(edict, modelindex)) // visible ent?
-                                       return true;
-                               if(PRVM_clientedictfloat(edict, effects)) // particle effect?
-                                       return true;
-                               if(PRVM_clientedictfunction(edict, think)) // has a think function?
-                                       if(PRVM_clientedictfloat(edict, nextthink) > 0) // that actually will eventually run?
-                                               return true;
-                               if(*prvm_leaktest_ignore_classnames.string)
-                               {
-                                       if(strstr(va(" %s ", prvm_leaktest_ignore_classnames.string), va(" %s ", PRVM_GetString(PRVM_clientedictstring(edict, classname)))))
-                                               return true;
-                               }
-                       }
-                       break;
-               case PRVM_MENUPROG:
-                       // menu prog does not have classnames
-                       break;
+               if(PRVM_serveredictfloat(edict, solid)) // can block other stuff, or is a trigger?
+                       return true;
+               if(PRVM_serveredictfloat(edict, modelindex)) // visible ent?
+                       return true;
+               if(PRVM_serveredictfloat(edict, effects)) // particle effect?
+                       return true;
+               if(PRVM_serveredictfunction(edict, think)) // has a think function?
+                       if(PRVM_serveredictfloat(edict, nextthink) > 0) // that actually will eventually run?
+                               return true;
+               if(PRVM_serveredictfloat(edict, takedamage))
+                       return true;
+               if(*prvm_leaktest_ignore_classnames.string)
+               {
+                       if(strstr(va(vabuf, sizeof(vabuf), " %s ", prvm_leaktest_ignore_classnames.string), va(vabuf2, sizeof(vabuf2), " %s ", PRVM_GetString(prog, PRVM_serveredictstring(edict, classname)))))
+                               return true;
+               }
+       }
+       else if (prog == CLVM_prog)
+       {
+               // TODO someone add more stuff here
+               if(PRVM_clientedictfloat(edict, entnum)) // csqc networked
+                       return true;
+               if(PRVM_clientedictfloat(edict, modelindex)) // visible ent?
+                       return true;
+               if(PRVM_clientedictfloat(edict, effects)) // particle effect?
+                       return true;
+               if(PRVM_clientedictfunction(edict, think)) // has a think function?
+                       if(PRVM_clientedictfloat(edict, nextthink) > 0) // that actually will eventually run?
+                               return true;
+               if(*prvm_leaktest_ignore_classnames.string)
+               {
+                       if(strstr(va(vabuf, sizeof(vabuf), " %s ", prvm_leaktest_ignore_classnames.string), va(vabuf2, sizeof(vabuf2), " %s ", PRVM_GetString(prog, PRVM_clientedictstring(edict, classname)))))
+                               return true;
+               }
+       }
+       else
+       {
+               // menu prog does not have classnames
        }
        return false;
 }
 
-static qboolean PRVM_IsEdictReferenced(prvm_edict_t *edict, int mark)
+static qboolean PRVM_IsEdictReferenced(prvm_prog_t *prog, prvm_edict_t *edict, int mark)
 {
        int i, j;
        int edictnum = PRVM_NUM_FOR_EDICT(edict);
        const char *targetname = NULL;
 
-       switch(prog - prog_list)
-       {
-               case PRVM_SERVERPROG:
-                       targetname = PRVM_GetString(PRVM_serveredictstring(edict, targetname));
-                       break;
-       }
+       if (prog == SVVM_prog && prvm_leaktest_follow_targetname.integer)
+               targetname = PRVM_GetString(prog, PRVM_serveredictstring(edict, targetname));
 
        if(targetname)
                if(!*targetname) // ""
                        targetname = NULL;
 
-       for (i = 0;i < prog->numglobaldefs;i++)
-       {
-               ddef_t *d = &prog->globaldefs[i];
-               if((etype_t)((int) d->type & ~DEF_SAVEGLOBAL) != ev_entity)
-                       continue;
-               if(edictnum == PRVM_GLOBALFIELDEDICT(d->ofs))
-                       return true;
-       }
-
        for(j = 0; j < prog->num_edicts; ++j)
        {
                prvm_edict_t *ed = PRVM_EDICT_NUM(j);
@@ -3095,7 +3296,7 @@ static qboolean PRVM_IsEdictReferenced(prvm_edict_t *edict, int mark)
                        continue;
                if(targetname)
                {
-                       const char *target = PRVM_GetString(PRVM_serveredictstring(ed, target));
+                       const char *target = PRVM_GetString(prog, PRVM_serveredictstring(ed, target));
                        if(target)
                                if(!strcmp(target, targetname))
                                        return true;
@@ -3113,21 +3314,37 @@ static qboolean PRVM_IsEdictReferenced(prvm_edict_t *edict, int mark)
        return false;
 }
 
-static void PRVM_MarkReferencedEdicts(void)
+static void PRVM_MarkReferencedEdicts(prvm_prog_t *prog)
 {
-       int j;
+       int i, j;
        qboolean found_new;
        int stage;
 
+       // Stage 1: world, all entities that are relevant, and all entities that are referenced by globals.
+       stage = 1;
        for(j = 0; j < prog->num_edicts; ++j)
        {
                prvm_edict_t *ed = PRVM_EDICT_NUM(j);
                if(ed->priv.required->free)
                        continue;
-               ed->priv.required->mark = PRVM_IsEdictRelevant(ed) ? 1 : 0;
+               ed->priv.required->mark = PRVM_IsEdictRelevant(prog, ed) ? stage : 0;
+       }
+       for (i = 0;i < prog->numglobaldefs;i++)
+       {
+               ddef_t *d = &prog->globaldefs[i];
+               prvm_edict_t *ed;
+               if((etype_t)((int) d->type & ~DEF_SAVEGLOBAL) != ev_entity)
+                       continue;
+               j = PRVM_GLOBALFIELDEDICT(d->ofs);
+               if (i < 0 || j >= prog->max_edicts) {
+                       Con_Printf("Invalid entity reference from global %s.\n", PRVM_GetString(prog, d->s_name));
+                       continue;
+               }
+               ed = PRVM_EDICT_NUM(j);;
+               ed->priv.required->mark = stage;
        }
 
-       stage = 1;
+       // Future stages: all entities that are referenced by an entity of the previous stage.
        do
        {
                found_new = false;
@@ -3138,7 +3355,7 @@ static void PRVM_MarkReferencedEdicts(void)
                                continue;
                        if(ed->priv.required->mark)
                                continue;
-                       if(PRVM_IsEdictReferenced(ed, stage))
+                       if(PRVM_IsEdictReferenced(prog, ed, stage))
                        {
                                ed->priv.required->mark = stage + 1;
                                found_new = true;
@@ -3150,7 +3367,7 @@ static void PRVM_MarkReferencedEdicts(void)
        Con_DPrintf("leak check used %d stages to find all references\n", stage);
 }
 
-void PRVM_LeakTest(void)
+void PRVM_LeakTest(prvm_prog_t *prog)
 {
        int i, j;
        qboolean leaked = false;
@@ -3164,7 +3381,7 @@ void PRVM_LeakTest(void)
                if(prog->knownstrings[i])
                if(prog->knownstrings_freeable[i])
                if(prog->knownstrings_origin[i])
-               if(!PRVM_IsStringReferenced(PRVM_KNOWNSTRINGBASE + i))
+               if(!PRVM_IsStringReferenced(prog, PRVM_KNOWNSTRINGBASE + i))
                {
                        Con_Printf("Unreferenced string found!\n  Value: %s\n  Origin: %s\n", prog->knownstrings[i], prog->knownstrings_origin[i]);
                        leaked = true;
@@ -3172,7 +3389,7 @@ void PRVM_LeakTest(void)
        }
 
        // 2. Edicts
-       PRVM_MarkReferencedEdicts();
+       PRVM_MarkReferencedEdicts(prog);
        for(j = 0; j < prog->num_edicts; ++j)
        {
                prvm_edict_t *ed = PRVM_EDICT_NUM(j);
@@ -3182,10 +3399,12 @@ void PRVM_LeakTest(void)
                if(ed->priv.required->allocation_origin)
                {
                        Con_Printf("Unreferenced edict found!\n  Allocated at: %s\n", ed->priv.required->allocation_origin);
-                       PRVM_ED_Print(ed, NULL);
+                       PRVM_ED_Print(prog, ed, NULL);
                        Con_Print("\n");
                        leaked = true;
                }
+
+               ed->priv.required->mark = 0; // clear marks again when done
        }
 
        for (i = 0; i < (int)Mem_ExpandableArray_IndexRange(&prog->stringbuffersarray); ++i)