--灯之魔神
local cm,m,o=GetID()
function cm.initial_effect(c)
    --code
    aux.EnableChangeCode(c,97590747,LOCATION_HAND)
    local e1=Effect.CreateEffect(c)
    e1:SetType(EFFECT_TYPE_FIELD)
    e1:SetCode(EFFECT_INDESTRUCTABLE_BATTLE)
    e1:SetRange(LOCATION_MZONE)
    e1:SetTargetRange(LOCATION_MZONE,LOCATION_MZONE)
    e1:SetTarget(cm.indtg)
    e1:SetValue(1,m*2)
    c:RegisterEffect(e1)
    local e2=Effect.CreateEffect(c)
    e2:SetDescription(aux.Stringid(m,0))
    e2:SetCategory(CATEGORY_RELEASE+CATEGORY_SPECIAL_SUMMON+CATEGORY_POSITION)
    e2:SetType(EFFECT_TYPE_QUICK_O)
    e2:SetCode(EVENT_FREE_CHAIN)
    e2:SetRange(LOCATION_HAND)
    e2:SetCountLimit(1,m)
    e2:SetHintTiming(0,TIMINGS_CHECK_MONSTER+TIMING_END_PHASE)
    e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
    e2:SetTarget(cm.tg2)
    e2:SetOperation(cm.op2)
    c:RegisterEffect(e2)
end
function cm.indtg(e,c)
    local tc=e:GetHandler()
    return c==tc or c==tc:GetBattleTarget()
end
function cm.filter(c,tp)
    return c:IsReleasableByEffect() and c:IsPosition(POS_FACEDOWN) and Duel.GetMZoneCount(tp,c)>0
end
function cm.filter2(c)
    return c:IsFaceup() and c:IsCanTurnSet()
end
function cm.tg2(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
    if chkc then return false end
    if chk==0 then return Duel.IsExistingTarget(cm.filter,tp,LOCATION_MZONE,0,1,nil,tp)
        and Duel.IsExistingTarget(cm.filter2,tp,0,LOCATION_MZONE,1,nil)
        and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end
    Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RELEASE)
    local g1=Duel.SelectTarget(tp,cm.filter,tp,LOCATION_MZONE,0,1,1,nil,tp)
    Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_POSCHANGE)
    local g2=Duel.SelectTarget(tp,cm.filter2,tp,0,LOCATION_MZONE,1,1,nil)
    Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
    Duel.SetOperationInfo(0,CATEGORY_RELEASE,g1,1,0,0)
    Duel.SetOperationInfo(0,CATEGORY_POSITION,g2,1,0,0)
    g1:GetFirst():RegisterFlagEffect(m,RESET_EVENT+RESET_CHAIN,0,1)
    g2:GetFirst():RegisterFlagEffect(m+1,RESET_EVENT+RESET_CHAIN,0,1)
end
function cm.op2(e,tp,eg,ep,ev,re,r,rp)
    local c=e:GetHandler()
    local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS):Filter(Card.IsRelateToEffect,nil,e)
    local g1=g:Filter(cm.cfilter1,nil,tp)
    local g2=g:Filter(cm.cfilter2,nil,tp)
    if Duel.Release(g1,REASON_EFFECT)>0 and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and c:IsRelateToEffect(e) and Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)>0 then
        if g2:GetFirst():IsLocation(LOCATION_MZONE) and g2:GetFirst():IsFaceup() then
            Duel.ChangePosition(g2,POS_FACEDOWN_DEFENSE)
        end
    end
end
function cm.cfilter1(c,tp)
    return c:IsControler(tp) and c:GetFlagEffect(m)==0
end
function cm.cfilter2(c,tp)
    return c:IsControler(1-tp) and c:GetFlagEffect(m+1)==0
end