// tile - starting tile for spear.
// damage - damage done.
// length - length of the spear in pixels.
item script IU_Spear {
  void run(int _, int tile, int damage, int length) {
    if (CLA_CanAct()) {
      CreateFFC(SCR_FFC_SPEAR, tile, damage, length);}}}

ffc script Spear {
  void run(int tile, int damage, int length) {
    this->Flags[FFCF_ETHEREAL] = true;
    Game->PlaySound(SFX_SWORD);

    int offset = length - 16;
    // Number of tiles the spear takes up.
    int size = (length + 15) >> 4;
    // Calculate offsets from standard.
    int strikeDX = DirX(Link->Dir) * offset;
    int strikeDY = DirY(Link->Dir) * offset;
    int drawDX = Min(strikeDX, 0);
    int drawDY = Min(strikeDY, 0);

    lweapon animation = Screen->CreateLWeapon(LW_ANIMATION2);
    int animationId = GetId(animation);
    animation->DeadState = -2;
    animation->OriginalTile = tile + Link->Dir * size;
    animation->Behind = true;
    animation->CSet = 5;
    animation->CollDetection = false;
    animation->Frame = 0;
    animation->NumFrames = 40;
    animation->ASpeed = 3600;
    animation->Extend = EXT_NORMAL;
    animation->TileWidth = size;
    animation->TileHeight = size;

    // Put after animation so that link is on top of spear.
    CLA_Stab();

    int strikeId = LWEAPON_ID_NULL;
    lweapon strike;

    while (CLA_Action == CLA_STAB) {
      animation = FindLWeapon(animationId);
      animation->DrawXOffset = CLA_ItemX + drawDX;
      animation->DrawYOffset = CLA_ItemY + drawDY;
      animation->Tile = animation->OriginalTile;

      // (Re)create strike if needed.
      if (strikeId == LWEAPON_ID_NULL || !strike->isValid()) {
        strike = Spear_CreateStrike(damage);
        strikeId = GetId(strike);}

      // Update strike position.
      strike->X = Clamp(CLA_ItemX + strikeDX, 0, 240);
      strike->Y = Clamp(CLA_ItemY + strikeDY, 0, 160);

      Slash_SlashSolid(strike);

      Waitframe();
      strike = FindLWeapon(strikeId);}

    if (strikeId != LWEAPON_ID_NULL) {
      Remove(FindLWeapon(strikeId));}

    Remove(FindLWeapon(animationId));}}

lweapon Spear_CreateStrike(int damage) {
  lweapon strike = CLWeaponCreate();
  strike->DrawXOffset = 500;
  strike->Damage = damage;
  strike->Dir = Link->Dir;
  return strike;}
