import rhinoscriptsyntax as rs
 
# AutoLabel Subroutine
def AutoLabel():
    # Select objects      
    arrObjects = rs.GetObjects("Select objects to name")
    if not arrObjects: return
 
    # Prompt for a prefix to add to the labels
    name = rs.GetString("Prefix for labels, press Enter for none")
    if name is None: name = ""
 
    # Prompt for a suffix starting number
    suffix = rs.GetInteger("Starting base number to increment",0)
    if suffix is None: return
 
    # Prompt for direction
    dirPoint1 = rs.GetPoint("Base point for sort direction")
    if not dirPoint1: return
    dirPoint2 = rs.GetPoint("Pick point for sort direction", dirPoint1)
    if not dirPoint2: return
 
    # Initialize collection
    collection = []
 
    # Process each seleted object
    for obj in arrObjects:
        bbox = rs.BoundingBox(obj)
        # Get bboc center
        point = (bbox[0] + bbox[6])*0.5
        collection.append( (point, obj) )

 

    # Determine Direction of sort for each axis
    sortDir = dirPoint2 - dirPoint1
    # compare function for sorting
    def sortcompare(a, b):
        pointa, pointb = a[0], b[0]
        rc = cmp(pointa.X, pointb.X)
        if sortDir.X<0: rc = -1*rc
        if rc==0:
            rc = cmp(pointa.Y, pointb.Y)
            if sortDir.Y<0: rc = -1*rc
        if rc==0:
            rc = cmp(pointa.Z, pointb.Z)
            if sortDir.Z<0: rc = -1*rc
        return rc
    # sort the collection
    collection = sorted(collection, sortcompare)
 
    # Process each item in the collection
    for point, item in collection:
        print 'named object : {}'.format(name+str(suffix))
        rs.ObjectName(item, name+str(suffix))
        suffix += 1
       
 
if __name__=="__main__":
    AutoLabel()