#!/bin/sh

""":"
exec python $0 ${1+"$@"}
"""

# ---------------------- HelloWeights.py ----------------------
# 
# This program demonstrates how to use weights (colored disks),
# which enable plotting of two quantites with one curve


from Tkinter import *        # The Tk package
import Pmw                   # The Python MegaWidget package
import math                  # import the sin-function

master = Tk()                # build Tk-environment
ncurves = 4                  # draw 4 curves
npoints = 16                 # use 16 points on each curve


def toHex(number):
    hex = "0123456789abcdef"
    if number == 0: return "00"
    if number < 16: return "0"+hex[number]
    
    s = ""
    while(number):
        val = number % 16
        number = number / 16
        s = hex[val] +s

    return s
    

if not Pmw.Blt.haveblt(master):     # Is Blt installed?
   print("BLT is not installed!")

else:
   vector_x = []                # make a vector with x values
   vector_y = []
   vector_dydx = []             # vector_dydx contains derivatives of vector_y
   dx = 1e-5                    # used in approximating the derivative

   for y in range(ncurves):
      vector_y.append([])       # vector of curves (containing y values)
      vector_dydx.append([])    # similar vector of dy/dx values

   for x in range(npoints+1):   
      vector_x.append(x*0.1)    # fill in the x values for all curves

      # compute y values:
      for c in range(ncurves): 
         vector_y[c].append(math.sin(c*x*0.1)) # make an y-value
         vector_dydx[c].append((math.sin(c*(x*0.1+dx))-math.sin(c*x*0.1))/dx)
         
   g = Pmw.Blt.Graph(master)         # make a new graph area
   g.pack(expand=1, fill='both')

   styles = ()
   
   for i in range(10):
       name = "pen" +str(i)

       # compute color range: red -> yellow -> green
       fill = "#"+toHex(min(255, i*50)) +toHex(510-max(255, i*50)) +"00"
       g.pen_create(name, fill=fill, pixels=7)
       styles = styles +((name, 0.6*(i-5), 0.6*(i-4)),)
       
   
   for c in range(ncurves):                      # for each curve...
      curvename = 'sin(' + str(c) +'x)'          # make a curvename
      g.line_create(curvename,                   # and create the graph
                    xdata=tuple(vector_x),       # with x data,
                    ydata=tuple(vector_y[c]),    # and  y data
                    weights=tuple(vector_dydx[c]), # and derivatives
                    pixels=10,                   # symbols 10 pixels wide
                    styles=styles)               # and their styles 
   
   g.configure(title='Hello Weights')            # enter a title
   
   master.mainloop()                             # ...and wait for input