<?xml version="1.1" encoding="utf-8"?><waypoints>

<!--  Daily, Take PFS , Do CoT sript by: lolita, v1.0	-->
<!--  require "userfunction_worldtraveler" "userfunction_teleport" "userfunction_swimhack" -->
<!--  GroupInvite addon latest version, you can find it here: http://rom.curseforge.com/addons/groupinvite/files/38-v2-3-902/	-->
<!--  Ty for help Rock5 and lisa -->
	<onLoad>
	--=== User Options ===--

	When_Finished = "end"		<!--	after finishing what will bot do: "end" to end script, "relog" to log next character and "waypointfilename" to load that waypointfile.	-->
	Do_Daily = "true" 			<!--	"true" to do daily, "false" don't do daily	-->
	Take_PFS = "true" 			<!--	"true" to take PFS, "false" don't take PFS	-->
	Do_CoT = "1" 				<!--	"1" for true or "0" for false	-->
	mode = "move"				<!--	"stay" to stay in 1 place when doing daily or "move" for going to item	-->
	SaveTokens = 200			<!--	enter valiu how much tokens you want to save, minimum for minigame is 30	-->
	
	CharList = {}
	<!--		example
				CharList = {
					{account=4,chars={}},
					{account=8,chars={1}},
					{account=7,chars={1,2,5}},
							} -->

	--====================--
	
	function SaveToken()
		if (player.Level >= 80)then
			cprintf(cli.yellow,"We are lv 80+, dont have to do daily. Checking for tokens.\n")
			if (SaveTokens > inventory:itemTotalCount(203038)) then
				cprintf(cli.yellow,",Not enof tokens, We going to Rorazan.\n")
				takemeto("Rorazan")
			else
				TakePFS()
			end
		else
			cprintf(cli.yellow,"We are not lv 80+, we have to do daily.\n")
			CheckForDaily()
		end
	end
			
	function CheckForDaily()
		if RoMScript("Daily_count()") > 9 then				
			cprintf(cli.yellow,"Daily not reset yet, or you finished already.\n")
			__WPL:setWaypointIndex(__WPL:findWaypointTag("End"));
		else
			if (Do_Daily == "true") then
				cprintf(cli.yellow,"We going to Rorazan.\n")
				takemeto("Rorazan")
			elseif (Do_Daily == "false") then
				TakePFS()
			end
		end
	end
	
	function TakePFS()
		if (Take_PFS == "true") then
			if (player.Level >= 80)then
				cprintf(cli.yellow,"We are going to take PFS.\n")
				__WPL:setWaypointIndex(__WPL:findWaypointTag("PFS"));
			elseif (Take_PFS == "false") then
				cprintf(cli.yellow,"LV to low to take PFS.\n")
				DoCoT()
			end
		end
	end
	
	function DoCoT()
		if (Do_CoT == "1") then
			cprintf(cli.yellow,"We going to Curse of Terror now.\n")
			__WPL:setWaypointIndex(__WPL:findWaypointTag("CoT"));
		elseif (Do_CoT == "0") then
			cprintf(cli.yellow,"We wont do Curse of Terror, going to end.\n")
			__WPL:setWaypointIndex(__WPL:findWaypointTag("End"));
		end
	end
	
	function StayInRorazan()
		if ((Take_PFS == "false") and (Do_CoT == "0")) then
			cprintf(cli.yellow,"We staying here in Rorazan.\n")
			checkRelog()
		else
			__WPL:setWaypointIndex(__WPL:findWaypointTag("GoVar"));
		end
	end
	
	function TryGetParty()
		local party = RoMScript("GetNumPartyMembers()")
		local raid = RoMScript("GetNumRaidMembers()")
		if ((not (party > 0)) or (not (raid > 0))) then
			sendMacro("SendChatMessage('inv','ZONE');")
			yrest(8000);
			RoMScript("AcceptGroup();")
		end
	end
	
	function DoDaily()
		if (mode == "stay") then
			StayInPlace()
		elseif (mode == "move") then
			MoveToItem()
		end
	end
			
	function MoveToItem()
		changeProfileOption("HARVEST_DISTANCE", 50);
		local queststate
		local party = RoMScript("GetNumPartyMembers()")
		local raid = RoMScript("GetNumRaidMembers()")
		if ((not (party > 0)) or (not (raid > 0))) then
			RoMScript("GroupInvite_Group_StartStop(true)")
		end
		repeat
			queststate = getQuestStatus("Extinguish More Flames")
				if queststate == "complete" then
					-- Complete quest
					player:target_NPC("Diandon");
					CompleteQuestByName(425186); yrest(1000);
				end
				if queststate ~= "incomplete" then
					-- Accept quest
					player:target_NPC("Diandon");
					AcceptQuestByName(425186); yrest(1000);
					if (RoMScript("Daily_count()") > 9) then
						__WPL:setWaypointIndex(__WPL:findWaypointTag("daily"));
					else
						player:moveTo(CWaypoint(-21673,-23225,572));
						repeat
							player:target_Object(119791)
							queststate = getQuestStatus("Extinguish More Flames")
						until queststate == "complete"
					end
				end
		until RoMScript("Daily_count()") > 9
	end
	
	function StayInPlace()
		local party = RoMScript("GetNumPartyMembers()")
		local raid = RoMScript("GetNumRaidMembers()")
		local queststate 
		if ((not (party > 0)) or (not (raid > 0))) then
			RoMScript("GroupInvite_Group_StartStop(true)")
			repeat
				yrest(5000);
				party = RoMScript("GetNumPartyMembers()")
				raid = RoMScript("GetNumRaidMembers()")
			until ((party > 0) or (raid > 0))
		end
		repeat
			yrest(1000) -- check every second
			queststate = getQuestStatus("Extinguish More Flames")
				if queststate == "complete" then
					-- Complete quest
					player:target_NPC("Diandon");
					CompleteQuestByName(425186); yrest(1000);
				end
				if queststate ~= "incomplete" then
					-- Accept quest
					player:target_NPC("Diandon");
					AcceptQuestByName(425186); yrest(1000);
				end
		until RoMScript("Daily_count()") > 9
	end

	function checkRelog()
		-- Log result
		local filename = getExecutionPath() .. "/logs/cot.log";
		local file, err = io.open(filename, "a+");
		if file then
			file:write("Account: "..RoMScript("GetAccountName()").."\tName: " ..string.format("%-10s",player.Name ).." \tDate: " .. os.date() ..
			" \tShells gained/total: "..inventory:getItemCount(240181) - numshells.."/".. inventory:getItemCount(240181).. "\t" ..logentry .. "\n")
			file:close();
		end

		if When_Finished == "relog" then
			sendMacro("}LoginNextToon=true;a={")
			sendMacro("Logout();");
			waitForLoadingScreen();
			loadPaths("cot_tele");
		elseif When_Finished == "charlist" then
			SetCharList(CharList)
			LoginNextChar()
			loadPaths("cot_tele");
		elseif When_Finished == "end" then
			error("Ending script",2)
		else
			if not string.find(When_Finished,".", 1, true) then
				When_Finished = When_Finished .. ".xml"
			end
			local filename = getExecutionPath() .. "/waypoints/" .. When_Finished
			local file, err = io.open(filename, "r");
			if file then
				file:close();
				loadPaths(When_Finished)
			else
				error("'When_Finished' option is invalid",0)
			end
		end
	end

	function checkaggro()
		repeat
			player:update()
			if player.Battling then
				local clown = player:findEnemy(true)
				player.X = clown.X player.Z = clown.Z -- Temporarily change player coords so we can find nearest seal to mob
				local seal = player:findNearestNameOrId(102384)
				player:target(seal) -- kills the summoning portal and not the ghost clown.
				player:fight()
				yrest(2000) -- give a couple of seconds for the clown to disappear.
				player:update()
			end
		until not player.Battling
	end

	function getallkeys()
		local lastSealAddress = 0
		repeat
			player:update()
			local seal = player:findNearestNameOrId(113112, lastSealAddress)
			if seal then
				-- goto seal
				teleport(nil,nil,75)            -- go up to height if 75
				teleport(seal.X, seal.Z, 75)	-- teleport to above seal
				teleport(seal.X + 1, seal.Z, 57)	-- teleport in range to click seal

				-- click seal
				repeat
					checkaggro()
					player:target(seal)
					yrest(100)
					Attack()
					yrest(1000)
					player:update()
				until player:findNearestNameOrId(113106) -- until a key appears

				-- Remember last seal
				lastSealAddress = seal.Address

				-- Collect key
				local keys = inventory:itemTotalCount(203027)

				repeat
					checkaggro()
					player:target_Object(113106,nil,nil,true) -- harvests key
				until inventory:itemTotalCount(203027) == keys + 1
				yrest(500)

			end
		until gotAllKeys()
	end

	function gotogate()
		teleport(nil,nil,75) 			-- go up to height if 75
		teleport(4080,3948.5,75) 		-- teleport to above portal
		teleport(4080,3974,30) 		-- teleport into portal
		player:faceDirection(3.14/2) -- Face forward
		keyboardPress( settings.hotkeys.MOVE_FORWARD.key );
		repeat
			player:update()
			dist = distance(player.X, player.Z, 4081, 3335)
			yrest(700)
		until 100 > dist
		printf("Distance checked and continuing.\n")
	end

	function gotAllKeys()
		local room = currentRoom()
		local keys = inventory:itemTotalCount(203027)
		local keyGoal = (room == 1 and 1) or (room == 2 and 3) or (room == 3 and 6) or (room == 4 and 10)
		return keys >= keyGoal
	end

	function currentRoom()
		return memoryReadRepeat("int",getProc(), player.Address + 0x1cc)
	end

	if fly == nil or teleport == nil then
		error("This waypoint cannot run without the 'swimhack' and 'teleport' userfunctions.")
	end

	numshells = inventory:getItemCount(240181)
	logentry = nil
	Malatina = GetIdName(111813)

	settings.profile.options.WP_NO_STOP = false
	table.insert(settings.profile.friends, "102382") -- adds the barrier to friend so doesn't try to kill it.
	
	function enterCoT()
	changeProfileOption("HARVEST_DISTANCE", 450);
		if (Do_CoT == "1") then
			cprintf(cli.yellow,"Entering Curse of Terror now.\n")
			local zoneid = RoMScript("GetZoneID()")
			if zoneid ~= 353 then -- not in Course of Terror
				if inventory:itemTotalCount(240181) > 950 then
					-- Wait for user to use some shells.
					cprintf(cli.yellow,"Reaching the maximum number of Phirius Shells (1000). Please spend some before continuing.\n")
					player:sleep()
					numshells = inventory:getItemCount(240181)
				end
				local empties = inventory:itemTotalCount(0)
				if 10 > empties then
					-- Wait for user to make some space in inventory.
					cprintf(cli.yellow,"Not much space left in inventory. Are you sure you want to continue with only %d spaces left?\n",empties)
					player:sleep()
				end
				if 30 > inventory:itemTotalCount(203038) then
					print("Not enough Phirius Token Coins.")
					logentry = "Not enough Phirius Token Coins."
					checkRelog()
					return
				end

				-- Try to find Malatina and teleport in
				if player:target_NPC(Malatina) then
					yrest(1000)

					if 2 > RoMScript("GetNumSpeakOption()") then -- try again
						player:target_NPC(Malatina) yrest(1000)
					end

					sendMacro("ChoiceOption(2);");
					yrest(2000)

					if RoMScript("GetNumSpeakOption()") > 0 then -- enter game
						sendMacro("ChoiceOption(1);");
						if not waitForLoadingScreen(30) then
							print("Failed to teleport into Course of Terror")
							logentry = "Failed to teleport into Course of Terror."
							checkRelog()
						end
						yrest(1000)
						__WPL:setWaypointIndex(__WPL:getNearestWaypoint(player.X,player.Z))
					else
						print("This character already did Course of Terror.")
						logentry = "Already did Course of Terror."
						checkRelog()
					end
				else
					print("You are too far from Malatina")
					logentry = "Too far from Malatina."
					checkRelog()
				end
			end
		elseif (Do_CoT == "0") then
			cprintf(cli.yellow,"We wont do Curse of Terror, going to end.\n")
			__WPL:setWaypointIndex(__WPL:findWaypointTag("End"));
		end
	end
</onLoad>
			<!--START-->
	<!-- #  1 --><waypoint x="4871" z="-1885" y="104">
		SaveToken()
	</waypoint>
				<!-- RORAZAN-->
	<!-- #  2 --><waypoint x="-20829" z="-22866" y="564"> 
		TryGetParty()
	</waypoint>
				<!-- DAILY SPOT-->
	<!-- #  3 --><waypoint x="-21541" z="-22945" y="572" tag = "daily">
		DoDaily()
		RoMScript("GroupInvite_Group_StartStop(false)")
		RoMScript("LeaveParty()")
		StayInRorazan()
	</waypoint>
				<!-- RETURN -->
	<!-- #  4 --><waypoint x="-20829" z="-22866" y="564" tag ="GoVar">
		takemeto("varanascentral")
		TakePFS()
	</waypoint>
	<!-- # 5 --><waypoint x="4872" z="-1952" y="109" tag="CoT">
	enterCoT()
	</waypoint>
			<!-- INSIDE MINI GAME -->
	<!-- # 6 --><waypoint x="4081" z="3340" y="18" tag="START">
		if currentRoom() == 1 then -- Just arrived
			if not RoMScript("TimeKeeperFrame:IsVisible()") then
				player:target_NPC(Malatina);
				yrest(2000)
				sendMacro("ChoiceOption(2);");
				yrest(2000)
				sendMacro("ChoiceOption(1);");
				repeat yrest(1000) until RoMScript("TimeKeeperFrame:IsVisible()")
			end
		elseif currentRoom() > 4 then -- Finished. Open chests
			--=== Create table for chests ===--
			chests = {left = {}, right = {}}

			local objectList = CObjectList();
			objectList:update();
			local objSize = objectList:size()

			for i = 0,objSize do
				local obj = objectList:getObject(i);
				if obj.Id == 113114 or obj.Id == 113137 then
					if obj.X > 4081 then -- right side
						table.insert(chests.right, table.copy(obj))
					else -- left side
						table.insert(chests.left, table.copy(obj))
					end
				end
			end

			-- Sort chests
			table.sort(chests.left, function(a,b) return b.Z > a.Z end)
			table.sort(chests.right, function(a,b) return a.Z > b.Z end)

			-- Get left side
			for k,v in pairs(chests.left) do
				player:target(v.Address);
				Attack()
				yrest(2000)
				Attack()
				yrest(2000)
				repeat
					yrest(2000)
					player:update()
				until not player.Casting
			end

			-- Get right side
			for k,v in pairs(chests.right) do
				player:target(v.Address);
				Attack()
				yrest(2000)
				Attack()
				yrest(2000)
				repeat
					yrest(2000)
					player:update()
				until not player.Casting
			end

			player:moveTo(CWaypoint(4081,3335))

			local secondsleft = RoMScript("TimeKeeperFrame.startTime-GetTime()")
			local mm = string.format("%2s", math.floor(secondsleft/ 60))
			local ss = string.format("%02s", math.floor(math.mod(secondsleft, 60)))
			printf("Succeeded with %s:%s remaining.\n",mm,ss)
			logentry = string.format("Succeeded with %s:%s remaining.",mm,ss)
			checkRelog()
		end
	</waypoint>
		<!-- JUST BEFORE THE DOOR -->
	<!-- # 7 --><waypoint x="4081" z="3499" y="18" >	</waypoint>
		<!-- JUST AFTER THE DOOR -->
	<!-- # 8 --><waypoint x="4081" z="3600" y="28" >
		logentry = "Ran out of time." -- default
		yrest(3000)
		fly()
		getallkeys()
		gotogate()
		flyoff()
		__WPL:setWaypointIndex(__WPL:findWaypointTag("START"));
	</waypoint>
				<!-- "PFS" NPS -->
	<!-- # 9 --><waypoint x="5249" z="-2080" y="121" tag="PFS">
		player:target_NPC("Sophia");
		sendMacro("ChoiceOption(1);");
		DoCoT()
	</waypoint>
				<!-- END -->
	<!-- # 10 --><waypoint x="4969" z="-1825" y="103" tag="End">
		checkRelog()
	</waypoint>
</waypoints>