//-----------------------------------------------------------------------------
// Copyright © 2003 - Philip Howard - All rights reserved
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
//-----------------------------------------------------------------------------
// package	libh/string
// homepage	http://libh.slashusr.org/
//-----------------------------------------------------------------------------
// author	Philip Howard
// email	libh at ipal dot org
// homepage	http://phil.ipal.org/
//-----------------------------------------------------------------------------
// This file is best viewed using a fixed spaced font such as Courier
// and in a display at least 120 columns wide.
//-----------------------------------------------------------------------------

#include "string_lib.h"

__PROTO_BEGIN__
//-----------------------------------------------------------------------------
// function	str_app_sub
//
// purpose	Append to the target string the contents of a substring of the
//		source string from one specified part to another specified part
//		as separated by a given separator pattern string.
//
//		A positive index refers to parts between separators in the
//		source string starting with number 0 at the beginning of the
//		source string and increasing in the forward direction.
//
//		A negative index refers to parts between separators in the
//		source string starting with number -1 at the end of the source
//		string and decreasing in the reverse direction.
//
//		If a pattern string is not given, the parts are characters and
//		the separators are between each character.
//
//		If the resultant string will not fit the available space,
//		then rollback everything leaving the original target string.
//
// arguments	1 (char *) pointer to beginning of target string
//		2 (size_t) total maximum length of target string
//		3 (int) index of first part to begin the substring
//		4 (int) index of last part to end the substring
//		5 (const char *) source string to select substring from
//		6 (const char *) pattern string to separate source parts
//
// returns	(size_t) final length of target string
//		(size_t) ~0 : error
//
// note		Any contents of the target string space located beyond the
//		first termination character found in the target space will be
//		overwritten even if there is insufficient space to complete
//		the appending.  No data of any kind should be kept there.
//-----------------------------------------------------------------------------
size_t
str_app_sub (
    char *		arg_target
    ,
    size_t		arg_length
    ,
    int			arg_bindex
    ,
    int			arg_eindex
    ,
    const char *	arg_source
    ,
    const char *	arg_pattern
    )
__PROTO_END__
{
    char *			target_app	;
    char *			target_end	;
    char *			target_undo	;

    const char *		source_end	;
    const char *		sub_beg		;
    const char *		sub_end		;
    const char *		pat_end		;

    size_t			pat_len		;


    //------------------------------------------------------------
    // Locate the end of the source string where it is terminated.
    //------------------------------------------------------------
    source_end = arg_source;
    while ( * source_end ) ++ source_end;

    //-------------------------------------------------------------------
    // Locate the end of the separator pattern string and get the length.
    //-------------------------------------------------------------------
    pat_end = arg_pattern;
    while ( * pat_end ) ++ pat_end;
    pat_len = pat_end - arg_pattern;

    //=================================================================
    // Locate the beginning and end of the substring in the source.
    //-----------------------------------------------------------------
    // The substring begins before the indexed part, so 0 always refers
    // to the beginning of the entire source string, and -1 refers to
    // the point in front of the last part (not the end of the string).
    //
    // The substring ends after the indexed part, so 0 refers to the
    // point after the first part (not the beginning of the string),
    // and -1 always refers the end of the entire source string.
    //=================================================================

    //-------------------------------------------------
    // Without a pattern string, just index characters.
    //-------------------------------------------------
    if ( ! arg_pattern || ! * arg_pattern ) {

	//-- Locate the beginning of the substring.
	if ( arg_bindex < 0 ) {
	    sub_beg = source_end + arg_bindex + 1;
	    if ( sub_beg < arg_source ) sub_beg = arg_source;
	} else {
	    sub_beg = arg_source + arg_bindex;
	    if ( sub_beg > source_end ) sub_beg = source_end;
	}

	//-- Locate the end of the substring.
	if ( arg_eindex < 0 ) {
	    sub_end = source_end + arg_eindex + 1;
	    if ( sub_end < arg_source ) sub_end = arg_source;
	} else {
	    sub_end = arg_source + arg_eindex;
	    if ( sub_end > source_end ) sub_end = source_end;
	}
    }

    //------------------------------------------------------------------------
    // With a separator pattern string, count matching patterns to find parts.
    //------------------------------------------------------------------------
    else {

	//----------------------------------------------------------
	// If the begin index is negative, go backward from the end.
	// An index of -1 should be before the last part.
	//----------------------------------------------------------
	if ( arg_bindex < 0 ) {
	    const char *	stop_ptr	;

	    sub_beg = source_end;
	    stop_ptr = arg_source + pat_len;

	    //-- Step backwards until stopped or count exhausted.
	    while ( sub_beg >= stop_ptr ) {
		const char *	pat_tmp		;
		const char *	src_tmp		;

		//-- Compare pattern and source, backwards.
		pat_tmp = pat_end;
		src_tmp = sub_beg;
		while ( -- pat_tmp >= arg_pattern && * pat_tmp == * -- src_tmp );

		//-- If the separator matches, count it and skip to the front of it.
		if ( pat_tmp < arg_pattern ) {
		    if ( ++ arg_bindex == 0 ) break;
		    sub_beg = src_tmp;
		} else {
		    -- sub_beg;
		}
	    }
	}

	//---------------------------------------------------------------
	// If the begin index is positive, go forward from the beginning.
	// An index of 0 should be before the first part, which is always
	// at the beginning of the source string.
	//---------------------------------------------------------------
	else {

	    //-- Set up starting pointer.
	    sub_beg = arg_source;

	    //-- Skip search if always starting at the beginning.
	    if ( arg_bindex > 0 ) {
		const char *	stop_ptr	;

		//-- Set up stopping pointer.
		stop_ptr = source_end - pat_len;

		//-- Step forwards until stopped or pattern count exhausted.
		while ( sub_beg < stop_ptr ) {
		    const char *	pat_tmp		;
		    const char *	src_tmp		;

		    //-- Compare pattern to source, forwards.
		    pat_tmp = arg_pattern;
		    src_tmp = sub_beg;
		    while ( pat_tmp < pat_end && * pat_tmp == * src_tmp ) { ++ pat_tmp; ++ src_tmp; };

		    //-- If equal, count it and skip it.
		    if ( pat_tmp >= pat_end ) {
			sub_beg = src_tmp;
			if ( -- arg_bindex == 0 ) break;
		    } else {
			++ sub_beg;
		    }
		}
	    }
	}

	//----------------------------------------------------------
	// If the end index is negative, go backward from the end.
	// An index of -1 should be after the last part, which is
	// always at the end of the source string.
	//----------------------------------------------------------
	if ( arg_eindex < 0 ) {

	    //-- Set up starting pointer.
	    sub_end = source_end;

	    //-- Skip search if always starting at the end.
	    if ( arg_eindex < -1 ) {
		const char *	stop_ptr	;

		//-- Set up stopping pointer.
		stop_ptr = arg_source + pat_len;

		//-- Step backwards until stopped or pattern count exhausted.
		while ( sub_end >= stop_ptr ) {
		    const char *	pat_tmp		;
		    const char *	src_tmp		;

		    //-- Compare pattern and source, backwards.
		    pat_tmp = pat_end;
		    src_tmp = sub_end;
		    while ( -- pat_tmp >= arg_pattern && * pat_tmp == * -- src_tmp );

		    //-- If the whole pattern is present, count it and skip it.
		    if ( pat_tmp < arg_pattern ) {
			sub_end = src_tmp;
			if ( ++ arg_eindex == -1 ) break;
		    } else {
			-- sub_end;
		    }
		}
	    }
	}

	//-------------------------------------------------------------
	// If the end index is positive, go forward from the beginning.
	// An index of 0 should be after the first part.
	//-------------------------------------------------------------
	else {
	    const char *	stop_ptr	;

	    //-- Set up starting and stopping pointers.
	    sub_end = arg_source;
	    stop_ptr = source_end - pat_len;

	    //-- Step forwards until stopped or pattern index exhausted.
	    while ( sub_end <= stop_ptr ) {
		const char *	pat_tmp		;
		const char *	src_tmp		;

		//-- Compare pattern to source, forwards.
		pat_tmp = arg_pattern;
		src_tmp = sub_end;
		while ( pat_tmp < pat_end && * pat_tmp == * src_tmp ) { ++ pat_tmp; ++ src_tmp; };

		//-- If equal, count it and skip it.
		if ( pat_tmp >= pat_end ) {
		    if ( -- arg_eindex < 0 ) break;
		    sub_end = src_tmp;
		} else {
		    ++ sub_end;
		}
	    }
	}
    }

    //================================================================
    // The substring beginning and ending pointers are now determined.
    //================================================================

    //--------------------------------------------------------
    // Locate the end of the target string space, and start
    // the target pointer where new content is to be appended.
    //--------------------------------------------------------
    target_end = ( target_app = arg_target ) + arg_length - 1;
    while ( target_app < target_end && * target_app ) ++ target_app;
    if ( target_app == target_end ) return ~ (size_t) 0;
    target_undo = target_app;

    //-------------------------------------------------------
    // Copy characters to append the substring to the target.
    //-------------------------------------------------------
    while ( sub_beg < sub_end && target_app < target_end ) {
	* target_app ++ = * sub_beg ++;
    }

    //----------------------------------------------
    // If more substring characters remain, then the
    // target is full and the append must be undone.
    //----------------------------------------------
    if ( sub_beg < sub_end ) {
	* target_undo = 0;
	return ~ (size_t) 0;
    }

    //--------------------------------------------------
    // Return the new total length of the target string.
    //--------------------------------------------------
    * target_app = 0;
    return target_app - arg_target;
}

