# report.tcl

class Report {
	protected variable parentWindow
	protected variable reportName
	protected variable reportDef
	protected variable reportData
	protected variable reportLastTuple
	protected variable sectionFields
	protected variable fieldLabel
	protected variable fieldAlignment
	protected variable fieldMaxLength
	protected variable sectionLayout
	protected variable lastLevel
	protected variable summaryList
	protected variable reportTree
	protected variable lastSeqnr
	protected variable summaryData
	protected variable MaxLabelWidth
	protected variable MaxColWidth
	protected variable MaxSummaryWidth
	protected variable textEdit

	constructor {c_parentWindow c_reportName} {
		set reportName $c_reportName
		set parentWindow $c_parentWindow
		set textEdit [TextEdit "#auto" $parentWindow [mc reportTitle $reportName] {} 0]
		$textEdit defineCallBack [list $this onDestroyTextEdit]
		if {[getReportDef]} then {
			set query $reportDef(sqlselect)
			if {[replaceParms query]} then {
				if {[runQuery $query errMsg]} then {
					if {[getSectionDef]} then {
						# printSectionDef
						wrapTooLongLines
						fillReportTree 0 $reportLastTuple 1 0
						calculateSummaries 1 0
						printReport $query
						$textEdit gotoBegin
					}
				} else {
					printReportHeader $query
					showError $errMsg
				}
			}
		}
		return
	}

	destructor {

		return
	}

	public method onDestroyTextEdit {} {
		delete object $textEdit
		delete object $this
		return
	}

	protected method printSectionDef {} {
		# for debugging only
		for {set level 1} {$level <= $lastLevel} {incr level} {
			puts "Section $level"
			puts "    Layout: $sectionLayout($level)"
			foreach field $sectionFields($level) {
				puts "    Field: $field"
				puts "    Label: $fieldLabel($field)"
				puts "    Alignment: $fieldAlignment($field)"
				puts "    MaxLength: $fieldMaxLength($field)"
			}
			puts "Summary: $summaryList($level)"
		}
		return
	}

	protected method wrapTooLongLines {} {

		proc wrapLine {lineVar maxLength} {
			upvar 1 $lineVar line

			if {[string length $line] > $maxLength} then {
				# We try to find a space between 30% of maxLength and maxLength
				set breakTo [expr $maxLength - 1]
				set breakFrom [expr int(0.3 * $maxLength)]
				set wrappedLine {}
				while {[string length $line] > $maxLength} {
					set oneLine [string range $line 0 $breakTo]
					set breakAt [string last { } $oneLine]
					if {$breakAt >= $breakFrom} then {
						# If possible we replace a space with a line break
						# So, we don't copy the space
						set oneLine [string range $oneLine 0 [expr $breakAt - 1]]
						set line [string range $line [expr $breakAt + 1] end]
					} else {
						# If not possible we just insert a line break
						set line [string range $line [expr $breakTo + 1] end]
					}
					append wrappedLine "${oneLine}\n"
				}
				append wrappedLine $line
				set line $wrappedLine
			}
			return
		}

		for {set level 1} {$level <= $lastLevel} {incr level} {
			foreach field $sectionFields($level) {
				if {$fieldMaxLength($field) ne {}} then {
					for {set tuple 0} {$tuple <= $reportLastTuple} {incr tuple} {
						set data $reportData($tuple,$field)
						set newData {}
						set moreLines 1
						while {$moreLines} {
							set moreLines 0
							set newLineIndex [string first "\n" $data]
							if {$newLineIndex >= 0} then {
								set moreLines 1
								set oneLine [string range $data 0 \
									[expr $newLineIndex - 1]]
								set data [string range $data \
									[expr $newLineIndex + 1] end]
								wrapLine oneLine $fieldMaxLength($field)
								append newData "${oneLine}\n"
							} else {
								set oneLine $data
								wrapLine oneLine $fieldMaxLength($field)
								append newData $oneLine
							}
						}
						set reportData($tuple,$field) $newData
					}
				}
			}
		}
		return
	}

	protected method runQuery {query errMsgName} {
		upvar $errMsgName errMsg
		if {[$::dbObject select_query $query numTuples reportData errMsg]} then {
			if {$numTuples > 0} then {
				set success 1
				set reportLastTuple [expr $numTuples - 1]
			} else {
				set success 0
				set errMsg [mc reportQueryNoData]
			}
		} else {
			set success 0
		}
		return $success
	}

	protected method getReportDef {} {
		set query {SELECT name, description, sqlselect FROM pfm_report}
		append query " WHERE name = '$reportName'"
		if {[$::dbObject select_query_list $query numTuples attribList resultList errorMsg]} then {
			if {$numTuples == 1} then {
				set status 1
				set idx 0
				foreach attrib $attribList {
					set reportDef($attrib) [lindex $resultList 0 $idx]
					incr idx
				}
			} else {
				showError [mc getReportFailed $reportName "numTuples = $numTuples"]
				set status 0
			}
		} else {
			showError [mc getReportFailed $reportName $errorMsg]
			set status 0
		}
		return $status
	}

	protected method replaceParms {queryName} {
		upvar $queryName query

		proc getParmDef {query parmListName} {
			upvar $parmListName parmList
			set parmList {}
			set startOfParm [string first "\$(" $query 0]
			while {$startOfParm >= 0} {
				set endOfParm [string first ")" $query $startOfParm]
				if {$endOfParm >= 0} then {
					set parm [string range $query [expr $startOfParm + 2] \
						[expr $endOfParm - 1]]
					if {$parm ni $parmList} then {
						lappend parmList $parm
					}
					set startOfParm \
						[string first "\$(" $query [expr $endOfParm + 1]]
				} else {
					set startOfParm -1
				}
			}
			return
		}

		getParmDef $query parmList
		if {[llength $parmList] > 0} then {
			if {[getParmValues $query $parmList value]} then {
				foreach parm $parmList {
					set query [string map \
						[list [format {$(%s)} $parm] $value($parm)] $query]
					incr idx
				}
				set success 1
			} else {
				set success 0
			}
		} else {
			set success 1
		}
		return $success
	}

	protected method getParmValues {query parmList valueName} {
		upvar $valueName value
		update
		set parmObject [ParmObject "#auto" [$textEdit cget -window] \
			$query $parmList]
		if {[$parmObject wait value]} then {
			set success 1
		} else {
			set success 0
		}
		return $success
	}

	protected method getSectionDef {} {
		set query {SELECT level, fieldlist, layout, summary FROM pfm_section}
		append query " WHERE report = '${reportName}' ORDER BY level"
		if {[$::dbObject select_query $query numTuples sectionDef errMsg]} then {
			if {$numTuples >= 1} then {
				set level 0
				for {set tuple 0} {$tuple < $numTuples} {incr tuple} {
					# We don't use the level numbers from pfm_section. We only
					# rely on the numbers for pfm_section for properly
					# ordering the sections. First level should be 1, next
					# levels should be consecutive integers.
					incr level
					set sectionLayout($level) $sectionDef(${tuple},layout)
					if {[catch {
							foreach item $sectionDef(${tuple},fieldlist) {
								lassign $item field label alignment maxLength
							}
						} errMsg]} then {
							showError [mc errorParsingFieldSpec \
								$sectionDef(${tuple},fieldlist) $level $errMsg]
							set sectionDef(${tuple},fieldlist) {}
					}
					set sectionFields($level) {}
					foreach item $sectionDef(${tuple},fieldlist) {
						lassign $item field label alignment maxLength
						if {[info exists reportData(0,$field)]} then {
							lappend sectionFields($level) $field
							set fieldLabel($field) $label
							set fieldAlignment($field) $alignment
							set fieldMaxLength($field) $maxLength
						} else {
							showError [mc reportDataMissing $field $level]
						}
					}
					set summaryList($level) $sectionDef(${tuple},summary)
				}
				set lastLevel $level
				set success 1
			} else {
				set success 0
				showError [mc noReportSections]
			}
		} else {
			set success 0
			showError "${errMsg}\n"
		}
		return $success
	}

	protected method showError {message} {
		$textEdit appendText "${message}\n" red
		return
	}

	protected method printString {string} {
		$textEdit appendText $string black
		return
	}

	protected method fillReportTree {firstTuple lastTuple level parent} {

		# the range $firstTuple .. $lastTuple is the range of tuples
		# in reportData that have the same vaules for all the fields
		# of all the levels lower than $level.

		# $parent is the node in the reportTree that points to a tuple
		# in reportData that has the values for the fields of all the
		# levels lower than $level.

		# We now create a node at $level for all records in the range
		# that have different values for at least one of the fields of
		# this level and we call fillReportTree recursively for each
		# node created at this level to also fill the higher levels.

		# At $lastLevel, we create a node for all tuples in the range,
		# and we don't call fillReportTree anymore.

		set seqnr 1
		set reportTree(${parent}.${seqnr}) $firstTuple
		set nextLevelFirstTuple $firstTuple
		if {$level < $lastLevel} then {
			for {set tuple [expr $firstTuple + 1]} {$tuple <= $lastTuple} \
			{incr tuple} {
				if {[differentData $level $tuple]} then {
					fillReportTree $nextLevelFirstTuple [expr $tuple - 1] \
						[expr $level + 1] "${parent}.${seqnr}"
				incr seqnr
				set reportTree(${parent}.${seqnr}) $tuple
				set nextLevelFirstTuple $tuple
				}
			}
			fillReportTree $nextLevelFirstTuple $lastTuple \
			[expr $level + 1] "${parent}.${seqnr}"

		} else {
			for {set tuple [expr $firstTuple + 1]} {$tuple <= $lastTuple} \
			{incr tuple} {
				incr seqnr
				set reportTree(${parent}.${seqnr}) $tuple
			}
		}
		set lastSeqnr($parent) $seqnr
		return
    }

	protected method differentData {level tuple} {

		set different 0
		foreach field $sectionFields($level) {
			if {$reportData([expr $tuple - 1],$field) ne \
				$reportData($tuple,$field)} then {
			set different 1
			break
			}
		}
		return $different
    }

    protected method calculateSummaries {level parent} {

		# Check summary definition
		if {[catch {
			foreach item $summaryList($level) {
				lassign $item field aggregate format
			}
		} tclerror]} then {
			showError [mc errorParsingSummary $summaryList($level) \
				$level $tclerror]
			set summaryList($level) {}
		}
		# Now we really begin
		foreach item $summaryList($level) {
			lassign $item field aggregate format
			set values {}
			if {[accumulateValues $level $parent $field values]} then {
				if {[info commands ::aggregate::$aggregate] ne {}} then {
					set summaryData($parent,$field,$aggregate) \
						[aggregate::$aggregate $values]
				} else {
					showError [mc unknownAggregateFunction $aggregate \
						$field $level]
					set index [lsearch $summaryList($level) $item]
					set summaryList($level) \
						[lreplace $summaryList($level) $index $index]
				}
			} else {
				showError [mc summaryWrongField $aggregate $field $level]
				set index [lsearch $summaryList($level) $item]
				set summaryList($level) \
					[lreplace $summaryList($level) $index $index]
			}
		}
		if {$level < $lastLevel} then {
			for {set seqnr 1} {$seqnr <= $lastSeqnr($parent)} \
				{incr seqnr} {
				calculateSummaries [expr $level + 1] "${parent}.${seqnr}"
			}
		}
		return
    }

	protected method accumulateValues {level parent field valueListName} {
		upvar 1 $valueListName values

		if {[lsearch $sectionFields($level) $field] >= 0} then {
			for {set seqnr 1} {$seqnr <= $lastSeqnr($parent)} \
					{incr seqnr} {
				set tuple $reportTree(${parent}.${seqnr})
				lappend values $reportData($tuple,$field)
			}
			set success 1
		} else {
			if {$level < $lastLevel} then {
				for {set seqnr 1} {$seqnr <= $lastSeqnr($parent)} \
						{incr seqnr} {
					set success [accumulateValues [expr $level + 1] \
							 "${parent}.${seqnr}" $field values]
				}
			} else {
				set success 0
			}
		}
		return $success
	}

	protected method printReport {query} {

		labelAndColumnWidths
		printReportHeader $query
		printReportTree 1 0
		return
    }

	protected method labelAndColumnWidths {} {

		# MaxLabelWidth($level) is needed for a column layout.
		# It determines the larges label for each level
		for {set level 1} {$level <= $lastLevel} {incr level} {
			set MaxLabelWidth($level) 0
			foreach field $sectionFields($level) {
				set length [string length $fieldLabel($field)]
				if {$length > $MaxLabelWidth($level)} then {
					set MaxLabelWidth($level) $length
				}
			}
		}
		# MaxDataWith($field) is needed for a table layout
		# It takes into account that there may be line breaks in the data
		for {set level 1} {$level <= $lastLevel} {incr level} {
			foreach field $sectionFields($level) {
				set MaxColWidth($field) [string length $fieldLabel($field)]
				for {set tuple 0} {$tuple <= $reportLastTuple} {incr tuple} {
					set data $reportData($tuple,$field)
					set moreLines 1
					while {$moreLines} {
						set moreLines 0
						set newLineIndex [string first "\n" $data]
						if {$newLineIndex >= 0} then {
							set moreLines 1
							set oneLine [string range $data 0 [expr $newLineIndex - 1]]
							set data [string range $data [expr $newLineIndex + 1] end]
						} else {
							set oneLine $data
							set data {}
						}
						set length [string length $oneLine]
						if {$length > $MaxColWidth($field)} then {
							set MaxColWidth($field) $length
						}
					}
				}
			}
		}
		# MaxSummaryWidth($level) is needed for properly formatting
		# the summaries
		for {set level 1} {$level <= $lastLevel} {incr level} {
			set MaxSummaryWidth($level) 0
			foreach item $summaryList($level) {
				set field [lindex $item 0]
				set aggregate [lindex $item 1]
				set length [string length "$aggregate\($field\)"]
				if {$length > $MaxSummaryWidth($level)} then {
					set MaxSummaryWidth($level) $length
				}
			}
		}
		return
    }

	protected method printReportHeader {sqlselect} {

		printString "$reportDef(name)\n"
		printString \
			"[string repeat - [string length $reportDef(name)]]\n\n"
		printString \
			"Description: $reportDef(description)\n"
		set formattedSQL [string map {\n "\n             "} $sqlselect]
		printString "SQL        : $formattedSQL\n"
		printString \
			"Date       : [clock format [clock seconds] -format {%d-%b-%Y}]\n"
		return
    }

    protected method printReportTree {level parent} {

		set firstChild 1
		for {set seqnr 1} {$seqnr <= $lastSeqnr($parent)} {incr seqnr} {
			printNode $level ${parent}.${seqnr} $firstChild
			set firstChild 0
			if {$level < $lastLevel} then {
				printReportTree [expr $level + 1] ${parent}.${seqnr}
			}
		}
		printSummary $level $parent
		return
    }

	protected method printNode {level node firstRecord} {

		set tuple $reportTree($node)
		set margin [string repeat " " [expr 6 * $level]]
		set sectionNr "[string range $node 2 end].  "
		set nrLength [string length $sectionNr]
		set beforeSectionNr [string repeat " " [expr (6 * $level) - $nrLength]]
		set sectionNr "${beforeSectionNr}${sectionNr}"
		switch -- $sectionLayout($level) {
			"row" {
				printRow $level $tuple $firstRecord $margin $sectionNr
			}
			"table" {
				printTable $level $tuple $firstRecord $margin $sectionNr
			}
			default {
				printColumn $level $tuple $firstRecord $margin $sectionNr
			}
		}
		return
    }

	protected method printRow {level tuple firstRecord margin sectionNr} {

		if {$firstRecord || ($level != $lastLevel)} then {
			set output "\n"
		} else {
			set output {}
		}
		if {$level != $lastLevel} then {
			append output $sectionNr
		} else {
			append output $margin
		}
		foreach field $sectionFields($level) {
			append output "$fieldLabel($field): $reportData($tuple,$field); "
		}
		append output "\n"
		printString $output
		return
    }

	protected method printColumn {level tuple firstRecord margin sectionNr} {

		set output "\n"
		set firstLine 1
		foreach field $sectionFields($level) {
			set formatString "%-$MaxLabelWidth($level)\s"
			if {$firstLine} then {
				set label $sectionNr
			} else {
				set label $margin
			}
			set firstLine 0
			append label "[format $formatString $fieldLabel($field)] : "
			append output $label
			set nextLineOffset [string repeat { } [string length $label]]
			set startIdx 0
			set nlIdx [string first "\n" $reportData($tuple,$field) $startIdx]
			while { $nlIdx >= 0 } {
				append output \
					[string range $reportData($tuple,$field) $startIdx $nlIdx]
				append output $nextLineOffset
				set startIdx [expr $nlIdx + 1]
				set nlIdx [string first "\n" $reportData($tuple,$field) $startIdx]
			}
			append output \
				"[string range $reportData($tuple,$field) $startIdx end]\n"
		}
		printString $output
		return
    }

	protected method printTable {level tuple firstRecord margin sectionNr} {

		if {$firstRecord || ($level != $lastLevel)} then {
			printTableHeader $level $margin $sectionNr
		}
		foreach field $sectionFields($level) {
			switch -- $fieldAlignment($field) {
				"r" {
					set formatString($field) "%$MaxColWidth($field)\s"
				}
				"l" -
				default {
					set formatString($field) "%-$MaxColWidth($field)\s"
				}
			}
			set data($field) $reportData($tuple,$field)
		}
		set moreLines 1
		while {$moreLines} {
			set output {}
			set moreLines 0
			foreach field $sectionFields($level) {
				set newLineIdx [string first "\n" $data($field)]
				if {$newLineIdx >= 0} then {
					set oneLine \
						[string range $data($field) 0 [expr $newLineIdx - 1]]
					set data($field) \
						[string range $data($field) [expr $newLineIdx + 1] end]
					set moreLines 1
				} else {
					set oneLine $data($field)
					set data($field) {}
				}
				append output \
					"| [format $formatString($field) $oneLine] "
			}
			set output "${margin}[string range $output 1 end]\n"
			printString $output
		}
		return
    }

	protected method printTableHeader {level margin sectionNr} {

		set header {}
		set underline {}
		foreach field $sectionFields($level) {
			switch $fieldAlignment($field) {
				r {
					set formatString "%$MaxColWidth($field)\s"
				}
				l -
				default {
					set formatString "%-$MaxColWidth($field)\s"
				}
			}
			append header \
				"| [format $formatString $fieldLabel($field)] "
			append underline \
				"+-[string repeat - $MaxColWidth($field)]-"
		}
		set header [string range $header 1 end]
		set underline [string range $underline 1 end]
		set output "\n${margin}${header}\n"
		set nrLength [string length $sectionNr]
		if {$level != $lastLevel} then {
			append output "${sectionNr}${underline}\n"
		} else {
			append output "${margin}${underline}\n"
		}
		printString $output
		return
    }

	protected method printSummary {level parent} {

		set margin [string repeat " " [expr 6 * ($level - 1)]]
		set summaryText "Summary [string range $parent 2 end] : "
		set summaryTextLength [string length $summaryText]
		set firstLine 1
		foreach item $summaryList($level) {
			if {$firstLine} then {
				set output "\n${margin}${summaryText}"
			} else {
				set output \
					"${margin}[string repeat { } $summaryTextLength]"
			}
			set firstLine 0
			set field [lindex $item 0]
			set aggregate [lindex $item 1]
			set format [lindex $item 2]
			set label "${aggregate}\($field\)"
			set formatLabel "%-$MaxSummaryWidth($level)\s"
			append output "[format $formatLabel $label] = "
			set value $summaryData($parent,$field,$aggregate)
			if {$format ne {}} then {
				if {[catch {format $format $value} formattedValue]} then {
					showError [mc summaryFormatError $format $aggregate \
						$field $level $formattedValue]
					set formattedValue $value
				}
				append output "$formattedValue\n"
			} else {
				append output "${value}\n"
			}
			printString $output
		}
		return
    }

}

class ParmObject {
	protected variable window
	protected variable parmList
	protected variable pressedOK 0
	protected variable waitCalled 0
	protected variable data
    protected variable dataIdx
	protected variable txtQuery

	constructor {parent query c_parmList} {
		set parmList $c_parmList
		set window [toplevel \
			[appendToPath $parent [namespace tail $this]]]
		wm transient $window $parent
		set x [expr [winfo rootx $parent] + 100]
		set y [expr [winfo rooty $parent] + 50]
		wm geometry $window "500x400+${x}+${y}"
		wm title $window [mc getReportParms]
		set frm1 [ttk::frame ${window}.frm1]
		set txtQuery [text ${frm1}.txt -width 1 -height 1]
		set vsb [ttk::scrollbar ${frm1}.vsb -orient vertical \
			-command [list $txtQuery yview]]
		$txtQuery configure -yscrollcommand [list $vsb set]
		$txtQuery insert end $query
		grid $txtQuery -column 0 -row 0 -sticky wens
		grid $vsb -column 1 -row 0 -sticky ns
		grid columnconfigure $frm1 0 -weight 1
		grid rowconfigure $frm1 0 -weight 1
		set frm2 [ttk::frame ${window}.frm2]
		set idx 0
		foreach parm $parmList {
            # Bug 1011308
            # Because of bugs 211 and 238 in Itcl 3.4 and 4.0
            # (see http://sourceforge.net/p/incrtcl/bugs/211/
            # and http://sourceforge.net/p/incrtcl/bugs/238/)
            # a translation table dataIdx is introduced.
            set dataIdx($parm) $idx
			set data($idx) {}
			set lb($idx) [ttk::label ${frm2}.lb$idx -text $parm]
			set ent($idx) [entry ${frm2}.ent$idx \
				-textvariable [scope data($idx)]]
			grid $lb($idx) -column 0 -row $idx
			grid $ent($idx) -column 1 -row $idx
			# bug 1069: add next statement
			incr idx
		}
		set frm3 [ttk::frame ${window}.frm3]
		set btnOK [defineButton ${frm3}.btnOK $window btnOK \
				[list $this onOK]]
		set btnCancel [defineButton ${frm3}.btnCancel $window btnCancel \
			[list $this onCancel]]
		pack $btnCancel -side right
		pack $btnOK -side right
		pack $frm1 -side top -expand 1 -fill both
		pack $frm2 -side top -padx {10 10} -pady {10 10}
		pack $frm3 -side top -padx {10 10} -pady {10 10} -fill x
		pack [ttk::sizegrip ${window}.sg] -side top -anchor e
		return
	}

	destructor {

		return
	}

	public method onDestroy {} {
		if {!$waitCalled} then {
			after idle [list delete object $this]
		}
		return
	}

	public method wait {resultVar} {
		upvar $resultVar result
		set waitCalled 1
		tkwait window $window
		foreach parm $parmList {
            set result($parm) $data($dataIdx($parm))
        }
		after idle [list delete object $this]
		return $pressedOK
	}

	public method onOK {} {
		set pressedOK 1
		destroy $window
		return
	}

	public method onCancel {} {
		set pressedOK 0
		destroy $window
		return
	}
}

namespace eval aggregate {

	proc SUM {List} {

		set sum 0
		foreach item $List {
			if {[string is double -strict $item]} then {
			set sum [expr $sum + $item]
			}
		}
		return $sum
	}

	proc COUNT {List} {

		return [llength $List]
	}

    proc AVG {List} {

		set sum 0.0
		set count 0
		foreach item $List {
			if {[string is double -strict $item]} then {
				set sum [expr $sum + $item]
				incr count
			}
		}
		if {$count != 0} then {
			set avg [expr double($sum) / double($count)]
		} else {
			set avg 0.0
		}
		return $avg
    }

	proc STDDEV {List} {

		set sum 0.0
		set count 0
		foreach item $List {
			if {[string is double -strict $item]} then {
			set sum [expr $sum + $item]
			incr count
			}
		}
		if {$count != 0} then {
			set avg [expr double($sum) / double($count)]
		} else {
			set avg 0.0
		}
		set squareDev 0.0
		foreach item $List {
			if {[string is double -strict $item]} then {
			set dev [expr double($item) - double($avg)]
			set squareDev [expr $squareDev + $dev * $dev]
			}
		}
		if {$count != 1} then {
			set stddev [expr sqrt(double($squareDev) / double($count - 1))]
		} else {
			set stddev 0.0
		}
		return $stddev
	}

	proc MIN {List} {

		set numeric 1
		set min {}
		foreach item $List {
			if {$item ne {}} then {
				set min $item
				if {![string is double -strict $item]} then {
					set numeric 0
				}
			}
		}
		if {$numeric} then {
			foreach item $List {
				if {$item ne {}} then {
					if {$item < $min} then {
						set min $item
					}
				}
			}
		} else {
			foreach item $List {
				if {[string compare -nocase $min $item] == 1} then {
					set min $item
				}
			}
		}
		return $min
    }

    proc MAX {List} {

		set numeric 1
		set max {}
		foreach item $List {
			if {$item ne {}} then {
				set max $item
				if {![string is double -strict $item]} then {
					set numeric 0
				}
			}
		}
		if {$numeric} then {
			foreach item $List {
				if {$item ne {}} then {
					if {$item > $max} then {
						set max $item
					}
				}
			}
		} else {
			foreach item $List {
				if {[string compare -nocase $max $item] == -1} then {
					set max $item
				}
			}
		}
		return $max
	}
}

# test aggregate functions

#     set lists {
# 	{5 6 3 {} 8 11}
# 	{}
# 	{{}}
# 	{23.5 een twee 13.0 7}
# 	{-2 3.45 6.25 9}
# 	{aarde Aarde aardappel {} appel grondpeer peer}
#     }
#     foreach list $lists {
# 	puts "list = $list"
# 	puts "COUNT = [COUNT $list]"
# 	puts "SUM = [SUM $list]"
# 	puts "AVG = [AVG $list]"
# 	puts "STDDEV = [STDDEV $list]"
# 	puts "MIN = [MIN $list]"
# 	puts "MAX = [MAX $list]"
# 	puts "------------------------"
#     }
