--Sp-疾风同调
function c87593015.initial_effect(c)
	--Activate
	local e1=Effect.CreateEffect(c)
	e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
	e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_CANNOT_DISABLE)
	e1:SetType(EFFECT_TYPE_ACTIVATE)
	e1:SetCode(EVENT_FREE_CHAIN)
	e1:SetHintTiming(0,TIMING_BATTLE_END)
	e1:SetCondition(c87593015.Condition)
	e1:SetTarget(c87593015.target)
	e1:SetOperation(c87593015.activate)
	c:RegisterEffect(e1)
end
function c87593015.cfilter1(c,e,tp,sc)
	local rg=Duel.GetMatchingGroup(c87593015.cfilter2,tp,LOCATION_MZONE,0,c,e,tp)
	return c:IsType(TYPE_TUNER) and c:IsFaceup() and c:IsCanBeSynchroMaterial() and sc:GetLevel()-c:GetLevel()>0
		and rg:CheckWithSumEqual(Card.GetLevel,sc:GetLevel()-c:GetLevel(),1,99) and c:IsAbleToRemove()
end
function c87593015.cfilter2(c,e,tp)
	return not c:IsType(TYPE_TUNER) and c:IsFaceup() and c:IsCanBeSynchroMaterial() and c:IsAbleToRemove()
end
function c87593015.spfilter(c,e,tp)
	local f=Duel.GetMatchingGroup(Card.IsCode,tp,LOCATION_SZONE,LOCATION_SZONE,nil,87593200):GetFirst()
	if f:GetControler()==tp then cou=0x871 else cou=0x872 end
	return c:IsType(TYPE_SYNCHRO) and c:GetLevel()<=f:GetCounter(cou) and c:IsCanBeSpecialSummoned(e,SUMMON_TYPE_SYNCHRO,tp,true,false)
		and Duel.IsExistingMatchingCard(c87593015.cfilter1,tp,LOCATION_MZONE,0,1,nil,e,tp,c)
end
function c87593015.Condition(e,tp,eg,ep,ev,re,r,rp,chk)
	local f=Duel.GetMatchingGroup(Card.IsCode,tp,LOCATION_SZONE,LOCATION_SZONE,nil,87593200):GetFirst()
	if f:GetControler()==tp then cou=0x871 else cou=0x872 end
	return f:GetCounter(cou)<=8 and Duel.GetTurnPlayer()~=tp and Duel.GetCurrentPhase()==PHASE_BATTLE
end
function c87593015.target(e,tp,eg,ep,ev,re,r,rp,chk)
	if chk==0 then
	return Duel.IsExistingMatchingCard(c87593015.spfilter,tp,LOCATION_EXTRA,0,1,nil,e,tp) end
	Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA)
end
function c87593015.activate(e,tp,eg,ep,ev,re,r,rp)
	Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
	local g=Duel.SelectMatchingCard(tp,c87593015.spfilter,tp,LOCATION_EXTRA,0,1,1,nil,e,tp):GetFirst()
	Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
	local g1=Duel.SelectMatchingCard(tp,c87593015.cfilter1,tp,LOCATION_MZONE,0,1,1,nil,e,tp,g)
	local rg=Duel.GetMatchingGroup(c87593015.cfilter2,tp,LOCATION_MZONE,0,g1:GetFirst(),e,tp)
	Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
	local g2=rg:SelectWithSumEqual(tp,Card.GetLevel,g:GetLevel()-g1:GetFirst():GetLevel(),1,99)
	g1:Merge(g2)
	if  Duel.Remove(g1,POS_FACEUP,REASON_EFFECT+REASON_SYNCHRO+REASON_MATERIAL)==g1:GetCount() then
		g:SetMaterial(g1)
		Duel.SpecialSummon(g,SUMMON_TYPE_SYNCHRO,tp,tp,true,false,POS_FACEUP_ATTACK)
		g:CompleteProcedure()
	end
end
