
/* TreeSize for Unix  http://treesize.sf.net/
 * Copyright (c) 2006-2007 Marcos Diez <marcos_AT_unitron.com.br>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 3 of the License, or (at your option)
 * any later version.
 *
 * This program 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.  See the GNU General Public License for
 * more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 */

#include <stdlib.h>		/*  */

#include "util.h"
#include "LLlinkedList.h"

/*
  extra feature: the list ALWAYS ends with NULL
  this guy is NOT counted as an element.
  example: { p1 , p2 , p3 , NULL } is a list with 3 elements

  
*/

list LLnewList(){
  list newList;
  myMalloc( newList );
  newList->elements=0;
  newList->data =   0;        /* we use lazy Alocation */
  newList->maxElements= 0;   /* we use lazy Alocation */
  return newList;
}

void LLaddElement( list theList , void *data ){
  if( theList->elements >= ( theList->maxElements -1 ) ){
    if( theList->elements == 0 ){
      theList->data =   xMalloc( sizeof( void* ) * LL_INITIAL_ELEMENTS );
      theList->elements=0;
      theList->maxElements= LL_INITIAL_ELEMENTS;
    }else{
      int newElements;
      theList->maxElements *= 2;
      newElements= (theList->maxElements * (sizeof (void *)) );
      theList->data = xRealloc( theList->data , newElements );
    }
  }

  theList->data[ theList->elements++ ] = data;
  theList->data[ theList->elements ] = 0;
}


void LLschrinkList( list theList ){
  int newElements  = (sizeof (void*) ) * (theList->elements +1);
  if( ! theList->data  ) return;

  if( theList->maxElements != theList->elements ){
	theList->data  = realloc( theList->data , newElements );
    theList->maxElements=theList->elements;
  }
}



void LLdelWholeList( list theList , void (*eraser)(void *element ) ){

  int i=theList->elements;
  while( i-- ){
    eraser( theList->data[i] );
  }
  if( theList->data ) free(theList->data );
  free( theList ); 
}


void LLcopyAllElements( const list sourceList , list targetList ){
  /* warning, if a element is already there, it will be there AGAIN.
     this is NOT a bug but  a FEATURE
  */
  int maxElements = sourceList->maxElements;
  void **sourceListData = LLlist2Array( sourceList );

  while( maxElements-- ){

    LLaddElement( targetList , *sourceListData );
    sourceListData++;

  }


}

