My weld script is supposed to weld the gasmask to the player positioning it over the player. It's supposed to be just like a hat. Instead it decides that it's okay to position itself behind/in front of my player when I need it to be in the exact location of the players head position. What is going on, and how can I fix this?

local hat= script.GasMask local weld


function weld(h,c)
	local hat2= h:clone()
	hat2.Parent= c
	local head = c:FindFirstChild("Head")
	if head ~= nil then
	local p
	for _,v in pairs(hat2:GetChildren()) do
		if v:IsA("Part") or v:IsA("UnionOperation") or v:IsA("MeshPart") then
			local weld= Instance.new("Weld")
			weld.Parent= head
			local core= v.Parent:FindFirstChild("Core")
			if core ~= nil then
				weld.Part0 = head
				weld.Part1 = v
				local lol = CFrame.new(head.Position.X,head.Position.Y,head.Position.Z)
				weld.C1 = v.CFrame:inverse()*lol
				p=v
			end
			v.Anchored= false
		end
	end
		if p ~= nil then
			local gM = p.Parent
			if gM:IsA("Model") then
				gM:SetPrimaryPartCFrame(CFrame.new(head.Position.X,head.Position.Y,head.Position.Z))
			end
		end
	end
end

function clean(c)
	for _,v in pairs(c:GetChildren()) do
		if v:IsA("Hat") or v:IsA("Accessory") then
			v:Destroy()
		end
	end
end

game.Players.PlayerAdded:Connect(function(plr)
	repeat wait() until plr.Character
	wait(3)
		clean(plr.Character)
		weld(hat,plr.Character)
	plr.CharacterAdded:Connect(function(char)
		clean(char)
		weld(hat,char)
	end)
end)