#include "stringlist.h"

#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>

Lines::Lines ( char * pszBuf, Lines * pLast ) {
  int iCount = strlen ( pszBuf );

  pszLine = new char [iCount + 1];
  strcpy ( pszLine, pszBuf );
}

Lines::~Lines ( void ) {
  delete [] pszLine;
}

Lines * Lines::getNext ( void ) {
  return pNext;
}

void Lines::setNext ( Lines * pLine ) {
  pNext = pLine;
}

char * Lines::Lines::getLine ( void ) {
  return pszLine;
}


StringList::StringList ( void ) {
  pFirst = NULL;
  pLast  = NULL;
  iCount = 0;
//  printf ( "Creating StringList object\n" );
}

StringList::~StringList (void) {
  Lines * pNext;

//  printf ( "Deleting StringList object - %d lines\n", iCount );
//  while ( pFirst ) {
//	printf ( "Deleting Line %s", pFirst->getLine () );
//	pNext = pFirst->getNext ();
//	delete pFirst;
//	pFirst = pNext;
//  }

  while ( iCount ) Delete (0);

//  printf ( "StringList object deleted\n" );
}

void StringList::Add ( char * psz ) {
//  printf ( "Adding line to  StringList object\n" );
  Lines * newline = new Lines ( psz, pLast );
  if ( pLast ) pLast->setNext ( newline );
  pLast = newline;
  iCount++;
  if ( pFirst ) return;
  pFirst = newline;
}


int StringList::Count ( void ) {
  return iCount;
}

char * StringList::Strings ( int i ) {
  Lines * pLine = pFirst;

  while ( i ) {
	  pLine = pLine->getNext ();
	  i--;
  };

  return pLine->getLine ();
}

int StringList::IndexOf ( char * pszSearch ) {
  char  * psz;
  int iIndex = 0;

  for ( Lines * pLine = pFirst;
        pLine;
        pLine = pLine->getNext (),
		iIndex++) {
	psz = pLine->getLine ();
	if ( strcasecmp ( pszSearch, psz ) ) continue;
	return iIndex;
  }
  return -1;
}

void StringList::Delete ( int i ) {
  Lines * pLine = pFirst;
  Lines * pNext;
  Lines * pNextLink;

  if ( i < 0 ) return;

  if ( i == 0 ) {
    pFirst = pLine->getNext ();
    delete pLine;
	iCount--;
	if ( pLast != pLine ) return;
	pLast = pLine;
	return;
  }

  if ( i < iCount ) {							// count from 0
    while ( --i ) pLine = pLine->getNext ();
	if ( pLine == NULL ) return; 				// should not occur
	pNext = pLine->getNext ();					// Line to delete
	if ( pNext == NULL ) {
		printf ( "Error deleting line %d\n", i + 1);
		return;
	}
	iCount--;
	pNextLink = pNext->getNext ();
	pLine->setNext ( pNextLink );		// relink
	delete pNext;
	if ( pLast != pNext ) return;		// check that we have not deleted the end
	pLast = pLine;
  }
}
