# units.tcl
#
# ****************************************************************************
# Copyright (c) 2001 Digi International Inc., All Rights Reserved
# 
# This software contains proprietary and confidential information of Digi
# International Inc.  By accepting transfer of this copy, Recipient agrees
# to retain this software in confidence, to prevent disclosure to others,
# and to make no use of this software other than that for which it was
# delivered.  This is an unpublished copyrighted work of Digi International
# Inc.  Except as permitted by federal law, 17 USC 117, copying is strictly
# prohibited.
# 
# Restricted Rights Legend
#
# Use, duplication, or disclosure by the Government is subject to
# restrictions set forth in sub-paragraph (c)(1)(ii) of The Rights in
# Technical Data and Computer Software clause at DFARS 252.227-7031 or
# subparagraphs (c)(1) and (2) of the Commercial Computer Software -
# Restricted Rights at 48 CFR 52.227-19, as applicable.
#
# Digi International Inc. 11001 Bren Road East, Minnetonka, MN 55343
#
# ***************************************************************************

package provide Tools 1.0
namespace eval Units {}
proc Units::label {numConvert strUnits {strFormat 4.2} {numDivisor 1000}} {
    ## This proc dynamically labels numbers with human readable units
    ## It does not do conversion!
    ## ex: units 100000000 foo   ===> 100 Mfoo
    ## ex: units 100000 foo       ===> 10 Kfoo
    ## 
    ## TODO: Add support for small units (milli, micro, pico)
    set lstFormat [split $strFormat .]
    set lDigits [lindex $lstFormat 0]
    set rDigits [lindex $lstFormat 1]
    set numLength [string length $numConvert]
    set numNumber [expr double($numConvert)]
    set indexUnits 0
        set arUnits(0) ""
        set arUnits(1) K
        set arUnits(2) M
        set arUnits(3) G
        set arUnits(4) T
    
    while {$numLength > $lDigits} {
        incr indexUnits
        set numNumber [expr {$numNumber / $numDivisor}]
        set numLength [string length [expr int($numNumber)]]
    }           
    set numNumber [expr pow(10,$rDigits) * $numNumber]
    set numNumber [expr round($numNumber)]
    set numNumber [expr double($numNumber) / pow(10,$rDigits)]  
    if {$numConvert == $numNumber || $rDigits == 0} {
        set numNumber [expr round($numNumber)]
    }
    return "$numNumber $arUnits($indexUnits)$strUnits"
}

    
 
