#include <amxmodx>
#include <engine>
#include <fakemeta>
#include <fun>
#include <hamsandwich>
#include <xs>
#include <cstrike>
#include <zombieplague>
#include <fakemeta_util>
#include <amxmisc>

#define BLOOD_SM_NUM 8
#define ENG_NULLENT		-1
#define EV_INT_WEAPONKEY	EV_INT_impulse
#define M79_WEAPONKEY	846
#define MAX_PLAYERS  			  32
#define IsValidUser(%1) (1 <= %1 <= g_MaxPlayers)

const USE_STOPPED = 0
const OFFSET_ACTIVE_ITEM = 373
const OFFSET_WEAPONOWNER = 41
const OFFSET_LINUX = 4
const OFFSET_LINUX_WEAPONS = 4

#define BLOOD_STREAM_RED	70
#define WEAP_LINUX_XTRA_OFF			4
#define m_fKnown				44
#define m_flNextPrimaryAttack 			46
#define m_flTimeWeaponIdle			48
#define m_iClip		51
#define m_fInReload				54
#define PLAYER_LINUX_XTRA_OFF			5
#define m_flNextAttack				83
#define BLOOD_LG_NUM 2
#define M79_RELOAD_TIME 2.4
#pragma tabsize 0

new const Fire_Sounds[][] = { "weapons/m79_fire1.wav" }
new const GRENADE_MODEL[] = "models/grenade.mdl"
new const GRENADE_EXPLOSION[] = "sprites/zerogxplode.spr"
new const GRENADE_SMOKE[] = "sprites/black_smoke3.spr"
new const g_GrenadeEntity [ ] = "zp_m79_grenade"

new M79_V_MODEL[64] = "models/zm/v_m79fix2.mdl"
new m79_P_MODEL[64] = "models/zm/p_m79.mdl"
new M79_P_MODEL[64] = "models/zm/w_m79.mdl"
new cvar_dmg_m79, g_itemid_m79, cvar_clip_m79, cvar_m79_ammo
new g_has_m79[33]
new g_MaxPlayers, g_orig_event_m79, g_clip_ammo[33]
new m_iBlood[2]
new g_m79_TmpClip[33]
new g_Reload[33]
new blood_small_red[BLOOD_SM_NUM], blood_large_red[BLOOD_LG_NUM]
new oldweap[33] , sTrail , sExplo , sSmoke , cvar_grenrad , cvar_firerate , cvar_speed
new g_iMetalPlateGibs;

const PRIMARY_WEAPONS_BIT_SUM = (1<<CSW_USP)|(1<<CSW_DEAGLE)|(1<<CSW_GLOCK18)|(1<<CSW_P228)|(1<<CSW_ELITE)|(1<<CSW_FIVESEVEN)
new const WEAPONENTNAMES[][] = { "", "weapon_p228", "", "weapon_scout", "weapon_hegrenade", "weapon_xm1014", "weapon_c4", "weapon_mac10",
			"weapon_aug", "weapon_smokegrenade", "weapon_sg550", "weapon_fiveseven", "weapon_ump45", "weapon_elite",
			"weapon_galil", "weapon_famas", "weapon_usp", "weapon_glock18", "weapon_awp", "weapon_mp5navy", "weapon_m249",
			"weapon_m3", "weapon_m4a1", "weapon_tmp", "weapon_g3sg1", "weapon_flashbang", "weapon_deagle", "weapon_sg552",
			"weapon_elite", "weapon_knife", "weapon_p90" }

public plugin_init()
{
	register_plugin("[ZP] Weapon: M79", "1.0", "Crock / =) / Opo4uMapy")
	register_message(get_user_msgid("DeathMsg"), "message_DeathMsg")
	register_event("CurWeapon","CurrentWeapon","be","1=1")
	RegisterHam(Ham_Item_AddToPlayer, "weapon_p228", "fw_m79_AddToPlayer")
	RegisterHam(Ham_Use, "func_tank", "fw_UseStationary_Post", 1)
	RegisterHam(Ham_Use, "func_tankmortar", "fw_UseStationary_Post", 1)
	RegisterHam(Ham_Use, "func_tankrocket", "fw_UseStationary_Post", 1)
	RegisterHam(Ham_Use, "func_tanklaser", "fw_UseStationary_Post", 1)
	for (new i = 1; i < sizeof WEAPONENTNAMES; i++)
		if (WEAPONENTNAMES[i][0]) RegisterHam(Ham_Item_Deploy, WEAPONENTNAMES[i], "fw_Item_Deploy_Post", 1)
	RegisterHam(Ham_Weapon_PrimaryAttack, "weapon_p228", "fw_m79_PrimaryAttack")
	RegisterHam(Ham_Item_PostFrame, "weapon_p228", "m79_ItemPostFrame");
	RegisterHam(Ham_Weapon_Reload, "weapon_p228", "m79_Reload");
	RegisterHam(Ham_Weapon_Reload, "weapon_p228", "m79_Reload_Post", 1);
	RegisterHam(Ham_TakeDamage, "player", "fw_TakeDamage")
	RegisterHam(Ham_Item_Deploy, "weapon_p228", "P228DeployPost", 1);
    RegisterHam(Ham_Item_Holster, "weapon_p228", "P228HolsterPost", 1);
	register_forward(FM_SetModel, "fw_SetModel")
	register_forward(FM_UpdateClientData, "fw_UpdateClientData_Post", 1)
	register_forward(FM_PlaybackEvent, "fwPlaybackEvent")
	register_touch ( g_GrenadeEntity, "*", "touch_m79nade" )
	cvar_dmg_m79 = register_cvar("zp_m79_dmg", "950.0")
	register_event("HLTV", 		"Event_NewRound", 	"a", 	"1=0", "2=0")
	cvar_clip_m79 = register_cvar("zp_m79_clip", "1")
	cvar_m79_ammo = register_cvar("zp_m79_ammo", "10")
	cvar_grenrad  = register_cvar("zp_m79_radius", "150")
	cvar_firerate =  register_cvar("zp_m79_firerate", "0.8")
	cvar_speed = register_cvar ( "zp_m79_knickback", "600" )

	g_itemid_m79 = zp_register_extra_item("M79", 10, ZP_TEAM_HUMAN)
	blood_large_red = {204,205}
	blood_small_red = {190,191,192,193,194,195,196,197}

	RegisterHam(Ham_Item_AddToPlayer, "weapon_p228", "Sprite", .Post = true);
	register_clcmd("weapon_m79", "Hook_SelectWeapon") 

	g_MaxPlayers = get_maxplayers()
}
public Hook_SelectWeapon(id)
{
	engclient_cmd(id, "weapon_p228")
}

public Sprite( const item, const player )  
{  
    if( pev_valid( item ) && is_user_alive( player ) )
    {  
        message_begin( MSG_ONE, get_user_msgid( "WeaponList" ), .player = player );  
        {  
            write_string(g_has_m79[player] ? "weapon_m79" : "weapon_p228");    // WeaponName  
            write_byte( 9 );                   // PrimaryAmmoID  
            write_byte( 52 );                   // PrimaryAmmoMaxAmount  
            write_byte( -1 );                   // SecondaryAmmoID  
            write_byte( -1 );                   // SecondaryAmmoMaxAmount  
            write_byte( 1 );                    // SlotID (0...N)  
            write_byte( 3 );                    // NumberInSlot (1...N)  
            write_byte( CSW_P228 );            // WeaponID  
            write_byte( 0 );                    // Flags  
        }  
        message_end();  
    }  
    return PLUGIN_CONTINUE  
} 

public plugin_precache()
{
	precache_model(M79_V_MODEL)
	precache_model(m79_P_MODEL)
	precache_model(M79_P_MODEL)
	precache_sound(Fire_Sounds[0])
	precache_sound("cso/m79_clipin.wav")
	precache_sound("cso/m79_clipon.wav")
	precache_sound("cso/m79_clipout.wav")
	precache_sound("cso/m79_draw.wav")
	precache_sound(Fire_Sounds[0])
	m_iBlood[0] = precache_model("sprites/blood.spr")
	m_iBlood[1] = precache_model("sprites/bloodspray.spr")

    	precache_generic("sprites/weapon_m79.txt")
	precache_model("sprites/640hud42.spr")
	precache_model("sprites/640hud7.spr")
	precache_model("sprites/scope_vip_grenade.spr")

	sExplo = precache_model(GRENADE_EXPLOSION)
	sSmoke = precache_model(GRENADE_SMOKE)
	precache_model("sprites/640hud5.spr")
	register_forward(FM_PrecacheEvent, "fwPrecacheEvent_Post", 1)
	g_iMetalPlateGibs = precache_model("models/ceilinggibs.mdl");
}
 
public fwPrecacheEvent_Post(type, const name[])
{
	if (equal("events/p228.sc", name))
	{
		g_orig_event_m79 = get_orig_retval()
		return FMRES_HANDLED
	}
	
	return FMRES_IGNORED
}

public fw_SetModel(entity, model[])
{
	if(!is_valid_ent(entity))
		return FMRES_IGNORED;
	
	static szClassName[33]
	entity_get_string(entity, EV_SZ_classname, szClassName, charsmax(szClassName))
		
	if(!equal(szClassName, "weaponbox"))
		return FMRES_IGNORED;
	
	static iOwner
	
	iOwner = entity_get_edict(entity, EV_ENT_owner)
	
	if(equal(model, "models/w_p228.mdl"))
	{
		static iStoredSVDID
		
		iStoredSVDID = find_ent_by_owner(ENG_NULLENT, "weapon_p228", entity)
	
		if(!is_valid_ent(iStoredSVDID))
			return FMRES_IGNORED;
	
		if(g_has_m79[iOwner])
		{
			entity_set_int(iStoredSVDID, EV_INT_WEAPONKEY, M79_WEAPONKEY)
			g_has_m79[iOwner] = false
			
			entity_set_model(entity, M79_P_MODEL)
			
			return FMRES_SUPERCEDE;
		}
	}
	
	
	return FMRES_IGNORED;
}

public touch_m79nade ( ptr, ptd )
{
	if (pev_valid(ptr))
	{	
		// Get classnames
		static classname[32], classnameptd[32]
		pev(ptr, pev_classname, classname, 31)
		pev(ptd, pev_classname, classnameptd, 31)
		
		// Our ent
		if(equal(classname, g_GrenadeEntity))
		{
			// Get it's origin
			new Float:originF[3] , Float:originZ[3]
			pev(ptr, pev_origin, originF)
			pev(ptr, pev_origin, originZ)
			originZ[2] -= 30.0
			
			// Draw explosion
			message_begin(MSG_BROADCAST, SVC_TEMPENTITY)
			write_byte(TE_EXPLOSION) // Temporary entity ID
			engfunc(EngFunc_WriteCoord, originF[0]) // engfunc because float
			engfunc(EngFunc_WriteCoord, originF[1])
			engfunc(EngFunc_WriteCoord, originF[2])
			write_short(sExplo) // Sprite index
			write_byte(50) // Scale
			write_byte(15) // Framerate
			write_byte(0) // Flags
			message_end()
			
			// Draw smoke
			message_begin(MSG_BROADCAST, SVC_TEMPENTITY)
			write_byte(TE_SMOKE) // Temporary entity IF
			engfunc(EngFunc_WriteCoord, originF[0]) // Pos X
			engfunc(EngFunc_WriteCoord, originF[1]) // Pos Y
			engfunc(EngFunc_WriteCoord, originF[2]) // Pos Z
			write_short(sSmoke) // Sprite index
			write_byte(75) // Scale
			write_byte(15) // Framerate
			message_end()
			
			if (!ptd)
            {
                new Float:fVelo[3];
                
                entity_get_vector(ptr, EV_VEC_velocity, fVelo);
                
                xs_vec_normalize(fVelo, fVelo);
                
                xs_vec_mul_scalar(fVelo, -64.0, fVelo);
                
                new iVelo[3];
                
                FVecIVec(fVelo, iVelo);
                
                new Float:fOrigin[3];
                
                entity_get_vector(ptr, EV_VEC_origin, fOrigin);
                
                xs_vec_mul_scalar(fVelo, 0.25, fVelo);
                
                xs_vec_add(fOrigin, fVelo, fOrigin);
                
                new iOrigin[3];
                
                FVecIVec(fOrigin, iOrigin);
                
                message_begin( MSG_PVS, SVC_TEMPENTITY, iOrigin );
                write_byte( TE_BREAKMODEL);
                write_coord( iOrigin[0] );
                write_coord( iOrigin[1] );
                write_coord( iOrigin[2] );
                write_coord( 32);
                write_coord( 400);
                write_coord( 300);
                write_coord( iVelo[0] );
                write_coord( iVelo[1] );
                write_coord( iVelo[2] );
                write_byte( 10 );
                write_short( g_iMetalPlateGibs );
                write_byte( 80 );
                write_byte( 25 );
                write_byte( 0x02 );
                message_end();
            }
			
			// Get owner
			new owner = pev(ptr, pev_owner)
			
			// Loop through all players
			for(new i = 1; i < 33; i++)
			{
				// Alive...
				if (is_user_alive(i) == 1)
				{
					// Start screen shake
					//message_begin(MSG_ONE, g_msgScreenShake, {0,0,0}, i)
					//write_short(1<<14) // Amount
					//write_short(1<<14) // Duration
					//write_short(1<<14) // Frequency
					//message_end()
					
					// A zombie/nemesis
					if (zp_get_user_zombie(i))
					{
						// Get victims origin and distance
						new Float:VictimOrigin[3], Float:distance
						pev(i, pev_origin, VictimOrigin)
						
						// Get distance between victim and epicenter
						distance = get_distance_f(VictimOrigin, originF)
						
						if (distance <= get_pcvar_num(cvar_grenrad)) 
						{
							ExecuteHamB(Ham_TakeDamage, i, owner, owner, get_pcvar_float(cvar_dmg_m79) , DMG_BULLET | DMG_NEVERGIB);
							make_blood(VictimOrigin,get_pcvar_float(cvar_dmg_m79),i)
               						
							static Float:flSpeed
							flSpeed = get_pcvar_float ( cvar_speed )
               
							static Float:flNewSpeed
							flNewSpeed = flSpeed * ( 1.0 - ( distance / 300.0) )
               
							static Float:flVelocity [ 3 ]
							get_speed_vector ( originZ, VictimOrigin, flNewSpeed, flVelocity )
               
							set_pev ( i, pev_velocity,flVelocity )
						}	
					}
				}
				// Destroy ent
				set_pev(ptr, pev_flags, FL_KILLME)
			}
			// We hit breakable
			if (equali(classnameptd, "func_breakable"))
			{
				// Destroy it
				force_use(ptr,ptd)
			}
		}
	}
}	

public give_m79(id)
{
    drop_weapons(id, 1);
    g_has_m79[id] = true;
    new iWep2 = give_item(id,"weapon_p228")
    if( iWep2 > 0 )
    {
        cs_set_weapon_ammo(iWep2, get_pcvar_num(cvar_clip_m79))
        cs_set_user_bpammo (id, CSW_P228, get_pcvar_num(cvar_m79_ammo))
    }
    if(get_user_weapon(id) == CSW_P228)
    {
        UTIL_PlayWeaponAnimation(id, 3)
        set_pdata_float(id, m_flNextAttack, 1.0, PLAYER_LINUX_XTRA_OFF)
    }
}

public fw_m79_AddToPlayer(DD, id)
{
	if(!is_valid_ent(DD) || !is_user_connected(id))
		return HAM_IGNORED;
	
	if(entity_get_int(DD, EV_INT_WEAPONKEY) == M79_WEAPONKEY)
	{
		g_has_m79[id] = true
		
		entity_set_int(DD, EV_INT_WEAPONKEY, 0)
		
		return HAM_HANDLED;
	}
	
	return HAM_IGNORED;
}

public fw_UseStationary_Post(entity, caller, activator, use_type)
{
	if (use_type == USE_STOPPED && is_user_connected(caller))
		replace_weapon_models(caller, get_user_weapon(caller))
}

public fw_Item_Deploy_Post(weapon_ent)
{
	static owner
	owner = fm_cs_get_weapon_ent_owner(weapon_ent)
	
	static weaponid
	weaponid = cs_get_weapon_id(weapon_ent)
	
	replace_weapon_models(owner, weaponid)
}

replace_weapon_models(id, weaponid)
{
		if(weaponid == CSW_P228)
		{
			if (zp_get_user_zombie(id) || zp_get_user_survivor(id))
				return;
			
			if(g_has_m79[id])
			{
				set_pev(id, pev_viewmodel2, M79_V_MODEL)
				set_pev(id, pev_weaponmodel2, m79_P_MODEL)
				if(oldweap[id] != CSW_P228)
				{
					UTIL_PlayWeaponAnimation(id, 3)
					set_pdata_float(id, m_flNextAttack, 1.0, PLAYER_LINUX_XTRA_OFF)
				}
			}
		}
		if(weaponid != CSW_P228) g_Reload[id] = 0
		if(weaponid != CSW_P228) remove_task(id)
		oldweap[id] = weaponid
}

public fw_UpdateClientData_Post(Player, SendWeapons, CD_Handle)
{
        if(!is_user_alive(Player) || (get_user_weapon(Player) != CSW_P228) || !g_has_m79[Player])
        return FMRES_IGNORED
	
	set_cd(CD_Handle, CD_flNextAttack, halflife_time () + 0.001)
	return FMRES_HANDLED
}

public fw_m79_PrimaryAttack(Weapon)
{
static Player ; Player = get_pdata_cbase(Weapon, 41, 4)
if (!g_has_m79[Player])
return HAM_IGNORED

static ClipAmmo ; ClipAmmo = get_pdata_int(Weapon, 51, 4)
 
if(!ClipAmmo)
return HAM_IGNORED
 
new szClip
new szWeapID = get_user_weapon(Player, szClip)
 
if(get_user_weapon(Player) == CSW_P228)
{
 
g_clip_ammo[Player] = cs_get_weapon_ammo(Weapon)

if(szWeapID == CSW_P228)
{
remove_task(Player)
replace_weapon_models(Player,CSW_P228)
if(szClip > 1) 
{
UTIL_PlayWeaponAnimation(Player, 2)
set_pdata_float(Player, m_flNextAttack, get_pcvar_float(cvar_firerate), PLAYER_LINUX_XTRA_OFF)
}
if(szClip == 1) 
{
UTIL_PlayWeaponAnimation(Player, 2) 
set_pdata_float(Player, m_flNextAttack, 0.3, PLAYER_LINUX_XTRA_OFF)
}
make_blood_and_bulletholes(Player)
static Float:punchAngle[3];
punchAngle[0] = float(random_num(-300, 0)) / 100.0;
punchAngle[1] = float(random_num(-50, 50)) / 100.0;
punchAngle[2] = 0.0;
set_pev(Player, pev_punchangle, punchAngle);
new ak = find_ent_by_owner ( -1, "weapon_p228", Player )
set_pdata_int ( ak, 51, szClip - 1, 4 )
if(szClip - 1 > get_pcvar_num(cvar_m79_ammo)) set_pdata_int ( ak, 51, get_pcvar_num(cvar_m79_ammo), 4 )
}
}
return HAM_SUPERCEDE
}

public reload_task(id)
{
	if(!is_user_alive(id) || zp_get_user_zombie(id) || !g_has_m79[id])
		return;

	new weapon_entity = find_ent_by_owner ( -1, "weapon_p228",id)

	new iBpAmmo = cs_get_user_bpammo(id, CSW_P228);
	new iClip = get_pdata_int(weapon_entity, m_iClip, WEAP_LINUX_XTRA_OFF)

	new j = min(get_pcvar_num(cvar_clip_m79) - iClip, iBpAmmo)
	
	set_pdata_int(weapon_entity, m_iClip, iClip + j, WEAP_LINUX_XTRA_OFF)
	cs_set_user_bpammo(id, CSW_P228, iBpAmmo-j);
}

public fwPlaybackEvent(flags, invoker, eventid, Float:delay, Float:origin[3], Float:angles[3], Float:fparam1, Float:fparam2, iParam1, iParam2, bParam1, bParam2)
{
	if ((eventid != g_orig_event_m79))
		return FMRES_IGNORED
	if (!(1 <= invoker <= g_MaxPlayers))
		return FMRES_IGNORED

	playback_event(flags | FEV_HOSTONLY, invoker, eventid, delay, origin, angles, fparam1, fparam2, iParam1, iParam2, bParam1, bParam2)
	return FMRES_SUPERCEDE
}

public fw_TakeDamage(victim, inflictor, attacker, Float:damage)
{
	if (victim != attacker && is_user_connected(attacker))
	{
		if(get_user_weapon(attacker) == CSW_P228)
		{
			if(g_has_m79[attacker])
				SetHamParamFloat(4, get_pcvar_float(cvar_dmg_m79))
		}
	}
}

public message_DeathMsg(msg_id, msg_dest, id)
{
	static szTruncatedWeapon[33], iAttacker, iVictim
	
	get_msg_arg_string(4, szTruncatedWeapon, charsmax(szTruncatedWeapon))
	
	iAttacker = get_msg_arg_int(1)
	iVictim = get_msg_arg_int(2)
	
	if(!is_user_connected(iAttacker) || iAttacker == iVictim)
		return PLUGIN_CONTINUE

	set_task(1.0,"zero_have",iVictim) 
	
	if(equal(szTruncatedWeapon, "p228") && get_user_weapon(iAttacker) == CSW_P228)
	{
		if(g_has_m79[iAttacker])
			set_msg_arg_string(4, "usp")
	}
		
	return PLUGIN_CONTINUE
}

public zp_extra_item_selected(id, itemid)	if(itemid == g_itemid_m79) give_m79(id)
public client_connect(id)	g_has_m79[id] = false
public client_disconnect(id) g_has_m79[id] = false
public CurrentWeapon(id) replace_weapon_models(id, read_data(2))
public zp_user_infected_post(id)	g_has_m79[id] = false
public Event_NewRound() for(new i; i <=32; i++) g_Reload[i] = 0
public plugin_natives() register_native("give_weapon_m79", "native_give_weapon_add", 1), register_native("has_weapon_m79", "native_has_weapon_m79", 1);
public native_give_weapon_add(id) give_m79(id)
public zero_have(id) g_has_m79[id] = false
public native_has_weapon_m79(id) return g_has_m79[id];

stock fm_cs_get_current_weapon_ent(id)
{
	return get_pdata_cbase(id, OFFSET_ACTIVE_ITEM, OFFSET_LINUX);
}

stock fm_cs_get_weapon_ent_owner(ent)
{
	return get_pdata_cbase(ent, OFFSET_WEAPONOWNER, OFFSET_LINUX_WEAPONS);
}

stock UTIL_PlayWeaponAnimation(const Player, const Sequence)
{
	set_pev(Player, pev_weaponanim, Sequence)
	
	message_begin(MSG_ONE_UNRELIABLE, SVC_WEAPONANIM, .player = Player)
	write_byte(Sequence)
	write_byte(pev(Player, pev_body))
	message_end()
}

stock make_blood_and_bulletholes(id)
{
	new aimOrigin[3], target, body
	get_user_origin(id, aimOrigin, 3)
	get_user_aiming(id, target, body)

	new szClip
 	get_user_weapon(id, szClip)

	engfunc(EngFunc_EmitSound, id, CHAN_WEAPON, Fire_Sounds[0], VOL_NORM, ATTN_NORM, 0, PITCH_NORM);
	
	new Float:fOrigin[3], Float:fAngle[3], Float:fVelocity[3]
	pev(id, pev_origin, fOrigin)
	pev(id, pev_v_angle, fAngle)

	new Float:vSrc[3],Float:vUp[3]
	pev(id, pev_origin, vSrc)
	
	global_get(glb_v_up, vUp)
	new up = 17
	vSrc[0] = vSrc[0] + vUp[0] * up
	vSrc[1] = vSrc[1] + vUp[1] * up
	vSrc[2] = vSrc[2] + vUp[2] * up

	// Create ent
	new grenade = create_entity("info_target")
	
	// Not grenade
	if (!grenade) return PLUGIN_HANDLED
	
	// Classname
	entity_set_string(grenade, EV_SZ_classname, g_GrenadeEntity)
	
	// Model
	entity_set_model(grenade, GRENADE_MODEL)
	
	// Origin
	entity_set_origin(grenade, vSrc)
	
	// Angles
	entity_set_vector(grenade, EV_VEC_angles, fAngle)
	
	// Size
	new Float:MinBox[3] = {-1.0, -1.0, -1.0}
	new Float:MaxBox[3] = {1.0, 1.0, 1.0}
	entity_set_vector(grenade, EV_VEC_mins, MinBox)
	entity_set_vector(grenade, EV_VEC_maxs, MaxBox)
	
	// Interaction
	entity_set_int(grenade, EV_INT_solid, SOLID_SLIDEBOX)
	
	// Movetype
	entity_set_int(grenade, EV_INT_movetype, MOVETYPE_TOSS)
	
	// Owner
	entity_set_edict(grenade, EV_ENT_owner, id)
	
	// Effects
	entity_set_int(grenade, EV_INT_effects, EF_BRIGHTLIGHT)
	
	// Velocity
	VelocityByAim(id, 1500, fVelocity)
	entity_set_vector(grenade, EV_VEC_velocity, fVelocity)
	
	message_begin(MSG_BROADCAST, SVC_TEMPENTITY)
	write_byte(TE_BEAMFOLLOW) // Temporary entity ID
	write_short(grenade) // Entity
	write_short(sTrail) // Sprite index
	write_byte(10) // Life
	write_byte(3) // Line width
	write_byte(255) // Red
	write_byte(255) // Green
	write_byte(255) // Blue
	write_byte(255) // Alpha
	message_end() 
	
	return PLUGIN_CONTINUE
}
public m79_ItemPostFrame(weapon_entity) {
	new id = pev(weapon_entity, pev_owner)

	if (!is_user_connected(id))
		return HAM_IGNORED;

	if (!g_has_m79[id])
		return HAM_IGNORED;

	new Float:flNextAttack = get_pdata_float(id, m_flNextAttack, PLAYER_LINUX_XTRA_OFF)

	new iBpAmmo = cs_get_user_bpammo(id, CSW_P228);
	new iClip = get_pdata_int(weapon_entity, m_iClip, WEAP_LINUX_XTRA_OFF)

	new fInReload = get_pdata_int(weapon_entity, m_fInReload, WEAP_LINUX_XTRA_OFF) 

	if( fInReload && flNextAttack <= 0.0 )
	{
		new j = min(get_pcvar_num(cvar_clip_m79) - iClip, iBpAmmo)
	
		set_pdata_int(weapon_entity, m_iClip, iClip + j, WEAP_LINUX_XTRA_OFF)
		cs_set_user_bpammo(id, CSW_P228, iBpAmmo-j);
		
		set_pdata_int(weapon_entity, m_fInReload, 0, WEAP_LINUX_XTRA_OFF)
		fInReload = 0
		g_Reload[id] = 0
	}

	return HAM_IGNORED;
}

public m79_Reload(weapon_entity) {
	new id = pev(weapon_entity, pev_owner)

	if (!is_user_connected(id))
		return HAM_IGNORED;

	if (!g_has_m79[id])
		return HAM_IGNORED;

	g_m79_TmpClip[id] = -1;
	new iBpAmmo = cs_get_user_bpammo(id, CSW_P228);
	new iClip = get_pdata_int(weapon_entity, m_iClip, WEAP_LINUX_XTRA_OFF)

	if (iBpAmmo <= 0)
		return HAM_SUPERCEDE;

	if (iClip >= get_pcvar_num(cvar_clip_m79))
		return HAM_SUPERCEDE;


	g_m79_TmpClip[id] = iClip;

	return HAM_IGNORED;
}

public m79_Reload_Post(weapon_entity) {
	new id = pev(weapon_entity, pev_owner)
	if (!is_user_connected(id))
		return HAM_IGNORED;

	if (!g_has_m79[id])
		return HAM_IGNORED;

	if (g_m79_TmpClip[id] == -1)
		return HAM_IGNORED;

	new iBpAmmo = cs_get_user_bpammo(id, CSW_P228);

	if (iBpAmmo <= 0)
		return HAM_IGNORED;

	set_pdata_int(weapon_entity, m_iClip, g_m79_TmpClip[id], WEAP_LINUX_XTRA_OFF)

	set_pdata_float(weapon_entity, m_flTimeWeaponIdle, 0.1, WEAP_LINUX_XTRA_OFF)

	set_pdata_float(id, m_flNextAttack, M79_RELOAD_TIME, PLAYER_LINUX_XTRA_OFF)

	set_pdata_int(weapon_entity, m_fInReload, 1, WEAP_LINUX_XTRA_OFF)

	// relaod animation
	UTIL_PlayWeaponAnimation(id, 1)

	remove_task(id)
	g_Reload[id] = 1

	set_task(M79_RELOAD_TIME - 0.1,"reload_task",id)

	return HAM_IGNORED;
}

// Make knockback
public make_knockback ( Victim, Float:origin [ 3 ], Float:maxspeed )
{
	// Get and set velocity
	new Float:fVelocity[3];
	kickback ( Victim, origin, maxspeed, fVelocity)
	entity_set_vector( Victim, EV_VEC_velocity, fVelocity);

	return (1);
}


// Extra calulation for knockback
stock kickback( ent, Float:fOrigin[3], Float:fSpeed, Float:fVelocity[3])
{
	// Find origin
	new Float:fEntOrigin[3];
	entity_get_vector( ent, EV_VEC_origin, fEntOrigin );

	// Do some calculations
	new Float:fDistance[3];
	fDistance[0] = fEntOrigin[0] - fOrigin[0];
	fDistance[1] = fEntOrigin[1] - fOrigin[1];
	fDistance[2] = fEntOrigin[2] - fOrigin[2];
	new Float:fTime = (vector_distance( fEntOrigin,fOrigin ) / fSpeed);
	fVelocity[0] = fDistance[0] / fTime;
	fVelocity[1] = fDistance[1] / fTime;
	fVelocity[2] = fDistance[2] / fTime;

	return (fVelocity[0] && fVelocity[1] && fVelocity[2]);
}

public get_origin_int(index, origin[3])
{
	new Float:FVec[3]

	pev(index,pev_origin,FVec)

	origin[0] = floatround(FVec[0])
	origin[1] = floatround(FVec[1])
	origin[2] = floatround(FVec[2])

	return 1
}
stock make_blood(const Float:vTraceEnd[3], Float:Damage, hitEnt) {
	new bloodColor = ExecuteHam(Ham_BloodColor, hitEnt);
	if (bloodColor == -1)
		return;

	new amount = floatround(Damage);

	amount *= 2; //according to HLSDK

	message_begin(MSG_BROADCAST, SVC_TEMPENTITY);
	write_byte(TE_BLOODSPRITE);
	write_coord(floatround(vTraceEnd[0]));
	write_coord(floatround(vTraceEnd[1]));
	write_coord(floatround(vTraceEnd[2]));
	write_short(m_iBlood[1]);
	write_short(m_iBlood[0]);
	write_byte(bloodColor);
	write_byte(min(max(3, amount/10), 16));
	message_end();
}
stock drop_weapons(id, dropwhat)
{
     static weapons[32], num, i, weaponid
     num = 0
     get_user_weapons(id, weapons, num)
     
     for (i = 0; i < num; i++)
     {
          weaponid = weapons[i]
          
          if (dropwhat == 1 && ((1<<weaponid) & PRIMARY_WEAPONS_BIT_SUM))
          {
               static wname[32]
               get_weaponname(weaponid, wname, sizeof wname - 1)
               engclient_cmd(id, "drop", wname)
          }
     }
}

stock get_speed_vector(const Float:origin1[3],const Float:origin2[3],Float:speed, Float:new_velocity[3])
{
        new_velocity[0] = origin2[0] - origin1[0]
        new_velocity[1] = origin2[1] - origin1[1]
        new_velocity[2] = origin2[2] - origin1[2]
        new Float:num = floatsqroot(speed*speed / (new_velocity[0]*new_velocity[0] + new_velocity[1]*new_velocity[1] + new_velocity[2]*new_velocity[2]))
        new_velocity[0] *= num
        new_velocity[1] *= num
        new_velocity[2] *= num
       
        return 1;
} 

public P228DeployPost(iEntity)
{
        new iPlayer = get_pdata_cbase(iEntity, 41, 4);
        
        if (!g_has_m79[iPlayer]) return;
        
        message_begin(MSG_ONE, get_user_msgid("HideWeapon"), _, iPlayer);
        write_byte(1 << 6);
        message_end();
}
 
public P228HolsterPost(iEntity)
{
        new iPlayer = get_pdata_cbase(iEntity, 41, 4);
        
        if (!g_has_m79[iPlayer]) return;
        
        message_begin(MSG_ONE, get_user_msgid("HideWeapon"), _, iPlayer);
        write_byte(0);
        message_end();
}