package parser

import 

// Shift and masks for sequence parameters and intermediates.
const (
	PrefixShift    = 8
	IntermedShift  = 16
	FinalMask      = 0xff
	HasMoreFlag    = math.MinInt32
	ParamMask      = ^HasMoreFlag
	MissingParam   = ParamMask
	MissingCommand = MissingParam
	MaxParam       = math.MaxUint16 // the maximum value a parameter can have
)

const (
	// MaxParamsSize is the maximum number of parameters a sequence can have.
	MaxParamsSize = 32

	// DefaultParamValue is the default value used for missing parameters.
	DefaultParamValue = 0
)

// Prefix returns the prefix byte of the sequence.
// This is always gonna be one of the following '<' '=' '>' '?' and in the
// range of 0x3C-0x3F.
// Zero is returned if the sequence does not have a prefix.
func ( int) int {
	return ( >> PrefixShift) & FinalMask
}

// Intermediate returns the intermediate byte of the sequence.
// An intermediate byte is in the range of 0x20-0x2F. This includes these
// characters from ' ', '!', '"', '#', '$', '%', '&', ”', '(', ')', '*', '+',
// ',', '-', '.', '/'.
// Zero is returned if the sequence does not have an intermediate byte.
func ( int) int {
	return ( >> IntermedShift) & FinalMask
}

// Command returns the command byte of the CSI sequence.
func ( int) int {
	return  & FinalMask
}

// Param returns the parameter at the given index.
// It returns -1 if the parameter does not exist.
func ( []int,  int) int {
	if len() == 0 ||  < 0 ||  >= len() {
		return -1
	}

	 := [] & ParamMask
	if  == MissingParam {
		return -1
	}

	return 
}

// HasMore returns true if the parameter has more sub-parameters.
func ( []int,  int) bool {
	if len() == 0 ||  >= len() {
		return false
	}

	return []&HasMoreFlag != 0
}

// Subparams returns the sub-parameters of the given parameter.
// It returns nil if the parameter does not exist.
func ( []int,  int) []int {
	if len() == 0 ||  < 0 ||  >= len() {
		return nil
	}

	// Count the number of parameters before the given parameter index.
	var  int
	var  int
	for  = range  {
		if  ==  {
			break
		}
		if !HasMore(, ) {
			++
		}
	}

	if  >  ||  >= len() {
		return nil
	}

	var  []int
	for ;  < len(); ++ {
		if !HasMore(, ) {
			break
		}
		 := Param(, )
		if  == -1 {
			 = DefaultParamValue
		}
		 = append(, )
	}

	 := Param(, )
	if  == -1 {
		 = DefaultParamValue
	}

	return append(, )
}

// Len returns the number of parameters in the sequence.
// This will return the number of parameters in the sequence, excluding any
// sub-parameters.
func ( []int) int {
	var  int
	for  := range  {
		if !HasMore(, ) {
			++
		}
	}
	return 
}

// Range iterates over the parameters of the sequence and calls the given
// function for each parameter.
// The function should return false to stop the iteration.
func ( []int,  func( int,  int,  bool) bool) {
	for  := range  {
		if !(, Param(, ), HasMore(, )) {
			break
		}
	}
}