# Author: Malcolm Kesson (2007)
proc render { lstr script filename } {
    global LROOT
    set out [open "$LROOT/$filename.mel" w]
    
    # Get the relevant data from the scriptDB
    upvar $script ScriptDB
    set scale     [getArrayValueOf ScriptDB scale]
    set translate [getArrayValueOf ScriptDB translate]
    set angle     [getArrayValueOf ScriptDB angle]
    
    if {$scale == ""} { set scale 1.0 }
    if {$translate == ""} { set translate 1.0 }
    if {$angle == ""} { set angle 90.0 }
  
    # Check for missing default values
    if {$scale == ""} { set scale 1.0 }
    if {$translate == ""} { set translate 1.0 }
    if {$angle == ""} { set angle 90.0 }
  
    # Statements assigned to characters in the 
    # script data file are stored as arrays of arrays
    set stats  [getArrayValueOf ScriptDB statement]
    array set Statements $stats
    set statechars [array names Statements]
    
    # MEL begin_________________________________________
    puts $out "source \"$LROOT/LMelProcs.mel\";"
    puts $out "global string \$stack\[\];"
    puts $out "select -all;"
    puts $out "delete;"
    puts $out "clear(\$stack);"
    puts $out "\$root = `group -em -n LSYS`;"
    puts $out "\$tnode = `group -em`;"
    puts $out "parent -r \$tnode \$root;"
  
    for {set i 0} {$i < [string length $lstr]} {incr i} {
        set char [string index $lstr $i]
  
  
        # Handle the custom statements__________________
        for {set j 0} {$j < [llength $statechars] } {incr j} {
            set ch [lindex $statechars $j]
            if { $ch == $char } {
                
                set item [subst [getArrayValueOf Statements $ch]]
                puts $out $item
                continue
                }
            }
        switch $char {
            > {set angle [expr abs($angle)] }
            < {set angle [expr abs($angle) * -1] }
            x {puts $out  "rotate -r $angle 0 0 \$tnode;"}
            y {puts $out  "rotate -r 0 $angle 0 \$tnode;"}
            z {puts $out  "rotate -r 0 0 $angle \$tnode;"}
            s {puts $out  "scale -r $scale $scale $scale \$tnode;"}
            R {set translate [expr abs($translate) * -1] }
            S {set scale [expr abs($scale) * -1] }
            X {puts $out  "move -r $translate 0 0 \$tnode;"}
            Y {puts $out  "move -r 0 $translate 0 \$tnode;"}
            Z {puts $out  "move -r 0 0 $translate \$tnode;"}
            + {set translate [expr abs($translate)] }
            - {set translate [expr abs($translate) * -1] }
            1 {puts $out  "\$tnode = addConeTo(\$tnode);"}
            4 {puts $out  "\$tnode = addCurveTo(\$tnode);"}
            \{ { puts $out "push(\$tnode);"}
            \} { puts $out "\$tnode = pop();"}
            }
        }
    # Delete "stray" group nodes
    puts $out "\$nulls = `ls \"|null*\"`;"
    puts $out "select -r \$nulls;"
    puts $out "delete;"
    close $out
    }