#  Copyright (C) 1999-2015
#  Smithsonian Astrophysical Observatory, Cambridge, MA, USA
#  For conditions of distribution and use, see copyright notice in "copyright"

package provide DS9 1.0

proc CATFltSort {varname} {
    upvar #0 $varname var
    global $varname
    global $var(catdb)
    global $var(tbldb)

    upvar #0 $var(catdb) src
    upvar #0 $var(tbldb) dest

    # create header
    set dest(Header) $src(Header)
    starbase_colmap dest

    set dest(Ndshs) [llength $dest(Header)]
    set dest(Nrows) 0
    set dest(HLines) $src(HLines)
    set dest(Dashes) $src(Dashes)

    # optional
    if {[info exists src(DataType)]} {
	set dest(DataType) $src(DataType)
    }
    if {[info exists src(Id)]} {
	set dest(Id) $src(Id)
    }
    if {[info exists src(ArraySize)]} {
	set dest(ArraySize) $src(ArraySize)
    }
    if {[info exists src(Width)]} {
	set dest(Width) $src(Width)
    }
    if {[info exists src(Precision)]} {
	set dest(Precision) $src(Precision)
    }
    if {[info exists src(Unit)]} {
	set dest(Unit) $src(Unit)
    }
    if {[info exists src(Ref)]} {
	set dest(Ref) $src(Ref)
    }
    if {[info exists src(Ucd)]} {
	set dest(Ucd) $src(Ucd)
    }
    if {[info exists src(Description)]} {
	set dest(Description) $src(Description)
    }

    for {set ii 1} {$ii<=$src(HLines)} {incr ii} {
	set dest(H_$ii) $src(H_$ii)
    }

    for {set jj 1} {$jj<=$src(Ncols)} {incr jj} {
	set dest(0,$jj) $src(0,$jj)
    }

    # sort?
    set order {}
    if {$var(sort) != {}} {
	set col $src($var(sort))

	for {set ii 1} {$ii<=$src(Nrows)} {incr ii} {
	    set val $src($ii,$col)
	    # if blank, set to 0
	    if {$val == {}} {
		set val 0
	    }
	    lappend order "[list $ii $val]"
	}

	# first try as real, if error, then ascii
	if {[catch {lsort $var(sort,dir) -real -index 1 $order} oo]} {
	    set oo [lsort $var(sort,dir) -ascii -index 1 $order]
	}
	set order $oo
    } else {
	for {set ii 1} {$ii<=$src(Nrows)} {incr ii} {
	    lappend order "[list $ii {}]"
	}
    }

    # data
    set kk 0
    for {set ii 1} {$ii<=$src(Nrows)} {incr ii} {
	set id [lindex [lindex $order [expr $ii-1]]  0]
	# now filter
	set pass 1
	if {$var(filter) != {}} {
	    # eval all colnames
	    foreach col $src(Header) {
		set col [string trim $col]
		set val $src($id,$src($col))
		# here's a tough one-- 
		# what to do if the column is blank
		# for now, just set it to '0'
		if {[string trim "$val"] == {}} {
		    set val 0
		}
		eval "set \{$col\} \{$val\}"
	    }
	    # subst any columv vars
	    if {[catch {subst $var(filter)} ff]} {
		return 0
	    }
	    # evaluate filter
	    if {[catch {expr $ff} result]} {
		return 0
	    }
	    # do we keep the row?
	    if {!$result} {
		set pass 0
	    }
	}

	if {$pass} {
	    incr kk
	    for {set jj 1} {$jj<=$src(Ncols)} {incr jj} {
		set dest($kk,$jj) $src($id,$jj)
	    }
	}
    }

    # success
    set dest(Nrows) $kk
    return 1
}


