local cm,m = GetID()
function cm.initial_effect(c)
    local e1 = Effect.CreateEffect(c)
    e1:SetType(EFFECT_TYPE_ACTIVATE)
    e1:SetCode(EVENT_FREE_CHAIN)
    e1:SetCondition(cm.con)
    e1:SetTarget(cm.tg)
    e1:SetOperation(cm.op)
    c:RegisterEffect(e1)
end
function cm.tg(e,tp,eg,ep,ev,re,r,rp,chk)
	if chk==0 then return Duel.IsPlayerCanDiscardDeck(tp,1) end
	Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_CODE)
	getmetatable(e:GetHandler()).announce_filter={TYPE_FUSION+TYPE_SYNCHRO+TYPE_XYZ+TYPE_LINK,OPCODE_ISTYPE,OPCODE_NOT}
	local ac=Duel.AnnounceCard(tp,table.unpack(getmetatable(e:GetHandler()).announce_filter))
	Duel.SetTargetParam(ac)
	Duel.SetOperationInfo(0,CATEGORY_ANNOUNCE,nil,0,tp,0)
end
function cm.op(e,tp,eg,ep,ev,re,r,rp)
    local ac=Duel.GetChainInfo(0,CHAININFO_TARGET_PARAM)
    local ft=Duel.GetLocationCount(1-tp,LOCATION_MZONE)
	if ft<=0 or not ac then return false end
	if Duel.IsPlayerAffectedByEffect(1-tp,59822133) then ft=1 end
	local g=Duel.SelectMatchingGroup(tp,function(c,e,tp,cod) return c:IsCode(cod) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end,tp,LOCATION_DECK,LOCATION_DECK,ft,ft,nil,e,1-tp,ac)
	Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
	for sc in aux.Next(g) do
	    Duel.SpecialSummonStep(sc,0,1-tp,tp,false,false,POS_FACEUP_ATTACKs)
	    local e1=Effect.CreateEffect(e:GetHandler())
    	e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
    	e1:SetRange(LOCATION_MZONE)
    	e1:SetCode(EVENT_TOSS_COIN_NEGATE)
    	e1:SetCondition(cm.con1)
    	e1:SetOperation(cm.op1)
    	sc:RegisterEffect(e1)
	end
	Duel.SpecialSummonComplete()
end
function cm.con1(e,tp,eg,ep,ev,re,r,rp)
	return ep==1-tp and Duel.GetFlagEffect(e:GetHandler(),m)==0
end
function cm.op1(e,tp,eg,ep,ev,re,r,rp)
	if Duel.GetFlagEffect(e:GetHandler(),m)~=0 then return end
	if Duel.SelectYesNo(tp,aux.Stringid(m,0)) then
		Duel.Hint(HINT_CARD,0,m)
		Duel.RegisterFlagEffect(e:GetHandler(),m,RESET_PHASE+PHASE_END,0,1)
		Duel.TossCoin(1-tp,ev)
	end
end