
TOOL.ClientConVar["forcelimit"] = "0"

TOOL.RightClickAutomatic = true

cleanup.Register( "nails" )

function TOOL:LeftClick( trace )

	// Bail if we hit world or a player
	if (  !trace.Entity:IsValid() || trace.Entity:IsPlayer() ) then return false end
	
	// If there's no physics object then we can't constraint it!
	if ( SERVER && !util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone ) ) then return false end
	
	local tr = {}
		tr.start = trace.HitPos
		tr.endpos = trace.HitPos + (self:GetOwner():GetAimVector() * 16.0)
		tr.filter = { self:GetOwner(), trace.Entity }
	local trTwo = util.TraceLine( tr )
	
	if ( trTwo.Hit && !trTwo.Entity:IsPlayer() ) then
	
		// Get client's CVars
		local forcelimit = tonumber( self:GetClientInfo( "forcelimit" ) )
		
		// Client can bail now
		if ( CLIENT ) then return true end
		
		local vOrigin = trace.HitPos - (self:GetOwner():GetAimVector() * 8.0)
		local vDirection = self:GetOwner():GetAimVector():Angle()
		
		local nail = ents.Create( "gmod_nail" )
		nail:GetTable().SetStuckIn( nail, trace.Entity, trace.PhysicsBone, vOrigin, vDirection )
		nail:Spawn()
		nail:Activate()
		
		trace.Entity:DeleteOnRemove( nail )
		
		// Weld them!
		local constraint = constraint.Weld( trace.Entity, trTwo.Entity, trace.PhysicsBone, trTwo.PhysicsBone, forcelimit, systemmanager )
		
		undo.Create("Nail")
		undo.AddEntity( constraint )
		undo.AddEntity( nail )
		undo.SetPlayer( self:GetOwner() )
		undo.Finish()

		self:GetOwner():AddCleanup( "nails", constraint )		
		self:GetOwner():AddCleanup( "nails", nail )
		
		return true
		
	end
	
end

function TOOL:RightClick( trace )

	self:GetWeapon():SetNextSecondaryFire( CurTime() + 0.2 )
	return self:LeftClick( trace )
	
end
