# Author: Malcolm Kesson (2007)
proc render {lstr script filename} {
    global LROOT
    if {$filename != ""} {
        set out [open "$LROOT/$filename.rib" w]
    } else {
        set out stdout
        }
  
    # 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]
  
    # 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 statements]
    array set Statements $stats
    set statechars [array names Statements]
    
    # RIB begin______________
    puts $out "AttributeBegin"
    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 $angle  1 0 0"}
            y {puts $out  "Rotate $angle  0 1 0"}
            z {puts $out  "Rotate $angle  0 0 1"}
            s {puts $out  "Scale $scale $scale $scale"}
            R {set translate [expr abs($translate) * -1] }
            S {set scale [expr abs($scale) * -1] }
            X {puts $out  "Translate 1 0 0"}
            Y {puts $out  "Translate 0 1 0"}
            Z {puts $out  "Translate 0 0 1"}
            + {set translate [expr abs($translate)] }
            - {set translate [expr abs($translate) * -1] }
            1 {puts $out  "Cone 0.25 1 360"}
            4 {puts $out  "Curves \"linear\" \[2\]"
               puts $out  "       \"nonperiodic\""
               puts $out  "       \"P\" \[0 0 0  0 1 0\]"
               puts $out  "       \"constantwidth\" \[0.3\]"
               puts $out  "Translate 0 1 0"
               }
            \{ { puts $out "AttributeBegin"}
            \} { puts $out "AttributeEnd"}
            }
        }
    puts $out  "AttributeEnd"
    # RIB end________________
    if {$filename != ""} {
        close $out
        }
    }