// Create the character
IfSpawned
  IfStateIs0
    // It's an imported spell in hand
    KeepAction
  Else
    // It's a Ball of Light
    JoinNullTeam
    MakeNameUnknown
    NotAnItem
    tmpargument = 0
    tmpdistance = SPAWNLAST
    SpawnAttachedParticle
    SpawnPoof
IfChanged
  // It's a spell in hand
  tmpargument = 0
  SetState
  KeepAction

// Monster AI
IfStateIs0
  GetState // NOP
Else
  // Handle disenchantment
  IfKilled
    GoPoof
  // Move around the owner
  IfTimeOut
    tmpx = ownerdistance
    tmpy = 400
    IfXIsLessThanY
      // Circle the leader
      tmpx = ownerx
      tmpy = ownery
      tmpdistance = 160
      tmpturn = ownerturnto + 16384
    Else
      // Catch up quick
      tmpx = ownerx
      tmpy = ownery
      tmpdistance = 400
      tmpturn = ownerturnto
    Compass
    ClearWaypoints
    AddWaypoint
    tmpargument = rand&7 + 5
    SetTime

// Spell AI
IfStateIs0
  // Say that it was taken out
  IfTakenOut
    SetTargetToWhoeverIsHolding
      IfTargetIsAPlayer
        tmpargument = 1
        IfNameIsKnown
          tmpargument = 2
        SendMessageNear
  // Allow it to be cast
  IfUsed
    tmpargument = 20
    SetReloadTime
    tmpargument = ACTIONMC
    TargetDoAction
    UndoEnchant
      // Killed the old one
      GetState // NOP
      UnsparkleIcon
      SpawnPoof
    Else
      // No old one, so make a new one
      SetTargetToWhoeverIsHolding
      tmpargument = [WMAG]
      IfTargetHasSkillID
        tmpx = 256
        tmpy = targetmanaflow
        IfXIsLessThanY
          tmpx = 4
          tmpargument = tmpx
          CostTargetMana
            tmpx = selfx
            tmpy = selfy
            tmpdistance = selfz
            tmpturn = selfturn
            SetOwnerToTarget
            SpawnCharacterXYZ
              EnchantChild
              tmpargument = 1
              SetChildState
              MakeNameKnown
              MakeUsageKnown
              tmpargument = WHITE
              SparkleIcon
            tmpargument = 0
            tmpdistance = 11025
            PlaySound

  // Return to spellbook, Do last!
  IfDropped
    tmpargument = 0
    SetContent
    BecomeSpellbook
    DisaffirmCharacter
    tmpargument = ACTIONJB
    DoAction
    KeepAction
End
