local function dynamiteInput()
	local dynamite = 3
	return GetInput"Dynamite" or (PlayerData().ActiveSecondWeapon == dynamite and GetInput"Projectile")
end

local function cameraSpeed()
	local arrowInput = (string.format("%x", GetInput())):sub(-7, -7)
	if arrowInput == "1" then return {x = -7, y = 0} end
	if arrowInput == "2" then return {x = 7, y = 0} end
	if arrowInput == "4" then return {x = 0, y = -7} end
	if arrowInput == "8" then return {x = 0, y = 7} end
	if arrowInput == "5" then return {x = -5, y = -5} end
	if arrowInput == "6" then return {x = 5, y = -5} end
	if arrowInput == "9" then return {x = -5, y = 5} end
	if arrowInput == "a" then return {x = 5, y = 5} end
	return {x = 0, y = 0}
end

function main(self)
	local claw = GetClaw()

    if self.State == 0 then
		self.Flags.AlwaysActive, self.DrawFlags.NoDraw = true, true
        self.freezeTime = 0
		local screenWidth, screenHeight = GetResolution()
		self.sight = CreateHUDObject{
			X = math.ceil(screenWidth/2),
			Y = math.ceil(screenHeight/2),
			Z = 10550,
			logic = "DoNothing",
			image = "CUSTOM_METEOR_AIM"
		}
		self.sight.DrawFlags.NoDraw = true
		self.State = 1
	end

	-- Check for dynamite input:
	if self.State == 1 and dynamiteInput() then
		if PlayerData().TNTAmmo > 0 and claw.Health > 0 and claw.State < ClawStates.Hit then
			self.sight.DrawFlags.NoDraw = false
			self.cameraX, self.cameraY = claw.X, claw.Y
			self.lastClawsState = claw.State
            self.freezeTime = GetTime() + 20
			if claw.State == ClawStates.MoveRight or claw.State == ClawStates.MoveLeft then
                claw:SetAnimation("CLAW_STAND", 100)
            end
			claw.State = ClawStates.Freeze
			self.State = 2
		end
	end

	if self.State == 2 and GetTime() > self.freezeTime then
		-- Control camera:
		local speed = cameraSpeed()
		self.cameraX = self.cameraX + speed.x
		self.cameraY = self.cameraY + speed.y
		-- limit camera to the 1280x1280 box:
		if self.cameraX > claw.X + 640 then self.cameraX = claw.X + 640 end
		if self.cameraX < claw.X - 640 then self.cameraX = claw.X - 640 end
		if self.cameraY > claw.Y + 480 then self.cameraY = claw.Y + 480 end
		if self.cameraY < claw.Y - 480 then self.cameraY = claw.Y - 480 end

		CameraToPoint(self.cameraX, self.cameraY)

		-- abort:
		if claw.State ~= ClawStates.Freeze or claw.Health <= 0 then
			CameraToClaw()
			self.sight.DrawFlags.NoDraw = true
			self.State = 3
		end

		-- create the meteor:
		if not dynamiteInput() or self.lastClawsState == ClawStates.Jump or self.lastClawsState == ClawStates.Fall then
			CreateObject{
				X = self.cameraX - 500,
				Y = self.cameraY - 500,
				Z = 8800,
				name = "ArtifactPower:FireEssenceProjectile"
			}
			PlaySound("CUSTOM_METEOR_FALL")
			PlayerData().TNTAmmo = PlayerData().TNTAmmo - 1

			claw.State = self.lastClawsState
			CameraToClaw()
			self.sight.DrawFlags.NoDraw = true
            self.State = 3
		end
	end

    if self.State == 3 and not dynamiteInput() then
        self.State = 1
    end
end
