/*
  Copyright (C) 2010-2011  Charles Pence <charles@charlespence.net>
  Copyright (C) 1996-1997  Id Software, Inc.

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "pch.h"
#include "quakedef.h"
#include "filesystem/filesystem.h"

int    current_skill;

void Mod_Print (void);

/*
==================
Host_Quit_f
==================
*/

extern void M_Menu_Quit_f (void);

void Host_Quit_f (void)
{
    if (key_dest != key_console)
    {
        M_Menu_Quit_f ();
        return;
    }
    CL_Disconnect ();
    Host_ShutdownServer(false);

    Sys_Quit ();
}



/*
==================
Host_God_f

Sets client to godmode
==================
*/
void Host_God_f (void)
{
    if (cmd_source == src_command)
    {
        Cmd_ForwardToServer ();
        return;
    }

    if (pr_global_struct->deathmatch && !host_client->privileged)
        return;

    sv_player->v.flags = (int)sv_player->v.flags ^ FL_GODMODE;
    if (!((int)sv_player->v.flags & FL_GODMODE) )
        SV_ClientPrintf ("godmode OFF\n");
    else
        SV_ClientPrintf ("godmode ON\n");
}

void Host_Notarget_f (void)
{
    if (cmd_source == src_command)
    {
        Cmd_ForwardToServer ();
        return;
    }

    if (pr_global_struct->deathmatch && !host_client->privileged)
        return;

    sv_player->v.flags = (int)sv_player->v.flags ^ FL_NOTARGET;
    if (!((int)sv_player->v.flags & FL_NOTARGET) )
        SV_ClientPrintf ("notarget OFF\n");
    else
        SV_ClientPrintf ("notarget ON\n");
}

qboolean noclip_anglehack;

void Host_Noclip_f (void)
{
    if (cmd_source == src_command)
    {
        Cmd_ForwardToServer ();
        return;
    }

    if (pr_global_struct->deathmatch && !host_client->privileged)
        return;

    if (sv_player->v.movetype != MOVETYPE_NOCLIP)
    {
        noclip_anglehack = true;
        sv_player->v.movetype = MOVETYPE_NOCLIP;
        SV_ClientPrintf ("noclip ON\n");
    }
    else
    {
        noclip_anglehack = false;
        sv_player->v.movetype = MOVETYPE_WALK;
        SV_ClientPrintf ("noclip OFF\n");
    }
}

/*
==================
Host_Fly_f

Sets client to flymode
==================
*/
void Host_Fly_f (void)
{
    if (cmd_source == src_command)
    {
        Cmd_ForwardToServer ();
        return;
    }

    if (pr_global_struct->deathmatch && !host_client->privileged)
        return;

    if (sv_player->v.movetype != MOVETYPE_FLY)
    {
        sv_player->v.movetype = MOVETYPE_FLY;
        SV_ClientPrintf ("flymode ON\n");
    }
    else
    {
        sv_player->v.movetype = MOVETYPE_WALK;
        SV_ClientPrintf ("flymode OFF\n");
    }
}


/*
==================
Host_Ping_f

==================
*/
void Host_Ping_f (void)
{
    int        i, j;
    float    total;
    client_t    *client;

    if (cmd_source == src_command)
    {
        Cmd_ForwardToServer ();
        return;
    }

    SV_ClientPrintf ("Client ping times:\n");
    for (i=0, client = svs.clients ; i<svs.maxclients ; i++, client++)
    {
        if (!client->active)
            continue;
        total = 0;
        for (j=0 ; j<NUM_PING_TIMES ; j++)
            total+=client->ping_times[j];
        total /= NUM_PING_TIMES;
        SV_ClientPrintf ("%4i %s\n", (int)(total*1000), client->name);
    }
}

/*
===============================================================================

SERVER TRANSITIONS

===============================================================================
*/


/*
======================
Host_Map_f

handle a
map <servername>
command from the console.  Active clients are kicked off.
======================
*/
void Host_Map_f (void)
{
    char    name[MAX_QPATH];

    if (cmd_source != src_command)
        return;

    cls.demonum = -1;        // stop demo loop in case this fails

    CL_Disconnect ();
    Host_ShutdownServer(false);

    key_dest = key_game;            // remove console or menu
    SCR_BeginLoadingPlaque ();

    cls.mapstring[0] = 0;
    for (size_t i = 0 ; i < Cmd_Argc() ; i++)
    {
        strcat (cls.mapstring, Cmd_Argv(i).c_str());
        strcat (cls.mapstring, " ");
    }
    strcat (cls.mapstring, "\n");

    svs.serverflags = 0;            // haven't completed an episode yet
    strcpy (name, Cmd_Argv(1).c_str());

    SV_SpawnServer (name);

    if (!sv.active)
        return;

    strcpy (cls.spawnparms, "");

    for (size_t i = 2 ; i < Cmd_Argc() ; i++)
    {
        strcat (cls.spawnparms, Cmd_Argv(i).c_str());
        strcat (cls.spawnparms, " ");
    }

    Cmd_ExecuteString ("connect local", src_command);
}

/*
==================
Host_Changelevel_f

Goes to a new map, taking all clients along
==================
*/
void Host_Changelevel_f (void)
{
    if (Cmd_Argc() != 2)
    {
        Con_Printf ("changelevel <levelname> : continue game on a new level\n");
        return;
    }
    if (!sv.active || cls.demoplayback)
    {
        Con_Printf ("Only the server may changelevel\n");
        return;
    }

    SV_SaveSpawnparms ();
    SV_SpawnServer (Cmd_Argv(1));
}

/*
==================
Host_Restart_f

Restarts the current server for a dead player
==================
*/
void Host_Restart_f (void)
{
    char    mapname[MAX_QPATH];

    if (cls.demoplayback || !sv.active)
        return;

    if (cmd_source != src_command)
        return;
    strcpy (mapname, sv.name);    // must copy out, because it gets cleared
                                // in sv_spawnserver

    SV_SpawnServer (mapname);
}

/*
==================
Host_Reconnect_f

This command causes the client to wait for the signon messages again.
This is sent just before a server changes levels
==================
*/
void Host_Reconnect_f (void)
{
    SCR_BeginLoadingPlaque ();
    cls.signon = 0;        // need new connection messages
}

/*
=====================
Host_Connect_f

User command to connect to server
=====================
*/
void Host_Connect_f()
{
    cls.demonum = -1;        // stop demo loop in case this fails
    if (cls.demoplayback)
    {
        CL_StopPlayback ();
        CL_Disconnect ();
    }

    CL_EstablishConnection(Cmd_Argv(1));
    Host_Reconnect_f ();
}


/*
===============================================================================

LOAD / SAVE GAME

===============================================================================
*/

#define    SAVEGAME_VERSION    5

/*
===============
Host_SavegameComment

Writes a SAVEGAME_COMMENT_LENGTH character comment describing the current
===============
*/
void Host_SavegameComment (char *text)
{
    int        i;
    char    kills[20];

    for (i=0 ; i<SAVEGAME_COMMENT_LENGTH ; i++)
        text[i] = ' ';
    memcpy (text, cl.levelname, strlen(cl.levelname));
    sprintf (kills,"kills:%3i/%3i", cl.stats[STAT_MONSTERS], cl.stats[STAT_TOTALMONSTERS]);
    memcpy (text+22, kills, strlen(kills));
// convert space to _ to make stdio happy
    for (i=0 ; i<SAVEGAME_COMMENT_LENGTH ; i++)
        if (text[i] == ' ')
            text[i] = '_';
    text[SAVEGAME_COMMENT_LENGTH] = '\0';
}


/*
===============
Host_Savegame_f
===============
*/
void Host_Savegame_f (void)
{
    std::string name;
    FILE    *f;
    int        i;
    char    comment[SAVEGAME_COMMENT_LENGTH+1];

    if (cmd_source != src_command)
        return;

    if (!sv.active)
    {
        Con_Printf ("Not playing a local game.\n");
        return;
    }

    if (cl.intermission)
    {
        Con_Printf ("Can't save in intermission.\n");
        return;
    }

    if (svs.maxclients != 1)
    {
        Con_Printf ("Can't save multiplayer games.\n");
        return;
    }

    if (Cmd_Argc() != 2)
    {
        Con_Printf ("save <savename> : save a game\n");
        return;
    }

    for (i=0 ; i<svs.maxclients ; i++)
    {
        if (svs.clients[i].active && (svs.clients[i].edict->v.health <= 0) )
        {
            Con_Printf ("Can't savegame with a dead player\n");
            return;
        }
    }

    name = Cmd_Argv(1);
    name = filesystem::DefaultPathExtension(name, ".sav");

    Con_Printf ("Saving game to %s...\n", name.c_str());
    f = fopen (name.c_str(), "w");
    if (!f)
    {
        Con_Printf ("ERROR: couldn't open.\n");
        return;
    }

    fprintf (f, "%i\n", SAVEGAME_VERSION);
    Host_SavegameComment (comment);
    fprintf (f, "%s\n", comment);
    for (i=0 ; i<NUM_SPAWN_PARMS ; i++)
        fprintf (f, "%f\n", svs.clients->spawn_parms[i]);
    fprintf (f, "%d\n", current_skill);
    fprintf (f, "%s\n", sv.name);
    fprintf (f, "%f\n",sv.time);

// write the light styles

    for (i=0 ; i<MAX_LIGHTSTYLES ; i++)
    {
        if (sv.lightstyles[i])
            fprintf (f, "%s\n", sv.lightstyles[i]);
        else
            fprintf (f,"m\n");
    }


    ED_WriteGlobals (f);
    for (i=0 ; i<sv.num_edicts ; i++)
    {
        ED_Write (f, EDICT_NUM(i));
        fflush (f);
    }
    fclose (f);
    Con_Printf ("done.\n");
}


/*
===============
Host_Loadgame_f
===============
*/
void Host_Loadgame_f (void)
{
    std::string name, mapname;
    float    time, tfloat;
    char    *start;
    edict_t    *ent;
    int        entnum;
    int        version;
    float            spawn_parms[NUM_SPAWN_PARMS];
    std::string buf;
    uint8_t b;

    if (cmd_source != src_command)
        return;

    if (Cmd_Argc() != 2)
    {
        Con_Printf ("load <savename> : load a game\n");
        return;
    }

    cls.demonum = -1;        // stop demo loop in case this fails

    name = Cmd_Argv(1);
    name = filesystem::DefaultPathExtension(name, ".sav");

// we can't call SCR_BeginLoadingPlaque, because too much stack space has
// been used.  The menu calls it before stuffing loadgame command
//    SCR_BeginLoadingPlaque ();

    Con_Printf ("Loading game from %s...\n", name.c_str());
    
    File fp;
    if (!fp.OpenRead(name))
    {
        Con_Printf ("ERROR: couldn't open.\n");
        return;
    }

    version = Util::lexical_cast<int>(fp.GetLine());
    if (version != SAVEGAME_VERSION)
    {
        fp.Close();
        Con_Printf ("Savegame is version %i, not %i\n", version, SAVEGAME_VERSION);
        return;
    }
    
    // Discard the comment
    fp.GetLine();

    for (int i=0 ; i<NUM_SPAWN_PARMS ; i++)
        spawn_parms[i] = Util::lexical_cast<float>(fp.GetLine());
    
    tfloat = Util::lexical_cast<float>(fp.GetLine());
    current_skill = (int)(tfloat + 0.1);
    Cvar_SetValue ("skill", (float)current_skill);

    Cvar_SetValue ("deathmatch", 0);
    Cvar_SetValue ("coop", 0);
    Cvar_SetValue ("teamplay", 0);

    mapname = fp.GetLine();
    time = Util::lexical_cast<float>(fp.GetLine());

    CL_Disconnect_f ();

    SV_SpawnServer (mapname.c_str());

    if (!sv.active)
    {
        Con_Printf ("Couldn't load map\n");
        return;
    }
    sv.paused = true;        // pause until all clients connect
    sv.loadgame = true;

// load the light styles

    for (int i=0 ; i<MAX_LIGHTSTYLES ; i++)
    {
        buf = fp.GetLine();
        sv.lightstyles[i] = (char *)Hunk_Alloc (buf.length() + 1);
        strcpy (sv.lightstyles[i], buf.c_str());
    }

// load the edicts out of the savegame file
    entnum = -1;        // -1 is the globals
    while (!fp.eof())
    {
        buf.erase();
        
        while (1)
        {
            if (!fp.Read(&b, 1))
                break;
            buf.push_back((char)b);

            if ((char)b == '}')
                break;
        }
        start = COM_Parse((char *)buf.c_str());
        if (!com_token[0])
            break;        // end of file
        if (strcmp(com_token,"{"))
            Sys_Error ("First token isn't a brace");

        if (entnum == -1)
        {    // parse the global vars
            ED_ParseGlobals (start);
        }
        else
        {    // parse an edict

            ent = EDICT_NUM(entnum);
            memset (&ent->v, 0, progs->entityfields * 4);
            ent->free = false;
            ED_ParseEdict (start, ent);

        // link it into the bsp tree
            if (!ent->free)
                SV_LinkEdict (ent, false);
        }

        entnum++;
    }

    sv.num_edicts = entnum;
    sv.time = time;

    fp.Close();

    for (int i=0 ; i<NUM_SPAWN_PARMS ; i++)
        svs.clients->spawn_parms[i] = spawn_parms[i];

    CL_EstablishConnection ("local");
    Host_Reconnect_f ();
}

//============================================================================

/*
======================
Host_Name_f
======================
*/
void Host_Name_f (void)
{
    std::string newName;

    if (Cmd_Argc () == 1)
    {
        Con_Printf ("\"name\" is \"%s\"\n", Cvar_VariableString("_cl_name").c_str());
        return;
    }
    if (Cmd_Argc () == 2)
        newName = Cmd_Argv(1);
    else
        newName = Cmd_Args();
    
    if (newName.length() > 15)
        newName.erase(15);

    if (cmd_source == src_command)
    {
        if (newName == Cvar_VariableString("_cl_name"))
            return;
        Cvar_Set ("_cl_name", newName);
        if (cls.state == ca_connected)
            Cmd_ForwardToServer ();
        return;
    }

    if (host_client->name[0] && strcmp(host_client->name, "unconnected"))
    {
        if (newName != host_client->name)
            Con_Printf ("%s renamed to %s\n", host_client->name, newName.c_str());
    }
    strcpy (host_client->name, newName.c_str());
    host_client->edict->v.netname = host_client->name - pr_strings;

// send notification to all clients

    MSG_WriteByte (&sv.reliable_datagram, svc_updatename);
    MSG_WriteByte (&sv.reliable_datagram, host_client - svs.clients);
    MSG_WriteString (&sv.reliable_datagram, host_client->name);
}


void Host_Say(qboolean teamonly)
{
    client_t *client;
    client_t *save;
    int        j;
    char    text[64];
    qboolean    fromServer = false;

    if (cmd_source == src_command)
    {
        Cmd_ForwardToServer ();
        return;
    }

    if (Cmd_Argc () < 2)
        return;

    save = host_client;

    std::string p = Cmd_Args();
// remove quotes if present
    if (p[0] == '"')
    {
        p.erase(0, 1);
        p.erase(p.length() - 1);
    }

// turn on color set 1
    if (!fromServer)
        sprintf (text, "%c%s: ", 1, save->name);
    else
        sprintf (text, "%c<%s> ", 1, Cvar_VariableString("hostname").c_str());

    // -2 for /n and null terminator
    if (p.length() > sizeof(text) - 2 - strlen(text))
        p.erase(sizeof(text) - 2 - strlen(text));

    strcat (text, p.c_str());
    strcat (text, "\n");

    for (j = 0, client = svs.clients; j < svs.maxclients; j++, client++)
    {
        if (!client || !client->active || !client->spawned)
            continue;
        if (Cvar_VariableValue("teamplay") && teamonly && 
            client->edict->v.team != save->edict->v.team)
            continue;
        host_client = client;
        SV_ClientPrintf("%s", text);
    }
    host_client = save;
}


void Host_Say_f(void)
{
    Host_Say(false);
}


void Host_Say_Team_f(void)
{
    Host_Say(true);
}


void Host_Tell_f(void)
{
    client_t *client;
    client_t *save;
    int        j;
    char    text[64];

    if (cmd_source == src_command)
    {
        Cmd_ForwardToServer ();
        return;
    }

    if (Cmd_Argc () < 3)
        return;

    strcpy(text, host_client->name);
    strcat(text, ": ");

    std::string p = Cmd_Args();

// remove quotes if present
    if (p[0] == '"')
    {
        p.erase(0, 1);
        p.erase(p.length() - 1);
    }

// check length & truncate if necessary
    // -2 for /n and null terminator
    if (p.length() > sizeof(text) - 2 - strlen(text))
        p.erase(sizeof(text) - 2 - strlen(text));

    strcat (text, p.c_str());
    strcat (text, "\n");

    save = host_client;
    for (j = 0, client = svs.clients; j < svs.maxclients; j++, client++)
    {
        if (!client->active || !client->spawned)
            continue;
        if (!boost::iequals(Cmd_Argv(1), client->name))
            continue;
        host_client = client;
        SV_ClientPrintf("%s", text);
        break;
    }
    host_client = save;
}


/*
==================
Host_Color_f
==================
*/
void Host_Color_f(void)
{
    int        top, bottom;
    int        playercolor;

    if (Cmd_Argc() == 1)
    {
        int c = (int)Cvar_VariableValue("_cl_color");
        Con_Printf ("\"color\" is \"%i %i\"\n", c >> 4, c & 0x0f);
        Con_Printf ("color <0-13> [0-13]\n");
        return;
    }

    if (Cmd_Argc() == 2)
        top = bottom = Util::lexical_cast<int>(Cmd_Argv(1));
    else
    {
        top = Util::lexical_cast<int>(Cmd_Argv(1));
        bottom = Util::lexical_cast<int>(Cmd_Argv(2));
    }

    top &= 15;
    if (top > 13)
        top = 13;
    bottom &= 15;
    if (bottom > 13)
        bottom = 13;

    playercolor = top*16 + bottom;

    if (cmd_source == src_command)
    {
        Cvar_SetValue ("_cl_color", playercolor);
        if (cls.state == ca_connected)
            Cmd_ForwardToServer ();
        return;
    }

    host_client->colors = playercolor;
    host_client->edict->v.team = bottom + 1;

// send notification to all clients
    MSG_WriteByte (&sv.reliable_datagram, svc_updatecolors);
    MSG_WriteByte (&sv.reliable_datagram, host_client - svs.clients);
    MSG_WriteByte (&sv.reliable_datagram, host_client->colors);
}

/*
==================
Host_Kill_f
==================
*/
void Host_Kill_f (void)
{
    if (cmd_source == src_command)
    {
        Cmd_ForwardToServer ();
        return;
    }

    if (sv_player->v.health <= 0)
    {
        SV_ClientPrintf ("Can't suicide -- allready dead!\n");
        return;
    }

    pr_global_struct->time = sv.time;
    pr_global_struct->self = EDICT_TO_PROG(sv_player);
    PR_ExecuteProgram (pr_global_struct->ClientKill);
}


/*
==================
Host_Pause_f
==================
*/
void Host_Pause_f (void)
{

    if (cmd_source == src_command)
    {
        Cmd_ForwardToServer ();
        return;
    }
    if (!Cvar_VariableValue("pausable"))
        SV_ClientPrintf ("Pause not allowed.\n");
    else
    {
        sv.paused ^= 1;

        if (sv.paused)
        {
            SV_BroadcastPrintf ("%s paused the game\n", pr_strings + sv_player->v.netname);
        }
        else
        {
            SV_BroadcastPrintf ("%s unpaused the game\n",pr_strings + sv_player->v.netname);
        }

    // send notification to all clients
        MSG_WriteByte (&sv.reliable_datagram, svc_setpause);
        MSG_WriteByte (&sv.reliable_datagram, sv.paused);
    }
}

//===========================================================================


/*
==================
Host_PreSpawn_f
==================
*/
void Host_PreSpawn_f (void)
{
    if (cmd_source == src_command)
    {
        Con_Printf ("prespawn is not valid from the console\n");
        return;
    }

    if (host_client->spawned)
    {
        Con_Printf ("prespawn not valid -- allready spawned\n");
        return;
    }

    SZ_Write (&host_client->message, sv.signon.data, sv.signon.cursize);
    MSG_WriteByte (&host_client->message, svc_signonnum);
    MSG_WriteByte (&host_client->message, 2);
    host_client->sendsignon = true;
}

/*
==================
Host_Spawn_f
==================
*/
void Host_Spawn_f (void)
{
    int        i;
    client_t    *client;
    edict_t    *ent;

    if (cmd_source == src_command)
    {
        Con_Printf ("spawn is not valid from the console\n");
        return;
    }

    if (host_client->spawned)
    {
        Con_Printf ("Spawn not valid -- allready spawned\n");
        return;
    }

// run the entrance script
    if (sv.loadgame)
    {    // loaded games are fully inited allready
        // if this is the last client to be connected, unpause
        sv.paused = false;
    }
    else
    {
        // set up the edict
        ent = host_client->edict;

        memset (&ent->v, 0, progs->entityfields * 4);
        ent->v.colormap = NUM_FOR_EDICT(ent);
        ent->v.team = (host_client->colors & 15) + 1;
        ent->v.netname = host_client->name - pr_strings;

        // copy spawn parms out of the client_t

        for (i=0 ; i< NUM_SPAWN_PARMS ; i++)
            (&pr_global_struct->parm1)[i] = host_client->spawn_parms[i];

        // call the spawn function

        pr_global_struct->time = sv.time;
        pr_global_struct->self = EDICT_TO_PROG(sv_player);
        PR_ExecuteProgram (pr_global_struct->ClientConnect);

        if ((Sys_FloatTime() - host_client->netconnection->connecttime) <= sv.time)
            Con_DPrintf ("%s entered the game\n", host_client->name);

        PR_ExecuteProgram (pr_global_struct->PutClientInServer);
    }


// send all current names, colors, and frag counts
    SZ_Clear (&host_client->message);

// send time of update
    MSG_WriteByte (&host_client->message, svc_time);
    MSG_WriteFloat (&host_client->message, sv.time);

    for (i=0, client = svs.clients ; i<svs.maxclients ; i++, client++)
    {
        MSG_WriteByte (&host_client->message, svc_updatename);
        MSG_WriteByte (&host_client->message, i);
        MSG_WriteString (&host_client->message, client->name);
        MSG_WriteByte (&host_client->message, svc_updatefrags);
        MSG_WriteByte (&host_client->message, i);
        MSG_WriteShort (&host_client->message, client->old_frags);
        MSG_WriteByte (&host_client->message, svc_updatecolors);
        MSG_WriteByte (&host_client->message, i);
        MSG_WriteByte (&host_client->message, client->colors);
    }

// send all current light styles
    for (i=0 ; i<MAX_LIGHTSTYLES ; i++)
    {
        MSG_WriteByte (&host_client->message, svc_lightstyle);
        MSG_WriteByte (&host_client->message, (char)i);
        MSG_WriteString (&host_client->message, sv.lightstyles[i]);
    }

//
// send some stats
//
    MSG_WriteByte (&host_client->message, svc_updatestat);
    MSG_WriteByte (&host_client->message, STAT_TOTALSECRETS);
    MSG_WriteLong (&host_client->message, pr_global_struct->total_secrets);

    MSG_WriteByte (&host_client->message, svc_updatestat);
    MSG_WriteByte (&host_client->message, STAT_TOTALMONSTERS);
    MSG_WriteLong (&host_client->message, pr_global_struct->total_monsters);

    MSG_WriteByte (&host_client->message, svc_updatestat);
    MSG_WriteByte (&host_client->message, STAT_SECRETS);
    MSG_WriteLong (&host_client->message, pr_global_struct->found_secrets);

    MSG_WriteByte (&host_client->message, svc_updatestat);
    MSG_WriteByte (&host_client->message, STAT_MONSTERS);
    MSG_WriteLong (&host_client->message, pr_global_struct->killed_monsters);


//
// send a fixangle
// Never send a roll angle, because savegames can catch the server
// in a state where it is expecting the client to correct the angle
// and it won't happen if the game was just loaded, so you wind up
// with a permanent head tilt
    ent = EDICT_NUM( 1 + (host_client - svs.clients) );
    MSG_WriteByte (&host_client->message, svc_setangle);
    for (i=0 ; i < 2 ; i++)
        MSG_WriteAngle (&host_client->message, ent->v.angles[i] );
    MSG_WriteAngle (&host_client->message, 0 );

    SV_WriteClientdataToMessage (sv_player, &host_client->message);

    MSG_WriteByte (&host_client->message, svc_signonnum);
    MSG_WriteByte (&host_client->message, 3);
    host_client->sendsignon = true;
}

/*
==================
Host_Begin_f
==================
*/
void Host_Begin_f (void)
{
    if (cmd_source == src_command)
    {
        Con_Printf ("begin is not valid from the console\n");
        return;
    }

    host_client->spawned = true;
}

//===========================================================================


/*
==================
Host_Kick_f

Kicks a user off of the server
==================
*/
void Host_Kick_f (void)
{
    const char  *who;
    char        *message = NULL;
    client_t    *save;
    int            i;
    qboolean    byNumber = false;

    if (cmd_source == src_command)
    {
        if (!sv.active)
        {
            Cmd_ForwardToServer ();
            return;
        }
    }
    else if (pr_global_struct->deathmatch && !host_client->privileged)
        return;

    save = host_client;

    if (Cmd_Argc() > 2 && Cmd_Argv(1) == "#")
    {
        i = Util::lexical_cast<int>(Cmd_Argv(2)) - 1;
        if (i < 0 || i >= svs.maxclients)
            return;
        if (!svs.clients[i].active)
            return;
        host_client = &svs.clients[i];
        byNumber = true;
    }
    else
    {
        for (i = 0, host_client = svs.clients; i < svs.maxclients; i++, host_client++)
        {
            if (!host_client->active)
                continue;
            if (boost::iequals(Cmd_Argv(1), host_client->name))
                break;
        }
    }

    if (i < svs.maxclients)
    {
        if (cmd_source == src_command)
            who = Cvar_VariableString("_cl_name").c_str();
        else
            who = save->name;

        // can't kick yourself!
        if (host_client == save)
            return;

        if (Cmd_Argc() > 2)
        {
            message = COM_Parse((char *)Cmd_Args().c_str());
            if (byNumber)
            {
                message++;                            // skip the #
                while (*message == ' ')                // skip white space
                    message++;
                message += Cmd_Argv(2).length();    // skip the number
            }
            while (*message && *message == ' ')
                message++;
        }
        if (message)
            SV_ClientPrintf ("Kicked by %s: %s\n", who, message);
        else
            SV_ClientPrintf ("Kicked by %s\n", who);
        SV_DropClient (false);
    }

    host_client = save;
}

/*
===============================================================================

DEBUGGING TOOLS

===============================================================================
*/

/*
==================
Host_Give_f
==================
*/
void Host_Give_f (void)
{
    if (cmd_source == src_command)
    {
        Cmd_ForwardToServer ();
        return;
    }

    if (pr_global_struct->deathmatch && !host_client->privileged)
        return;

    std::string t = Cmd_Argv(1);
    int v = Util::lexical_cast<int>(Cmd_Argv(2));

    switch (t[0])
    {
   case '0':
   case '1':
   case '2':
   case '3':
   case '4':
   case '5':
   case '6':
   case '7':
   case '8':
   case '9':
        if (t[0] >= '2')
            sv_player->v.items = (int)sv_player->v.items | (IT_SHOTGUN << (t[0] - '2'));
        break;

    case 's':
        sv_player->v.ammo_shells = v;
        break;
    case 'n':
        sv_player->v.ammo_nails = v;
        break;
    case 'r':
        sv_player->v.ammo_rockets = v;
        break;
    case 'h':
        sv_player->v.health = v;
        break;
    case 'c':
        sv_player->v.ammo_cells = v;
        break;
    }
}

/*
===============================================================================

DEMO LOOP CONTROL

===============================================================================
*/


/*
==================
Host_Startdemos_f
==================
*/
void Host_Startdemos_f (void)
{
    int        i, c;

    c = Cmd_Argc() - 1;
    if (c > MAX_DEMOS)
    {
        Con_Printf ("Max %i demos in demoloop\n", MAX_DEMOS);
        c = MAX_DEMOS;
    }
    Con_Printf ("%i demo(s) in loop\n", c);

    for (i=1 ; i<c+1 ; i++)
        strncpy (cls.demos[i-1], Cmd_Argv(i).c_str(), sizeof(cls.demos[0])-1);

    if (!sv.active && cls.demonum != -1 && !cls.demoplayback)
    {
        cls.demonum = 0;
        CL_NextDemo ();
    }
    else
        cls.demonum = -1;
}


/*
==================
Host_Demos_f

Return to looping demos
==================
*/
void Host_Demos_f (void)
{
    if (cls.demonum == -1)
        cls.demonum = 1;
    CL_Disconnect_f ();
    CL_NextDemo ();
}

/*
==================
Host_Stopdemo_f

Return to looping demos
==================
*/
void Host_Stopdemo_f (void)
{
    if (!cls.demoplayback)
        return;
    CL_StopPlayback ();
    CL_Disconnect ();
}

//=============================================================================

/*
==================
Host_InitCommands
==================
*/
void Host_InitCommands (void)
{
    Cmd_AddCommand ("quit", Host_Quit_f);
    Cmd_AddCommand ("god", Host_God_f);
    Cmd_AddCommand ("notarget", Host_Notarget_f);
    Cmd_AddCommand ("fly", Host_Fly_f);
    Cmd_AddCommand ("map", Host_Map_f);
    Cmd_AddCommand ("restart", Host_Restart_f);
    Cmd_AddCommand ("changelevel", Host_Changelevel_f);
    Cmd_AddCommand ("connect", Host_Connect_f);
    Cmd_AddCommand ("reconnect", Host_Reconnect_f);
    Cmd_AddCommand ("name", Host_Name_f);
    Cmd_AddCommand ("noclip", Host_Noclip_f);
    Cmd_AddCommand ("say", Host_Say_f);
    Cmd_AddCommand ("say_team", Host_Say_Team_f);
    Cmd_AddCommand ("tell", Host_Tell_f);
    Cmd_AddCommand ("color", Host_Color_f);
    Cmd_AddCommand ("kill", Host_Kill_f);
    Cmd_AddCommand ("pause", Host_Pause_f);
    Cmd_AddCommand ("spawn", Host_Spawn_f);
    Cmd_AddCommand ("begin", Host_Begin_f);
    Cmd_AddCommand ("prespawn", Host_PreSpawn_f);
    Cmd_AddCommand ("kick", Host_Kick_f);
    Cmd_AddCommand ("ping", Host_Ping_f);
    Cmd_AddCommand ("load", Host_Loadgame_f);
    Cmd_AddCommand ("save", Host_Savegame_f);
    Cmd_AddCommand ("give", Host_Give_f);

    Cmd_AddCommand ("startdemos", Host_Startdemos_f);
    Cmd_AddCommand ("demos", Host_Demos_f);
    Cmd_AddCommand ("stopdemo", Host_Stopdemo_f);

    Cmd_AddCommand ("mcache", Mod_Print);
}
