--齿轮指挥官
local cm,m,o=GetID()
function cm.initial_effect(c)
    local e1=Effect.CreateEffect(c)
    e1:SetType(EFFECT_TYPE_FIELD)
    e1:SetCode(EFFECT_SPSUMMON_PROC)
    e1:SetProperty(EFFECT_FLAG_UNCOPYABLE)
    e1:SetRange(LOCATION_HAND)
    e1:SetCondition(cm.con1)
    c:RegisterEffect(e1)
    local e2=Effect.CreateEffect(c)
    e2:SetDescription(aux.Stringid(m,0))
    e2:SetCategory(CATEGORY_DESTROY+CATEGORY_TOHAND)
    e2:SetType(EFFECT_TYPE_QUICK_O)
    e2:SetCode(EVENT_FREE_CHAIN)
    e2:SetRange(LOCATION_MZONE)
    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.filter1(c)
    return c:IsLevelAbove(5) and (c:IsType(TYPE_NORMAL) or c:IsRace(RACE_MACHINE))
end
function cm.con1(e,c)
    if c==nil then return true end
    local tp=c:GetControler()
    return Duel.IsExistingMatchingCard(cm.filter1,tp,LOCATION_MZONE,0,1,nil)
end
function cm.filter2(c)
    return c:IsLevelBelow(7) and (c:IsType(TYPE_NORMAL) or c:IsRace(RACE_MACHINE))
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.filter2,tp,LOCATION_MZONE,0,1,nil)
        and Duel.IsExistingTarget(Card.IsAbleToHand,tp,0,LOCATION_ONFIELD,1,nil) end
    Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
    local g1=Duel.SelectTarget(tp,cm.filter2,tp,LOCATION_MZONE,0,1,1,nil)
    Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RTOHAND)
    local g2=Duel.SelectTarget(tp,Card.IsAbleToHand,tp,0,LOCATION_ONFIELD,1,1,nil)
    Duel.SetOperationInfo(0,CATEGORY_DESTROY,g1,1,0,0)
    Duel.SetOperationInfo(0,CATEGORY_TOHAND,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 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.Destroy(g1,REASON_EFFECT)>0 then
        Duel.SendtoHand(g2,nil,REASON_EFFECT)
    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