# AVSLib :: 'array' package :: 'properties' module
# Copyright (c) 2005 George Zarkadas (gzarkadas@users.sourceforge.net)

# 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"

DefineModule("avslib", "array", "properties")

global __load__ = IsPackageLoaded("avslib", "base") ? NOP : Eval("""
	LoadModule("avslib", "base", "core")
	LoadModule("avslib", "base", "conversion")
	""")
global __load__ = IsPackageLoaded("avslib", "array") ? NOP : Eval("""
	LoadModule("avslib", "array", "core")
	LoadModule("avslib", "array", "operators")
	""")

# Returns the minimum element of array. Should not be used in mixed-type arrays
# unless the types are compatible (eg. ints and floats)
#
Function ArrayMin(string array)
{
	_min = array.ArrayGet(0)
	return (array.ArrayLen() > 1) \
		? __min2( _min, ArrayMin(array.ArrayDelete(0)) ) \
		: _min
}

# Returns the maximum element of array. Should not be used in mixed-type arrays
# unless the types are compatible (eg. ints and floats)
#
Function ArrayMax(string array)
{
	_max = array.ArrayGet(0)
	return (array.ArrayLen() > 1) \
		? __max2( _max, ArrayMax(array.ArrayDelete(0)) ) \
		: _max
}

# Returns the number of occurences of 'value' in array; 
# does not work with clip arrays
#
Function ArrayElmCount(string array, val value)
{
	b_arr = ArrayOpValue(array, value, "==")
	return b_arr.ArrayOpFunc("CInt").ArraySum()
}

# Returns true if 'value' is contained in array; 
# does not work with clip arrays
#
Function ArrayContains(string array, val value)
{
	return ArrayElmCount(array, value) > 0
}

# Returns the index of the first array element equal to value

	# __index always point to the current element's index
	# at the initial 'matches' array
	#
	Function __array_index_first(string matches, int "__index")
	{
		__index = Default(__index, -1) + 1
		return matches.ArrayGet(0) == 1 ? \
			__index : ( \
		matches.ArrayLen <= 1 ? \
			-1 \
		: __array_index_first(matches.ArrayDelete(0), __index) )
	}

Function ArrayIndexOf(string array, val value, int "start_from")
{
	start_from = __bound_array_index(array, Default(start_from, 0))
	matches = array.ArrayGetRange(start_from).ArrayOpValue(value, \
		"==").ArrayOpFunc("CInt")
	part_index = __array_index_first(matches)
	return part_index < 0 ? -1 : start_from + part_index
}
