
// SPDX-License-Identifier: CC-BY-NC-SA-4.0
//
// Copyright (C) 2026 Bit by Bit Signal Processing LLC (https://bxbsp.com)
//
// This work is placed under the "Creative Commons Attribution
// NonCommercial ShareAlike 4.0 International" license, known
// by the shortened acronym "CC-BY-NC-SA-4.0".
//
// This work is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
// A CC-BY-NC-SA-4.0 license allows you to use this work for
// noncommercial purposes so long as attribution is made to the
// original author.  Modified versions of this work may be distributed,
// but only under the same license.  For further details, see the
// Creative Commons License "CC-BY-NC-SA-4.0".
//
// You should have received a copy of the CC-BY-NC-SA-4.0 license
// along with this work. If not, see
// <https://creativecommons.org/licenses/by-nc-sa/4.0/>.
//
//

#include "BasicList.hh"

BasicList::~BasicList()
{
  BasicListElement *a;

  //
  // Must be careful here.  Deleting one element from the list may cause actions that also
  // come back to affect the list.  So keep the list valid when an element is deleted
  // by calling the remove() method.
  //
  a = first_element;
  while(a)
    {
      remove(a);
      a = first_element;
    }
}

void
BasicList::addAtEnd(BasicListElement* e)
{
  if(last_element==0)
    {
      first_element = last_element = e;
    }
  else
    {
      e->previous_element         = last_element;
      e->next_element             = 0;
      last_element->next_element  = e;
      last_element                = e;
    }
}

void
BasicList::remove(BasicListElement* e)
{
  if(last_element == e)
    {
      last_element               = e->previous_element;

      if(last_element)
	last_element->next_element = 0;
      else
	first_element = 0;
    }
  else if (first_element==e)
    {
      first_element                   = e->next_element;

      if(first_element)
	first_element->previous_element = 0;
      else
	last_element = 0;
    }
  else
    {
      e->previous_element->next_element = e->next_element;
      e->next_element->previous_element = e->previous_element;
    }

  delete e;
}


void
BasicList::replace_extract(BasicListElement* orig, BasicListElement* replacement)
{
  replacement->previous_element = orig->previous_element;
  replacement->next_element     = orig->next_element;

  if(orig->previous_element==0)
    first_element = replacement;
  else
    orig->previous_element->next_element = replacement;

  if(orig->next_element==0)
    last_element = replacement;
  else
    orig->next_element->previous_element = replacement;
}
