--凶导的告悔
local s,id,o=GetID()
function s.initial_effect(c)
	--Activate
	local e1=Effect.CreateEffect(c)
	e1:SetCategory(CATEGORY_TOGRAVE)
	e1:SetType(EFFECT_TYPE_ACTIVATE)
	e1:SetCode(EVENT_FREE_CHAIN)
	e1:SetCountLimit(1,id)
	e1:SetCondition(s.con)
	e1:SetTarget(s.tg)
	e1:SetOperation(s.op)
	c:RegisterEffect(e1)
	--search
	local e2=Effect.CreateEffect(c)
	e2:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
	e2:SetType(EFFECT_TYPE_IGNITION)
	e2:SetRange(LOCATION_GRAVE)
	e2:SetCountLimit(1,id*2)
	e2:SetCost(s.cost2)
	e2:SetTarget(s.tg2)
	e2:SetOperation(s.op2)
	c:RegisterEffect(e2)
end
function s.con(e,tp,eg,ep,ev,re,r,rp)
	local g1=Duel.GetFieldGroupCount(tp,LOCATION_EXTRA,0)
	local g2=Duel.GetFieldGroupCount(tp,0,LOCATION_EXTRA)
	return g1>g2
end
function s.tg(e,tp,eg,ep,ev,re,r,rp,chk)
	local g1=Duel.GetFieldGroupCount(tp,LOCATION_EXTRA,0)
	local g2=Duel.GetFieldGroupCount(tp,0,LOCATION_EXTRA)
	local g=Duel.GetMatchingGroupCount(Card.IsAbleToGraveAsCost,tp,LOCATION_EXTRA,0,nil)
	if chk==0 then return g>=g1-g2 end
	Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,g1-g2,tp,LOCATION_EXTRA)
end
function s.op(e,tp,eg,ep,ev,re,r,rp)
	local g1=Duel.GetFieldGroupCount(tp,LOCATION_EXTRA,0)
	local g2=Duel.GetFieldGroupCount(tp,0,LOCATION_EXTRA)
	local g=Duel.GetMatchingGroup(Card.IsAbleToGraveAsCost,tp,LOCATION_EXTRA,0,nil)
	if g1<=g2 or #g<=0 then return end
	Duel.ShuffleExtra(tp)
	local rg=g:RandomSelect(tp,g1-g2)
	Duel.SendtoGrave(rg,REASON_EFFECT)
end
function s.cfilter2(c)
	return c:IsType(TYPE_RITUAL+TYPE_LINK+TYPE_XYZ) and c:IsAbleToRemoveAsCost()
end
function s.cost2(e,tp,eg,ep,ev,re,r,rp,chk)
	if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() and Duel.IsExistingMatchingCard(s.cfilter2,tp,LOCATION_GRAVE,LOCATION_GRAVE,6,nil) end
	Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
	local g=Duel.SelectMatchingCard(tp,s.cfilter2,tp,LOCATION_GRAVE,LOCATION_GRAVE,6,6,nil)
	g:AddCard(e:GetHandler())
	Duel.Remove(g,POS_FACEUP,REASON_COST)
end
function s.filter2(c)
	return c:IsSetCard(0x145) and c:IsAbleToHand()
end
function s.tg2(e,tp,eg,ep,ev,re,r,rp,chk)
	if chk==0 then return Duel.IsExistingMatchingCard(s.filter2,tp,LOCATION_DECK,0,2,nil) end
	Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,2,tp,LOCATION_DECK)
end
function s.op2(e,tp,eg,ep,ev,re,r,rp)
	local g=Duel.GetMatchingGroup(s.filter2,tp,LOCATION_DECK,0,nil)
	if g:GetCount()>1 then
		Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
		local sg=g:Select(tp,2,2,nil)
		Duel.SendtoHand(sg,nil,REASON_EFFECT)
		Duel.ConfirmCards(1-tp,sg)
	end
end