# Copyright (c) 2001, 2002 by Intevation GmbH
# Authors:
# Frank Koormann <frank.koormann@intevation.de>
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with Thuban for details.

__version__ = "$Revision: 1.4 $"

from Thuban import _

def deriveInterval(width, scale):
    """Calculate scalebar interval and unit which fits width for scale."""
    try:
        interval = width / scale
    except ZeroDivisionError:
        return -1, ''

    if interval / 1000 > 1:
        interval = long(interval / 1000)
        unit = 'km'
    else: 
        interval = long(interval)
        unit = 'm'

    return interval, unit

def roundInterval(d):
    """Round float."""
    if d<.001: 
        interval = long(d*10000)/10000.0
        return interval, "%.4f" % interval
    if d<.01:
        interval = long(d*1000)/1000.0
        return interval, "%.3f" % interval
    if d<.1:
        interval = long(d*100)/100.0
        return interval, "%.2f" % interval
    if d<1:
        interval = long(d*10)/10.0
        return interval, "%.1f" % interval
    if d<10:
        return long(d), "%d" % d
    if d<100:
        interval = long(d/10) * 10
        return interval, "%d" % interval
    if d<1000:
        interval = long(d/100) * 100
        return interval, "%d" % interval
    if d<10000:
        interval = long(d/1000) * 1000
        return interval, "%d" % interval
    if d<100000:
        interval = long(d/10000) * 10000
        return interval, "%d" % interval

    return -1, ''

