//------------------------------------------------------------------------
//                  Library Extended String-List routines
//
// Author: Mattias Hansson
// Copyright (c) : 2005 Mattias Hansson
// License: GNU LGPL 2
// Language: 65CM v0.4+
// Dependencies: string.c65 memlib.c65
// Target: generic 6502
//
// Purpose: Provide more advanced functions for manipulating/maintaining
//          stringlists. By making a additional library, developers can
//          choose how much they wsnt compared to the memory size cost
//          of the libraries.
//------------------------------------------------------------------------


#IFNDEF __LIB_STRLIST2
#DEFINE __LIB_STRLIST2 = 1

GOTO lib_strlist2_skip

#INCLUDE <strlist.c65>

//-----------------------------------------------------------
// lib_str_to_strlist
//
// purpose:
//   To splitt a string into 0..several elements into a new
//   stringlist. The separator character defines the
//   "splitt indicator".
//
// Note: If several separator-chars are found together they
//   are still threated as one.
//
//-----------------------------------------------------------

  FUNC lib_strlist2_str_to_strlist ( {WORD s} {BYTE separator} io:{WORD slref} )

    BYTE b
    BYTE inword
    WORD start
    WORD copylen
    WORD tmpstr_ptr
    BYTE eow //end of word

    LET inword = 0
    LET eow = 0

    WHILE 1
      PEEK s -> b

      IF inword == 0
        IF b == 0
          EXIT
        ENDIF
        IF b != separator //start of new "word"
	  LET inword = 1
	  LET start = s
	ENDIF
      ELSE //we are inside a "word"
        IF b == 0
          LET eow = 1
        ENDIF
        IF b == separator //end of this "word"
          LET eow = 1
        ENDIF

        IF eow == 1
	  //copy the "word" to a new string

	  SUBT s - start -> copylen
          //hexoutw ( copylen )
	  INC copylen //make room for zero termination
	  lib_mem_malloc ( copylen tmpstr_ptr )
	  IF tmpstr_ptr == NULL
	    EXIT //if errorhandling is to be added in the future, check this :-)
	  ENDIF
	  DEC copylen
	  lib_string_strncpy ( start tmpstr_ptr copylen )
	  //manually zero terminating the copy to add (borrowing start as temp)
	  ADD tmpstr_ptr + copylen -> start
	  POKE start , NULL
	  lib_strlist_add ( slref tmpstr_ptr )
	  lib_mem_free ( tmpstr_ptr )
  	  LET inword = 0
          LET eow = 0
	ENDIF
      ENDIF
      IF b == 0
        EXIT
      ENDIF

      INC s
    WEND

  FEND

LABEL lib_strlist2_skip

#IFEND
