Check-in [2275705c46]
Not logged in

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:merge with trunk
Timelines: family | ancestors | descendants | both | wtf-8-experiment
Files: files | file ages | folders
SHA1: 2275705c46a9d2f020366cc1719d6f4b4568cfc4
User & Date: chw 2018-08-12 17:06:33.341
Context
2018-08-13
15:39
merge with trunk check-in: adefd1245e user: chw tags: wtf-8-experiment
2018-08-12
17:06
merge with trunk check-in: 2275705c46 user: chw tags: wtf-8-experiment
17:01
add a proof of concept minimal Tcl binding to the OPC/UA implementation of http://www.open62541.org check-in: 2436586fc1 user: chw tags: trunk
2018-08-05
03:55
merge with trunk check-in: adedeba8b2 user: chw tags: wtf-8-experiment
Changes
Unified Diff Ignore Whitespace Patch
Changes to assets/INVENTORY.
64
65
66
67
68
69
70

71
72
73
74
75
76
77
{opt assets/TkMC*}
{opt assets/tkpath* {libs/$arch/libtkpath.so jni/tkpath}}
{opt assets/tksqlite*}
{opt assets/tksvg* {libs/$arch/libtksvg.so jni/tksvg}}
{opt assets/tktable* {libs/$arch/libtktable.so jni/tktable}}
{opt assets/Tkzinc* {libs/$arch/libTkzinc.so jni/tkzinc}}
{opt assets/tls* {libs/$arch/libtcltls.so libs/$arch/libssl_tls.so libs/$arch/libcrypto_tls.so jni/tls jni/openssl jni/libressl}}

{opt assets/treectrl* {libs/$arch/libtreectrl.so jni/tktreectrl}}
{opt assets/trf* {libs/$arch/libtcltrf.so jni/trf}}
{opt assets/trofs* {libs/$arch/libtrofs.so jni/trofs}}
{opt jni/tcl/library/tzdata}
{opt assets/twdbgi*}
{opt assets/udp* {libs/$arch/libtcludp.so jni/tcludp}}
{opt assets/ukaz*}







>







64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
{opt assets/TkMC*}
{opt assets/tkpath* {libs/$arch/libtkpath.so jni/tkpath}}
{opt assets/tksqlite*}
{opt assets/tksvg* {libs/$arch/libtksvg.so jni/tksvg}}
{opt assets/tktable* {libs/$arch/libtktable.so jni/tktable}}
{opt assets/Tkzinc* {libs/$arch/libTkzinc.so jni/tkzinc}}
{opt assets/tls* {libs/$arch/libtcltls.so libs/$arch/libssl_tls.so libs/$arch/libcrypto_tls.so jni/tls jni/openssl jni/libressl}}
{opt assets/topcua* {libs/$arch/libtopcua.so jni/topcua}}
{opt assets/treectrl* {libs/$arch/libtreectrl.so jni/tktreectrl}}
{opt assets/trf* {libs/$arch/libtcltrf.so jni/trf}}
{opt assets/trofs* {libs/$arch/libtrofs.so jni/trofs}}
{opt jni/tcl/library/tzdata}
{opt assets/twdbgi*}
{opt assets/udp* {libs/$arch/libtcludp.so jni/tcludp}}
{opt assets/ukaz*}
Changes to assets/tclws2.6.0/ClientSide.tcl.
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# Version     Date     Programmer   Comments / Changes / Reasons
# -------  ----------  ----------   -------------------------------------------
#       1  04/272009   G.Lester     Initial version
#   2.4.5  2017-12-04  H.Oehlmann   Return all current options if no argument
#                                   given. Options -globalonly or -defaultonly
#                                   limit this to options which are (not)
#                                   copied to the service.
#                                   
###########################################################################
proc ::WS::Client::SetOption {args} {
    variable options
    variable serviceLocalOptionsList
    if {0 == [llength $args]} {
        return [array get options]
    }
    set args [lassign $args option]
    
    switch -exact -- $option {
        -globalonly {
            ##
            ## Return list of global options
            ##
            # A list convertible to a dict is build for performance reasons:
            # - lappend does not test existence for each element







|








|







194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# Version     Date     Programmer   Comments / Changes / Reasons
# -------  ----------  ----------   -------------------------------------------
#       1  04/272009   G.Lester     Initial version
#   2.4.5  2017-12-04  H.Oehlmann   Return all current options if no argument
#                                   given. Options -globalonly or -defaultonly
#                                   limit this to options which are (not)
#                                   copied to the service.
#
###########################################################################
proc ::WS::Client::SetOption {args} {
    variable options
    variable serviceLocalOptionsList
    if {0 == [llength $args]} {
        return [array get options]
    }
    set args [lassign $args option]

    switch -exact -- $option {
        -globalonly {
            ##
            ## Return list of global options
            ##
            # A list convertible to a dict is build for performance reasons:
            # - lappend does not test existence for each element
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
proc ::WS::Client::Config {args} {
    variable serviceArr
    variable options
    variable serviceLocalOptionsList

    set validOptionList $serviceLocalOptionsList
    lappend validOptionList location targetNamespace
    
    if {0 == [llength $args]} {
        # A list convertible to a dict is build for performance reasons:
        # - lappend does not test existence for each element
        # - if a list is needed, dict build burden is avoided
        set res {}
        foreach item $validOptionList {
            lappend res $item
            if {[info exists options($item)]} {
                lappend res $options($item)
            } else {
                lappend res {}
            }
        }
        return $res
    }    
    set args [lassign $args serviceName]
    if {0 == [llength $args]} {
        set res {}
        foreach item $validOptionList {
            lappend res $item [dict get $serviceArr($serviceName) $item]
        }
        return $res
    }
    
    set args [lassign $args item]
    if { $item ni $validOptionList } {
        return -code error "Uknown option '$item' -- must be one of: [join $validOptionList {, }]"
    }

    switch -exact -- [llength $args] {
        0 {







|














|








|







400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
proc ::WS::Client::Config {args} {
    variable serviceArr
    variable options
    variable serviceLocalOptionsList

    set validOptionList $serviceLocalOptionsList
    lappend validOptionList location targetNamespace

    if {0 == [llength $args]} {
        # A list convertible to a dict is build for performance reasons:
        # - lappend does not test existence for each element
        # - if a list is needed, dict build burden is avoided
        set res {}
        foreach item $validOptionList {
            lappend res $item
            if {[info exists options($item)]} {
                lappend res $options($item)
            } else {
                lappend res {}
            }
        }
        return $res
    }
    set args [lassign $args serviceName]
    if {0 == [llength $args]} {
        set res {}
        foreach item $validOptionList {
            lappend res $item [dict get $serviceArr($serviceName) $item]
        }
        return $res
    }

    set args [lassign $args item]
    if { $item ni $validOptionList } {
        return -code error "Uknown option '$item' -- must be one of: [join $validOptionList {, }]"
    }

    switch -exact -- [llength $args] {
        0 {
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
#                       is a key value list argument. It must be a list with
#                       an even number of elements that alternate between
#                       keys and values. The keys become header field names.
#                       Newlines are stripped from the values so the header
#                       cannot be corrupted.
#                       This is an optional argument and defaults to {}.
#       serviceAlias  - Alias (unique) name for service.
#                       This is an optional argument and defaults to the name 
#                       of the service in serviceInfo.
#       serviceNumber - Number of service within the WSDL to assign the
#                       serviceAlias to. Only usable with a serviceAlias.
#                       First service (default) is addressed by value "1".
#
# Returns : The parsed service definition
#







|







1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
#                       is a key value list argument. It must be a list with
#                       an even number of elements that alternate between
#                       keys and values. The keys become header field names.
#                       Newlines are stripped from the values so the header
#                       cannot be corrupted.
#                       This is an optional argument and defaults to {}.
#       serviceAlias  - Alias (unique) name for service.
#                       This is an optional argument and defaults to the name
#                       of the service in serviceInfo.
#       serviceNumber - Number of service within the WSDL to assign the
#                       serviceAlias to. Only usable with a serviceAlias.
#                       First service (default) is addressed by value "1".
#
# Returns : The parsed service definition
#
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
    }

    ##
    ## build list of namespace definition nodes
    ##
    ## the top node is always used
    set NSDefinitionNodeList [list $wsdlNode]
    
    ##
    ## get namespace definitions in element nodes
    ##
    ## Element nodes may declare namespaces inline like:
    ## <xs:element xmlns:q1="myURI" type="q1:MessageQ1"/>
    ## ticket [dcce437d7a]
    
    # This is only done, if option inlineElementNS is set in the default
    # options. Service dependent options may not be used at this stage,
    # as serviceArr is not created jet (Client::Config will fail) and the
    # service name is not known jet.
    if {$options(inlineElementNS)} {
        lappend NSDefinitionNodeList {*}[$wsdlDoc selectNodes {//xs:element}]
    }
    foreach elemNode $NSDefinitionNodeList {
        # Get list of xmlns attributes
        # This list looks for the example like: {{q1 q1 {}} ... }
        set xmlnsAttributes [$elemNode attributes xmlns:*] 
        # Loop over found namespaces
        foreach itemList $xmlnsAttributes {
            set ns [lindex $itemList 0]
            set url [$elemNode getAttribute xmlns:$ns]

            if {[dict exists $nsDict url $url]} {
                set tns [dict get $nsDict url $url]







|






|










|







1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
    }

    ##
    ## build list of namespace definition nodes
    ##
    ## the top node is always used
    set NSDefinitionNodeList [list $wsdlNode]

    ##
    ## get namespace definitions in element nodes
    ##
    ## Element nodes may declare namespaces inline like:
    ## <xs:element xmlns:q1="myURI" type="q1:MessageQ1"/>
    ## ticket [dcce437d7a]

    # This is only done, if option inlineElementNS is set in the default
    # options. Service dependent options may not be used at this stage,
    # as serviceArr is not created jet (Client::Config will fail) and the
    # service name is not known jet.
    if {$options(inlineElementNS)} {
        lappend NSDefinitionNodeList {*}[$wsdlDoc selectNodes {//xs:element}]
    }
    foreach elemNode $NSDefinitionNodeList {
        # Get list of xmlns attributes
        # This list looks for the example like: {{q1 q1 {}} ... }
        set xmlnsAttributes [$elemNode attributes xmlns:*]
        # Loop over found namespaces
        foreach itemList $xmlnsAttributes {
            set ns [lindex $itemList 0]
            set url [$elemNode getAttribute xmlns:$ns]

            if {[dict exists $nsDict url $url]} {
                set tns [dict get $nsDict url $url]
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
    set serviceInfo $serviceArr($serviceName)
    if {![dict exists $serviceInfo operation $operationName]} {
        return \
            -code error \
            -errorcode [list WS CLIENT UNKOPER [list $serviceName $operationName]] \
            "Unknown operation '$operationName' for service '$serviceName'"
    }
    
    ##
    ## build query
    ##
    
    set url [dict get $serviceInfo location]
    SaveAndSetOptions $serviceName
    if {[catch {set query [buildCallquery $serviceName $operationName $url $argList]} err]} {
        RestoreSavedOptions $serviceName
        return -code error -errorcode $::errorCode -errorinfo $::errorInfo $err
    } else {
        RestoreSavedOptions $serviceName
    }
    if {[dict exists $serviceInfo headers]} {
        set headers [concat $headers [dict get $serviceInfo headers]]
    }
    if {[dict exists $serviceInfo operation $operationName action]} {
        lappend headers  SOAPAction [format {"%s"} [dict get $serviceInfo operation $operationName action]]
    }
    
    ##
    ## do http call
    ##
    
    if {[llength $headers]} {
        set body [::WS::Utils::geturl_fetchbody $url -query $query -type [dict get $serviceInfo contentType] -headers $headers]
    } else {
        set body [::WS::Utils::geturl_fetchbody $url -query $query -type [dict get $serviceInfo contentType]]
    }

    ::log::logsubst debug {Leaving ::WS::Client::DoRawCall with {$body}}







|



|














|



|







1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
    set serviceInfo $serviceArr($serviceName)
    if {![dict exists $serviceInfo operation $operationName]} {
        return \
            -code error \
            -errorcode [list WS CLIENT UNKOPER [list $serviceName $operationName]] \
            "Unknown operation '$operationName' for service '$serviceName'"
    }

    ##
    ## build query
    ##

    set url [dict get $serviceInfo location]
    SaveAndSetOptions $serviceName
    if {[catch {set query [buildCallquery $serviceName $operationName $url $argList]} err]} {
        RestoreSavedOptions $serviceName
        return -code error -errorcode $::errorCode -errorinfo $::errorInfo $err
    } else {
        RestoreSavedOptions $serviceName
    }
    if {[dict exists $serviceInfo headers]} {
        set headers [concat $headers [dict get $serviceInfo headers]]
    }
    if {[dict exists $serviceInfo operation $operationName action]} {
        lappend headers  SOAPAction [format {"%s"} [dict get $serviceInfo operation $operationName action]]
    }

    ##
    ## do http call
    ##

    if {[llength $headers]} {
        set body [::WS::Utils::geturl_fetchbody $url -query $query -type [dict get $serviceInfo contentType] -headers $headers]
    } else {
        set body [::WS::Utils::geturl_fetchbody $url -query $query -type [dict get $serviceInfo contentType]]
    }

    ::log::logsubst debug {Leaving ::WS::Client::DoRawCall with {$body}}
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
            if {$URIServer eq $URICur} {
                dict set xnsDistantToLocalDict $attributeCur $prefixCur
                break
            }
        }
    }
    ::log::logsubst debug {Server to Client prefix dict: $xnsDistantToLocalDict}
    
    ##
    ## Get body tag
    ##
    set body [$top selectNodes ENV:Body]
    if {![llength $body]} {
        return \
            -code error \







|







2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
            if {$URIServer eq $URICur} {
                dict set xnsDistantToLocalDict $attributeCur $prefixCur
                break
            }
        }
    }
    ::log::logsubst debug {Server to Client prefix dict: $xnsDistantToLocalDict}

    ##
    ## Get body tag
    ##
    set body [$top selectNodes ENV:Body]
    if {![llength $body]} {
        return \
            -code error \
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
    set nodeNameCandidateList [list Fault $expectedMsgTypeBase]
    # We check if the preparsed wsdl contains the name flag.
    # This is not the case, if it was parsed with tclws prior 2.4.2
    # *** ToDo *** This security may be removed on a major release
    if {[dict exists $serviceInfo operation $operationName outputsname]} {
        lappend nodeNameCandidateList [dict get $serviceInfo operation $operationName outputsname]
    }
    
    set rootNodeList [$body childNodes]
    ::log::logsubst debug {Have [llength $rootNodeList] node under Body}
    foreach rootNodeCur $rootNodeList {
        set rootNameCur [$rootNodeCur localName]
        if {$rootNameCur eq {}} {
            set rootNameCur [$rootNodeCur nodeName]
        }







|







2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
    set nodeNameCandidateList [list Fault $expectedMsgTypeBase]
    # We check if the preparsed wsdl contains the name flag.
    # This is not the case, if it was parsed with tclws prior 2.4.2
    # *** ToDo *** This security may be removed on a major release
    if {[dict exists $serviceInfo operation $operationName outputsname]} {
        lappend nodeNameCandidateList [dict get $serviceInfo operation $operationName outputsname]
    }

    set rootNodeList [$body childNodes]
    ::log::logsubst debug {Have [llength $rootNodeList] node under Body}
    foreach rootNodeCur $rootNodeList {
        set rootNameCur [$rootNodeCur localName]
        if {$rootNameCur eq {}} {
            set rootNameCur [$rootNodeCur nodeName]
        }
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
# Version     Date     Programmer   Comments / Changes / Reasons
# -------  ----------  ----------   -------------------------------------------
#       1  08/06/2006  G.Lester     Initial version
#
#
###########################################################################
proc ::WS::Client::parseTypes {wsdlNode serviceName serviceInfoVar} {
    ::log:::log debug "Entering [info level 0]"

    upvar 1 $serviceInfoVar serviceInfo


    set tnsCount [llength [dict keys [dict get $serviceInfo tnsList url]]]
    set baseUrl [dict get $serviceInfo location]
    foreach schemaNode [$wsdlNode selectNodes w:types/xs:schema] {
        ::log:::log debug "Parsing node $schemaNode"
        ::WS::Utils::parseScheme Client $baseUrl $schemaNode $serviceName serviceInfo tnsCount
    }

    ::log:::log debug "Leaving [lindex [info level 0] 0]"
}

###########################################################################
#
# Private Procedure Header - as this procedure is modified, please be sure
#                            that you update this header block. Thanks.
#







|







|



|







2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
# Version     Date     Programmer   Comments / Changes / Reasons
# -------  ----------  ----------   -------------------------------------------
#       1  08/06/2006  G.Lester     Initial version
#
#
###########################################################################
proc ::WS::Client::parseTypes {wsdlNode serviceName serviceInfoVar} {
    ::log::log debug "Entering [info level 0]"

    upvar 1 $serviceInfoVar serviceInfo


    set tnsCount [llength [dict keys [dict get $serviceInfo tnsList url]]]
    set baseUrl [dict get $serviceInfo location]
    foreach schemaNode [$wsdlNode selectNodes w:types/xs:schema] {
        ::log::log debug "Parsing node $schemaNode"
        ::WS::Utils::parseScheme Client $baseUrl $schemaNode $serviceName serviceInfo tnsCount
    }

    ::log::log debug "Leaving [lindex [info level 0] 0]"
}

###########################################################################
#
# Private Procedure Header - as this procedure is modified, please be sure
#                            that you update this header block. Thanks.
#
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
#       1  08/06/2006  G.Lester     Initial version
# 2.4.2    2017-08-31  H.Oehlmann   Also set serviceArr operation members
#                                   inputsName and outputsName.
#
#
###########################################################################
proc ::WS::Client::parseBinding {wsdlNode serviceName bindingName serviceInfoVar} {
    ::log:::log debug "Entering [info level 0]"
    upvar 1 $serviceInfoVar serviceInfo
    variable options

    set bindQuery [format {w:binding[attribute::name='%s']} $bindingName]
    array set msgToOper {}
    foreach binding [$wsdlNode selectNodes $bindQuery] {
        array unset msgToOper *
        set portName [lindex [split [$binding  getAttribute type] {:}] end]
        ::log:::log debug "\t Processing binding '$bindingName' on port '$portName'"
        set operList [$binding selectNodes w:operation]
        set styleNode [$binding selectNodes d:binding]
        if {![info exists style]} {
            if {[catch {$styleNode getAttribute style} tmpStyle]} {
                set styleNode [$binding selectNodes {w:operation[1]/d:operation}]
                if {$styleNode eq {}} {
                    ##
                    ## This binding is for a SOAP level other than 1.1
                    ##
                    ::log:::log debug "Skiping non-SOAP 1.1 binding [$binding asXML]"
                    continue
                }
                set style [$styleNode getAttribute style]
                #puts "Using style for first operation {$style}"
            } else {
                set style $tmpStyle
                #puts "Using style for first binding {$style}"
            }
            if {!($style eq {document} || $style eq {rpc} )} {
                ::log:::log debug "Leaving [lindex [info level 0] 0] with error @1"
                return \
                    -code error \
                    -errorcode [list WS CLIENT UNSSTY $style] \
                    "Unsupported calling style: '$style'"
            }

            if {![info exists use]} {
                set use [[$binding selectNodes {w:operation[1]/w:input/d:body}] getAttribute use]
                if {!($style eq {document} && $use eq {literal} ) &&
                    !($style eq {rpc} && $use eq {encoded} )} {
                    ::log:::log debug "Leaving [lindex [info level 0] 0] with error @2"
                    return \
                        -code error \
                        -errorcode [list WS CLIENT UNSMODE $use] \
                        "Unsupported mode: $style/$use"
                }
            }
        }

        set style $style/$use

        ##
        ## Process each operation
        ##
        foreach oper $operList {
            set operName [$oper getAttribute name]
            set baseName $operName
            ::log:::log debug "\t Processing operation '$operName'"

            ##
            ## Check for overloading
            ##
            set inNode [$oper selectNodes w:input]
            if {[llength $inNode] == 1 && [$inNode hasAttribute name]} {
                set inName [$inNode getAttribute name]







|








|









|









|










|
















|







2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
#       1  08/06/2006  G.Lester     Initial version
# 2.4.2    2017-08-31  H.Oehlmann   Also set serviceArr operation members
#                                   inputsName and outputsName.
#
#
###########################################################################
proc ::WS::Client::parseBinding {wsdlNode serviceName bindingName serviceInfoVar} {
    ::log::log debug "Entering [info level 0]"
    upvar 1 $serviceInfoVar serviceInfo
    variable options

    set bindQuery [format {w:binding[attribute::name='%s']} $bindingName]
    array set msgToOper {}
    foreach binding [$wsdlNode selectNodes $bindQuery] {
        array unset msgToOper *
        set portName [lindex [split [$binding  getAttribute type] {:}] end]
        ::log::log debug "\t Processing binding '$bindingName' on port '$portName'"
        set operList [$binding selectNodes w:operation]
        set styleNode [$binding selectNodes d:binding]
        if {![info exists style]} {
            if {[catch {$styleNode getAttribute style} tmpStyle]} {
                set styleNode [$binding selectNodes {w:operation[1]/d:operation}]
                if {$styleNode eq {}} {
                    ##
                    ## This binding is for a SOAP level other than 1.1
                    ##
                    ::log::log debug "Skiping non-SOAP 1.1 binding [$binding asXML]"
                    continue
                }
                set style [$styleNode getAttribute style]
                #puts "Using style for first operation {$style}"
            } else {
                set style $tmpStyle
                #puts "Using style for first binding {$style}"
            }
            if {!($style eq {document} || $style eq {rpc} )} {
                ::log::log debug "Leaving [lindex [info level 0] 0] with error @1"
                return \
                    -code error \
                    -errorcode [list WS CLIENT UNSSTY $style] \
                    "Unsupported calling style: '$style'"
            }

            if {![info exists use]} {
                set use [[$binding selectNodes {w:operation[1]/w:input/d:body}] getAttribute use]
                if {!($style eq {document} && $use eq {literal} ) &&
                    !($style eq {rpc} && $use eq {encoded} )} {
                    ::log::log debug "Leaving [lindex [info level 0] 0] with error @2"
                    return \
                        -code error \
                        -errorcode [list WS CLIENT UNSMODE $use] \
                        "Unsupported mode: $style/$use"
                }
            }
        }

        set style $style/$use

        ##
        ## Process each operation
        ##
        foreach oper $operList {
            set operName [$oper getAttribute name]
            set baseName $operName
            ::log::log debug "\t Processing operation '$operName'"

            ##
            ## Check for overloading
            ##
            set inNode [$oper selectNodes w:input]
            if {[llength $inNode] == 1 && [$inNode hasAttribute name]} {
                set inName [$inNode getAttribute name]
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
                set typeNameList [getTypesForPort $wsdlNode $serviceName $baseName $portName $inName serviceInfo $style]
                dict set serviceInfo operation $operName isClone 0
            }

            #puts "Processing operation $operName"
            set actionNode [$oper selectNodes d:operation]
            if {$actionNode eq {}} {
                ::log:::log debug "Skiping operation with no action [$oper asXML]"
                continue
            }
            dict lappend serviceInfo operList $operName
            dict set serviceInfo operation $operName cloneList {}
            dict set serviceInfo operation $operName cloned 0
            dict set serviceInfo operation $operName name $baseName
            dict set serviceInfo operation $operName style $style







|







3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
                set typeNameList [getTypesForPort $wsdlNode $serviceName $baseName $portName $inName serviceInfo $style]
                dict set serviceInfo operation $operName isClone 0
            }

            #puts "Processing operation $operName"
            set actionNode [$oper selectNodes d:operation]
            if {$actionNode eq {}} {
                ::log::log debug "Skiping operation with no action [$oper asXML]"
                continue
            }
            dict lappend serviceInfo operList $operName
            dict set serviceInfo operation $operName cloneList {}
            dict set serviceInfo operation $operName cloned 0
            dict set serviceInfo operation $operName name $baseName
            dict set serviceInfo operation $operName style $style
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
            ## Get the input headers, if any
            ##
            set soapRequestHeaderList {{}}
            foreach inHeader [$oper selectNodes w:input/d:header] {
                ##set part [$inHeader getAttribute part]
                set tmp [$inHeader getAttribute use]
                if {$tmp ne $use} {
                    ::log:::log debug "Leaving [lindex [info level 0] 0] with error @3"
                    return \
                        -code error \
                        -errorcode [list WS CLIENT MIXUSE $use $tmp] \
                        "Mixed usageage not supported!'"
                }
                set msgName [$inHeader getAttribute message]
                ::log:::log debug [list messageToType $wsdlNode $serviceName $baseName $msgName serviceInfo $style]
                set type [messageToType $wsdlNode $serviceName $baseName $msgName serviceInfo $style]
                lappend soapRequestHeaderList $type
            }
            dict set serviceInfo operation $operName soapRequestHeader $soapRequestHeaderList
            if {![dict exists [dict get $serviceInfo operation $operName] action]} {
                dict set serviceInfo operation $operName action $serviceName
            }

            ##
            ## Get the output header, if one
            ##
            set soapReplyHeaderList {{}}
            foreach outHeader [$oper selectNodes w:output/d:header] {
                ##set part [$outHeader getAttribute part]
                set tmp [$outHeader getAttribute use]
                if {$tmp ne $use} {
                    ::log:::log debug "Leaving [lindex [info level 0] 0] with error @4"
                    return \
                        -code error \
                        -errorcode [list WS CLIENT MIXUSE $use $tmp] \
                        "Mixed usageage not supported!'"
                }
                set messagePath [$outHeader getAttribute message]
                set msgName [lindex [split $messagePath {:}] end]
                ::log:::log debug [list messageToType $wsdlNode $serviceName $baseName $msgName serviceInfo $style]
                set type [messageToType $wsdlNode $serviceName $baseName $msgName serviceInfo $style]
                lappend soapReplyHeaderList $type
            }
            dict set serviceInfo operation $operName soapReplyHeader $soapReplyHeaderList

            ##
            ## Validate that the input and output uses are the same
            ##
            set inUse $use
            set outUse $use
            catch {set inUse [[$oper selectNodes w:input/d:body] getAttribute use]}
            catch {set outUse [[$oper selectNodes w:output/d:body] getAttribute use]}
            foreach tmp [list $inUse $outUse] {
                if {$tmp ne $use} {
                    ::log:::log debug "Leaving [lindex [info level 0] 0] with error @5"
                    return \
                        -code error \
                        -errorcode [list WS CLIENT MIXUSE $use $tmp] \
                        "Mixed usageage not supported!'"
                }
            }
            ::log:::log debug "\t Input/Output types and names are {$typeNameList}"
            foreach {type name} $typeNameList mode {inputs outputs} {
                dict set serviceInfo operation $operName $mode $type
                # also set outputsname which is used to match it as alternate response node name
                dict set serviceInfo operation $operName ${mode}name $name
            }
            set inMessage [dict get $serviceInfo operation $operName inputs]
            if {[dict exists $serviceInfo inputMessages $inMessage] } {







|






|
















|







|














|






|







3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
            ## Get the input headers, if any
            ##
            set soapRequestHeaderList {{}}
            foreach inHeader [$oper selectNodes w:input/d:header] {
                ##set part [$inHeader getAttribute part]
                set tmp [$inHeader getAttribute use]
                if {$tmp ne $use} {
                    ::log::log debug "Leaving [lindex [info level 0] 0] with error @3"
                    return \
                        -code error \
                        -errorcode [list WS CLIENT MIXUSE $use $tmp] \
                        "Mixed usageage not supported!'"
                }
                set msgName [$inHeader getAttribute message]
                ::log::log debug [list messageToType $wsdlNode $serviceName $baseName $msgName serviceInfo $style]
                set type [messageToType $wsdlNode $serviceName $baseName $msgName serviceInfo $style]
                lappend soapRequestHeaderList $type
            }
            dict set serviceInfo operation $operName soapRequestHeader $soapRequestHeaderList
            if {![dict exists [dict get $serviceInfo operation $operName] action]} {
                dict set serviceInfo operation $operName action $serviceName
            }

            ##
            ## Get the output header, if one
            ##
            set soapReplyHeaderList {{}}
            foreach outHeader [$oper selectNodes w:output/d:header] {
                ##set part [$outHeader getAttribute part]
                set tmp [$outHeader getAttribute use]
                if {$tmp ne $use} {
                    ::log::log debug "Leaving [lindex [info level 0] 0] with error @4"
                    return \
                        -code error \
                        -errorcode [list WS CLIENT MIXUSE $use $tmp] \
                        "Mixed usageage not supported!'"
                }
                set messagePath [$outHeader getAttribute message]
                set msgName [lindex [split $messagePath {:}] end]
                ::log::log debug [list messageToType $wsdlNode $serviceName $baseName $msgName serviceInfo $style]
                set type [messageToType $wsdlNode $serviceName $baseName $msgName serviceInfo $style]
                lappend soapReplyHeaderList $type
            }
            dict set serviceInfo operation $operName soapReplyHeader $soapReplyHeaderList

            ##
            ## Validate that the input and output uses are the same
            ##
            set inUse $use
            set outUse $use
            catch {set inUse [[$oper selectNodes w:input/d:body] getAttribute use]}
            catch {set outUse [[$oper selectNodes w:output/d:body] getAttribute use]}
            foreach tmp [list $inUse $outUse] {
                if {$tmp ne $use} {
                    ::log::log debug "Leaving [lindex [info level 0] 0] with error @5"
                    return \
                        -code error \
                        -errorcode [list WS CLIENT MIXUSE $use $tmp] \
                        "Mixed usageage not supported!'"
                }
            }
            ::log::log debug "\t Input/Output types and names are {$typeNameList}"
            foreach {type name} $typeNameList mode {inputs outputs} {
                dict set serviceInfo operation $operName $mode $type
                # also set outputsname which is used to match it as alternate response node name
                dict set serviceInfo operation $operName ${mode}name $name
            }
            set inMessage [dict get $serviceInfo operation $operName inputs]
            if {[dict exists $serviceInfo inputMessages $inMessage] } {
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
                }
            }
            set xns tns1
            dict set serviceInfo operation $operName xns $xns
        }
    }

    ::log:::log debug "Leaving [lindex [info level 0] 0]"
}

###########################################################################
#
# Private Procedure Header - as this procedure is modified, please be sure
#                            that you update this header block. Thanks.
#







|







3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
                }
            }
            set xns tns1
            dict set serviceInfo operation $operName xns $xns
        }
    }

    ::log::log debug "Leaving [lindex [info level 0] 0]"
}

###########################################################################
#
# Private Procedure Header - as this procedure is modified, please be sure
#                            that you update this header block. Thanks.
#
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
# 2.4.3    2017-11-03  H.Oehlmann   If name is not given, set the default
#                                   name of <OP>Request/Response given by the
#                                   WSDL 1.0 standard.
#
#
###########################################################################
proc ::WS::Client::getTypesForPort {wsdlNode serviceName operName portName inName serviceInfoVar style} {
    ::log:::log debug "Entering [info level 0]"
    upvar 1 $serviceInfoVar serviceInfo

    set inType {}
    set outType {}

    #set portQuery [format {w:portType[attribute::name='%s']} $portName]
    #set portNode [lindex [$wsdlNode selectNodes $portQuery] 0]
    if {$inName eq {}} {
        set operQuery [format {w:portType[attribute::name='%s']/w:operation[attribute::name='%s']} \
                        $portName $operName]
    } else {
        set operQuery [format {w:portType[attribute::name='%s']/w:operation[attribute::name='%s']/w:input[attribute::name='%s']/parent::*} \
                        $portName $operName $inName]
    }
    ::log:::log debug "\t operNode query is {$operQuery}"
    set operNode [$wsdlNode selectNodes $operQuery]
    if {$operNode eq {} && $inName ne {}} {
        set operQuery [format {w:portType[attribute::name='%s']/w:operation[attribute::name='%s']} \
                        $portName $operName]
        ::log:::log debug "\t operNode query is {$operQuery}"
        set operNode [$wsdlNode selectNodes $operQuery]
    }
    
    set resList {}
    foreach sel {w:input w:output} defaultNameSuffix {Request Response} {
        set nodeList [$operNode selectNodes $sel]
        if {1 == [llength $nodeList]} {
            set nodeCur [lindex $nodeList 0]
            set msgPath [$nodeCur getAttribute message]
            set msgCur [lindex [split $msgPath {:}] end]







|














|




|


|







3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
# 2.4.3    2017-11-03  H.Oehlmann   If name is not given, set the default
#                                   name of <OP>Request/Response given by the
#                                   WSDL 1.0 standard.
#
#
###########################################################################
proc ::WS::Client::getTypesForPort {wsdlNode serviceName operName portName inName serviceInfoVar style} {
    ::log::log debug "Entering [info level 0]"
    upvar 1 $serviceInfoVar serviceInfo

    set inType {}
    set outType {}

    #set portQuery [format {w:portType[attribute::name='%s']} $portName]
    #set portNode [lindex [$wsdlNode selectNodes $portQuery] 0]
    if {$inName eq {}} {
        set operQuery [format {w:portType[attribute::name='%s']/w:operation[attribute::name='%s']} \
                        $portName $operName]
    } else {
        set operQuery [format {w:portType[attribute::name='%s']/w:operation[attribute::name='%s']/w:input[attribute::name='%s']/parent::*} \
                        $portName $operName $inName]
    }
    ::log::log debug "\t operNode query is {$operQuery}"
    set operNode [$wsdlNode selectNodes $operQuery]
    if {$operNode eq {} && $inName ne {}} {
        set operQuery [format {w:portType[attribute::name='%s']/w:operation[attribute::name='%s']} \
                        $portName $operName]
        ::log::log debug "\t operNode query is {$operQuery}"
        set operNode [$wsdlNode selectNodes $operQuery]
    }

    set resList {}
    foreach sel {w:input w:output} defaultNameSuffix {Request Response} {
        set nodeList [$operNode selectNodes $sel]
        if {1 == [llength $nodeList]} {
            set nodeCur [lindex $nodeList 0]
            set msgPath [$nodeCur getAttribute message]
            set msgCur [lindex [split $msgPath {:}] end]
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
            }
        }
    }

    ##
    ## Return the types
    ##
    ::log:::log debug "Leaving [lindex [info level 0] 0] with $resList"
    return $resList
}

###########################################################################
#
# Private Procedure Header - as this procedure is modified, please be sure
#                            that you update this header block. Thanks.







|







3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
            }
        }
    }

    ##
    ## Return the types
    ##
    ::log::log debug "Leaving [lindex [info level 0] 0] with $resList"
    return $resList
}

###########################################################################
#
# Private Procedure Header - as this procedure is modified, please be sure
#                            that you update this header block. Thanks.
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
# -------  ----------  ----------   -------------------------------------------
#       1  08/06/2006  G.Lester     Initial version
#
#
###########################################################################
proc ::WS::Client::messageToType {wsdlNode serviceName operName msgName serviceInfoVar style} {
    upvar 1 $serviceInfoVar serviceInfo
    ::log:::log debug "Entering [info level 0]"

    #puts "Message to Type $serviceName $operName $msgName"

    set msgQuery [format {w:message[attribute::name='%s']} $msgName]
    set msg [$wsdlNode selectNodes $msgQuery]
    if {$msg eq {} &&
        [llength [set msgNameList [split $msgName {:}]]] > 1} {







|







3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
# -------  ----------  ----------   -------------------------------------------
#       1  08/06/2006  G.Lester     Initial version
#
#
###########################################################################
proc ::WS::Client::messageToType {wsdlNode serviceName operName msgName serviceInfoVar style} {
    upvar 1 $serviceInfoVar serviceInfo
    ::log::log debug "Entering [info level 0]"

    #puts "Message to Type $serviceName $operName $msgName"

    set msgQuery [format {w:message[attribute::name='%s']} $msgName]
    set msg [$wsdlNode selectNodes $msgQuery]
    if {$msg eq {} &&
        [llength [set msgNameList [split $msgName {:}]]] > 1} {
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
            -errorcode [list WS CLIENT BADMSGSEC $msgName] \
            "Can not find message '$msgName'"
    }
    switch -exact -- $style {
        document/literal {
            set partNode [$msg selectNodes w:part]
            set partNodeCount [llength $partNode]
            ::log:::log debug  "partNodeCount = {$partNodeCount}"
            if {$partNodeCount == 1} {
                if {[$partNode hasAttribute element]} {
                    set type [::WS::Utils::getQualifiedType $serviceInfo [$partNode getAttribute element] tns1]
                }
            }
            if {($partNodeCount > 1) || ![info exist type]} {
                set tmpType {}







|







3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
            -errorcode [list WS CLIENT BADMSGSEC $msgName] \
            "Can not find message '$msgName'"
    }
    switch -exact -- $style {
        document/literal {
            set partNode [$msg selectNodes w:part]
            set partNodeCount [llength $partNode]
            ::log::log debug  "partNodeCount = {$partNodeCount}"
            if {$partNodeCount == 1} {
                if {[$partNode hasAttribute element]} {
                    set type [::WS::Utils::getQualifiedType $serviceInfo [$partNode getAttribute element] tns1]
                }
            }
            if {($partNodeCount > 1) || ![info exist type]} {
                set tmpType {}
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
                "Unknown style combination $style"
        }
    }

    ##
    ## Return the type name
    ##
    ::log:::log debug "Leaving [lindex [info level 0] 0] with {$type}"
    return $type
}

#---------------------------------------
#---------------------------------------

###########################################################################







|







3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
                "Unknown style combination $style"
        }
    }

    ##
    ## Return the type name
    ##
    ::log::log debug "Leaving [lindex [info level 0] 0] with {$type}"
    return $type
}

#---------------------------------------
#---------------------------------------

###########################################################################
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
    }
    if {![dict exists $serviceInfo object $objectName operation $operationName]} {
        return \
            -code error \
            -errorcode [list WS CLIENT UNKOPER [list $serviceName $objectName $operationName]] \
            "Unknown operation '$operationName' for object '$objectName' of service '$serviceName'"
    }
    
    ##
    ## build call query
    ##
    
    if {$location ne {}} {
        set url $location
    } else {
        set url [dict get $serviceInfo object $objectName location]
    }
    SaveAndSetOptions $serviceName
    if {[catch {set query [buildRestCallquery $serviceName $objectName $operationName $url $argList]} err]} {
        RestoreSavedOptions $serviceName
        return -code error -errorcode $::errorCode -errorinfo $::errorInfo $err
    } else {
        RestoreSavedOptions $serviceName
    }
    if {[dict exists $serviceInfo headers]} {
        set headers [concat $headers [dict get $serviceInfo headers]]
    }
    
    ##
    ## do http call
    ##
    
    if {[llength $headers]} {
        set body [::WS::Utils::geturl_fetchbody $url -query $query -type [dict get $serviceInfo contentType] -headers $headers]
    } else {
        set body [::WS::Utils::geturl_fetchbody $url -query $query -type [dict get $serviceInfo contentType]]
    }

    ::log::logsubst debug {Leaving ::WS::Client::DoRawRestCall with {$body}}







|



|















|



|







3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
    }
    if {![dict exists $serviceInfo object $objectName operation $operationName]} {
        return \
            -code error \
            -errorcode [list WS CLIENT UNKOPER [list $serviceName $objectName $operationName]] \
            "Unknown operation '$operationName' for object '$objectName' of service '$serviceName'"
    }

    ##
    ## build call query
    ##

    if {$location ne {}} {
        set url $location
    } else {
        set url [dict get $serviceInfo object $objectName location]
    }
    SaveAndSetOptions $serviceName
    if {[catch {set query [buildRestCallquery $serviceName $objectName $operationName $url $argList]} err]} {
        RestoreSavedOptions $serviceName
        return -code error -errorcode $::errorCode -errorinfo $::errorInfo $err
    } else {
        RestoreSavedOptions $serviceName
    }
    if {[dict exists $serviceInfo headers]} {
        set headers [concat $headers [dict get $serviceInfo headers]]
    }

    ##
    ## do http call
    ##

    if {[llength $headers]} {
        set body [::WS::Utils::geturl_fetchbody $url -query $query -type [dict get $serviceInfo contentType] -headers $headers]
    } else {
        set body [::WS::Utils::geturl_fetchbody $url -query $query -type [dict get $serviceInfo contentType]]
    }

    ::log::logsubst debug {Leaving ::WS::Client::DoRawRestCall with {$body}}
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
            "Unknown operation '$operationName' for object '$objectName' of service '$serviceName'"
    }
    if {$location ne {}} {
        set url $location
    } else {
        set url [dict get $serviceInfo object $objectName location]
    }
    
    ##
    ## build call query
    ##
    
    SaveAndSetOptions $serviceName
    if {[catch {set query [buildRestCallquery $serviceName $objectName $operationName $url $argList]} err]} {
        RestoreSavedOptions $serviceName
        return -code error -errorcode $::errorCode -errorinfo $::errorInfo $err
    }
    RestoreSavedOptions $serviceName
    
    ##
    ## Do http call
    ##
    
    if {[dict exists $serviceInfo headers]} {
        set headers [concat $headers [dict get $serviceInfo headers]]
    }
    if {[llength $headers]} {
        set body [::WS::Utils::geturl_fetchbody $url -query $query -type [dict get $serviceInfo contentType] -headers $headers]
    } else {
        set body [::WS::Utils::geturl_fetchbody $url -query $query -type [dict get $serviceInfo contentType]]
    }

    ##
    ## Parse results
    ##
    
    SaveAndSetOptions $serviceName
    if {[catch {
        parseRestResults $serviceName $objectName $operationName $body
    } results]} {
        RestoreSavedOptions $serviceName
        ::log::log debug "Leaving (error) ::WS::Client::DoRestCall"
        return -code error $results







|



|






|



|












|







3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
            "Unknown operation '$operationName' for object '$objectName' of service '$serviceName'"
    }
    if {$location ne {}} {
        set url $location
    } else {
        set url [dict get $serviceInfo object $objectName location]
    }

    ##
    ## build call query
    ##

    SaveAndSetOptions $serviceName
    if {[catch {set query [buildRestCallquery $serviceName $objectName $operationName $url $argList]} err]} {
        RestoreSavedOptions $serviceName
        return -code error -errorcode $::errorCode -errorinfo $::errorInfo $err
    }
    RestoreSavedOptions $serviceName

    ##
    ## Do http call
    ##

    if {[dict exists $serviceInfo headers]} {
        set headers [concat $headers [dict get $serviceInfo headers]]
    }
    if {[llength $headers]} {
        set body [::WS::Utils::geturl_fetchbody $url -query $query -type [dict get $serviceInfo contentType] -headers $headers]
    } else {
        set body [::WS::Utils::geturl_fetchbody $url -query $query -type [dict get $serviceInfo contentType]]
    }

    ##
    ## Parse results
    ##

    SaveAndSetOptions $serviceName
    if {[catch {
        parseRestResults $serviceName $objectName $operationName $body
    } results]} {
        RestoreSavedOptions $serviceName
        ::log::log debug "Leaving (error) ::WS::Client::DoRestCall"
        return -code error $results
Changes to assets/tclws2.6.0/ServerSide.tcl.
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
    array set serviceData $serviceInfo
    set doc [yajl create #auto -beautify $serviceData(-beautifyJson)]

    $doc map_open

    $doc string operations array_open
    ::log::log debug "\tDisplay Operations (json)"
        
    foreach oper [lsort -dictionary [dict get $procInfo $service operationList]] {
        $doc map_open

        # operation name
        $doc string name string $oper

        # description
        set description [dict get $procInfo $service op$oper docs]
        $doc string description string $description

        # parameters
        if {[llength [dict get $procInfo $service op$oper argOrder]]} {
            $doc string inputs array_open
            
            foreach arg [dict get $procInfo $service op$oper argOrder] {
                ::log::logsubst debug {\t\t\tDisplaying '$arg'}
                if {[dict exists $procInfo $service op$oper argList $arg comment]} {
                    set comment [dict get $procInfo $service op$oper argList $arg comment]
                } else {
                    set comment {}
                }

                set type [dict get $procInfo $service op$oper argList $arg type]
                                
                $doc map_open string name string $arg string type string $type string comment string $comment map_close
            }

            $doc array_close
        } else {
            $doc string inputs array_open array_close
        }
        
        $doc string returns map_open

        if {[dict exists $procInfo $service op$oper returnInfo comment]} {
            set comment [dict get $procInfo $service op$oper returnInfo comment]
        } else {
            set comment {}
        }

        set type [dict get $procInfo $service op$oper returnInfo type]
                
        $doc string comment string $comment string type string $type
        $doc map_close
        
        $doc map_close
    }

    $doc array_close

    ::log::log debug "\tDisplay custom types"
    $doc string types array_open
    set localTypeInfo [::WS::Utils::GetServiceTypeDef Server $service]
    foreach type [lsort -dictionary [dict keys $localTypeInfo]] {
        ::log::logsubst debug {\t\tDisplaying '$type'}

        $doc map_open
        $doc string name string $type
        $doc string fields array_open
        
        set typeDetails [dict get $localTypeInfo $type definition]
        foreach part [lsort -dictionary [dict keys $typeDetails]] {
            ::log::logsubst debug {\t\t\tDisplaying '$part'}
            set subType [dict get $typeDetails $part type]
            set comment {}
            if {[dict exists $typeDetails $part comment]} {
                set comment [dict get $typeDetails $part comment]
            }
            $doc map_open string field string $part string type string $subType string comment string $comment map_close
        }

        $doc array_close
        $doc map_close
    }

    $doc array_close
        
    $doc map_close

    set contentType "application/json; charset=UTF-8"
    headers type $contentType
    headers numeric 200
    puts [$doc get]
    $doc delete







|













|









|







|









|


|














|
















|







906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
    array set serviceData $serviceInfo
    set doc [yajl create #auto -beautify $serviceData(-beautifyJson)]

    $doc map_open

    $doc string operations array_open
    ::log::log debug "\tDisplay Operations (json)"

    foreach oper [lsort -dictionary [dict get $procInfo $service operationList]] {
        $doc map_open

        # operation name
        $doc string name string $oper

        # description
        set description [dict get $procInfo $service op$oper docs]
        $doc string description string $description

        # parameters
        if {[llength [dict get $procInfo $service op$oper argOrder]]} {
            $doc string inputs array_open

            foreach arg [dict get $procInfo $service op$oper argOrder] {
                ::log::logsubst debug {\t\t\tDisplaying '$arg'}
                if {[dict exists $procInfo $service op$oper argList $arg comment]} {
                    set comment [dict get $procInfo $service op$oper argList $arg comment]
                } else {
                    set comment {}
                }

                set type [dict get $procInfo $service op$oper argList $arg type]

                $doc map_open string name string $arg string type string $type string comment string $comment map_close
            }

            $doc array_close
        } else {
            $doc string inputs array_open array_close
        }

        $doc string returns map_open

        if {[dict exists $procInfo $service op$oper returnInfo comment]} {
            set comment [dict get $procInfo $service op$oper returnInfo comment]
        } else {
            set comment {}
        }

        set type [dict get $procInfo $service op$oper returnInfo type]

        $doc string comment string $comment string type string $type
        $doc map_close

        $doc map_close
    }

    $doc array_close

    ::log::log debug "\tDisplay custom types"
    $doc string types array_open
    set localTypeInfo [::WS::Utils::GetServiceTypeDef Server $service]
    foreach type [lsort -dictionary [dict keys $localTypeInfo]] {
        ::log::logsubst debug {\t\tDisplaying '$type'}

        $doc map_open
        $doc string name string $type
        $doc string fields array_open

        set typeDetails [dict get $localTypeInfo $type definition]
        foreach part [lsort -dictionary [dict keys $typeDetails]] {
            ::log::logsubst debug {\t\t\tDisplaying '$part'}
            set subType [dict get $typeDetails $part type]
            set comment {}
            if {[dict exists $typeDetails $part comment]} {
                set comment [dict get $typeDetails $part comment]
            }
            $doc map_open string field string $part string type string $subType string comment string $comment map_close
        }

        $doc array_close
        $doc map_close
    }

    $doc array_close

    $doc map_close

    set contentType "application/json; charset=UTF-8"
    headers type $contentType
    headers numeric 200
    puts [$doc get]
    $doc delete
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
            ::log::logsubst debug {$doc selectNodesNamespaces \
                    [list ENV http://schemas.xmlsoap.org/soap/envelope/ \
                    $service http://$serviceInfo(-host)$serviceInfo(-prefix)]}
            $doc selectNodesNamespaces \
                [list ENV http://schemas.xmlsoap.org/soap/envelope/ \
                     $service http://$serviceInfo(-host)$serviceInfo(-prefix)]
            $doc documentElement rootNode
            
            # extract the name of the method
            set top [$rootNode selectNodes /ENV:Envelope/ENV:Body/*]
            catch {$top localName} requestMessage
            set legacyRpcMode 0
            if {$requestMessage == ""} {
                # older RPC/Encoded clients need to try nodeName instead.
                # Python pySoap needs this.







|







1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
            ::log::logsubst debug {$doc selectNodesNamespaces \
                    [list ENV http://schemas.xmlsoap.org/soap/envelope/ \
                    $service http://$serviceInfo(-host)$serviceInfo(-prefix)]}
            $doc selectNodesNamespaces \
                [list ENV http://schemas.xmlsoap.org/soap/envelope/ \
                     $service http://$serviceInfo(-host)$serviceInfo(-prefix)]
            $doc documentElement rootNode

            # extract the name of the method
            set top [$rootNode selectNodes /ENV:Envelope/ENV:Body/*]
            catch {$top localName} requestMessage
            set legacyRpcMode 0
            if {$requestMessage == ""} {
                # older RPC/Encoded clients need to try nodeName instead.
                # Python pySoap needs this.
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
                "xmlns:SOAP-ENC" "http://schemas.xmlsoap.org/soap/encoding/"
            $env appendChild [$doc createElement "SOAP-ENV:Body" bod]
            $bod appendChild [$doc createElement "SOAP-ENV:Fault" flt]
            $flt appendChild [$doc createElement "faultcode" fcd]
            $fcd appendChild [$doc createTextNode $faultcode]
            $flt appendChild [$doc createElement "faultstring" fst]
            $fst appendChild [$doc createTextNode $faultstring]
            
            if { $detail != {} } {
                $flt appendChild [$doc createElement "SOAP-ENV:detail" dtl0]
                $dtl0 appendChild [$doc createElement "e:errorInfo" dtl]
                $dtl setAttribute "xmlns:e" "urn:TclErrorInfo"
                
                foreach {detailName detailInfo} $detail {
                    if {!$includeTrace && $detailName == "stackTrace"} {
                        continue
                    }
                    $dtl appendChild [$doc createElement $detailName err]
                    $err appendChild [$doc createTextNode $detailInfo]
                }
            }
            
            # serialize the DOM document and return the XML text
            append response  \
                {<?xml version="1.0"  encoding="utf-8"?>} \
                "\n" \
                [$doc asXML -indent none -doctypeDeclaration 0]
            $doc delete
        }







|




|








|







1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
                "xmlns:SOAP-ENC" "http://schemas.xmlsoap.org/soap/encoding/"
            $env appendChild [$doc createElement "SOAP-ENV:Body" bod]
            $bod appendChild [$doc createElement "SOAP-ENV:Fault" flt]
            $flt appendChild [$doc createElement "faultcode" fcd]
            $fcd appendChild [$doc createTextNode $faultcode]
            $flt appendChild [$doc createElement "faultstring" fst]
            $fst appendChild [$doc createTextNode $faultstring]

            if { $detail != {} } {
                $flt appendChild [$doc createElement "SOAP-ENV:detail" dtl0]
                $dtl0 appendChild [$doc createElement "e:errorInfo" dtl]
                $dtl setAttribute "xmlns:e" "urn:TclErrorInfo"

                foreach {detailName detailInfo} $detail {
                    if {!$includeTrace && $detailName == "stackTrace"} {
                        continue
                    }
                    $dtl appendChild [$doc createElement $detailName err]
                    $err appendChild [$doc createTextNode $detailInfo]
                }
            }

            # serialize the DOM document and return the XML text
            append response  \
                {<?xml version="1.0"  encoding="utf-8"?>} \
                "\n" \
                [$doc asXML -indent none -doctypeDeclaration 0]
            $doc delete
        }
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
                                     $serviceData(-host) \
                                     $serviceName \
                                     $operation]
                append replaceText "\n"
            } else {
                set replaceText {}
            }
            
            dom createDocument "SOAP-ENV:Envelope" doc
            $doc documentElement env
            $env setAttribute  \
                "xmlns:SOAP-ENV" "http://schemas.xmlsoap.org/soap/envelope/" \
                "xmlns:xsi"      "http://www.w3.org/1999/XMLSchema-instance" \
                "xmlns:xsd"      "http://www.w3.org/1999/XMLSchema" \
                "xmlns:SOAP-ENC" "http://schemas.xmlsoap.org/soap/encoding/" \







|







1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
                                     $serviceData(-host) \
                                     $serviceName \
                                     $operation]
                append replaceText "\n"
            } else {
                set replaceText {}
            }

            dom createDocument "SOAP-ENV:Envelope" doc
            $doc documentElement env
            $env setAttribute  \
                "xmlns:SOAP-ENV" "http://schemas.xmlsoap.org/soap/envelope/" \
                "xmlns:xsi"      "http://www.w3.org/1999/XMLSchema-instance" \
                "xmlns:xsd"      "http://www.w3.org/1999/XMLSchema" \
                "xmlns:SOAP-ENC" "http://schemas.xmlsoap.org/soap/encoding/" \
Changes to assets/tclws2.6.0/Utilities.tcl.
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
                                set nodeFound 1
                                set partList [concat $partList $tmp]
                            } elseif {[llength $tmp]} {
                                ##
                                ## Found extension, but it is an empty type
                                ##
                            } else {
                                ::log:::log debug  "Unknown extension!"
                                return
                            }
                        }
                        default {
                            ##
                            ## Placed here to shut up tclchecker
                            ##







|







3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
                                set nodeFound 1
                                set partList [concat $partList $tmp]
                            } elseif {[llength $tmp]} {
                                ##
                                ## Found extension, but it is an empty type
                                ##
                            } else {
                                ::log::log debug  "Unknown extension!"
                                return
                            }
                        }
                        default {
                            ##
                            ## Placed here to shut up tclchecker
                            ##
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
            }
        }
    }
    ::log::logsubst debug {at end of foreach {$typeName} with {$partList}}
    if {[llength $partList] || $isAbstractType} {
        #dict set results types $tns:$typeName $partList
        dict set results types $typeName $partList
        ::log:::logsubst debug  {Defining $typeName as '$partList'}
        ##
        ## Add complex type definition, if:
        ##   *  there is a part list
        ##   *  or it is an abstract type announced as complex
        ##      (see xml snipped above about [Bug 584bfb77])
        ##      -> will set dict typeInfo client $service tns1:envelope {
        ##          definition {} xns tns1 abstract true}







|







3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
            }
        }
    }
    ::log::logsubst debug {at end of foreach {$typeName} with {$partList}}
    if {[llength $partList] || $isAbstractType} {
        #dict set results types $tns:$typeName $partList
        dict set results types $typeName $partList
        ::log::logsubst debug  {Defining $typeName as '$partList'}
        ##
        ## Add complex type definition, if:
        ##   *  there is a part list
        ##   *  or it is an abstract type announced as complex
        ##      (see xml snipped above about [Bug 584bfb77])
        ##      -> will set dict typeInfo client $service tns1:envelope {
        ##          definition {} xns tns1 abstract true}
Added assets/topcua0.1/pkgIndex.tcl.








>
>
>
>
1
2
3
4
package ifneeded topcua 0.1 [subst {
    load libtopcua[info sharedlibextension] topcua
    source [list [file join $dir topcua.tcl]]
}]
Added assets/topcua0.1/topcua.tcl.




































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# topcua.tcl --
#
# Library functions of a proof of concept Tcl binding to the
# open62541 OPC UA library (client only).
#
# Copyright (c) 2018 Christian Werner <chw at ch minus werner dot de>
#
# See the file "license.terms" for information on usage and redistribution of
# this file, and for a DISCLAIMER OF ALL WARRANTIES.

namespace eval ::opcua {

    proc _walk {client nodeid browsename dispname nodeclass
		    refnodeid typenodeid result {level 0} {path {}}} {
	if {$level > 32} return
	if {[lsearch -exact $path $nodeid] >= 0} return
	upvar $result ret
	lappend ret $level $nodeid $browsename $dispname \
	    $nodeclass $refnodeid $typenodeid
	if {$nodeclass eq "Variable"} return
	incr level
	set path [concat $path $nodeid]
	foreach {n b d c r t} [lsort -stride 6 -index 1 \
		[browse $client $nodeid Forward \
		    [reftype HierarchicalReferences]]] {
	    if {$b eq "FolderType"} continue
	    _walk $client $n $b $d $c $r $t ret $level $path
	}
    }

    # Return a list of the address space resembling the
    # tree view of UAExpert. List layout adds level column
    # to "opcua::browse ..." list:
    #
    #   level        - 0 is Root, 1 is Objects etc.
    #   nodeid       - the node identifier, e.g. "ns=1;i=99"
    #   browsename   - name of node for browsing
    #   dispname     - name of node for display
    #   nodeclass    - class of node, e.g. "Variable"
    #   refnodeid    - reference node identifer
    #   typenodeid   - type node identifier

    proc tree {client} {
	set ret {}
	_walk $client i=84 Root Root Object i=35 i=61 ret
	return $ret
    }

    # Similar to tree, but make path like layout
    # as in "browsepath nodeid nodeclasspath refnodeid typenodeid ..."

    proc ptree {client} {
	set ret {}
	set pp {}
	set cc {}
	set last_b {}
	set last_c {}
	set i -1
	foreach {l n b d c r t} [tree $client] {
	    if {[scan $n "ns=%d;%s" ns rest] == 2} {
		set nsb ${ns}:$b
	    } else {
		set nsb $b
	    }
	    if {$l > $i} {
		set i $l
		lappend pp $last_b
		lappend cc $last_c
	    } elseif {$l < $i} {
		set diff [expr {$i - $l}]
		set i $l
		set pp [lrange $pp 0 end-$diff]
		set cc [lrange $cc 0 end-$diff]
	    }
	    set last_b $nsb
	    set last_c $c
	    set br $pp
	    lappend br $nsb
	    set cl $cc
	    lappend cl $c
	    lappend ret [join $br "/"] $n [join $cl "/"] $r $t
	}
	return $ret
    }

    # Return a list of child nodes given parent

    proc children {client nodeid} {
	set ret {}
	foreach {n b d c r t} [browse $client $nodeid Forward \
		[reftype HierarchicalReferences]] {
	    lappend ret $n
	}
	return $ret
    }

    # Return the parent node given child

    proc parent {client nodeid} {
	set ret {}
	foreach {n b d c r t} [browse $client $nodeid Inverse \
		[reftype HierarchicalReferences]] {
	    set ret $n
	    # only the first item
	    break
	}
	return $ret
    }

    # Generate stubs for methods in sub-namespace derived from
    # client name. Argument strip is cut off from the begin
    # of browsepaths, all following arguments are glob patterns
    # for matching browsepaths.
    #
    # TBD: find out argument types of generated procs.

    proc genstubs {client strip args} {
	namespace eval ::opcua::$client {}
	set all [expr {[llength $args] == 0}]
	foreach {b n c r t} [ptree $client] {
	    if {[string first $strip $b] != 0} {
		continue
	    }
	    if {![string match "*Object/Method" $c]} {
		continue
	    }
	    if {$all} {
		set found 1
	    } else {
		set found 0
		foreach pat $args {
		    if {[string match $pat $b]} {
			set found 1
			break
		    }
		}
	    }
	    if {$found} {
		set b [string range $b [string length $strip] end]
		set o [parent $client $n]
		set o [list $o]		;# beware of semicolon
		set n [list $n]		;# beware of semicolon
		eval [subst -nocommands {
		    proc ::opcua::${client}::${b} args {
			tailcall ::opcua::call $client $o $n {*}\$args
		    }}]
	    }
	}
    }

    # Make some procs visible in opcua ensemble

    proc _init {} {
	set cmds [namespace ensemble configure ::opcua -subcommands]
	lappend cmds tree ptree children parent genstubs
	namespace ensemble configure ::opcua -subcommands $cmds
    }

    _init
    rename _init {}

}
Changes to jni/sdl2tk/generic/tkConfig.c.
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
 *----------------------------------------------------------------------
 */

static int
ObjectIsEmpty(
    Tcl_Obj *objPtr)		/* Object to test. May be NULL. */
{
    int length;

    if (objPtr == NULL) {
	return 1;
    }
    if (objPtr->bytes != NULL) {
	return (objPtr->length == 0);
    }
    (void)Tcl_GetStringFromObj(objPtr, &length);
    return (length == 0);
}

/*
 *----------------------------------------------------------------------
 *
 * GetOption --
 *







<
<



|
|

<
|







933
934
935
936
937
938
939


940
941
942
943
944
945

946
947
948
949
950
951
952
953
 *----------------------------------------------------------------------
 */

static int
ObjectIsEmpty(
    Tcl_Obj *objPtr)		/* Object to test. May be NULL. */
{


    if (objPtr == NULL) {
	return 1;
    }
    if (objPtr->bytes == NULL) {
	Tcl_GetString(objPtr);
    }

    return (objPtr->length == 0);
}

/*
 *----------------------------------------------------------------------
 *
 * GetOption --
 *
Changes to jni/sdl2tk/generic/tkMenu.c.
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
     * Tk_ConfigureWidget, such as special processing for defaults, sizing
     * strings, graphics contexts, etc.
     */

    if (mePtr->labelPtr == NULL) {
	mePtr->labelLength = 0;
    } else {
	(void)Tcl_GetStringFromObj(mePtr->labelPtr, &mePtr->labelLength);
    }
    if (mePtr->accelPtr == NULL) {
	mePtr->accelLength = 0;
    } else {
	(void)Tcl_GetStringFromObj(mePtr->accelPtr, &mePtr->accelLength);
    }

    /*
     * If this is a cascade entry, the platform-specific data of the child
     * menu has to be updated. Also, the links that point to parents and
     * cascades have to be updated.
     */







|




|







1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
     * Tk_ConfigureWidget, such as special processing for defaults, sizing
     * strings, graphics contexts, etc.
     */

    if (mePtr->labelPtr == NULL) {
	mePtr->labelLength = 0;
    } else {
	Tcl_GetStringFromObj(mePtr->labelPtr, &mePtr->labelLength);
    }
    if (mePtr->accelPtr == NULL) {
	mePtr->accelLength = 0;
    } else {
	Tcl_GetStringFromObj(mePtr->accelPtr, &mePtr->accelLength);
    }

    /*
     * If this is a cascade entry, the platform-specific data of the child
     * menu has to be updated. Also, the links that point to parents and
     * cascades have to be updated.
     */
Changes to jni/sdl2tk/generic/tkObj.c.
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720

static void
UpdateStringOfMM(
    register Tcl_Obj *objPtr)   /* pixel obj with string rep to update. */
{
    MMRep *mmPtr;
    char buffer[TCL_DOUBLE_SPACE];
    register int len;

    mmPtr = objPtr->internalRep.twoPtrValue.ptr1;
    /* assert( mmPtr->units == -1 && objPtr->bytes == NULL ); */
    if ((mmPtr->units != -1) || (objPtr->bytes != NULL)) {
	Tcl_Panic("UpdateStringOfMM: false precondition");
    }

    Tcl_PrintDouble(NULL, mmPtr->value, buffer);
    len = (int)strlen(buffer);

    objPtr->bytes = ckalloc(len + 1);
    strcpy(objPtr->bytes, buffer);
    objPtr->length = len;
}

/*







|








|







697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720

static void
UpdateStringOfMM(
    register Tcl_Obj *objPtr)   /* pixel obj with string rep to update. */
{
    MMRep *mmPtr;
    char buffer[TCL_DOUBLE_SPACE];
    size_t len;

    mmPtr = objPtr->internalRep.twoPtrValue.ptr1;
    /* assert( mmPtr->units == -1 && objPtr->bytes == NULL ); */
    if ((mmPtr->units != -1) || (objPtr->bytes != NULL)) {
	Tcl_Panic("UpdateStringOfMM: false precondition");
    }

    Tcl_PrintDouble(NULL, mmPtr->value, buffer);
    len = strlen(buffer);

    objPtr->bytes = ckalloc(len + 1);
    strcpy(objPtr->bytes, buffer);
    objPtr->length = len;
}

/*
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
    const Tcl_ObjType *typePtr;
    WindowRep *winPtr;

    /*
     * Free the old internalRep before setting the new one.
     */

    (void)Tcl_GetString(objPtr);
    typePtr = objPtr->typePtr;
    if ((typePtr != NULL) && (typePtr->freeIntRepProc != NULL)) {
	typePtr->freeIntRepProc(objPtr);
    }

    winPtr = ckalloc(sizeof(WindowRep));
    winPtr->tkwin = NULL;







|







921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
    const Tcl_ObjType *typePtr;
    WindowRep *winPtr;

    /*
     * Free the old internalRep before setting the new one.
     */

    Tcl_GetString(objPtr);
    typePtr = objPtr->typePtr;
    if ((typePtr != NULL) && (typePtr->freeIntRepProc != NULL)) {
	typePtr->freeIntRepProc(objPtr);
    }

    winPtr = ckalloc(sizeof(WindowRep));
    winPtr->tkwin = NULL;
Changes to jni/sdl2tk/generic/tkOldTest.c.
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
    }

    timPtr = ckalloc(sizeof(TImageMaster));
    timPtr->master = master;
    timPtr->interp = interp;
    timPtr->width = 30;
    timPtr->height = 15;
    timPtr->imageName = ckalloc((unsigned) (strlen(name) + 1));
    strcpy(timPtr->imageName, name);
    timPtr->varName = ckalloc((unsigned) (strlen(varName) + 1));
    strcpy(timPtr->varName, varName);
    Tcl_CreateObjCommand(interp, name, ImageObjCmd, timPtr, NULL);
    *clientDataPtr = timPtr;
    Tk_ImageChanged(master, 0, 0, 30, 15, 30, 15);
    return TCL_OK;
}








|

|







168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
    }

    timPtr = ckalloc(sizeof(TImageMaster));
    timPtr->master = master;
    timPtr->interp = interp;
    timPtr->width = 30;
    timPtr->height = 15;
    timPtr->imageName = ckalloc(strlen(name) + 1);
    strcpy(timPtr->imageName, name);
    timPtr->varName = ckalloc(strlen(varName) + 1);
    strcpy(timPtr->varName, varName);
    Tcl_CreateObjCommand(interp, name, ImageObjCmd, timPtr, NULL);
    *clientDataPtr = timPtr;
    Tk_ImageChanged(master, 0, 0, 30, 15, 30, 15);
    return TCL_OK;
}

Changes to jni/sdl2tk/generic/tkPanedWindow.c.
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
 *----------------------------------------------------------------------
 */

static int
ObjectIsEmpty(
    Tcl_Obj *objPtr)		/* Object to test. May be NULL. */
{
    int length;

    if (objPtr == NULL) {
	return 1;
    }
    if (objPtr->bytes != NULL) {
	return (objPtr->length == 0);
    }
    (void)Tcl_GetStringFromObj(objPtr, &length);
    return (length == 0);
}

/*
 *----------------------------------------------------------------------
 *
 * ComputeInternalPointer --
 *







<
<



|
|

<
|







2988
2989
2990
2991
2992
2993
2994


2995
2996
2997
2998
2999
3000

3001
3002
3003
3004
3005
3006
3007
3008
 *----------------------------------------------------------------------
 */

static int
ObjectIsEmpty(
    Tcl_Obj *objPtr)		/* Object to test. May be NULL. */
{


    if (objPtr == NULL) {
	return 1;
    }
    if (objPtr->bytes == NULL) {
	Tcl_GetString(objPtr);
    }

    return (objPtr->length == 0);
}

/*
 *----------------------------------------------------------------------
 *
 * ComputeInternalPointer --
 *
Changes to jni/sdl2tk/generic/tkText.c.
860
861
862
863
864
865
866
867

868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
	indexToPtr = TkTextGetIndexFromObj(interp, textPtr, objv[objc-1]);
	if (indexToPtr == NULL) {
	    result = TCL_ERROR;
	    goto done;
	}

	for (i = 2; i < objc-2; i++) {
	    int value, length;

	    const char *option = Tcl_GetString(objv[i]);
	    char c;

	    length = objv[i]->length;
	    if (length < 2 || option[0] != '-') {
		goto badOption;
	    }
	    c = option[1];
	    if (c == 'c' && !strncmp("-chars", option, (unsigned) length)) {
		value = CountIndices(textPtr, indexFromPtr, indexToPtr,
			COUNT_CHARS);
	    } else if (c == 'd' && (length > 8)
		    && !strncmp("-displaychars", option, (unsigned) length)) {
		value = CountIndices(textPtr, indexFromPtr, indexToPtr,
			COUNT_DISPLAY_CHARS);
	    } else if (c == 'd' && (length > 8)
		    && !strncmp("-displayindices", option,(unsigned)length)) {
		value = CountIndices(textPtr, indexFromPtr, indexToPtr,
			COUNT_DISPLAY_INDICES);
	    } else if (c == 'd' && (length > 8)
		    && !strncmp("-displaylines", option, (unsigned) length)) {
		TkTextLine *fromPtr, *lastPtr;
		TkTextIndex index, index2;

		int compare = TkTextIndexCmp(indexFromPtr, indexToPtr);
		value = 0;

		if (compare == 0) {







|
>








|



|



|



|







860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
	indexToPtr = TkTextGetIndexFromObj(interp, textPtr, objv[objc-1]);
	if (indexToPtr == NULL) {
	    result = TCL_ERROR;
	    goto done;
	}

	for (i = 2; i < objc-2; i++) {
	    int value;
	    size_t length;
	    const char *option = Tcl_GetString(objv[i]);
	    char c;

	    length = objv[i]->length;
	    if (length < 2 || option[0] != '-') {
		goto badOption;
	    }
	    c = option[1];
	    if (c == 'c' && !strncmp("-chars", option, length)) {
		value = CountIndices(textPtr, indexFromPtr, indexToPtr,
			COUNT_CHARS);
	    } else if (c == 'd' && (length > 8)
		    && !strncmp("-displaychars", option, length)) {
		value = CountIndices(textPtr, indexFromPtr, indexToPtr,
			COUNT_DISPLAY_CHARS);
	    } else if (c == 'd' && (length > 8)
		    && !strncmp("-displayindices", option,length)) {
		value = CountIndices(textPtr, indexFromPtr, indexToPtr,
			COUNT_DISPLAY_INDICES);
	    } else if (c == 'd' && (length > 8)
		    && !strncmp("-displaylines", option, length)) {
		TkTextLine *fromPtr, *lastPtr;
		TkTextIndex index, index2;

		int compare = TkTextIndexCmp(indexFromPtr, indexToPtr);
		value = 0;

		if (compare == 0) {
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
		    }
		}

		if (compare > 0) {
		    value = -value;
		}
	    } else if (c == 'i'
		    && !strncmp("-indices", option, (unsigned) length)) {
		value = CountIndices(textPtr, indexFromPtr, indexToPtr,
			COUNT_INDICES);
	    } else if (c == 'l'
		    && !strncmp("-lines", option, (unsigned) length)) {
		value = TkBTreeLinesTo(textPtr, indexToPtr->linePtr)
			- TkBTreeLinesTo(textPtr, indexFromPtr->linePtr);
	    } else if (c == 'u'
		    && !strncmp("-update", option, (unsigned) length)) {
		update = 1;
		continue;
	    } else if (c == 'x'
		    && !strncmp("-xpixels", option, (unsigned) length)) {
		int x1, x2;
		TkTextIndex index;

		index = *indexFromPtr;
		TkTextFindDisplayLineEnd(textPtr, &index, 0, &x1);
		index = *indexToPtr;
		TkTextFindDisplayLineEnd(textPtr, &index, 0, &x2);
		value = x2 - x1;
	    } else if (c == 'y'
		    && !strncmp("-ypixels", option, (unsigned) length)) {
		if (update) {
		    TkTextUpdateLineMetrics(textPtr,
			    TkBTreeLinesTo(textPtr, indexFromPtr->linePtr),
			    TkBTreeLinesTo(textPtr, indexToPtr->linePtr), -1);
		}
		value = TkTextIndexYPixels(textPtr, indexToPtr)
			- TkTextIndexYPixels(textPtr, indexFromPtr);







|



|



|



|









|







980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
		    }
		}

		if (compare > 0) {
		    value = -value;
		}
	    } else if (c == 'i'
		    && !strncmp("-indices", option, length)) {
		value = CountIndices(textPtr, indexFromPtr, indexToPtr,
			COUNT_INDICES);
	    } else if (c == 'l'
		    && !strncmp("-lines", option, length)) {
		value = TkBTreeLinesTo(textPtr, indexToPtr->linePtr)
			- TkBTreeLinesTo(textPtr, indexFromPtr->linePtr);
	    } else if (c == 'u'
		    && !strncmp("-update", option, length)) {
		update = 1;
		continue;
	    } else if (c == 'x'
		    && !strncmp("-xpixels", option, length)) {
		int x1, x2;
		TkTextIndex index;

		index = *indexFromPtr;
		TkTextFindDisplayLineEnd(textPtr, &index, 0, &x1);
		index = *indexToPtr;
		TkTextFindDisplayLineEnd(textPtr, &index, 0, &x2);
		value = x2 - x1;
	    } else if (c == 'y'
		    && !strncmp("-ypixels", option, length)) {
		if (update) {
		    TkTextUpdateLineMetrics(textPtr,
			    TkBTreeLinesTo(textPtr, indexFromPtr->linePtr),
			    TkBTreeLinesTo(textPtr, indexToPtr->linePtr), -1);
		}
		value = TkTextIndexYPixels(textPtr, indexToPtr)
			- TkTextIndexYPixels(textPtr, indexFromPtr);
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
		if (objc & 1) {
		    indices[i] = indices[i-1];
		    TkTextIndexForwChars(NULL, &indices[i], 1, &indices[i],
			    COUNT_INDICES);
		    objc++;
		}
		useIdx = ckalloc(objc);
		memset(useIdx, 0, (unsigned) objc);

		/*
		 * Do a decreasing order sort so that we delete the end ranges
		 * first to maintain index consistency.
		 */

		qsort(indices, (unsigned) objc / 2,
			2 * sizeof(TkTextIndex), TextIndexSortProc);
		lastStart = NULL;

		/*
		 * Second pass will handle bogus ranges (end < start) and
		 * overlapping ranges.
		 */







|






|







1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
		if (objc & 1) {
		    indices[i] = indices[i-1];
		    TkTextIndexForwChars(NULL, &indices[i], 1, &indices[i],
			    COUNT_INDICES);
		    objc++;
		}
		useIdx = ckalloc(objc);
		memset(useIdx, 0, (size_t) objc);

		/*
		 * Do a decreasing order sort so that we delete the end ranges
		 * first to maintain index consistency.
		 */

		qsort(indices, (size_t) objc / 2,
			2 * sizeof(TkTextIndex), TextIndexSortProc);
		lastStart = NULL;

		/*
		 * Second pass will handle bogus ranges (end < start) and
		 * overlapping ranges.
		 */
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
    case TEXT_EDIT:
	result = TextEditCmd(textPtr, interp, objc, objv);
	break;
    case TEXT_GET: {
	Tcl_Obj *objPtr = NULL;
	int i, found = 0, visible = 0;
	const char *name;
	int length;

	if (objc < 3) {
	    Tcl_WrongNumArgs(interp, 2, objv,
		    "?-displaychars? ?--? index1 ?index2 ...?");
	    result = TCL_ERROR;
	    goto done;
	}

	/*
	 * Simple, restrictive argument parsing. The only options are -- and
	 * -displaychars (or any unique prefix).
	 */

	i = 2;
	if (objc > 3) {
	    name = Tcl_GetString(objv[i]);
	    length = objv[i]->length;
	    if (length > 1 && name[0] == '-') {
		if (strncmp("-displaychars", name, (unsigned) length) == 0) {
		    i++;
		    visible = 1;
		    name = Tcl_GetString(objv[i]);
		    length = objv[i]->length;
		}
		if ((i < objc-1) && (length == 2) && !strcmp("--", name)) {
		    i++;







|


















|







1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
    case TEXT_EDIT:
	result = TextEditCmd(textPtr, interp, objc, objv);
	break;
    case TEXT_GET: {
	Tcl_Obj *objPtr = NULL;
	int i, found = 0, visible = 0;
	const char *name;
	size_t length;

	if (objc < 3) {
	    Tcl_WrongNumArgs(interp, 2, objv,
		    "?-displaychars? ?--? index1 ?index2 ...?");
	    result = TCL_ERROR;
	    goto done;
	}

	/*
	 * Simple, restrictive argument parsing. The only options are -- and
	 * -displaychars (or any unique prefix).
	 */

	i = 2;
	if (objc > 3) {
	    name = Tcl_GetString(objv[i]);
	    length = objv[i]->length;
	    if (length > 1 && name[0] == '-') {
		if (strncmp("-displaychars", name, length) == 0) {
		    i++;
		    visible = 1;
		    name = Tcl_GetString(objv[i]);
		    length = objv[i]->length;
		}
		if ((i < objc-1) && (length == 2) && !strcmp("--", name)) {
		    i++;
2633
2634
2635
2636
2637
2638
2639
2640

2641
2642
2643
2644
2645
2646
2647
    TkTextIndex *indexPtr,	/* Where to insert new characters. May be
				 * modified if the index is not valid for
				 * insertion (e.g. if at "end"). */
    Tcl_Obj *stringPtr,		/* Null-terminated string containing new
				 * information to add to text. */
    int viewUpdate)		/* Update the view if set. */
{
    int lineIndex, length;

    TkText *tPtr;
    int *lineAndByteIndex;
    int resetViewCount;
    int pixels[2*PIXEL_CLIENTS];
    const char *string = Tcl_GetString(stringPtr);

    length = stringPtr->length;







|
>







2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
    TkTextIndex *indexPtr,	/* Where to insert new characters. May be
				 * modified if the index is not valid for
				 * insertion (e.g. if at "end"). */
    Tcl_Obj *stringPtr,		/* Null-terminated string containing new
				 * information to add to text. */
    int viewUpdate)		/* Update the view if set. */
{
    int lineIndex;
    size_t length;
    TkText *tPtr;
    int *lineAndByteIndex;
    int resetViewCount;
    int pixels[2*PIXEL_CLIENTS];
    const char *string = Tcl_GetString(stringPtr);

    length = stringPtr->length;
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199

    if (searchSpecPtr->exact && searchSpecPtr->noCase) {
	Tcl_SetObjLength(theLine, Tcl_UtfToLower(Tcl_GetString(theLine)));
    }

    if (lenPtr != NULL) {
	if (searchSpecPtr->exact) {
	    (void)Tcl_GetString(theLine);
	    *lenPtr = theLine->length;
	} else {
	    *lenPtr = Tcl_GetCharLength(theLine);
	}
    }
    return linePtr;
}







|







4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201

    if (searchSpecPtr->exact && searchSpecPtr->noCase) {
	Tcl_SetObjLength(theLine, Tcl_UtfToLower(Tcl_GetString(theLine)));
    }

    if (lenPtr != NULL) {
	if (searchSpecPtr->exact) {
	    Tcl_GetString(theLine);
	    *lenPtr = theLine->length;
	} else {
	    *lenPtr = Tcl_GetCharLength(theLine);
	}
    }
    return linePtr;
}
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
	return TCL_ERROR;
    }
    arg++;
    atEnd = 0;
    if (objc == arg) {
	TkTextIndexForwChars(NULL, &index1, 1, &index2, COUNT_INDICES);
    } else {
	int length;
	const char *str;

	if (TkTextGetObjIndex(interp, textPtr, objv[arg], &index2) != TCL_OK) {
	    return TCL_ERROR;
	}
	str = Tcl_GetString(objv[arg]);
	length = objv[arg]->length;
	if (strncmp(str, "end", (unsigned) length) == 0) {
	    atEnd = 1;
	}
    }
    if (TkTextIndexCmp(&index1, &index2) >= 0) {
	return TCL_OK;
    }
    lineno = TkBTreeLinesTo(textPtr, index1.linePtr);







|







|







4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
	return TCL_ERROR;
    }
    arg++;
    atEnd = 0;
    if (objc == arg) {
	TkTextIndexForwChars(NULL, &index1, 1, &index2, COUNT_INDICES);
    } else {
	size_t length;
	const char *str;

	if (TkTextGetObjIndex(interp, textPtr, objv[arg], &index2) != TCL_OK) {
	    return TCL_ERROR;
	}
	str = Tcl_GetString(objv[arg]);
	length = objv[arg]->length;
	if (strncmp(str, "end", length) == 0) {
	    atEnd = 1;
	}
    }
    if (TkTextIndexCmp(&index1, &index2) >= 0) {
	return TCL_OK;
    }
    lineno = TkBTreeLinesTo(textPtr, index1.linePtr);
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
			    p = startOfLine + alreadySearchOffset;
			    alreadySearchOffset = -1;
			} else {
			    p = startOfLine + lastOffset -1;
			}
			while (p >= startOfLine + firstOffset) {
			    if (p[0] == c && !strncmp(p, pattern,
				    (unsigned) matchLength)) {
				goto backwardsMatch;
			    }
			    p--;
			}
			break;
		    } else {
			p = strstr(startOfLine + firstOffset, pattern);







|







5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
			    p = startOfLine + alreadySearchOffset;
			    alreadySearchOffset = -1;
			} else {
			    p = startOfLine + lastOffset -1;
			}
			while (p >= startOfLine + firstOffset) {
			    if (p[0] == c && !strncmp(p, pattern,
				    (size_t) matchLength)) {
				goto backwardsMatch;
			    }
			    p--;
			}
			break;
		    } else {
			p = strstr(startOfLine + firstOffset, pattern);
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
			    if ((lastTotal - skipFirst) >= matchLength) {
				/*
				 * We now have enough text to match, so we
				 * make a final test and break whatever the
				 * result.
				 */

				if (strncmp(p,pattern,(unsigned)matchLength)) {
				    p = NULL;
				}
				break;
			    } else {
				/*
				 * Not enough text yet, but check the prefix.
				 */







|







6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
			    if ((lastTotal - skipFirst) >= matchLength) {
				/*
				 * We now have enough text to match, so we
				 * make a final test and break whatever the
				 * result.
				 */

				if (strncmp(p,pattern,(size_t)matchLength)) {
				    p = NULL;
				}
				break;
			    } else {
				/*
				 * Not enough text yet, but check the prefix.
				 */
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
static int
ObjectIsEmpty(
    Tcl_Obj *objPtr)		/* Object to test. May be NULL. */
{
    if (objPtr == NULL) {
	return 1;
    }
    if (objPtr->bytes != NULL) {
	return (objPtr->length == 0);
    }
    (void)Tcl_GetString(objPtr);
    return (objPtr->length == 0);
}

/*
 *----------------------------------------------------------------------
 *
 * TkpTesttextCmd --







|
|

<







6827
6828
6829
6830
6831
6832
6833
6834
6835
6836

6837
6838
6839
6840
6841
6842
6843
static int
ObjectIsEmpty(
    Tcl_Obj *objPtr)		/* Object to test. May be NULL. */
{
    if (objPtr == NULL) {
	return 1;
    }
    if (objPtr->bytes == NULL) {
	Tcl_GetString(objPtr);
    }

    return (objPtr->length == 0);
}

/*
 *----------------------------------------------------------------------
 *
 * TkpTesttextCmd --
Changes to jni/sdl2tk/generic/tkTextIndex.c.
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
 */

static void
UpdateStringOfTextIndex(
    Tcl_Obj *objPtr)
{
    char buffer[TK_POS_CHARS];
    register int len;
    const TkTextIndex *indexPtr = GET_TEXTINDEX(objPtr);

    len = TkTextPrintIndex(indexPtr->textPtr, indexPtr, buffer);

    objPtr->bytes = ckalloc(len + 1);
    strcpy(objPtr->bytes, buffer);
    objPtr->length = len;







|







130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
 */

static void
UpdateStringOfTextIndex(
    Tcl_Obj *objPtr)
{
    char buffer[TK_POS_CHARS];
    size_t len;
    const TkTextIndex *indexPtr = GET_TEXTINDEX(objPtr);

    len = TkTextPrintIndex(indexPtr->textPtr, indexPtr, buffer);

    objPtr->bytes = ckalloc(len + 1);
    strcpy(objPtr->bytes, buffer);
    objPtr->length = len;
Changes to jni/sdl2tk/generic/tkUtil.c.
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
    int *intPtr)		/* Filled in with number of pages or lines to
				 * scroll, if any. */
{
    const char *arg = Tcl_GetString(objv[2]);
    size_t length = objv[2]->length;

#define ArgPfxEq(str) \
	((arg[0] == str[0]) && !strncmp(arg, str, (unsigned)length))

    if (ArgPfxEq("moveto")) {
	if (objc != 4) {
	    Tcl_WrongNumArgs(interp, 2, objv, "moveto fraction");
	    return TK_SCROLL_ERROR;
	}
	if (Tcl_GetDoubleFromObj(interp, objv[3], dblPtr) != TCL_OK) {







|







729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
    int *intPtr)		/* Filled in with number of pages or lines to
				 * scroll, if any. */
{
    const char *arg = Tcl_GetString(objv[2]);
    size_t length = objv[2]->length;

#define ArgPfxEq(str) \
	((arg[0] == str[0]) && !strncmp(arg, str, length))

    if (ArgPfxEq("moveto")) {
	if (objc != 4) {
	    Tcl_WrongNumArgs(interp, 2, objv, "moveto fraction");
	    return TK_SCROLL_ERROR;
	}
	if (Tcl_GetDoubleFromObj(interp, objv[3], dblPtr) != TCL_OK) {
Changes to jni/sdl2tk/generic/ttk/ttkState.c.
126
127
128
129
130
131
132
133

134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158

static void StateSpecUpdateString(Tcl_Obj *objPtr)
{
    unsigned int onbits = (objPtr->internalRep.longValue & 0xFFFF0000) >> 16;
    unsigned int offbits = objPtr->internalRep.longValue & 0x0000FFFF;
    unsigned int mask = onbits | offbits;
    Tcl_DString result;
    int i, len;


    Tcl_DStringInit(&result);

    for (i=0; stateNames[i] != NULL; ++i) {
	if (mask & (1<<i)) {
	    if (offbits & (1<<i))
		Tcl_DStringAppend(&result, "!", 1);
	    Tcl_DStringAppend(&result, stateNames[i], -1);
	    Tcl_DStringAppend(&result, " ", 1);
	}
    }

    len = Tcl_DStringLength(&result);
    if (len) {
	/* 'len' includes extra trailing ' ' */
	objPtr->bytes = Tcl_Alloc((unsigned)len);
	objPtr->length = len-1;
	strncpy(objPtr->bytes, Tcl_DStringValue(&result), (size_t)len-1);
	objPtr->bytes[len-1] = '\0';
    } else {
	/* empty string */
	objPtr->length = 0;
	objPtr->bytes = Tcl_Alloc(1);
	*objPtr->bytes = '\0';
    }







|
>















|

|







126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159

static void StateSpecUpdateString(Tcl_Obj *objPtr)
{
    unsigned int onbits = (objPtr->internalRep.longValue & 0xFFFF0000) >> 16;
    unsigned int offbits = objPtr->internalRep.longValue & 0x0000FFFF;
    unsigned int mask = onbits | offbits;
    Tcl_DString result;
    int i;
    size_t len;

    Tcl_DStringInit(&result);

    for (i=0; stateNames[i] != NULL; ++i) {
	if (mask & (1<<i)) {
	    if (offbits & (1<<i))
		Tcl_DStringAppend(&result, "!", 1);
	    Tcl_DStringAppend(&result, stateNames[i], -1);
	    Tcl_DStringAppend(&result, " ", 1);
	}
    }

    len = Tcl_DStringLength(&result);
    if (len) {
	/* 'len' includes extra trailing ' ' */
	objPtr->bytes = Tcl_Alloc(len);
	objPtr->length = len-1;
	strncpy(objPtr->bytes, Tcl_DStringValue(&result), len-1);
	objPtr->bytes[len-1] = '\0';
    } else {
	/* empty string */
	objPtr->length = 0;
	objPtr->bytes = Tcl_Alloc(1);
	*objPtr->bytes = '\0';
    }
Changes to jni/sdl2tk/macosx/tkMacOSXWm.c.
385
386
387
388
389
390
391
392

393



394
395



396

397
398



399

400



401




402
403
404
405
406
407
408
@end


@implementation TKWindow: NSWindow
#if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_12
/*
 * Override automatic fullscreen button on >10.12 because system fullscreen API
 * confuses Tk window geometry.

 */



- (void)toggleFullScreen:(id)sender
{



    if ([self isZoomed]) {

	TkMacOSXZoomToplevel(self, inZoomIn);
    } else {



	TkMacOSXZoomToplevel(self, inZoomOut);

    }



}




#endif
@end

@implementation TKWindow(TKWm)

- (BOOL) canBecomeKeyWindow
{







|
>

>
>
>


>
>
>
|
>
|

>
>
>
|
>
|
>
>
>
|
>
>
>
>







385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
@end


@implementation TKWindow: NSWindow
#if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_12
/*
 * Override automatic fullscreen button on >10.12 because system fullscreen API
 * confuses Tk window geometry. Custom implementation setting fullscreen status using 
 * Tk API and NSStatusItem in menubar to exit fullscreen status.
 */

NSStatusItem *exitFullScreen;

- (void)toggleFullScreen:(id)sender
{
    TkWindow *winPtr = TkMacOSXGetTkWindow(self);
    Tk_Window tkwin = (TkWindow*)winPtr;
    Tcl_Interp *interp = Tk_Interp(tkwin);

    if (([self styleMask] & NSFullScreenWindowMask) == NSFullScreenWindowMask) {
    	TkMacOSXMakeFullscreen(winPtr, self, 0, interp);
    } else {
    	TkMacOSXMakeFullscreen(winPtr, self, 1, interp);
    }
}

-(void)restoreOldScreen:(id)sender {

    TkWindow *winPtr = TkMacOSXGetTkWindow(self);
    Tk_Window tkwin = (TkWindow*)winPtr;
    Tcl_Interp *interp = Tk_Interp(tkwin);

    TkMacOSXMakeFullscreen(winPtr, self, 0, interp);
    [[NSStatusBar systemStatusBar] removeStatusItem: exitFullScreen];
}

#endif
@end

@implementation TKWindow(TKWm)

- (BOOL) canBecomeKeyWindow
{
6496
6497
6498
6499
6500
6501
6502

6503
6504
6505
6506
6507
6508
6509
    NSWindow *window,
    int fullscreen,
    Tcl_Interp *interp)
{
    WmInfo *wmPtr = winPtr->wmInfoPtr;
    int result = TCL_OK, wasFullscreen = (wmPtr->flags & WM_FULLSCREEN);
    static unsigned long prevMask = 0, prevPres = 0;


    if (fullscreen) {
	int screenWidth =  WidthOfScreen(Tk_Screen(winPtr));
	int screenHeight = HeightOfScreen(Tk_Screen(winPtr));

	/*
	 * Check max width and height if set by the user.







>







6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
    NSWindow *window,
    int fullscreen,
    Tcl_Interp *interp)
{
    WmInfo *wmPtr = winPtr->wmInfoPtr;
    int result = TCL_OK, wasFullscreen = (wmPtr->flags & WM_FULLSCREEN);
    static unsigned long prevMask = 0, prevPres = 0;


    if (fullscreen) {
	int screenWidth =  WidthOfScreen(Tk_Screen(winPtr));
	int screenHeight = HeightOfScreen(Tk_Screen(winPtr));

	/*
	 * Check max width and height if set by the user.
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547












6548
6549
6550
6551
6552
6553
6554
		wmPtr->configY = wmPtr->y;
		wmPtr->configAttributes = wmPtr->attributes;
		wmPtr->attributes &= ~kWindowResizableAttribute;
		ApplyWindowAttributeFlagChanges(winPtr, window,
			wmPtr->configAttributes, wmPtr->flags, 1, 0);
		wmPtr->flags |= WM_SYNC_PENDING;
		[window setFrame:[window frameRectForContentRect:
			screenBounds] display:YES];
		wmPtr->flags &= ~WM_SYNC_PENDING;
	    }
	    wmPtr->flags |= WM_FULLSCREEN;
	}

	prevMask = [window styleMask];
	prevPres = [NSApp presentationOptions];
	[window setStyleMask: NSBorderlessWindowMask];
	[NSApp setPresentationOptions: NSApplicationPresentationAutoHideDock
	                          | NSApplicationPresentationAutoHideMenuBar];












	Tk_MapWindow((Tk_Window) winPtr);
    } else {
	wmPtr->flags &= ~WM_FULLSCREEN;
	[NSApp setPresentationOptions: prevPres];
	[window setStyleMask: prevMask];
    }








|







|
|
|
>
>
>
>
>
>
>
>
>
>
>
>







6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
		wmPtr->configY = wmPtr->y;
		wmPtr->configAttributes = wmPtr->attributes;
		wmPtr->attributes &= ~kWindowResizableAttribute;
		ApplyWindowAttributeFlagChanges(winPtr, window,
			wmPtr->configAttributes, wmPtr->flags, 1, 0);
		wmPtr->flags |= WM_SYNC_PENDING;
		[window setFrame:[window frameRectForContentRect:
					   screenBounds] display:YES];
		wmPtr->flags &= ~WM_SYNC_PENDING;
	    }
	    wmPtr->flags |= WM_FULLSCREEN;
	}

	prevMask = [window styleMask];
	prevPres = [NSApp presentationOptions];
	[window setStyleMask: NSFullScreenWindowMask];
	[NSApp setPresentationOptions: NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar];
	
	/*Fullscreen implementation for 10.13 and later.*/
	#if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_12
	exitFullScreen = [[[NSStatusBar systemStatusBar] 
				   statusItemWithLength:NSVariableStatusItemLength] retain];
	NSImage *exitIcon = [NSImage imageNamed:@"NSExitFullScreenTemplate"];
	[exitFullScreen setImage:exitIcon];
	[exitFullScreen setHighlightMode:YES];
	[exitFullScreen setToolTip:@"Exit Full Screen"];
	[exitFullScreen setTarget:window];
	[exitFullScreen setAction:@selector(restoreOldScreen:)];
	#endif
	
	Tk_MapWindow((Tk_Window) winPtr);
    } else {
	wmPtr->flags &= ~WM_FULLSCREEN;
	[NSApp setPresentationOptions: prevPres];
	[window setStyleMask: prevMask];
    }

Changes to jni/sdl2tk/win/tkWinDialog.c.
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
	    }
	    Tcl_IncrRefCount(hdPtr->titleObj);
	    break;
	case FontchooserFont:
	    if (hdPtr->fontObj) {
		Tcl_DecrRefCount(hdPtr->fontObj);
	    }
	    (void)Tcl_GetString(objv[i+1]);
	    if (objv[i+1]->length) {
		hdPtr->fontObj = objv[i+1];
		if (Tcl_IsShared(hdPtr->fontObj)) {
		    hdPtr->fontObj = Tcl_DuplicateObj(hdPtr->fontObj);
		}
		Tcl_IncrRefCount(hdPtr->fontObj);
	    } else {
		hdPtr->fontObj = NULL;
	    }
	    break;
	case FontchooserCmd:
	    if (hdPtr->cmdObj) {
		Tcl_DecrRefCount(hdPtr->cmdObj);
	    }
	    (void)Tcl_GetString(objv[i+1]);
	    if (objv[i+1]->length) {
		hdPtr->cmdObj = objv[i+1];
		if (Tcl_IsShared(hdPtr->cmdObj)) {
		    hdPtr->cmdObj = Tcl_DuplicateObj(hdPtr->cmdObj);
		}
		Tcl_IncrRefCount(hdPtr->cmdObj);
	    } else {







|














|







3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
	    }
	    Tcl_IncrRefCount(hdPtr->titleObj);
	    break;
	case FontchooserFont:
	    if (hdPtr->fontObj) {
		Tcl_DecrRefCount(hdPtr->fontObj);
	    }
	    Tcl_GetString(objv[i+1]);
	    if (objv[i+1]->length) {
		hdPtr->fontObj = objv[i+1];
		if (Tcl_IsShared(hdPtr->fontObj)) {
		    hdPtr->fontObj = Tcl_DuplicateObj(hdPtr->fontObj);
		}
		Tcl_IncrRefCount(hdPtr->fontObj);
	    } else {
		hdPtr->fontObj = NULL;
	    }
	    break;
	case FontchooserCmd:
	    if (hdPtr->cmdObj) {
		Tcl_DecrRefCount(hdPtr->cmdObj);
	    }
	    Tcl_GetString(objv[i+1]);
	    if (objv[i+1]->length) {
		hdPtr->cmdObj = objv[i+1];
		if (Tcl_IsShared(hdPtr->cmdObj)) {
		    hdPtr->cmdObj = Tcl_DuplicateObj(hdPtr->cmdObj);
		}
		Tcl_IncrRefCount(hdPtr->cmdObj);
	    } else {
Changes to jni/sdl2tk/win/tkWinEmbed.c.
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
 *	    TK_CONTAINER_ISAVAILABLE - a container window should return either
 *		a TRUE (non-zero) if it is available for use or a FALSE (zero)
 *		othersize.
 *
 *	The TK_INFO messages are required in order to verify if the window to
 *	use is a valid container. Without an id verification, an invalid
 *	window attachment may cause unexpected crashes/panics (bug 1096074).
 *	Additional sub messages may be definded/used in future for other
 *	needs.
 *
 *	We do not enforce the above protocol for the reason of backward
 *	compatibility. If the window to use is unable to handle TK_INFO
 *	messages (e.g., legacy Tk container applications before 8.5), a dialog
 *	box with a warning message pops up and the user is asked to confirm if
 *	the attachment should proceed. However, we may have to enforce it in







|







196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
 *	    TK_CONTAINER_ISAVAILABLE - a container window should return either
 *		a TRUE (non-zero) if it is available for use or a FALSE (zero)
 *		othersize.
 *
 *	The TK_INFO messages are required in order to verify if the window to
 *	use is a valid container. Without an id verification, an invalid
 *	window attachment may cause unexpected crashes/panics (bug 1096074).
 *	Additional sub messages may be defined/used in future for other
 *	needs.
 *
 *	We do not enforce the above protocol for the reason of backward
 *	compatibility. If the window to use is unable to handle TK_INFO
 *	messages (e.g., legacy Tk container applications before 8.5), a dialog
 *	box with a warning message pops up and the user is asked to confirm if
 *	the attachment should proceed. However, we may have to enforce it in
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
    } else {
	/*
	 * Proceed if the user decide to do so because it can be a legacy
	 * container application. However we may have to return a TCL_ERROR in
	 * order to avoid bug 1096074 in future.
	 */

	char msg[256];

	sprintf(msg, "Unable to get information of window \"%.80s\".  Attach to this\nwindow may have unpredictable results if it is not a valid container.\n\nPress Ok to proceed or Cancel to abort attaching.", string);
	if (IDCANCEL == MessageBoxA(hwnd, msg, "Tk Warning",
		MB_OKCANCEL | MB_ICONWARNING)) {
    	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    "Operation has been canceled", -1));
	    Tcl_SetErrorCode(interp, "TK", "EMBED", "CANCEL", NULL);
	    return TCL_ERROR;
	}
    }







|

|
|







299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
    } else {
	/*
	 * Proceed if the user decide to do so because it can be a legacy
	 * container application. However we may have to return a TCL_ERROR in
	 * order to avoid bug 1096074 in future.
	 */

	TCHAR msg[256];

	wsprintf(msg, TEXT("Unable to get information of window \"%.40hs\".  Attach to this\nwindow may have unpredictable results if it is not a valid container.\n\nPress Ok to proceed or Cancel to abort attaching."), string);
	if (IDCANCEL == MessageBox(hwnd, msg, TEXT("Tk Warning"),
		MB_OKCANCEL | MB_ICONWARNING)) {
    	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    "Operation has been canceled", -1));
	    Tcl_SetErrorCode(interp, "TK", "EMBED", "CANCEL", NULL);
	    return TCL_ERROR;
	}
    }
Changes to jni/sdl2tk/win/tkWinPixmap.c.
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
	 * people to report this as a bug...
	 */

	if (newTwdPtr->bitmap.handle == NULL && !repeatError) {
	    LPVOID lpMsgBuf;

	    repeatError = 1;
	    if (FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
		    FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
		    NULL, GetLastError(),
		    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
		    (LPSTR) &lpMsgBuf, 0, NULL)) {
		MessageBoxA(NULL, (LPCSTR) lpMsgBuf,
			"Tk_GetPixmap: Error from CreateDIBSection",
			MB_OK | MB_ICONINFORMATION);
		LocalFree(lpMsgBuf);
	    }
	}
    }

    if (newTwdPtr->bitmap.handle == NULL) {







|



|
|
|







96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
	 * people to report this as a bug...
	 */

	if (newTwdPtr->bitmap.handle == NULL && !repeatError) {
	    LPVOID lpMsgBuf;

	    repeatError = 1;
	    if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
		    FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
		    NULL, GetLastError(),
		    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
		    (LPTSTR)&lpMsgBuf, 0, NULL)) {
		MessageBox(NULL, (LPTSTR) lpMsgBuf,
			TEXT("Tk_GetPixmap: Error from CreateDIBSection"),
			MB_OK | MB_ICONINFORMATION);
		LocalFree(lpMsgBuf);
	    }
	}
    }

    if (newTwdPtr->bitmap.handle == NULL) {
Changes to jni/tcl/generic/tclDate.c.
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
#endif
#endif
{
  /* The look-ahead symbol.  */
int yychar;

/* The semantic value of the look-ahead symbol.  */
YYSTYPE yylval;

/* Number of syntax errors so far.  */
int yynerrs;
/* Location data for the look-ahead symbol.  */
YYLTYPE yylloc;

  int yystate;







|







1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
#endif
#endif
{
  /* The look-ahead symbol.  */
int yychar;

/* The semantic value of the look-ahead symbol.  */
YYSTYPE yylval = {0};

/* Number of syntax errors so far.  */
int yynerrs;
/* Location data for the look-ahead symbol.  */
YYLTYPE yylloc;

  int yystate;
Changes to jni/tcl/tests/env.test.
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
    variable keep
    variable env2

    set env2 [array get env]
    foreach name [array names env] {
	# Keep some environment variables that support operation of the tcltest
	# package.
	if {[string toupper $name] ni $keep} {
	    unset env($name)
	}
    }
    return
}









|







49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
    variable keep
    variable env2

    set env2 [array get env]
    foreach name [array names env] {
	# Keep some environment variables that support operation of the tcltest
	# package.
	if {[string toupper $name] ni [string toupper $keep]} {
	    unset env($name)
	}
    }
    return
}


94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112

proc cleanup1 {} {
    encodingrestore
    envrestore
}

variable keep {
    TCL_LIBRARY PATH LD_LIBRARY_PATH LIBPATH DISPLAY SHLIB_PATH
    SYSTEMDRIVE SYSTEMROOT DYLD_LIBRARY_PATH DYLD_FRAMEWORK_PATH
    DYLD_NEW_LOCAL_SHARED_REGIONS DYLD_NO_FIX_PREBINDING
    SECURITYSESSIONID LANG WINDIR TERM
    CONNOMPROGRAMFILES PROGRAMFILES COMMONPROGRAMW6432 PROGRAMW6432
}

variable printenvScript [makeFile [string map [list @keep@ [list $keep]] {
    encoding system iso8859-1
    proc lrem {listname name} {
	upvar $listname list
	set i [lsearch -nocase $list $name]







|
|

|
|







94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112

proc cleanup1 {} {
    encodingrestore
    envrestore
}

variable keep {
    TCL_LIBRARY PATH LD_LIBRARY_PATH LIBPATH PURE_PROG_NAME DISPLAY
    SHLIB_PATH SYSTEMDRIVE SYSTEMROOT DYLD_LIBRARY_PATH DYLD_FRAMEWORK_PATH
    DYLD_NEW_LOCAL_SHARED_REGIONS DYLD_NO_FIX_PREBINDING
    __CF_USER_TEXT_ENCODING SECURITYSESSIONID LANG WINDIR TERM
    CommonProgramFiles ProgramFiles CommonProgramW6432 ProgramW6432
}

variable printenvScript [makeFile [string map [list @keep@ [list $keep]] {
    encoding system iso8859-1
    proc lrem {listname name} {
	upvar $listname list
	set i [lsearch -nocase $list $name]
Added jni/topcua/Android.mk.










































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
LOCAL_PATH := $(call my-dir)

###########################
#
# topcua shared library
#
###########################

include $(CLEAR_VARS)

LOCAL_MODULE := topcua

tcl_path := $(LOCAL_PATH)/../tcl

include $(tcl_path)/tcl-config.mk

LOCAL_ADDITIONAL_DEPENDENCIES += $(tcl_path)/tcl-config.mk

LOCAL_C_INCLUDES := $(tcl_includes) \
	$(LOCAL_PATH) $(LOCAL_PATH)/open62541

LOCAL_EXPORT_C_INCLUDES := $(LOCAL_C_INCLUDES)

LOCAL_SRC_FILES := \
	topcua.c \
	open62541/open62541.c

LOCAL_CFLAGS := $(tcl_cflags) $(tk_cflags) \
	-DPACKAGE_NAME="\"topcua\"" \
	-DPACKAGE_VERSION="\"0.1\"" \
	-fvisibility=hidden -std=c99 \
	-D_THREAD_SAFE=1 \
	-O2

LOCAL_SHARED_LIBRARIES := libtcl

include $(BUILD_SHARED_LIBRARY)
Added jni/topcua/Makefile.in.






































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# Makefile.in --
#
#	This file is a Makefile for Sample TEA Extension.  If it has the name
#	"Makefile.in" then it is a template for a Makefile;  to generate the
#	actual Makefile, run "./configure", which is a configuration script
#	generated by the "autoconf" program (constructs like "@foo@" will get
#	replaced in the actual Makefile.
#
# Copyright (c) 1999 Scriptics Corporation.
# Copyright (c) 2003-2008 ActiveState Software
#
# See the file "license.terms" for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.

#========================================================================
# Nothing of the variables below this line need to be changed.  Please
# check the TARGETS section below to make sure the make targets are
# correct.
#========================================================================

#========================================================================
# The names of the source files is defined in the configure script.
# The object files are used for linking into the final library.
# This will be used when a dist target is added to the Makefile.
# It is not important to specify the directory, as long as it is the
# $(srcdir) subdirectory.
#========================================================================

PKG_SOURCES	= @PKG_SOURCES@
PKG_OBJECTS	= @PKG_OBJECTS@

#========================================================================
# PKG_TCL_SOURCES identifies Tcl runtime files that are associated with
# this package that need to be installed, if any.
#========================================================================

PKG_TCL_SOURCES = @PKG_TCL_SOURCES@

#========================================================================
# This is a list of public header files to be installed, if any.
#========================================================================

PKG_HEADERS	= @PKG_HEADERS@

PKG_EXTRA_FILES =

PKG_MAN_PAGES	=

#========================================================================
# "PKG_LIB_FILE" refers to the library (dynamic or static as per
# configuration options) composed of the named objects.
#========================================================================

PKG_LIB_FILE	= @PKG_LIB_FILE@
PKG_STUB_LIB_FILE = @PKG_STUB_LIB_FILE@

lib_BINARIES	= $(PKG_LIB_FILE)
BINARIES	= $(lib_BINARIES)

SHELL		= @SHELL@

srcdir		= @srcdir@
prefix		= @prefix@
exec_prefix	= @exec_prefix@

bindir		= @bindir@
libdir		= @libdir@
datarootdir	= @datarootdir@
datadir		= @datadir@
mandir		= @mandir@
includedir	= @includedir@

DESTDIR		=

PKG_DIR		= $(PACKAGE_NAME)$(PACKAGE_VERSION)
pkgdatadir	= $(datadir)/$(PKG_DIR)
pkglibdir	= $(libdir)/$(PKG_DIR)
pkgincludedir	= $(includedir)/$(PKG_DIR)

top_builddir	= .

INSTALL		= @INSTALL@
INSTALL_PROGRAM	= @INSTALL_PROGRAM@
INSTALL_DATA	= @INSTALL_DATA@
INSTALL_SCRIPT	= @INSTALL_SCRIPT@

PACKAGE_NAME	= @PACKAGE_NAME@
PACKAGE_VERSION	= @PACKAGE_VERSION@
CC		= @CC@
CFLAGS_DEFAULT	= @CFLAGS_DEFAULT@
CFLAGS_WARNING	= @CFLAGS_WARNING@
CLEANFILES	= @CLEANFILES@
EXEEXT		= @EXEEXT@
LDFLAGS_DEFAULT	= @LDFLAGS_DEFAULT@
MAKE_LIB	= @MAKE_LIB@
MAKE_SHARED_LIB	= @MAKE_SHARED_LIB@
MAKE_STATIC_LIB	= @MAKE_STATIC_LIB@
MAKE_STUB_LIB	= @MAKE_STUB_LIB@
OBJEXT		= @OBJEXT@
RANLIB		= @RANLIB@
RANLIB_STUB	= @RANLIB_STUB@
SHLIB_CFLAGS	= @SHLIB_CFLAGS@
SHLIB_LD	= @SHLIB_LD@
SHLIB_LD_LIBS	= @SHLIB_LD_LIBS@
STLIB_LD	= @STLIB_LD@
TCL_DEFS	= @TCL_DEFS@
TCL_SRC_DIR	= @TCL_SRC_DIR@
TCL_BIN_DIR	= @TCL_BIN_DIR@

# Not used by sample, but retained for reference of what Tcl required
TCL_LIBS	= @TCL_LIBS@

#========================================================================
# TCLLIBPATH seeds the auto_path in Tcl's init.tcl so we can test our
# package without installing.  The other environment variables allow us
# to test against an uninstalled Tcl.  Add special env vars that you
# require for testing here (like TCLX_LIBRARY).
#========================================================================

EXTRA_PATH	= $(top_builddir):$(TCL_BIN_DIR)
TCLSH_ENV	= TCL_LIBRARY=`@CYGPATH@ $(TCL_SRC_DIR)/library` \
		  @LD_LIBRARY_PATH_VAR@="$(EXTRA_PATH):$(@LD_LIBRARY_PATH_VAR@)" \
		  PATH="$(EXTRA_PATH):$(PATH)" \
		  TCLLIBPATH="$(top_builddir)"
TCLSH_PROG	= @TCLSH_PROG@
TCLSH		= $(TCLSH_ENV) $(TCLSH_PROG)

# The local includes must come first
INCLUDES	= @PKG_INCLUDES@ @TCL_INCLUDES@

PKG_CFLAGS	= @PKG_CFLAGS@

DEFS		= @DEFS@ $(PKG_CFLAGS)

CONFIG_CLEAN_FILES = Makefile

CPPFLAGS	= @CPPFLAGS@
LIBS		= @PKG_LIBS@ @LIBS@
AR		= @AR@
CFLAGS		= @CFLAGS@
COMPILE		= $(CC) $(DEFS) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)

#========================================================================
# Start of user-definable TARGETS section
#========================================================================

#========================================================================
# TEA TARGETS.  Please note that the "libraries:" target refers to platform
# independent files, and the "binaries:" target inclues executable programs and
# platform-dependent libraries.  Modify these targets so that they install
# the various pieces of your package.  The make and install rules
# for the BINARIES that you specified above have already been done.
#========================================================================

all: binaries libraries doc

#========================================================================
# The binaries target builds executable programs, Windows .dll's, unix
# shared/static libraries, and any other platform-dependent files.
# The list of targets to build for "binaries:" is specified at the top
# of the Makefile, in the "BINARIES" variable.
#========================================================================

binaries: $(BINARIES)

libraries:

doc:

install: all install-binaries install-libraries install-doc

install-binaries: binaries install-lib-binaries install-bin-binaries
	@mkdir -p $(DESTDIR)$(pkglibdir)
	$(INSTALL_DATA) pkgIndex.tcl $(DESTDIR)$(pkglibdir)
	@list='$(PKG_EXTRA_FILES)'; for p in $$list; do \
	  if test -f $(srcdir)/$$p; then \
	    destp=`basename $$p`; \
	    echo " Install $$destp $(DESTDIR)$(pkglibdir)/$$destp"; \
	    $(INSTALL_DATA) $(srcdir)/$$p $(DESTDIR)$(pkglibdir)/$$destp; \
	  fi; \
	done

#========================================================================
# This rule installs platform-independent files, such as header files.
#========================================================================

install-libraries: libraries

#========================================================================
# Install documentation.  Unix manpages should go in the $(mandir)
# directory.
#========================================================================

install-doc: doc
	@mkdir -p $(DESTDIR)$(mandir)/mann
	@echo "Installing documentation in $(DESTDIR)$(mandir)"
	@list='$(srcdir)/doc/*.n'; for i in $$list; do \
	  echo "Installing $$i"; \
	  rm -f $(DESTDIR)$(mandir)/mann/`basename $$i`; \
	  $(INSTALL_DATA) $$i $(DESTDIR)$(mandir)/mann ; \
	done

test:

shell: binaries libraries
	@$(TCLSH) $(SCRIPT)

gdb:
	$(TCLSH_ENV) gdb $(TCLSH_PROG) $(SCRIPT)

depend:

#========================================================================
# $(PKG_LIB_FILE) should be listed as part of the BINARIES variable
# mentioned above.  That will ensure that this target is built when you
# run "make binaries".
#
# The $(PKG_OBJECTS) objects are created and linked into the final
# library.  In most cases these object files will correspond to the
# source files above.
#========================================================================

$(PKG_LIB_FILE): $(PKG_OBJECTS)
	-rm -f $(PKG_LIB_FILE)
	${MAKE_LIB}
	$(RANLIB) $(PKG_LIB_FILE)

#========================================================================
# In the following lines, $(srcdir) refers to the toplevel directory
# containing your extension.  If your sources are in a subdirectory,
# you will have to modify the paths to reflect this:
#
# tkpkg.$(OBJEXT): $(srcdir)/tkpkg.c
# 	$(COMPILE) -c `@CYGPATH@ $(srcdir)/tkpkg.c` -o $@
#
# Setting the VPATH variable to a list of paths will cause the
# makefile to look into these paths when resolving .c to .obj
# dependencies.
#========================================================================

# I added leading $(srcdir) because autoconf 2.53 strips it off
VPATH = $(srcdir):$(srcdir)/open62541

.SUFFIXES: .c .$(OBJEXT)

.c.@OBJEXT@:
	$(COMPILE) -c `@CYGPATH@ $<` -o $@

#========================================================================
# End of user-definable section
#========================================================================

#========================================================================
# Don't modify the file to clean here.  Instead, set the "CLEANFILES"
# variable in configure.in
#========================================================================

clean:
	-test -z "$(BINARIES)" || rm -f $(BINARIES)
	-rm -f *.$(OBJEXT) core *.core *~
	-test -z "$(CLEANFILES)" || rm -f $(CLEANFILES)

distclean: clean
	-rm -f *.tab.c
	-rm -f $(CONFIG_CLEAN_FILES)
	-rm -f config.cache config.log config.status

#========================================================================
# Install binary object libraries.  On Windows this includes both .dll and
# .lib files.  Because the .lib files are not explicitly listed anywhere,
# we need to deduce their existence from the .dll file of the same name.
#
# You should not have to modify this target.
#========================================================================

install-lib-binaries:
	@mkdir -p $(DESTDIR)$(pkglibdir)
	@list='$(lib_BINARIES)'; for p in $$list; do \
	  if test -f $$p; then \
	    echo " $(INSTALL_PROGRAM) $$p $(DESTDIR)$(pkglibdir)/$$p"; \
	    $(INSTALL_PROGRAM) $$p $(DESTDIR)$(pkglibdir)/$$p; \
	    echo " $(RANLIB) $(DESTDIR)$(pkglibdir)/$$p"; \
	    $(RANLIB) $(DESTDIR)$(pkglibdir)/$$p; \
	    ext=`echo $$p|sed -e "s/.*\.//"`; \
	    if test "x$$ext" = "xdll"; then \
		lib=`basename $$p|sed -e 's/.[^.]*$$//'`.lib; \
		if test -f $$lib; then \
		    echo " $(INSTALL_DATA) $$lib $(DESTDIR)$(pkglibdir)/$$lib"; \
	            $(INSTALL_DATA) $$lib $(DESTDIR)$(pkglibdir)/$$lib; \
		fi; \
	    fi; \
	  fi; \
	done
	@list='$(PKG_TCL_SOURCES)'; for p in $$list; do \
	  if test -f $(srcdir)/$$p; then \
	    destp=`basename $$p`; \
	    echo " Install $$destp $(DESTDIR)$(pkglibdir)/$$destp"; \
	    $(INSTALL_DATA) $(srcdir)/$$p $(DESTDIR)$(pkglibdir)/$$destp; \
	  fi; \
	done

#========================================================================
# Install binary executables (e.g. .exe files)
#
# You should not have to modify this target.
#========================================================================

install-bin-binaries:
	@mkdir -p $(DESTDIR)$(bindir)
	@list='$(bin_BINARIES)'; for p in $$list; do \
	  if test -f $$p; then \
	    echo " $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/$$p"; \
	    $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/$$p; \
	  fi; \
	done

Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
	cd $(top_builddir) \
	  && CONFIG_FILES=$@ CONFIG_HEADERS= $(SHELL) ./config.status

uninstall-binaries:
	list='$(lib_BINARIES)'; for p in $$list; do \
	  rm -f $(DESTDIR)$(pkglibdir)/$$p; \
	done
	list='$(PKG_TCL_SOURCES)'; for p in $$list; do \
	  p=`basename $$p`; \
	  rm -f $(DESTDIR)$(pkglibdir)/$$p; \
	done
	list='$(bin_BINARIES)'; for p in $$list; do \
	  rm -f $(DESTDIR)$(bindir)/$$p; \
	done

#========================================================================
# Distribution creation
# You should not have to modify this target.
#========================================================================

TAR		= tar
#COMPRESS	= $(TAR) cvf $(PKG_DIR).tar $(PKG_DIR); compress $(PKG_DIR).tar
COMPRESS	= $(TAR) zcvf $(PKG_DIR).tar.gz $(PKG_DIR)
DIST_ROOT	= /tmp/dist
DIST_DIR	= $(DIST_ROOT)/$(PKG_DIR)

dist-clean:
	rm -rf $(DIST_DIR) $(DIST_ROOT)/$(PKG_DIR).tar.*

dist: dist-clean
	mkdir -p $(DIST_DIR)
	cp -p $(srcdir)/license.terms \
		$(srcdir)/Makefile.in $(srcdir)/aclocal.m4 \
		$(srcdir)/configure $(srcdir)/configure.in  $(DIST_DIR)/
	chmod 664 $(DIST_DIR)/Makefile.in $(DIST_DIR)/aclocal.m4
	chmod 775 $(DIST_DIR)/configure $(DIST_DIR)/configure.in
	mkdir -p $(DIST_DIR)/tclconfig
	cp $(srcdir)/tclconfig/install-sh $(srcdir)/tclconfig/tcl.m4 \
		$(DIST_DIR)/tclconfig/
	chmod 664 $(DIST_DIR)/tclconfig/tcl.m4
	chmod +x $(DIST_DIR)/tclconfig/install-sh
	mkdir -p $(DIST_DIR)/demos
	cp -p $(srcdir)/demos/*.tcl $(DIST_DIR)/demos/
	mkdir -p $(DIST_DIR)/doc
	cp -p $(srcdir)/doc/*.n $(DIST_DIR)/doc/
	mkdir -p $(DIST_DIR)
	cp -p $(srcdir)/*.[ch] $(DIST_DIR)
	(cd $(DIST_ROOT); $(COMPRESS);)

.PHONY: all binaries clean depend distclean doc install libraries test

# Tell versions [3.59,3.63) of GNU make to not export all variables.
# Otherwise a system limit (for SysV at least) may be exceeded.
.NOEXPORT:
Added jni/topcua/README.txt.




















>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
topcua
======

Proof of concept minimal Tcl binding to the OPC/UA implementation
of http://www.open62541.org

Many things are still missing: documentation, checking for memory
leaks, higher level OPC/UA services like subscription, monitoring,
node management, support for extension types, asynchronous mode of
operation.
Added jni/topcua/aclocal.m4.


















>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
#
# Include the TEA standard macro set
#

builtin(include,tclconfig/tcl.m4)

#
# Add here whatever m4 macros you want to define for your package
#
Added jni/topcua/configure.

more than 10,000 changes

Added jni/topcua/configure.in.




























































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
#! /bin/bash -norc
#
#--------------------------------------------------------------------
# Sample configure.in for Tcl Extensions.  The only places you should
# need to modify this file are marked by the string __CHANGE__
#--------------------------------------------------------------------

#-----------------------------------------------------------------------
# __CHANGE__
# Set your package name and version numbers here.
#
# This initializes the environment with PACKAGE_NAME and PACKAGE_VERSION
# set as provided.  These will also be added as -D defs in your Makefile
# so you can encode the package version directly into the source files.
#-----------------------------------------------------------------------

AC_INIT([topcua], [0.1])

#--------------------------------------------------------------------
# Call TEA_INIT as the first TEA_ macro to set up initial vars.
# This will define a ${TEA_PLATFORM} variable == "unix" or "windows"
# as well as PKG_LIB_FILE and PKG_STUB_LIB_FILE.
#--------------------------------------------------------------------

TEA_INIT([3.9])

AC_CONFIG_AUX_DIR(tclconfig)

#--------------------------------------------------------------------
# Load the tclConfig.sh file
#--------------------------------------------------------------------

TEA_PATH_TCLCONFIG
TEA_LOAD_TCLCONFIG

#-----------------------------------------------------------------------
# Handle the --prefix=... option by defaulting to what Tcl gave.
# Must be called after TEA_LOAD_TCLCONFIG and before TEA_SETUP_COMPILER.
#-----------------------------------------------------------------------

TEA_PREFIX

#-----------------------------------------------------------------------
# Standard compiler checks.
# This sets up CC by using the CC env var, or looks for gcc otherwise.
# This also calls AC_PROG_CC, AC_PROG_INSTALL and a few others to create
# the basic setup necessary to compile executables.
#-----------------------------------------------------------------------

TEA_SETUP_COMPILER

#-----------------------------------------------------------------------
# __CHANGE__
# Specify the C source files to compile in TEA_ADD_SOURCES,
# public headers that need to be installed in TEA_ADD_HEADERS,
# stub library C source files to compile in TEA_ADD_STUB_SOURCES,
# and runtime Tcl library files in TEA_ADD_TCL_SOURCES.
# This defines PKG(_STUB)_SOURCES, PKG(_STUB)_OBJECTS, PKG_HEADERS
# and PKG_TCL_SOURCES.
#-----------------------------------------------------------------------

TEA_ADD_SOURCES([
    topcua.c
    open62541/open62541.c
])
TEA_ADD_CFLAGS([-Iopen62541])
TEA_ADD_STUB_SOURCES([])
TEA_ADD_TCL_SOURCES([library/topcua.tcl])

#--------------------------------------------------------------------
# __CHANGE__
# Choose which headers you need.  Extension authors should try very
# hard to only rely on the Tcl public header files.  Internal headers
# contain private data structures and are subject to change without
# notice.
# This MUST be called after TEA_PATH_TCLCONFIG/TEA_LOAD_TCLCONFIG
#--------------------------------------------------------------------

TEA_PUBLIC_TCL_HEADERS
#TEA_PRIVATE_TCL_HEADERS

#--------------------------------------------------------------------
# __CHANGE__
# A few miscellaneous platform-specific items:
#
# Define a special symbol for Windows (BUILD_Tktable in this case) so
# that we create the export library with the dll.
#
# Windows creates a few extra files that need to be cleaned up.
# You can add more files to clean if your extension creates any extra
# files.
#
# TEA_ADD any extra compiler/build info here.
#--------------------------------------------------------------------

TEA_ADD_CLEANFILES([pkgIndex.tcl])

#--------------------------------------------------------------------
# Check whether --enable-threads or --disable-threads was given.
# So far only Tcl responds to this one.
#--------------------------------------------------------------------

TEA_ENABLE_THREADS

#--------------------------------------------------------------------
# The statement below defines a collection of symbols related to
# building as a shared library instead of a static library.
#--------------------------------------------------------------------

TEA_ENABLE_SHARED

#--------------------------------------------------------------------
# This macro figures out what flags to use with the compiler/linker
# when building shared/static debug/optimized objects.  This information
# can be taken from the tclConfig.sh file, but this figures it all out.
#--------------------------------------------------------------------

TEA_CONFIG_CFLAGS

#--------------------------------------------------------------------
# Set the default compiler switches based on the --enable-symbols
# option.
#--------------------------------------------------------------------

TEA_ENABLE_SYMBOLS

#--------------------------------------------------------------------
# Everyone should be linking against the Tcl stub library.  If you
# can't for some reason, remove this definition.  If you aren't using
# stubs, you also need to modify the SHLIB_LD_LIBS setting below to
# link against the non-stubbed Tcl library.
#--------------------------------------------------------------------

AC_DEFINE(USE_TCL_STUBS)

#--------------------------------------------------------------------
# This macro generates a line to use when building a library.  It
# depends on values set by the TEA_ENABLE_SHARED, TEA_ENABLE_SYMBOLS,
# and TEA_LOAD_TCLCONFIG macros above.
#--------------------------------------------------------------------

TEA_MAKE_LIB

#--------------------------------------------------------------------
# Find tclsh so that we can run pkg_mkIndex to generate the pkgIndex.tcl
# file during the install process.  Don't run the TCLSH_PROG through
# ${CYGPATH} because it's being used directly by make.
# Require that we use a tclsh shell version 8.2 or later since earlier
# versions have bugs in the pkg_mkIndex routine.
#--------------------------------------------------------------------

TEA_PROG_TCLSH

#--------------------------------------------------------------------
# Finally, substitute all of the various values into the Makefile.
#--------------------------------------------------------------------

AC_OUTPUT([Makefile pkgIndex.tcl])
Added jni/topcua/library/topcua.tcl.




































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# topcua.tcl --
#
# Library functions of a proof of concept Tcl binding to the
# open62541 OPC UA library (client only).
#
# Copyright (c) 2018 Christian Werner <chw at ch minus werner dot de>
#
# See the file "license.terms" for information on usage and redistribution of
# this file, and for a DISCLAIMER OF ALL WARRANTIES.

namespace eval ::opcua {

    proc _walk {client nodeid browsename dispname nodeclass
		    refnodeid typenodeid result {level 0} {path {}}} {
	if {$level > 32} return
	if {[lsearch -exact $path $nodeid] >= 0} return
	upvar $result ret
	lappend ret $level $nodeid $browsename $dispname \
	    $nodeclass $refnodeid $typenodeid
	if {$nodeclass eq "Variable"} return
	incr level
	set path [concat $path $nodeid]
	foreach {n b d c r t} [lsort -stride 6 -index 1 \
		[browse $client $nodeid Forward \
		    [reftype HierarchicalReferences]]] {
	    if {$b eq "FolderType"} continue
	    _walk $client $n $b $d $c $r $t ret $level $path
	}
    }

    # Return a list of the address space resembling the
    # tree view of UAExpert. List layout adds level column
    # to "opcua::browse ..." list:
    #
    #   level        - 0 is Root, 1 is Objects etc.
    #   nodeid       - the node identifier, e.g. "ns=1;i=99"
    #   browsename   - name of node for browsing
    #   dispname     - name of node for display
    #   nodeclass    - class of node, e.g. "Variable"
    #   refnodeid    - reference node identifer
    #   typenodeid   - type node identifier

    proc tree {client} {
	set ret {}
	_walk $client i=84 Root Root Object i=35 i=61 ret
	return $ret
    }

    # Similar to tree, but make path like layout
    # as in "browsepath nodeid nodeclasspath refnodeid typenodeid ..."

    proc ptree {client} {
	set ret {}
	set pp {}
	set cc {}
	set last_b {}
	set last_c {}
	set i -1
	foreach {l n b d c r t} [tree $client] {
	    if {[scan $n "ns=%d;%s" ns rest] == 2} {
		set nsb ${ns}:$b
	    } else {
		set nsb $b
	    }
	    if {$l > $i} {
		set i $l
		lappend pp $last_b
		lappend cc $last_c
	    } elseif {$l < $i} {
		set diff [expr {$i - $l}]
		set i $l
		set pp [lrange $pp 0 end-$diff]
		set cc [lrange $cc 0 end-$diff]
	    }
	    set last_b $nsb
	    set last_c $c
	    set br $pp
	    lappend br $nsb
	    set cl $cc
	    lappend cl $c
	    lappend ret [join $br "/"] $n [join $cl "/"] $r $t
	}
	return $ret
    }

    # Return a list of child nodes given parent

    proc children {client nodeid} {
	set ret {}
	foreach {n b d c r t} [browse $client $nodeid Forward \
		[reftype HierarchicalReferences]] {
	    lappend ret $n
	}
	return $ret
    }

    # Return the parent node given child

    proc parent {client nodeid} {
	set ret {}
	foreach {n b d c r t} [browse $client $nodeid Inverse \
		[reftype HierarchicalReferences]] {
	    set ret $n
	    # only the first item
	    break
	}
	return $ret
    }

    # Generate stubs for methods in sub-namespace derived from
    # client name. Argument strip is cut off from the begin
    # of browsepaths, all following arguments are glob patterns
    # for matching browsepaths.
    #
    # TBD: find out argument types of generated procs.

    proc genstubs {client strip args} {
	namespace eval ::opcua::$client {}
	set all [expr {[llength $args] == 0}]
	foreach {b n c r t} [ptree $client] {
	    if {[string first $strip $b] != 0} {
		continue
	    }
	    if {![string match "*Object/Method" $c]} {
		continue
	    }
	    if {$all} {
		set found 1
	    } else {
		set found 0
		foreach pat $args {
		    if {[string match $pat $b]} {
			set found 1
			break
		    }
		}
	    }
	    if {$found} {
		set b [string range $b [string length $strip] end]
		set o [parent $client $n]
		set o [list $o]		;# beware of semicolon
		set n [list $n]		;# beware of semicolon
		eval [subst -nocommands {
		    proc ::opcua::${client}::${b} args {
			tailcall ::opcua::call $client $o $n {*}\$args
		    }}]
	    }
	}
    }

    # Make some procs visible in opcua ensemble

    proc _init {} {
	set cmds [namespace ensemble configure ::opcua -subcommands]
	lappend cmds tree ptree children parent genstubs
	namespace ensemble configure ::opcua -subcommands $cmds
    }

    _init
    rename _init {}

}
Added jni/topcua/open62541/AUTHORS.


























>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
The authors of open62541 are (in alphabetical order)

Bauer, Maximilian
Ebrahimi, Reza <reza.ebrahimi.dev (at) gmail.com>
Graube, Markus <markus.graube (at) tu-dresden.de>
Gruener, Sten <s.gruener (at) plt.rwth-aachen.de>
Iatrou, Chris Paul <chris_paul.iatrou (at) tu-dresden.de>
Jeromin, Holger
Palm, Florian <f.palm (at) plt.rwth-aachen.de>
Pfrommer, Julius <julius.pfrommer (at) kit.edu>
Profanter, Stefan <profanter (at) fortiss.org>
Stalder, Thomas <t.stalder (at) bluetimeconcept.ch>
Urbas, Leon <leon.urbas (at) tu-dresden.de>
Added jni/topcua/open62541/LICENSE.










































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
Mozilla Public License Version 2.0
==================================

1. Definitions
--------------

1.1. "Contributor"
    means each individual or legal entity that creates, contributes to
    the creation of, or owns Covered Software.

1.2. "Contributor Version"
    means the combination of the Contributions of others (if any) used
    by a Contributor and that particular Contributor's Contribution.

1.3. "Contribution"
    means Covered Software of a particular Contributor.

1.4. "Covered Software"
    means Source Code Form to which the initial Contributor has attached
    the notice in Exhibit A, the Executable Form of such Source Code
    Form, and Modifications of such Source Code Form, in each case
    including portions thereof.

1.5. "Incompatible With Secondary Licenses"
    means

    (a) that the initial Contributor has attached the notice described
        in Exhibit B to the Covered Software; or

    (b) that the Covered Software was made available under the terms of
        version 1.1 or earlier of the License, but not also under the
        terms of a Secondary License.

1.6. "Executable Form"
    means any form of the work other than Source Code Form.

1.7. "Larger Work"
    means a work that combines Covered Software with other material, in 
    a separate file or files, that is not Covered Software.

1.8. "License"
    means this document.

1.9. "Licensable"
    means having the right to grant, to the maximum extent possible,
    whether at the time of the initial grant or subsequently, any and
    all of the rights conveyed by this License.

1.10. "Modifications"
    means any of the following:

    (a) any file in Source Code Form that results from an addition to,
        deletion from, or modification of the contents of Covered
        Software; or

    (b) any new file in Source Code Form that contains any Covered
        Software.

1.11. "Patent Claims" of a Contributor
    means any patent claim(s), including without limitation, method,
    process, and apparatus claims, in any patent Licensable by such
    Contributor that would be infringed, but for the grant of the
    License, by the making, using, selling, offering for sale, having
    made, import, or transfer of either its Contributions or its
    Contributor Version.

1.12. "Secondary License"
    means either the GNU General Public License, Version 2.0, the GNU
    Lesser General Public License, Version 2.1, the GNU Affero General
    Public License, Version 3.0, or any later versions of those
    licenses.

1.13. "Source Code Form"
    means the form of the work preferred for making modifications.

1.14. "You" (or "Your")
    means an individual or a legal entity exercising rights under this
    License. For legal entities, "You" includes any entity that
    controls, is controlled by, or is under common control with You. For
    purposes of this definition, "control" means (a) the power, direct
    or indirect, to cause the direction or management of such entity,
    whether by contract or otherwise, or (b) ownership of more than
    fifty percent (50%) of the outstanding shares or beneficial
    ownership of such entity.

2. License Grants and Conditions
--------------------------------

2.1. Grants

Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:

(a) under intellectual property rights (other than patent or trademark)
    Licensable by such Contributor to use, reproduce, make available,
    modify, display, perform, distribute, and otherwise exploit its
    Contributions, either on an unmodified basis, with Modifications, or
    as part of a Larger Work; and

(b) under Patent Claims of such Contributor to make, use, sell, offer
    for sale, have made, import, and otherwise transfer either its
    Contributions or its Contributor Version.

2.2. Effective Date

The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.

2.3. Limitations on Grant Scope

The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:

(a) for any code that a Contributor has removed from Covered Software;
    or

(b) for infringements caused by: (i) Your and any other third party's
    modifications of Covered Software, or (ii) the combination of its
    Contributions with other software (except as part of its Contributor
    Version); or

(c) under Patent Claims infringed by Covered Software in the absence of
    its Contributions.

This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).

2.4. Subsequent Licenses

No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).

2.5. Representation

Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.

2.6. Fair Use

This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.

2.7. Conditions

Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.

3. Responsibilities
-------------------

3.1. Distribution of Source Form

All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.

3.2. Distribution of Executable Form

If You distribute Covered Software in Executable Form then:

(a) such Covered Software must also be made available in Source Code
    Form, as described in Section 3.1, and You must inform recipients of
    the Executable Form how they can obtain a copy of such Source Code
    Form by reasonable means in a timely manner, at a charge no more
    than the cost of distribution to the recipient; and

(b) You may distribute such Executable Form under the terms of this
    License, or sublicense it under different terms, provided that the
    license for the Executable Form does not attempt to limit or alter
    the recipients' rights in the Source Code Form under this License.

3.3. Distribution of a Larger Work

You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).

3.4. Notices

You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.

3.5. Application of Additional Terms

You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.

4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------

If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.

5. Termination
--------------

5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.

5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.

5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.

************************************************************************
*                                                                      *
*  6. Disclaimer of Warranty                                           *
*  -------------------------                                           *
*                                                                      *
*  Covered Software is provided under this License on an "as is"       *
*  basis, without warranty of any kind, either expressed, implied, or  *
*  statutory, including, without limitation, warranties that the       *
*  Covered Software is free of defects, merchantable, fit for a        *
*  particular purpose or non-infringing. The entire risk as to the     *
*  quality and performance of the Covered Software is with You.        *
*  Should any Covered Software prove defective in any respect, You     *
*  (not any Contributor) assume the cost of any necessary servicing,   *
*  repair, or correction. This disclaimer of warranty constitutes an   *
*  essential part of this License. No use of any Covered Software is   *
*  authorized under this License except under this disclaimer.         *
*                                                                      *
************************************************************************

************************************************************************
*                                                                      *
*  7. Limitation of Liability                                          *
*  --------------------------                                          *
*                                                                      *
*  Under no circumstances and under no legal theory, whether tort      *
*  (including negligence), contract, or otherwise, shall any           *
*  Contributor, or anyone who distributes Covered Software as          *
*  permitted above, be liable to You for any direct, indirect,         *
*  special, incidental, or consequential damages of any character      *
*  including, without limitation, damages for lost profits, loss of    *
*  goodwill, work stoppage, computer failure or malfunction, or any    *
*  and all other commercial damages or losses, even if such party      *
*  shall have been informed of the possibility of such damages. This   *
*  limitation of liability shall not apply to liability for death or   *
*  personal injury resulting from such party's negligence to the       *
*  extent applicable law prohibits such limitation. Some               *
*  jurisdictions do not allow the exclusion or limitation of           *
*  incidental or consequential damages, so this exclusion and          *
*  limitation may not apply to You.                                    *
*                                                                      *
************************************************************************

8. Litigation
-------------

Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.

9. Miscellaneous
----------------

This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.

10. Versions of the License
---------------------------

10.1. New Versions

Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.

10.2. Effect of New Versions

You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.

10.3. Modified Versions

If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).

10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses

If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.

Exhibit A - Source Code Form License Notice
-------------------------------------------

  This Source Code Form is subject to the terms of the Mozilla Public
  License, v. 2.0. If a copy of the MPL was not distributed with this
  file, You can obtain one at http://mozilla.org/MPL/2.0/.

If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.

You may add additional accurate notices of copyright ownership.

Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------

  This Source Code Form is "Incompatible With Secondary Licenses", as
  defined by the Mozilla Public License, v. 2.0.
Added jni/topcua/open62541/README.md.




















































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
open62541
=========

open62541 (http://open62541.org) is an open source and free implementation of OPC UA (OPC Unified Architecture) written in the common subset of the C99 and C++98 languages. The library is usable with all major compilers and provides the necessary tools to implement dedicated OPC UA clients and servers, or to integrate OPC UA-based communication into existing applications. open62541 library is platform independent. All platform-specific functionality is implemented via exchangeable plugins. Plugin implementations are provided for the major operating systems.

open62541 is licensed under the Mozilla Public License v2.0. So the *open62541 library can be used in projects that are not open source*. Only changes to the open62541 library itself need to published under the same license. The plugins, as well as the server and client examples are in the public domain (CC0 license). They can be reused under any license and changes do not have to be published.

The library is [available](https://github.com/open62541/open62541/releases) in standard source and binary form. In addition, the single-file source distribution merges the entire library into a single .c and .h file that can be easily added to existing projects. Example server and client implementations can be found in the [/examples](examples/) directory or further down on this page.

[![Ohloh Project Status](https://www.ohloh.net/p/open62541/widgets/project_thin_badge.gif)](https://www.ohloh.net/p/open62541)
[![Build Status](https://img.shields.io/travis/open62541/open62541/master.svg)](https://travis-ci.org/open62541/open62541)
[![MSVS build status](https://img.shields.io/appveyor/ci/open62541/open62541/master.svg)](https://ci.appveyor.com/project/open62541/open62541/branch/master)
[![Coverity Scan Build Status](https://img.shields.io/coverity/scan/12248.svg)](https://scan.coverity.com/projects/open62541-open62541)
[![Coverage Status](https://img.shields.io/coveralls/open62541/open62541/master.svg)](https://coveralls.io/r/open62541/open62541?branch=master)
[![Overall Downloads](https://img.shields.io/github/downloads/open62541/open62541/total.svg)](https://github.com/open62541/open62541/releases)

### Features

For a complete list of features check: [open62541 Features](FEATURES.md)

open62541 implements the OPC UA binary protocol stack as well as a client and server SDK. It currently supports the Micro Embedded Device Server Profile plus some additional features. The final server binaries can be well under 100kb, depending on the size of the information model.
- Communication Stack
  - OPC UA binary protocol
  - Chunking (splitting of large messages)
  - Exchangeable network layer (plugin) for using custom networking APIs (e.g. on embedded targets)
- Information model
  - Support for all OPC UA node types (including method nodes)
  - Support for adding and removing nodes and references also at runtime.
  - Support for inheritance and instantiation of object- and variable-types (custom constructor/destructor, instantiation of child nodes)
- Subscriptions
  - Support for subscriptions/monitoreditems for data change notifications
  - Very low resource consumption for each monitored value (event-based server architecture)
- Code-Generation
  - Support for generating data types from standard XML definitions
  - Support for generating server-side information models (nodesets) from standard XML definitions
  
Features currently being implemented:
- Target 0.3 release (to be released in the coming weeks):
  - Secure communication with encrypted messages (Done)
  - Access control for individual nodes (Done)
  - Asynchronous service requests in the client (Done)
- Target 0.4 release:
  - Events (notifications emitted by objects, data change notifications are implemented), WIP by @Pro
  - Event-loop (background tasks) in the client
  - Publish/Subscribe based on UDP (Specification Part 14), WIP @ Fraunhofer IOSB

### Dependencies

On most systems, open62541 requires the C standard library only. For dependencies during the build process, see the following list and the [build documentation](https://open62541.org/doc/current/building.html) for details.

- Core Library: The core library has no dependencies besides the C99 standard headers.
- Default Plugins: The default plugins use the POSIX interfaces for networking and accessing the system clock. Ports to different (embedded) architectures are achieved by customizing the plugins.
- Building and Code Generation: The build environment is generated via CMake. Some code is auto-generated from XML definitions that are part of the OPC UA standard. The code generation scripts run with both Python 2 and 3.

### Code Quality

We emphasize code quality. The following quality metrics are continuously checked and are ensured to hold before an official release is made:

- Zero errors indicated by the Compliance Testing Tool (CTT) of the OPC Foundation for the supported features
- Zero compiler warnings from GCC/Clang/MSVC with very strict compilation flags
- Zero issues indicated by unit tests (more than 80% coverage)
- Zero issues indicated by clang-analyzer, clang-tidy, cpp-check and the Coverity static code analysis tools
- Zero unresolved issues from fuzzing the library in Google's oss-fuzz infrastructure
- Zero issues indicated by Valgrind (Linux), DrMemory (Windows) and Clang AddressSanitizer / MemorySanitizer for the CTT tests, unit tests and fuzzing

### Documentation and Support

A general introduction to OPC UA and the open62541 documentation can be found at http://open62541.org/doc/current.
Past releases of the library can be downloaded at https://github.com/open62541/open62541/releases.
To use the latest improvements, download a nightly build of the *single-file distribution* (the entire library merged into a single source and header file) from http://open62541.org/releases. Nightly builds of MSVC binaries of the library are available [here](https://ci.appveyor.com/project/open62541/open62541/build/artifacts).

For individual discussion and support, use the following channels

- the [mailing list](https://groups.google.com/d/forum/open62541)
- our [IRC channel](http://webchat.freenode.net/?channels=%23open62541)
- the [bugtracker](https://github.com/open62541/open62541/issues)

or contact a member of the core development group (see below).

### Development

Besides the general open62541 community, a group of core maintainers jointly steers the long-term development. The current core maintainers are (as of Mai 2017, in alphabetical order):

- Chris-Paul Iatrou (Dresden University of Technology, Chair for Process Control Systems Engineering)
- Florian Palm (RWTH Aachen University, Chair of Process Control Engineering)
- Julius Pfrommer (Fraunhofer IOSB, Karlsruhe)
- Stefan Profanter (fortiss, Munich)

As an open source project, we encourage new contributors to help improve open62541. The following are good starting points for new contributors:
- [Report bugs](https://github.com/open62541/open62541/issues)
- Improve the [documentation](http://open62541.org/doc/current)
- Work on issues marked as "[good first issue](https://github.com/open62541/open62541/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22)"

### Example Server Implementation
Compile the examples with the single-file distribution `open62541.h/.c` header and source file.
Using the GCC compiler, just run ```gcc -std=c99 <server.c> open62541.c -o server``` (under Windows you may need to add ``` -lws2_32```).
```c
#include <signal.h>
#include "open62541.h"

UA_Boolean running = true;
void signalHandler(int sig) {
    running = false;
}

int main(int argc, char** argv)
{
    signal(SIGINT, signalHandler); /* catch ctrl-c */

    /* Create a server listening on port 4840 */
    UA_ServerConfig *config = UA_ServerConfig_new_default();
    UA_Server *server = UA_Server_new(config);

    /* Add a variable node */
    /* 1) Define the node attributes */
    UA_VariableAttributes attr = UA_VariableAttributes_default;
    attr.displayName = UA_LOCALIZEDTEXT("en-US", "the answer");
    UA_Int32 myInteger = 42;
    UA_Variant_setScalar(&attr.value, &myInteger, &UA_TYPES[UA_TYPES_INT32]);

    /* 2) Define where the node shall be added with which browsename */
    UA_NodeId newNodeId = UA_NODEID_STRING(1, "the.answer");
    UA_NodeId parentNodeId = UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER);
    UA_NodeId parentReferenceNodeId = UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES);
    UA_NodeId variableType = UA_NODEID_NULL; /* take the default variable type */
    UA_QualifiedName browseName = UA_QUALIFIEDNAME(1, "the answer");

    /* 3) Add the node */
    UA_Server_addVariableNode(server, newNodeId, parentNodeId, parentReferenceNodeId,
                              browseName, variableType, attr, NULL, NULL);

    /* Run the server loop */
    UA_StatusCode status = UA_Server_run(server, &running);
    UA_Server_delete(server);
    UA_ServerConfig_delete(config);
    return status;
}
```

### Example Client Implementation
```c
#include <stdio.h>
#include "open62541.h"

int main(int argc, char *argv[])
{
    /* Create a client and connect */
    UA_Client *client = UA_Client_new(UA_ClientConfig_default);
    UA_StatusCode status = UA_Client_connect(client, "opc.tcp://localhost:4840");
    if(status != UA_STATUSCODE_GOOD) {
        UA_Client_delete(client);
        return status;
    }

    /* Read the value attribute of the node. UA_Client_readValueAttribute is a
     * wrapper for the raw read service available as UA_Client_Service_read. */
    UA_Variant value; /* Variants can hold scalar values and arrays of any type */
    UA_Variant_init(&value);
    status = UA_Client_readValueAttribute(client, UA_NODEID_STRING(1, "the.answer"), &value);
    if(status == UA_STATUSCODE_GOOD &&
       UA_Variant_hasScalarType(&value, &UA_TYPES[UA_TYPES_INT32])) {
        printf("the value is: %i\n", *(UA_Int32*)value.data);
    }

    /* Clean up */
    UA_Variant_deleteMembers(&value);
    UA_Client_delete(client); /* Disconnects the client internally */
    return status;
}
```
Added jni/topcua/open62541/chw.patch.






































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
The following patch relaxes type checking on attribute R/W functions.
This simplifies the "opcua read ..." and "opcua write ..." logic.

--- open62541.c.orig	2018-06-12 21:22:43.000000000 +0200
+++ open62541.c	2018-08-08 20:56:19.362605790 +0200
@@ -37019,7 +37019,8 @@
     UA_WriteValue_init(&wValue);
     wValue.nodeId = *nodeId;
     wValue.attributeId = attributeId;
-    if(attributeId == UA_ATTRIBUTEID_VALUE)
+    if(attributeId == UA_ATTRIBUTEID_VALUE &&
+       inDataType == &UA_TYPES[UA_TYPES_VARIANT])
         wValue.value.value = *(const UA_Variant*)in;
     else
         /* hack. is never written into. */
@@ -37122,13 +37123,18 @@
     if(attributeId == UA_ATTRIBUTEID_VALUE) {
         memcpy(out, &res->value, sizeof(UA_Variant));
         UA_Variant_init(&res->value);
-    } else if(attributeId == UA_ATTRIBUTEID_NODECLASS) {
+    } else if(attributeId == UA_ATTRIBUTEID_NODECLASS &&
+              outDataType != &UA_TYPES[UA_TYPES_VARIANT]) {
         memcpy(out, (UA_NodeClass*)res->value.data, sizeof(UA_NodeClass));
     } else if(UA_Variant_isScalar(&res->value) &&
               res->value.type == outDataType) {
         memcpy(out, res->value.data, res->value.type->memSize);
         UA_free(res->value.data);
         res->value.data = NULL;
+    } else if(UA_Variant_isScalar(&res->value) &&
+              outDataType == &UA_TYPES[UA_TYPES_VARIANT]) {
+        memcpy(out, &res->value, sizeof(UA_Variant));
+        UA_Variant_init(&res->value);
     } else {
         retval = UA_STATUSCODE_BADUNEXPECTEDERROR;
     }
Added jni/topcua/open62541/open62541.c.

more than 10,000 changes

Added jni/topcua/open62541/open62541.h.

more than 10,000 changes

Added jni/topcua/open62541/open62541.pdf.

cannot compute difference between binary files

Added jni/topcua/pkgIndex.tcl.in.








>
>
>
>
1
2
3
4
package ifneeded @PACKAGE_NAME@ @PACKAGE_VERSION@ [subst {
    load [list [file join $dir @PKG_LIB_FILE@]] @PACKAGE_NAME@
    source [list [file join $dir @PACKAGE_NAME@.tcl]]
}]
Added jni/topcua/tclconfig/README.txt.




















































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
These files comprise the basic building blocks for a Tcl Extension
Architecture (TEA) extension.  For more information on TEA see:

	http://www.tcl.tk/doc/tea/

This package is part of the Tcl project at SourceForge, and latest
sources should be available there:

	http://tcl.sourceforge.net/

This package is a freely available open source package.  You can do
virtually anything you like with it, such as modifying it, redistributing
it, and selling it either in whole or in part.

CONTENTS
========
The following is a short description of the files you will find in
the sample extension.

README.txt	This file

install-sh	Program used for copying binaries and script files
		to their install locations.

tcl.m4		Collection of Tcl autoconf macros.  Included by a package's
		aclocal.m4 to define SC_* macros.
Added jni/topcua/tclconfig/install-sh.
































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
#!/bin/sh
# install - install a program, script, or datafile

scriptversion=2011-04-20.01; # UTC

# This originates from X11R5 (mit/util/scripts/install.sh), which was
# later released in X11R6 (xc/config/util/install.sh) with the
# following copyright and license.
#
# Copyright (C) 1994 X Consortium
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC-
# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Except as contained in this notice, the name of the X Consortium shall not
# be used in advertising or otherwise to promote the sale, use or other deal-
# ings in this Software without prior written authorization from the X Consor-
# tium.
#
#
# FSF changes to this file are in the public domain.
#
# Calling this script install-sh is preferred over install.sh, to prevent
# `make' implicit rules from creating a file called install from it
# when there is no Makefile.
#
# This script is compatible with the BSD install script, but was written
# from scratch.

nl='
'
IFS=" ""	$nl"

# set DOITPROG to echo to test this script

# Don't use :- since 4.3BSD and earlier shells don't like it.
doit=${DOITPROG-}
if test -z "$doit"; then
  doit_exec=exec
else
  doit_exec=$doit
fi

# Put in absolute file names if you don't have them in your path;
# or use environment vars.

chgrpprog=${CHGRPPROG-chgrp}
chmodprog=${CHMODPROG-chmod}
chownprog=${CHOWNPROG-chown}
cmpprog=${CMPPROG-cmp}
cpprog=${CPPROG-cp}
mkdirprog=${MKDIRPROG-mkdir}
mvprog=${MVPROG-mv}
rmprog=${RMPROG-rm}
stripprog=${STRIPPROG-strip}

posix_glob='?'
initialize_posix_glob='
  test "$posix_glob" != "?" || {
    if (set -f) 2>/dev/null; then
      posix_glob=
    else
      posix_glob=:
    fi
  }
'

posix_mkdir=

# Desired mode of installed file.
mode=0755

chgrpcmd=
chmodcmd=$chmodprog
chowncmd=
mvcmd=$mvprog
rmcmd="$rmprog -f"
stripcmd=

src=
dst=
dir_arg=
dst_arg=

copy_on_change=false
no_target_directory=

usage="\
Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
   or: $0 [OPTION]... SRCFILES... DIRECTORY
   or: $0 [OPTION]... -t DIRECTORY SRCFILES...
   or: $0 [OPTION]... -d DIRECTORIES...

In the 1st form, copy SRCFILE to DSTFILE.
In the 2nd and 3rd, copy all SRCFILES to DIRECTORY.
In the 4th, create DIRECTORIES.

Options:
     --help     display this help and exit.
     --version  display version info and exit.

  -c            (ignored)
  -C            install only if different (preserve the last data modification time)
  -d            create directories instead of installing files.
  -g GROUP      $chgrpprog installed files to GROUP.
  -m MODE       $chmodprog installed files to MODE.
  -o USER       $chownprog installed files to USER.
  -s            $stripprog installed files.
  -S            $stripprog installed files.
  -t DIRECTORY  install into DIRECTORY.
  -T            report an error if DSTFILE is a directory.

Environment variables override the default commands:
  CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG
  RMPROG STRIPPROG
"

while test $# -ne 0; do
  case $1 in
    -c) ;;

    -C) copy_on_change=true;;

    -d) dir_arg=true;;

    -g) chgrpcmd="$chgrpprog $2"
	shift;;

    --help) echo "$usage"; exit $?;;

    -m) mode=$2
	case $mode in
	  *' '* | *'	'* | *'
'*	  | *'*'* | *'?'* | *'['*)
	    echo "$0: invalid mode: $mode" >&2
	    exit 1;;
	esac
	shift;;

    -o) chowncmd="$chownprog $2"
	shift;;

    -s) stripcmd=$stripprog;;

    -S) stripcmd="$stripprog $2"
	shift;;

    -t) dst_arg=$2
	shift;;

    -T) no_target_directory=true;;

    --version) echo "$0 $scriptversion"; exit $?;;

    --)	shift
	break;;

    -*)	echo "$0: invalid option: $1" >&2
	exit 1;;

    *)  break;;
  esac
  shift
done

if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
  # When -d is used, all remaining arguments are directories to create.
  # When -t is used, the destination is already specified.
  # Otherwise, the last argument is the destination.  Remove it from $@.
  for arg
  do
    if test -n "$dst_arg"; then
      # $@ is not empty: it contains at least $arg.
      set fnord "$@" "$dst_arg"
      shift # fnord
    fi
    shift # arg
    dst_arg=$arg
  done
fi

if test $# -eq 0; then
  if test -z "$dir_arg"; then
    echo "$0: no input file specified." >&2
    exit 1
  fi
  # It's OK to call `install-sh -d' without argument.
  # This can happen when creating conditional directories.
  exit 0
fi

if test -z "$dir_arg"; then
  do_exit='(exit $ret); exit $ret'
  trap "ret=129; $do_exit" 1
  trap "ret=130; $do_exit" 2
  trap "ret=141; $do_exit" 13
  trap "ret=143; $do_exit" 15

  # Set umask so as not to create temps with too-generous modes.
  # However, 'strip' requires both read and write access to temps.
  case $mode in
    # Optimize common cases.
    *644) cp_umask=133;;
    *755) cp_umask=22;;

    *[0-7])
      if test -z "$stripcmd"; then
	u_plus_rw=
      else
	u_plus_rw='% 200'
      fi
      cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;;
    *)
      if test -z "$stripcmd"; then
	u_plus_rw=
      else
	u_plus_rw=,u+rw
      fi
      cp_umask=$mode$u_plus_rw;;
  esac
fi

for src
do
  # Protect names starting with `-'.
  case $src in
    -*) src=./$src;;
  esac

  if test -n "$dir_arg"; then
    dst=$src
    dstdir=$dst
    test -d "$dstdir"
    dstdir_status=$?
  else

    # Waiting for this to be detected by the "$cpprog $src $dsttmp" command
    # might cause directories to be created, which would be especially bad
    # if $src (and thus $dsttmp) contains '*'.
    if test ! -f "$src" && test ! -d "$src"; then
      echo "$0: $src does not exist." >&2
      exit 1
    fi

    if test -z "$dst_arg"; then
      echo "$0: no destination specified." >&2
      exit 1
    fi

    dst=$dst_arg
    # Protect names starting with `-'.
    case $dst in
      -*) dst=./$dst;;
    esac

    # If destination is a directory, append the input filename; won't work
    # if double slashes aren't ignored.
    if test -d "$dst"; then
      if test -n "$no_target_directory"; then
	echo "$0: $dst_arg: Is a directory" >&2
	exit 1
      fi
      dstdir=$dst
      dst=$dstdir/`basename "$src"`
      dstdir_status=0
    else
      # Prefer dirname, but fall back on a substitute if dirname fails.
      dstdir=`
	(dirname "$dst") 2>/dev/null ||
	expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
	     X"$dst" : 'X\(//\)[^/]' \| \
	     X"$dst" : 'X\(//\)$' \| \
	     X"$dst" : 'X\(/\)' \| . 2>/dev/null ||
	echo X"$dst" |
	    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
		   s//\1/
		   q
		 }
		 /^X\(\/\/\)[^/].*/{
		   s//\1/
		   q
		 }
		 /^X\(\/\/\)$/{
		   s//\1/
		   q
		 }
		 /^X\(\/\).*/{
		   s//\1/
		   q
		 }
		 s/.*/./; q'
      `

      test -d "$dstdir"
      dstdir_status=$?
    fi
  fi

  obsolete_mkdir_used=false

  if test $dstdir_status != 0; then
    case $posix_mkdir in
      '')
	# Create intermediate dirs using mode 755 as modified by the umask.
	# This is like FreeBSD 'install' as of 1997-10-28.
	umask=`umask`
	case $stripcmd.$umask in
	  # Optimize common cases.
	  *[2367][2367]) mkdir_umask=$umask;;
	  .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;;

	  *[0-7])
	    mkdir_umask=`expr $umask + 22 \
	      - $umask % 100 % 40 + $umask % 20 \
	      - $umask % 10 % 4 + $umask % 2
	    `;;
	  *) mkdir_umask=$umask,go-w;;
	esac

	# With -d, create the new directory with the user-specified mode.
	# Otherwise, rely on $mkdir_umask.
	if test -n "$dir_arg"; then
	  mkdir_mode=-m$mode
	else
	  mkdir_mode=
	fi

	posix_mkdir=false
	case $umask in
	  *[123567][0-7][0-7])
	    # POSIX mkdir -p sets u+wx bits regardless of umask, which
	    # is incompatible with FreeBSD 'install' when (umask & 300) != 0.
	    ;;
	  *)
	    tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
	    trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0

	    if (umask $mkdir_umask &&
		exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1
	    then
	      if test -z "$dir_arg" || {
		   # Check for POSIX incompatibilities with -m.
		   # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
		   # other-writeable bit of parent directory when it shouldn't.
		   # FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
		   ls_ld_tmpdir=`ls -ld "$tmpdir"`
		   case $ls_ld_tmpdir in
		     d????-?r-*) different_mode=700;;
		     d????-?--*) different_mode=755;;
		     *) false;;
		   esac &&
		   $mkdirprog -m$different_mode -p -- "$tmpdir" && {
		     ls_ld_tmpdir_1=`ls -ld "$tmpdir"`
		     test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
		   }
		 }
	      then posix_mkdir=:
	      fi
	      rmdir "$tmpdir/d" "$tmpdir"
	    else
	      # Remove any dirs left behind by ancient mkdir implementations.
	      rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null
	    fi
	    trap '' 0;;
	esac;;
    esac

    if
      $posix_mkdir && (
	umask $mkdir_umask &&
	$doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
      )
    then :
    else

      # The umask is ridiculous, or mkdir does not conform to POSIX,
      # or it failed possibly due to a race condition.  Create the
      # directory the slow way, step by step, checking for races as we go.

      case $dstdir in
	/*) prefix='/';;
	-*) prefix='./';;
	*)  prefix='';;
      esac

      eval "$initialize_posix_glob"

      oIFS=$IFS
      IFS=/
      $posix_glob set -f
      set fnord $dstdir
      shift
      $posix_glob set +f
      IFS=$oIFS

      prefixes=

      for d
      do
	test -z "$d" && continue

	prefix=$prefix$d
	if test -d "$prefix"; then
	  prefixes=
	else
	  if $posix_mkdir; then
	    (umask=$mkdir_umask &&
	     $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
	    # Don't fail if two instances are running concurrently.
	    test -d "$prefix" || exit 1
	  else
	    case $prefix in
	      *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
	      *) qprefix=$prefix;;
	    esac
	    prefixes="$prefixes '$qprefix'"
	  fi
	fi
	prefix=$prefix/
      done

      if test -n "$prefixes"; then
	# Don't fail if two instances are running concurrently.
	(umask $mkdir_umask &&
	 eval "\$doit_exec \$mkdirprog $prefixes") ||
	  test -d "$dstdir" || exit 1
	obsolete_mkdir_used=true
      fi
    fi
  fi

  if test -n "$dir_arg"; then
    { test -z "$chowncmd" || $doit $chowncmd "$dst"; } &&
    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } &&
    { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false ||
      test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1
  else

    # Make a couple of temp file names in the proper directory.
    dsttmp=$dstdir/_inst.$$_
    rmtmp=$dstdir/_rm.$$_

    # Trap to clean up those temp files at exit.
    trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0

    # Copy the file name to the temp name.
    (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") &&

    # and set any options; do chmod last to preserve setuid bits.
    #
    # If any of these fail, we abort the whole thing.  If we want to
    # ignore errors from any of these, just make sure not to ignore
    # errors from the above "$doit $cpprog $src $dsttmp" command.
    #
    { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } &&
    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } &&
    { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } &&
    { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } &&

    # If -C, don't bother to copy if it wouldn't change the file.
    if $copy_on_change &&
       old=`LC_ALL=C ls -dlL "$dst"	2>/dev/null` &&
       new=`LC_ALL=C ls -dlL "$dsttmp"	2>/dev/null` &&

       eval "$initialize_posix_glob" &&
       $posix_glob set -f &&
       set X $old && old=:$2:$4:$5:$6 &&
       set X $new && new=:$2:$4:$5:$6 &&
       $posix_glob set +f &&

       test "$old" = "$new" &&
       $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1
    then
      rm -f "$dsttmp"
    else
      # Rename the file to the real destination.
      $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null ||

      # The rename failed, perhaps because mv can't rename something else
      # to itself, or perhaps because mv is so ancient that it does not
      # support -f.
      {
	# Now remove or move aside any old file at destination location.
	# We try this two ways since rm can't unlink itself on some
	# systems and the destination file might be busy for other
	# reasons.  In this case, the final cleanup might fail but the new
	# file should still install successfully.
	{
	  test ! -f "$dst" ||
	  $doit $rmcmd -f "$dst" 2>/dev/null ||
	  { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
	    { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
	  } ||
	  { echo "$0: cannot unlink or rename $dst" >&2
	    (exit 1); exit 1
	  }
	} &&

	# Now rename the file to the real destination.
	$doit $mvcmd "$dsttmp" "$dst"
      }
    fi || exit 1

    trap '' 0
  fi
done

# Local variables:
# eval: (add-hook 'write-file-hooks 'time-stamp)
# time-stamp-start: "scriptversion="
# time-stamp-format: "%:y-%02m-%02d.%02H"
# time-stamp-time-zone: "UTC"
# time-stamp-end: "; # UTC"
# End:
Added jni/topcua/tclconfig/tcl.m4.






































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
# tcl.m4 --
#
#	This file provides a set of autoconf macros to help TEA-enable
#	a Tcl extension.
#
# Copyright (c) 1999-2000 Ajuba Solutions.
# Copyright (c) 2002-2005 ActiveState Corporation.
#
# See the file "license.terms" for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.

AC_PREREQ(2.57)

dnl TEA extensions pass us the version of TEA they think they
dnl are compatible with (must be set in TEA_INIT below)
dnl TEA_VERSION="3.9"

# Possible values for key variables defined:
#
# TEA_WINDOWINGSYSTEM - win32 aqua x11 (mirrors 'tk windowingsystem')
# TEA_PLATFORM        - windows unix
#

#------------------------------------------------------------------------
# TEA_PATH_TCLCONFIG --
#
#	Locate the tclConfig.sh file and perform a sanity check on
#	the Tcl compile flags
#
# Arguments:
#	none
#
# Results:
#
#	Adds the following arguments to configure:
#		--with-tcl=...
#
#	Defines the following vars:
#		TCL_BIN_DIR	Full path to the directory containing
#				the tclConfig.sh file
#------------------------------------------------------------------------

AC_DEFUN([TEA_PATH_TCLCONFIG], [
    dnl TEA specific: Make sure we are initialized
    AC_REQUIRE([TEA_INIT])
    #
    # Ok, lets find the tcl configuration
    # First, look for one uninstalled.
    # the alternative search directory is invoked by --with-tcl
    #

    if test x"${no_tcl}" = x ; then
	# we reset no_tcl in case something fails here
	no_tcl=true
	AC_ARG_WITH(tcl,
	    AC_HELP_STRING([--with-tcl],
		[directory containing tcl configuration (tclConfig.sh)]),
	    with_tclconfig="${withval}")
	AC_MSG_CHECKING([for Tcl configuration])
	AC_CACHE_VAL(ac_cv_c_tclconfig,[

	    # First check to see if --with-tcl was specified.
	    if test x"${with_tclconfig}" != x ; then
		case "${with_tclconfig}" in
		    */tclConfig.sh )
			if test -f "${with_tclconfig}"; then
			    AC_MSG_WARN([--with-tcl argument should refer to directory containing tclConfig.sh, not to tclConfig.sh itself])
			    with_tclconfig="`echo "${with_tclconfig}" | sed 's!/tclConfig\.sh$!!'`"
			fi ;;
		esac
		if test -f "${with_tclconfig}/tclConfig.sh" ; then
		    ac_cv_c_tclconfig="`(cd "${with_tclconfig}"; pwd)`"
		else
		    AC_MSG_ERROR([${with_tclconfig} directory doesn't contain tclConfig.sh])
		fi
	    fi

	    # then check for a private Tcl installation
	    if test x"${ac_cv_c_tclconfig}" = x ; then
		for i in \
			../tcl \
			`ls -dr ../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
			`ls -dr ../tcl[[8-9]].[[0-9]] 2>/dev/null` \
			`ls -dr ../tcl[[8-9]].[[0-9]]* 2>/dev/null` \
			../../tcl \
			`ls -dr ../../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
			`ls -dr ../../tcl[[8-9]].[[0-9]] 2>/dev/null` \
			`ls -dr ../../tcl[[8-9]].[[0-9]]* 2>/dev/null` \
			../../../tcl \
			`ls -dr ../../../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
			`ls -dr ../../../tcl[[8-9]].[[0-9]] 2>/dev/null` \
			`ls -dr ../../../tcl[[8-9]].[[0-9]]* 2>/dev/null` ; do
		    if test "${TEA_PLATFORM}" = "windows" \
			    -a -f "$i/win/tclConfig.sh" ; then
			ac_cv_c_tclconfig="`(cd $i/win; pwd)`"
			break
		    fi
		    if test -f "$i/unix/tclConfig.sh" ; then
			ac_cv_c_tclconfig="`(cd $i/unix; pwd)`"
			break
		    fi
		done
	    fi

	    # on Darwin, check in Framework installation locations
	    if test "`uname -s`" = "Darwin" -a x"${ac_cv_c_tclconfig}" = x ; then
		for i in `ls -d ~/Library/Frameworks 2>/dev/null` \
			`ls -d /Library/Frameworks 2>/dev/null` \
			`ls -d /Network/Library/Frameworks 2>/dev/null` \
			`ls -d /System/Library/Frameworks 2>/dev/null` \
			; do
		    if test -f "$i/Tcl.framework/tclConfig.sh" ; then
			ac_cv_c_tclconfig="`(cd $i/Tcl.framework; pwd)`"
			break
		    fi
		done
	    fi

	    # TEA specific: on Windows, check in common installation locations
	    if test "${TEA_PLATFORM}" = "windows" \
		-a x"${ac_cv_c_tclconfig}" = x ; then
		for i in `ls -d C:/Tcl/lib 2>/dev/null` \
			`ls -d C:/Progra~1/Tcl/lib 2>/dev/null` \
			; do
		    if test -f "$i/tclConfig.sh" ; then
			ac_cv_c_tclconfig="`(cd $i; pwd)`"
			break
		    fi
		done
	    fi

	    # check in a few common install locations
	    if test x"${ac_cv_c_tclconfig}" = x ; then
		for i in `ls -d ${libdir} 2>/dev/null` \
			`ls -d ${exec_prefix}/lib 2>/dev/null` \
			`ls -d ${prefix}/lib 2>/dev/null` \
			`ls -d /usr/local/lib 2>/dev/null` \
			`ls -d /usr/contrib/lib 2>/dev/null` \
			`ls -d /usr/lib 2>/dev/null` \
			`ls -d /usr/lib64 2>/dev/null` \
			`ls -d /usr/lib/tcl8.6 2>/dev/null` \
			`ls -d /usr/lib/tcl8.5 2>/dev/null` \
			; do
		    if test -f "$i/tclConfig.sh" ; then
			ac_cv_c_tclconfig="`(cd $i; pwd)`"
			break
		    fi
		done
	    fi

	    # check in a few other private locations
	    if test x"${ac_cv_c_tclconfig}" = x ; then
		for i in \
			${srcdir}/../tcl \
			`ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
			`ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]] 2>/dev/null` \
			`ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]]* 2>/dev/null` ; do
		    if test "${TEA_PLATFORM}" = "windows" \
			    -a -f "$i/win/tclConfig.sh" ; then
			ac_cv_c_tclconfig="`(cd $i/win; pwd)`"
			break
		    fi
		    if test -f "$i/unix/tclConfig.sh" ; then
			ac_cv_c_tclconfig="`(cd $i/unix; pwd)`"
			break
		    fi
		done
	    fi
	])

	if test x"${ac_cv_c_tclconfig}" = x ; then
	    TCL_BIN_DIR="# no Tcl configs found"
	    AC_MSG_ERROR([Can't find Tcl configuration definitions. Use --with-tcl to specify a directory containing tclConfig.sh])
	else
	    no_tcl=
	    TCL_BIN_DIR="${ac_cv_c_tclconfig}"
	    AC_MSG_RESULT([found ${TCL_BIN_DIR}/tclConfig.sh])
	fi
    fi
])

#------------------------------------------------------------------------
# TEA_PATH_TKCONFIG --
#
#	Locate the tkConfig.sh file
#
# Arguments:
#	none
#
# Results:
#
#	Adds the following arguments to configure:
#		--with-tk=...
#
#	Defines the following vars:
#		TK_BIN_DIR	Full path to the directory containing
#				the tkConfig.sh file
#------------------------------------------------------------------------

AC_DEFUN([TEA_PATH_TKCONFIG], [
    #
    # Ok, lets find the tk configuration
    # First, look for one uninstalled.
    # the alternative search directory is invoked by --with-tk
    #

    if test x"${no_tk}" = x ; then
	# we reset no_tk in case something fails here
	no_tk=true
	AC_ARG_WITH(tk,
	    AC_HELP_STRING([--with-tk],
		[directory containing tk configuration (tkConfig.sh)]),
	    with_tkconfig="${withval}")
	AC_MSG_CHECKING([for Tk configuration])
	AC_CACHE_VAL(ac_cv_c_tkconfig,[

	    # First check to see if --with-tkconfig was specified.
	    if test x"${with_tkconfig}" != x ; then
		case "${with_tkconfig}" in
		    */tkConfig.sh )
			if test -f "${with_tkconfig}"; then
			    AC_MSG_WARN([--with-tk argument should refer to directory containing tkConfig.sh, not to tkConfig.sh itself])
			    with_tkconfig="`echo "${with_tkconfig}" | sed 's!/tkConfig\.sh$!!'`"
			fi ;;
		esac
		if test -f "${with_tkconfig}/tkConfig.sh" ; then
		    ac_cv_c_tkconfig="`(cd "${with_tkconfig}"; pwd)`"
		elif test -f "${with_tkconfig}/sdl2tkConfig.sh" ; then
		    ac_cv_c_tkconfig="`(cd "${with_tkconfig}"; pwd)`"
		else
		    AC_MSG_ERROR([${with_tkconfig} directory doesn't contain tkConfig.sh])
		fi
	    fi

	    # then check for a private Tk library
	    if test x"${ac_cv_c_tkconfig}" = x ; then
		for i in \
			../tk \
			`ls -dr ../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
			`ls -dr ../tk[[8-9]].[[0-9]] 2>/dev/null` \
			`ls -dr ../tk[[8-9]].[[0-9]]* 2>/dev/null` \
			../../tk \
			`ls -dr ../../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
			`ls -dr ../../tk[[8-9]].[[0-9]] 2>/dev/null` \
			`ls -dr ../../tk[[8-9]].[[0-9]]* 2>/dev/null` \
			../../../tk \
			`ls -dr ../../../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
			`ls -dr ../../../tk[[8-9]].[[0-9]] 2>/dev/null` \
			`ls -dr ../../../tk[[8-9]].[[0-9]]* 2>/dev/null` ; do
		    if test "${TEA_PLATFORM}" = "windows" \
			    -a -f "$i/win/tkConfig.sh" ; then
			ac_cv_c_tkconfig="`(cd $i/win; pwd)`"
			break
		    fi
		    if test -f "$i/unix/tkConfig.sh" ; then
			ac_cv_c_tkconfig="`(cd $i/unix; pwd)`"
			break
		    fi
		    if test -f "$i/sdl/sdl2tkConfig.sh" ; then
			ac_cv_c_tkconfig="`(cd $i/sdl; pwd)`"
			break
		    fi
		done
	    fi

	    # on Darwin, check in Framework installation locations
	    if test "`uname -s`" = "Darwin" -a x"${ac_cv_c_tkconfig}" = x ; then
		for i in `ls -d ~/Library/Frameworks 2>/dev/null` \
			`ls -d /Library/Frameworks 2>/dev/null` \
			`ls -d /Network/Library/Frameworks 2>/dev/null` \
			`ls -d /System/Library/Frameworks 2>/dev/null` \
			; do
		    if test -f "$i/Tk.framework/tkConfig.sh" ; then
			ac_cv_c_tkconfig="`(cd $i/Tk.framework; pwd)`"
			break
		    fi
		done
	    fi

	    # check in a few common install locations
	    if test x"${ac_cv_c_tkconfig}" = x ; then
		for i in `ls -d ${libdir} 2>/dev/null` \
			`ls -d ${exec_prefix}/lib 2>/dev/null` \
			`ls -d ${prefix}/lib 2>/dev/null` \
			`ls -d /usr/local/lib 2>/dev/null` \
			`ls -d /usr/contrib/lib 2>/dev/null` \
			`ls -d /usr/lib 2>/dev/null` \
			`ls -d /usr/lib64 2>/dev/null` \
			; do
		    if test -f "$i/tkConfig.sh" ; then
			ac_cv_c_tkconfig="`(cd $i; pwd)`"
			break
		    fi
		done
	    fi

	    # TEA specific: on Windows, check in common installation locations
	    if test "${TEA_PLATFORM}" = "windows" \
		-a x"${ac_cv_c_tkconfig}" = x ; then
		for i in `ls -d C:/Tcl/lib 2>/dev/null` \
			`ls -d C:/Progra~1/Tcl/lib 2>/dev/null` \
			; do
		    if test -f "$i/tkConfig.sh" ; then
			ac_cv_c_tkconfig="`(cd $i; pwd)`"
			break
		    fi
		done
	    fi

	    # check in a few other private locations
	    if test x"${ac_cv_c_tkconfig}" = x ; then
		for i in \
			${srcdir}/../tk \
			`ls -dr ${srcdir}/../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
			`ls -dr ${srcdir}/../tk[[8-9]].[[0-9]] 2>/dev/null` \
			`ls -dr ${srcdir}/../tk[[8-9]].[[0-9]]* 2>/dev/null` ; do
		    if test "${TEA_PLATFORM}" = "windows" \
			    -a -f "$i/win/tkConfig.sh" ; then
			ac_cv_c_tkconfig="`(cd $i/win; pwd)`"
			break
		    fi
		    if test -f "$i/unix/tkConfig.sh" ; then
			ac_cv_c_tkconfig="`(cd $i/unix; pwd)`"
			break
		    fi
		    if test -f "$i/sdl/sdl2tkConfig.sh" ; then
			ac_cv_c_tkconfig="`(cd $i/sdl; pwd)`"
			break
		    fi
		done
	    fi
	])

	if test x"${ac_cv_c_tkconfig}" = x ; then
	    TK_BIN_DIR="# no Tk configs found"
	    AC_MSG_ERROR([Can't find Tk configuration definitions. Use --with-tk to specify a directory containing tkConfig.sh])
	else
	    no_tk=
	    TK_BIN_DIR="${ac_cv_c_tkconfig}"
	    AC_MSG_RESULT([found ${TK_BIN_DIR}/tkConfig.sh])
	fi
    fi
])

#------------------------------------------------------------------------
# TEA_LOAD_TCLCONFIG --
#
#	Load the tclConfig.sh file
#
# Arguments:
#
#	Requires the following vars to be set:
#		TCL_BIN_DIR
#
# Results:
#
#	Substitutes the following vars:
#		TCL_BIN_DIR
#		TCL_SRC_DIR
#		TCL_LIB_FILE
#------------------------------------------------------------------------

AC_DEFUN([TEA_LOAD_TCLCONFIG], [
    AC_MSG_CHECKING([for existence of ${TCL_BIN_DIR}/tclConfig.sh])

    if test -f "${TCL_BIN_DIR}/tclConfig.sh" ; then
        AC_MSG_RESULT([loading])
	. "${TCL_BIN_DIR}/tclConfig.sh"
    else
        AC_MSG_RESULT([could not find ${TCL_BIN_DIR}/tclConfig.sh])
    fi

    # eval is required to do the TCL_DBGX substitution
    eval "TCL_LIB_FILE=\"${TCL_LIB_FILE}\""
    eval "TCL_STUB_LIB_FILE=\"${TCL_STUB_LIB_FILE}\""

    # If the TCL_BIN_DIR is the build directory (not the install directory),
    # then set the common variable name to the value of the build variables.
    # For example, the variable TCL_LIB_SPEC will be set to the value
    # of TCL_BUILD_LIB_SPEC. An extension should make use of TCL_LIB_SPEC
    # instead of TCL_BUILD_LIB_SPEC since it will work with both an
    # installed and uninstalled version of Tcl.
    if test -f "${TCL_BIN_DIR}/Makefile" ; then
        TCL_LIB_SPEC="${TCL_BUILD_LIB_SPEC}"
        TCL_STUB_LIB_SPEC="${TCL_BUILD_STUB_LIB_SPEC}"
        TCL_STUB_LIB_PATH="${TCL_BUILD_STUB_LIB_PATH}"
    elif test "`uname -s`" = "Darwin"; then
	# If Tcl was built as a framework, attempt to use the libraries
	# from the framework at the given location so that linking works
	# against Tcl.framework installed in an arbitrary location.
	case ${TCL_DEFS} in
	    *TCL_FRAMEWORK*)
		if test -f "${TCL_BIN_DIR}/${TCL_LIB_FILE}"; then
		    for i in "`cd "${TCL_BIN_DIR}"; pwd`" \
			     "`cd "${TCL_BIN_DIR}"/../..; pwd`"; do
			if test "`basename "$i"`" = "${TCL_LIB_FILE}.framework"; then
			    TCL_LIB_SPEC="-F`dirname "$i" | sed -e 's/ /\\\\ /g'` -framework ${TCL_LIB_FILE}"
			    break
			fi
		    done
		fi
		if test -f "${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}"; then
		    TCL_STUB_LIB_SPEC="-L`echo "${TCL_BIN_DIR}"  | sed -e 's/ /\\\\ /g'` ${TCL_STUB_LIB_FLAG}"
		    TCL_STUB_LIB_PATH="${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}"
		fi
		;;
	esac
    fi

    # eval is required to do the TCL_DBGX substitution
    eval "TCL_LIB_FLAG=\"${TCL_LIB_FLAG}\""
    eval "TCL_LIB_SPEC=\"${TCL_LIB_SPEC}\""
    eval "TCL_STUB_LIB_FLAG=\"${TCL_STUB_LIB_FLAG}\""
    eval "TCL_STUB_LIB_SPEC=\"${TCL_STUB_LIB_SPEC}\""

    AC_SUBST(TCL_VERSION)
    AC_SUBST(TCL_PATCH_LEVEL)
    AC_SUBST(TCL_BIN_DIR)
    AC_SUBST(TCL_SRC_DIR)

    AC_SUBST(TCL_LIB_FILE)
    AC_SUBST(TCL_LIB_FLAG)
    AC_SUBST(TCL_LIB_SPEC)

    AC_SUBST(TCL_STUB_LIB_FILE)
    AC_SUBST(TCL_STUB_LIB_FLAG)
    AC_SUBST(TCL_STUB_LIB_SPEC)

    AC_MSG_CHECKING([platform])
    hold_cc=$CC; CC="$TCL_CC"
    AC_TRY_COMPILE(,[
	    #ifdef _WIN32
		#error win32
	    #endif
    ], TEA_PLATFORM="unix",
	    TEA_PLATFORM="windows"
    )
    CC=$hold_cc
    AC_MSG_RESULT($TEA_PLATFORM)

    # The BUILD_$pkg is to define the correct extern storage class
    # handling when making this package
    AC_DEFINE_UNQUOTED(BUILD_${PACKAGE_NAME}, [],
	    [Building extension source?])
    # Do this here as we have fully defined TEA_PLATFORM now
    if test "${TEA_PLATFORM}" = "windows" ; then
	EXEEXT=".exe"
	CLEANFILES="$CLEANFILES *.lib *.dll *.pdb *.exp"
    fi

    # TEA specific:
    AC_SUBST(CLEANFILES)
    AC_SUBST(TCL_LIBS)
    AC_SUBST(TCL_DEFS)
    AC_SUBST(TCL_EXTRA_CFLAGS)
    AC_SUBST(TCL_LD_FLAGS)
    AC_SUBST(TCL_SHLIB_LD_LIBS)
])

#------------------------------------------------------------------------
# TEA_LOAD_TKCONFIG --
#
#	Load the tkConfig.sh file
#
# Arguments:
#
#	Requires the following vars to be set:
#		TK_BIN_DIR
#
# Results:
#
#	Sets the following vars that should be in tkConfig.sh:
#		TK_BIN_DIR
#------------------------------------------------------------------------

AC_DEFUN([TEA_LOAD_TKCONFIG], [
    AC_MSG_CHECKING([for existence of ${TK_BIN_DIR}/tkConfig.sh])

    if test -f "${TK_BIN_DIR}/tkConfig.sh" ; then
        AC_MSG_RESULT([loading])
	. "${TK_BIN_DIR}/tkConfig.sh"
    elif test -f "${TK_BIN_DIR}/sdl2tkConfig.sh" ; then
        AC_MSG_RESULT([loading])
	. "${TK_BIN_DIR}/sdl2tkConfig.sh"
    else
        AC_MSG_RESULT([could not find ${TK_BIN_DIR}/tkConfig.sh])
    fi

    # eval is required to do the TK_DBGX substitution
    eval "TK_LIB_FILE=\"${TK_LIB_FILE}\""
    eval "TK_STUB_LIB_FILE=\"${TK_STUB_LIB_FILE}\""

    # If the TK_BIN_DIR is the build directory (not the install directory),
    # then set the common variable name to the value of the build variables.
    # For example, the variable TK_LIB_SPEC will be set to the value
    # of TK_BUILD_LIB_SPEC. An extension should make use of TK_LIB_SPEC
    # instead of TK_BUILD_LIB_SPEC since it will work with both an
    # installed and uninstalled version of Tcl.
    if test -f "${TK_BIN_DIR}/Makefile" ; then
        TK_LIB_SPEC="${TK_BUILD_LIB_SPEC}"
        TK_STUB_LIB_SPEC="${TK_BUILD_STUB_LIB_SPEC}"
        TK_STUB_LIB_PATH="${TK_BUILD_STUB_LIB_PATH}"
    elif test "`uname -s`" = "Darwin"; then
	# If Tk was built as a framework, attempt to use the libraries
	# from the framework at the given location so that linking works
	# against Tk.framework installed in an arbitrary location.
	case ${TK_DEFS} in
	    *TK_FRAMEWORK*)
		if test -f "${TK_BIN_DIR}/${TK_LIB_FILE}"; then
		    for i in "`cd "${TK_BIN_DIR}"; pwd`" \
			     "`cd "${TK_BIN_DIR}"/../..; pwd`"; do
			if test "`basename "$i"`" = "${TK_LIB_FILE}.framework"; then
			    TK_LIB_SPEC="-F`dirname "$i" | sed -e 's/ /\\\\ /g'` -framework ${TK_LIB_FILE}"
			    break
			fi
		    done
		fi
		if test -f "${TK_BIN_DIR}/${TK_STUB_LIB_FILE}"; then
		    TK_STUB_LIB_SPEC="-L` echo "${TK_BIN_DIR}"  | sed -e 's/ /\\\\ /g'` ${TK_STUB_LIB_FLAG}"
		    TK_STUB_LIB_PATH="${TK_BIN_DIR}/${TK_STUB_LIB_FILE}"
		fi
		;;
	esac
    fi

    # eval is required to do the TK_DBGX substitution
    eval "TK_LIB_FLAG=\"${TK_LIB_FLAG}\""
    eval "TK_LIB_SPEC=\"${TK_LIB_SPEC}\""
    eval "TK_STUB_LIB_FLAG=\"${TK_STUB_LIB_FLAG}\""
    eval "TK_STUB_LIB_SPEC=\"${TK_STUB_LIB_SPEC}\""

    # TEA specific: Ensure windowingsystem is defined
    case ${TK_DEFS} in
	*PLATFORM_SDL*)
	    TEA_WINDOWINGSYSTEM="x11"
	    TEA_USE_SDL=yes
	    ;;
    esac
    if test "${TEA_USE_SDL}" = "yes" ; then
	true
    elif test "${TEA_PLATFORM}" = "unix" ; then
	case ${TK_DEFS} in
	    *MAC_OSX_TK*)
		AC_DEFINE(MAC_OSX_TK, 1, [Are we building against Mac OS X TkAqua?])
		TEA_WINDOWINGSYSTEM="aqua"
		;;
	    *)
		TEA_WINDOWINGSYSTEM="x11"
		;;
	esac
    elif test "${TEA_PLATFORM}" = "windows" ; then
	TEA_WINDOWINGSYSTEM="win32"
    fi

    AC_SUBST(TK_VERSION)
    AC_SUBST(TK_BIN_DIR)
    AC_SUBST(TK_SRC_DIR)

    AC_SUBST(TK_LIB_FILE)
    AC_SUBST(TK_LIB_FLAG)
    AC_SUBST(TK_LIB_SPEC)

    AC_SUBST(TK_STUB_LIB_FILE)
    AC_SUBST(TK_STUB_LIB_FLAG)
    AC_SUBST(TK_STUB_LIB_SPEC)

    # TEA specific:
    AC_SUBST(TK_LIBS)
    AC_SUBST(TK_XINCLUDES)
])

#------------------------------------------------------------------------
# TEA_PROG_TCLSH
#	Determine the fully qualified path name of the tclsh executable
#	in the Tcl build directory or the tclsh installed in a bin
#	directory. This macro will correctly determine the name
#	of the tclsh executable even if tclsh has not yet been
#	built in the build directory. The tclsh found is always
#	associated with a tclConfig.sh file. This tclsh should be used
#	only for running extension test cases. It should never be
#	or generation of files (like pkgIndex.tcl) at build time.
#
# Arguments:
#	none
#
# Results:
#	Substitutes the following vars:
#		TCLSH_PROG
#------------------------------------------------------------------------

AC_DEFUN([TEA_PROG_TCLSH], [
    AC_MSG_CHECKING([for tclsh])
    if test -f "${TCL_BIN_DIR}/Makefile" ; then
        # tclConfig.sh is in Tcl build directory
        if test "${TEA_PLATFORM}" = "windows"; then
            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
        else
            TCLSH_PROG="${TCL_BIN_DIR}/tclsh"
        fi
    else
        # tclConfig.sh is in install location
        if test "${TEA_PLATFORM}" = "windows"; then
            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
        else
            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}${TCL_DBGX}"
        fi
        list="`ls -d ${TCL_BIN_DIR}/../bin 2>/dev/null` \
              `ls -d ${TCL_BIN_DIR}/..     2>/dev/null` \
              `ls -d ${TCL_PREFIX}/bin     2>/dev/null`"
        for i in $list ; do
            if test -f "$i/${TCLSH_PROG}" ; then
                REAL_TCL_BIN_DIR="`cd "$i"; pwd`/"
                break
            fi
        done
        TCLSH_PROG="${REAL_TCL_BIN_DIR}${TCLSH_PROG}"
    fi
    AC_MSG_RESULT([${TCLSH_PROG}])
    AC_SUBST(TCLSH_PROG)
])

#------------------------------------------------------------------------
# TEA_PROG_WISH
#	Determine the fully qualified path name of the wish executable
#	in the Tk build directory or the wish installed in a bin
#	directory. This macro will correctly determine the name
#	of the wish executable even if wish has not yet been
#	built in the build directory. The wish found is always
#	associated with a tkConfig.sh file. This wish should be used
#	only for running extension test cases. It should never be
#	or generation of files (like pkgIndex.tcl) at build time.
#
# Arguments:
#	none
#
# Results:
#	Substitutes the following vars:
#		WISH_PROG
#------------------------------------------------------------------------

AC_DEFUN([TEA_PROG_WISH], [
    AC_MSG_CHECKING([for wish])
    if test -f "${TK_BIN_DIR}/Makefile" ; then
        # tkConfig.sh is in Tk build directory
        if test "${TEA_PLATFORM}" = "windows"; then
            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}${EXEEXT}"
        else
            WISH_PROG="${TK_BIN_DIR}/wish"
        fi
    else
        # tkConfig.sh is in install location
        if test "${TEA_PLATFORM}" = "windows"; then
            WISH_PROG="wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}${EXEEXT}"
        else
            WISH_PROG="wish${TK_MAJOR_VERSION}.${TK_MINOR_VERSION}${TK_DBGX}"
        fi
        list="`ls -d ${TK_BIN_DIR}/../bin 2>/dev/null` \
              `ls -d ${TK_BIN_DIR}/..     2>/dev/null` \
              `ls -d ${TK_PREFIX}/bin     2>/dev/null`"
        for i in $list ; do
            if test -f "$i/${WISH_PROG}" ; then
                REAL_TK_BIN_DIR="`cd "$i"; pwd`/"
                break
            fi
        done
        WISH_PROG="${REAL_TK_BIN_DIR}${WISH_PROG}"
    fi
    AC_MSG_RESULT([${WISH_PROG}])
    AC_SUBST(WISH_PROG)
])

#------------------------------------------------------------------------
# TEA_ENABLE_SHARED --
#
#	Allows the building of shared libraries
#
# Arguments:
#	none
#
# Results:
#
#	Adds the following arguments to configure:
#		--enable-shared=yes|no
#
#	Defines the following vars:
#		STATIC_BUILD	Used for building import/export libraries
#				on Windows.
#
#	Sets the following vars:
#		SHARED_BUILD	Value of 1 or 0
#------------------------------------------------------------------------

AC_DEFUN([TEA_ENABLE_SHARED], [
    AC_MSG_CHECKING([how to build libraries])
    AC_ARG_ENABLE(shared,
	AC_HELP_STRING([--enable-shared],
	    [build and link with shared libraries (default: on)]),
	[tcl_ok=$enableval], [tcl_ok=yes])

    if test "${enable_shared+set}" = set; then
	enableval="$enable_shared"
	tcl_ok=$enableval
    else
	tcl_ok=yes
    fi

    if test "$tcl_ok" = "yes" ; then
	AC_MSG_RESULT([shared])
	SHARED_BUILD=1
    else
	AC_MSG_RESULT([static])
	SHARED_BUILD=0
	AC_DEFINE(STATIC_BUILD, 1, [Is this a static build?])
    fi
    AC_SUBST(SHARED_BUILD)
])

#------------------------------------------------------------------------
# TEA_ENABLE_THREADS --
#
#	Specify if thread support should be enabled.  If "yes" is specified
#	as an arg (optional), threads are enabled by default, "no" means
#	threads are disabled.  "yes" is the default.
#
#	TCL_THREADS is checked so that if you are compiling an extension
#	against a threaded core, your extension must be compiled threaded
#	as well.
#
#	Note that it is legal to have a thread enabled extension run in a
#	threaded or non-threaded Tcl core, but a non-threaded extension may
#	only run in a non-threaded Tcl core.
#
# Arguments:
#	none
#
# Results:
#
#	Adds the following arguments to configure:
#		--enable-threads
#
#	Sets the following vars:
#		THREADS_LIBS	Thread library(s)
#
#	Defines the following vars:
#		TCL_THREADS
#		_REENTRANT
#		_THREAD_SAFE
#------------------------------------------------------------------------

AC_DEFUN([TEA_ENABLE_THREADS], [
    AC_ARG_ENABLE(threads,
	AC_HELP_STRING([--enable-threads],
	    [build with threads]),
	[tcl_ok=$enableval], [tcl_ok=yes])

    if test "${enable_threads+set}" = set; then
	enableval="$enable_threads"
	tcl_ok=$enableval
    else
	tcl_ok=yes
    fi

    if test "$tcl_ok" = "yes" -o "${TCL_THREADS}" = 1; then
	TCL_THREADS=1

	if test "${TEA_PLATFORM}" != "windows" ; then
	    # We are always OK on Windows, so check what this platform wants:

	    # USE_THREAD_ALLOC tells us to try the special thread-based
	    # allocator that significantly reduces lock contention
	    AC_DEFINE(USE_THREAD_ALLOC, 1,
		[Do we want to use the threaded memory allocator?])
	    AC_DEFINE(_REENTRANT, 1, [Do we want the reentrant OS API?])
	    if test "`uname -s`" = "SunOS" ; then
		AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1,
			[Do we really want to follow the standard? Yes we do!])
	    fi
	    AC_DEFINE(_THREAD_SAFE, 1, [Do we want the thread-safe OS API?])
	    AC_CHECK_LIB(pthread,pthread_mutex_init,tcl_ok=yes,tcl_ok=no)
	    if test "$tcl_ok" = "no"; then
		# Check a little harder for __pthread_mutex_init in the same
		# library, as some systems hide it there until pthread.h is
		# defined.  We could alternatively do an AC_TRY_COMPILE with
		# pthread.h, but that will work with libpthread really doesn't
		# exist, like AIX 4.2.  [Bug: 4359]
		AC_CHECK_LIB(pthread, __pthread_mutex_init,
		    tcl_ok=yes, tcl_ok=no)
	    fi

	    if test "$tcl_ok" = "yes"; then
		# The space is needed
		THREADS_LIBS=" -lpthread"
	    else
		AC_CHECK_LIB(pthreads, pthread_mutex_init,
		    tcl_ok=yes, tcl_ok=no)
		if test "$tcl_ok" = "yes"; then
		    # The space is needed
		    THREADS_LIBS=" -lpthreads"
		else
		    AC_CHECK_LIB(c, pthread_mutex_init,
			tcl_ok=yes, tcl_ok=no)
		    if test "$tcl_ok" = "no"; then
			AC_CHECK_LIB(c_r, pthread_mutex_init,
			    tcl_ok=yes, tcl_ok=no)
			if test "$tcl_ok" = "yes"; then
			    # The space is needed
			    THREADS_LIBS=" -pthread"
			else
			    TCL_THREADS=0
			    AC_MSG_WARN([Do not know how to find pthread lib on your system - thread support disabled])
			fi
		    fi
		fi
	    fi
	fi
    else
	TCL_THREADS=0
    fi
    # Do checking message here to not mess up interleaved configure output
    AC_MSG_CHECKING([for building with threads])
    if test "${TCL_THREADS}" = 1; then
	AC_DEFINE(TCL_THREADS, 1, [Are we building with threads enabled?])
	AC_MSG_RESULT([yes (default)])
    else
	AC_MSG_RESULT([no])
    fi
    # TCL_THREADS sanity checking.  See if our request for building with
    # threads is the same as the way Tcl was built.  If not, warn the user.
    case ${TCL_DEFS} in
	*THREADS=1*)
	    if test "${TCL_THREADS}" = "0"; then
		AC_MSG_WARN([
    Building ${PACKAGE_NAME} without threads enabled, but building against Tcl
    that IS thread-enabled.  It is recommended to use --enable-threads.])
	    fi
	    ;;
	*)
	    if test "${TCL_THREADS}" = "1"; then
		AC_MSG_WARN([
    --enable-threads requested, but building against a Tcl that is NOT
    thread-enabled.  This is an OK configuration that will also run in
    a thread-enabled core.])
	    fi
	    ;;
    esac
    AC_SUBST(TCL_THREADS)
])

#------------------------------------------------------------------------
# TEA_ENABLE_SYMBOLS --
#
#	Specify if debugging symbols should be used.
#	Memory (TCL_MEM_DEBUG) debugging can also be enabled.
#
# Arguments:
#	none
#
#	TEA varies from core Tcl in that C|LDFLAGS_DEFAULT receives
#	the value of C|LDFLAGS_OPTIMIZE|DEBUG already substituted.
#	Requires the following vars to be set in the Makefile:
#		CFLAGS_DEFAULT
#		LDFLAGS_DEFAULT
#
# Results:
#
#	Adds the following arguments to configure:
#		--enable-symbols
#
#	Defines the following vars:
#		CFLAGS_DEFAULT	Sets to $(CFLAGS_DEBUG) if true
#				Sets to "$(CFLAGS_OPTIMIZE) -DNDEBUG" if false
#		LDFLAGS_DEFAULT	Sets to $(LDFLAGS_DEBUG) if true
#				Sets to $(LDFLAGS_OPTIMIZE) if false
#		DBGX		Formerly used as debug library extension;
#				always blank now.
#------------------------------------------------------------------------

AC_DEFUN([TEA_ENABLE_SYMBOLS], [
    dnl TEA specific: Make sure we are initialized
    AC_REQUIRE([TEA_CONFIG_CFLAGS])
    AC_MSG_CHECKING([for build with symbols])
    AC_ARG_ENABLE(symbols,
	AC_HELP_STRING([--enable-symbols],
	    [build with debugging symbols (default: off)]),
	[tcl_ok=$enableval], [tcl_ok=no])
    DBGX=""
    if test "$tcl_ok" = "no"; then
	CFLAGS_DEFAULT="${CFLAGS_OPTIMIZE} -DNDEBUG"
	LDFLAGS_DEFAULT="${LDFLAGS_OPTIMIZE}"
	AC_MSG_RESULT([no])
    else
	CFLAGS_DEFAULT="${CFLAGS_DEBUG}"
	LDFLAGS_DEFAULT="${LDFLAGS_DEBUG}"
	if test "$tcl_ok" = "yes"; then
	    AC_MSG_RESULT([yes (standard debugging)])
	fi
    fi
    # TEA specific:
    if test "${TEA_PLATFORM}" != "windows" ; then
	LDFLAGS_DEFAULT="${LDFLAGS}"
    fi
    AC_SUBST(CFLAGS_DEFAULT)
    AC_SUBST(LDFLAGS_DEFAULT)
    AC_SUBST(TCL_DBGX)

    if test "$tcl_ok" = "mem" -o "$tcl_ok" = "all"; then
	AC_DEFINE(TCL_MEM_DEBUG, 1, [Is memory debugging enabled?])
    fi

    if test "$tcl_ok" != "yes" -a "$tcl_ok" != "no"; then
	if test "$tcl_ok" = "all"; then
	    AC_MSG_RESULT([enabled symbols mem debugging])
	else
	    AC_MSG_RESULT([enabled $tcl_ok debugging])
	fi
    fi
])

#------------------------------------------------------------------------
# TEA_ENABLE_LANGINFO --
#
#	Allows use of modern nl_langinfo check for better l10n.
#	This is only relevant for Unix.
#
# Arguments:
#	none
#
# Results:
#
#	Adds the following arguments to configure:
#		--enable-langinfo=yes|no (default is yes)
#
#	Defines the following vars:
#		HAVE_LANGINFO	Triggers use of nl_langinfo if defined.
#------------------------------------------------------------------------

AC_DEFUN([TEA_ENABLE_LANGINFO], [
    AC_ARG_ENABLE(langinfo,
	AC_HELP_STRING([--enable-langinfo],
	    [use nl_langinfo if possible to determine encoding at startup, otherwise use old heuristic (default: on)]),
	[langinfo_ok=$enableval], [langinfo_ok=yes])

    HAVE_LANGINFO=0
    if test "$langinfo_ok" = "yes"; then
	AC_CHECK_HEADER(langinfo.h,[langinfo_ok=yes],[langinfo_ok=no])
    fi
    AC_MSG_CHECKING([whether to use nl_langinfo])
    if test "$langinfo_ok" = "yes"; then
	AC_CACHE_VAL(tcl_cv_langinfo_h, [
	    AC_TRY_COMPILE([#include <langinfo.h>], [nl_langinfo(CODESET);],
		    [tcl_cv_langinfo_h=yes],[tcl_cv_langinfo_h=no])])
	AC_MSG_RESULT([$tcl_cv_langinfo_h])
	if test $tcl_cv_langinfo_h = yes; then
	    AC_DEFINE(HAVE_LANGINFO, 1, [Do we have nl_langinfo()?])
	fi
    else
	AC_MSG_RESULT([$langinfo_ok])
    fi
])

#--------------------------------------------------------------------
# TEA_CONFIG_SYSTEM
#
#	Determine what the system is (some things cannot be easily checked
#	on a feature-driven basis, alas). This can usually be done via the
#	"uname" command.
#
# Arguments:
#	none
#
# Results:
#	Defines the following var:
#
#	system -	System/platform/version identification code.
#--------------------------------------------------------------------

AC_DEFUN([TEA_CONFIG_SYSTEM], [
    AC_CACHE_CHECK([system version], tcl_cv_sys_version, [
	# TEA specific:
	if test "${TEA_PLATFORM}" = "windows" ; then
	    tcl_cv_sys_version=windows
	else
	    tcl_cv_sys_version=`uname -s`-`uname -r`
	    if test "$?" -ne 0 ; then
		AC_MSG_WARN([can't find uname command])
		tcl_cv_sys_version=unknown
	    else
		if test "`uname -s`" = "AIX" ; then
		    tcl_cv_sys_version=AIX-`uname -v`.`uname -r`
		fi
	    fi
	fi
    ])
    system=$tcl_cv_sys_version
])

#--------------------------------------------------------------------
# TEA_CONFIG_CFLAGS
#
#	Try to determine the proper flags to pass to the compiler
#	for building shared libraries and other such nonsense.
#
# Arguments:
#	none
#
# Results:
#
#	Defines and substitutes the following vars:
#
#	DL_OBJS, DL_LIBS - removed for TEA, only needed by core.
#       LDFLAGS -      Flags to pass to the compiler when linking object
#                       files into an executable application binary such
#                       as tclsh.
#       LD_SEARCH_FLAGS-Flags to pass to ld, such as "-R /usr/local/tcl/lib",
#                       that tell the run-time dynamic linker where to look
#                       for shared libraries such as libtcl.so.  Depends on
#                       the variable LIB_RUNTIME_DIR in the Makefile. Could
#                       be the same as CC_SEARCH_FLAGS if ${CC} is used to link.
#       CC_SEARCH_FLAGS-Flags to pass to ${CC}, such as "-Wl,-rpath,/usr/local/tcl/lib",
#                       that tell the run-time dynamic linker where to look
#                       for shared libraries such as libtcl.so.  Depends on
#                       the variable LIB_RUNTIME_DIR in the Makefile.
#       SHLIB_CFLAGS -  Flags to pass to cc when compiling the components
#                       of a shared library (may request position-independent
#                       code, among other things).
#       SHLIB_LD -      Base command to use for combining object files
#                       into a shared library.
#       SHLIB_LD_LIBS - Dependent libraries for the linker to scan when
#                       creating shared libraries.  This symbol typically
#                       goes at the end of the "ld" commands that build
#                       shared libraries. The value of the symbol defaults to
#                       "${LIBS}" if all of the dependent libraries should
#                       be specified when creating a shared library.  If
#                       dependent libraries should not be specified (as on
#                       SunOS 4.x, where they cause the link to fail, or in
#                       general if Tcl and Tk aren't themselves shared
#                       libraries), then this symbol has an empty string
#                       as its value.
#       SHLIB_SUFFIX -  Suffix to use for the names of dynamically loadable
#                       extensions.  An empty string means we don't know how
#                       to use shared libraries on this platform.
#       LIB_SUFFIX -    Specifies everything that comes after the "libfoo"
#                       in a static or shared library name, using the $PACKAGE_VERSION variable
#                       to put the version in the right place.  This is used
#                       by platforms that need non-standard library names.
#                       Examples:  ${PACKAGE_VERSION}.so.1.1 on NetBSD, since it needs
#                       to have a version after the .so, and ${PACKAGE_VERSION}.a
#                       on AIX, since a shared library needs to have
#                       a .a extension whereas shared objects for loadable
#                       extensions have a .so extension.  Defaults to
#                       ${PACKAGE_VERSION}${SHLIB_SUFFIX}.
#	CFLAGS_DEBUG -
#			Flags used when running the compiler in debug mode
#	CFLAGS_OPTIMIZE -
#			Flags used when running the compiler in optimize mode
#	CFLAGS -	Additional CFLAGS added as necessary (usually 64-bit)
#--------------------------------------------------------------------

AC_DEFUN([TEA_CONFIG_CFLAGS], [
    dnl TEA specific: Make sure we are initialized
    AC_REQUIRE([TEA_INIT])

    # Step 0.a: Enable 64 bit support?

    AC_MSG_CHECKING([if 64bit support is requested])
    AC_ARG_ENABLE(64bit,
	AC_HELP_STRING([--enable-64bit],
	    [enable 64bit support (default: off)]),
	[do64bit=$enableval], [do64bit=no])
    AC_MSG_RESULT([$do64bit])

    # Step 0.b: Enable Solaris 64 bit VIS support?

    AC_MSG_CHECKING([if 64bit Sparc VIS support is requested])
    AC_ARG_ENABLE(64bit-vis,
	AC_HELP_STRING([--enable-64bit-vis],
	    [enable 64bit Sparc VIS support (default: off)]),
	[do64bitVIS=$enableval], [do64bitVIS=no])
    AC_MSG_RESULT([$do64bitVIS])
    # Force 64bit on with VIS
    AS_IF([test "$do64bitVIS" = "yes"], [do64bit=yes])

    # Step 0.c: Check if visibility support is available. Do this here so
    # that platform specific alternatives can be used below if this fails.

    AC_CACHE_CHECK([if compiler supports visibility "hidden"],
	tcl_cv_cc_visibility_hidden, [
	hold_cflags=$CFLAGS; CFLAGS="$CFLAGS -Werror"
	AC_TRY_LINK([
	    extern __attribute__((__visibility__("hidden"))) void f(void);
	    void f(void) {}], [f();], tcl_cv_cc_visibility_hidden=yes,
	    tcl_cv_cc_visibility_hidden=no)
	CFLAGS=$hold_cflags])
    AS_IF([test $tcl_cv_cc_visibility_hidden = yes], [
	AC_DEFINE(MODULE_SCOPE,
	    [extern __attribute__((__visibility__("hidden")))],
	    [Compiler support for module scope symbols])
	AC_DEFINE(HAVE_HIDDEN, [1], [Compiler support for module scope symbols])
    ])

    # Step 0.d: Disable -rpath support?

    AC_MSG_CHECKING([if rpath support is requested])
    AC_ARG_ENABLE(rpath,
	AC_HELP_STRING([--disable-rpath],
	    [disable rpath support (default: on)]),
	[doRpath=$enableval], [doRpath=yes])
    AC_MSG_RESULT([$doRpath])

    # TEA specific: Cross-compiling options for Windows/CE builds?

    AS_IF([test "${TEA_PLATFORM}" = windows], [
	AC_MSG_CHECKING([if Windows/CE build is requested])
	AC_ARG_ENABLE(wince,
	    AC_HELP_STRING([--enable-wince],
		[enable Win/CE support (where applicable)]),
	    [doWince=$enableval], [doWince=no])
	AC_MSG_RESULT([$doWince])
    ])

    # Set the variable "system" to hold the name and version number
    # for the system.

    TEA_CONFIG_SYSTEM

    # Require ranlib early so we can override it in special cases below.

    AC_REQUIRE([AC_PROG_RANLIB])

    # Set configuration options based on system name and version.
    # This is similar to Tcl's unix/tcl.m4 except that we've added a
    # "windows" case and removed some core-only vars.

    do64bit_ok=no
    # default to '{$LIBS}' and set to "" on per-platform necessary basis
    SHLIB_LD_LIBS='${LIBS}'
    # When ld needs options to work in 64-bit mode, put them in
    # LDFLAGS_ARCH so they eventually end up in LDFLAGS even if [load]
    # is disabled by the user. [Bug 1016796]
    LDFLAGS_ARCH=""
    UNSHARED_LIB_SUFFIX=""
    # TEA specific: use PACKAGE_VERSION instead of VERSION
    TCL_TRIM_DOTS='`echo ${PACKAGE_VERSION} | tr -d .`'
    ECHO_VERSION='`echo ${PACKAGE_VERSION}`'
    TCL_LIB_VERSIONS_OK=ok
    CFLAGS_DEBUG=-g
    AS_IF([test "$GCC" = yes], [
	CFLAGS_OPTIMIZE=-O2
	CFLAGS_WARNING="-Wall"
    ], [
	CFLAGS_OPTIMIZE=-O
	CFLAGS_WARNING=""
    ])
    CC_OBJNAME="-o \[$]@"
    AC_CHECK_TOOL(AR, ar)
    STLIB_LD='${AR} cr'
    LD_LIBRARY_PATH_VAR="LD_LIBRARY_PATH"
    AS_IF([test "x$SHLIB_VERSION" = x],[SHLIB_VERSION="1.0"])
    case $system in
	# TEA specific:
	windows)
	    # This is a 2-stage check to make sure we have the 64-bit SDK
	    # We have to know where the SDK is installed.
	    # This magic is based on MS Platform SDK for Win2003 SP1 - hobbs
	    # MACHINE is IX86 for LINK, but this is used by the manifest,
	    # which requires x86|amd64|ia64.
	    MACHINE="X86"
	    if test "$do64bit" != "no" ; then
		if test "x${MSSDK}x" = "xx" ; then
		    MSSDK="C:/Progra~1/Microsoft Platform SDK"
		fi
		MSSDK=`echo "$MSSDK" | sed -e  's!\\\!/!g'`
		PATH64=""
		case "$do64bit" in
		    amd64|x64|yes)
			MACHINE="AMD64" ; # default to AMD64 64-bit build
			PATH64="${MSSDK}/Bin/Win64/x86/AMD64"
			;;
		    ia64)
			MACHINE="IA64"
			PATH64="${MSSDK}/Bin/Win64"
			;;
		esac
		if test "$GCC" != "yes" -a ! -d "${PATH64}" ; then
		    AC_MSG_WARN([Could not find 64-bit $MACHINE SDK to enable 64bit mode])
		    AC_MSG_WARN([Ensure latest Platform SDK is installed])
		    do64bit="no"
		else
		    AC_MSG_RESULT([   Using 64-bit $MACHINE mode])
		    do64bit_ok="yes"
		fi
	    fi

	    if test "$doWince" != "no" ; then
		if test "$do64bit" != "no" ; then
		    AC_MSG_ERROR([Windows/CE and 64-bit builds incompatible])
		fi
		if test "$GCC" = "yes" ; then
		    AC_MSG_ERROR([Windows/CE and GCC builds incompatible])
		fi
		TEA_PATH_CELIB
		# Set defaults for common evc4/PPC2003 setup
		# Currently Tcl requires 300+, possibly 420+ for sockets
		CEVERSION=420; 		# could be 211 300 301 400 420 ...
		TARGETCPU=ARMV4;	# could be ARMV4 ARM MIPS SH3 X86 ...
		ARCH=ARM;		# could be ARM MIPS X86EM ...
		PLATFORM="Pocket PC 2003"; # or "Pocket PC 2002"
		if test "$doWince" != "yes"; then
		    # If !yes then the user specified something
		    # Reset ARCH to allow user to skip specifying it
		    ARCH=
		    eval `echo $doWince | awk -F, '{ \
	    if (length([$]1)) { printf "CEVERSION=\"%s\"\n", [$]1; \
	    if ([$]1 < 400)   { printf "PLATFORM=\"Pocket PC 2002\"\n" } }; \
	    if (length([$]2)) { printf "TARGETCPU=\"%s\"\n", toupper([$]2) }; \
	    if (length([$]3)) { printf "ARCH=\"%s\"\n", toupper([$]3) }; \
	    if (length([$]4)) { printf "PLATFORM=\"%s\"\n", [$]4 }; \
		    }'`
		    if test "x${ARCH}" = "x" ; then
			ARCH=$TARGETCPU;
		    fi
		fi
		OSVERSION=WCE$CEVERSION;
	    	if test "x${WCEROOT}" = "x" ; then
			WCEROOT="C:/Program Files/Microsoft eMbedded C++ 4.0"
		    if test ! -d "${WCEROOT}" ; then
			WCEROOT="C:/Program Files/Microsoft eMbedded Tools"
		    fi
		fi
		if test "x${SDKROOT}" = "x" ; then
		    SDKROOT="C:/Program Files/Windows CE Tools"
		    if test ! -d "${SDKROOT}" ; then
			SDKROOT="C:/Windows CE Tools"
		    fi
		fi
		WCEROOT=`echo "$WCEROOT" | sed -e 's!\\\!/!g'`
		SDKROOT=`echo "$SDKROOT" | sed -e 's!\\\!/!g'`
		if test ! -d "${SDKROOT}/${OSVERSION}/${PLATFORM}/Lib/${TARGETCPU}" \
		    -o ! -d "${WCEROOT}/EVC/${OSVERSION}/bin"; then
		    AC_MSG_ERROR([could not find PocketPC SDK or target compiler to enable WinCE mode [$CEVERSION,$TARGETCPU,$ARCH,$PLATFORM]])
		    doWince="no"
		else
		    # We could PATH_NOSPACE these, but that's not important,
		    # as long as we quote them when used.
		    CEINCLUDE="${SDKROOT}/${OSVERSION}/${PLATFORM}/include"
		    if test -d "${CEINCLUDE}/${TARGETCPU}" ; then
			CEINCLUDE="${CEINCLUDE}/${TARGETCPU}"
		    fi
		    CELIBPATH="${SDKROOT}/${OSVERSION}/${PLATFORM}/Lib/${TARGETCPU}"
    		fi
	    fi

	    if test "$GCC" != "yes" ; then
	        if test "${SHARED_BUILD}" = "0" ; then
		    runtime=-MT
	        else
		    runtime=-MD
	        fi

                if test "$do64bit" != "no" ; then
		    # All this magic is necessary for the Win64 SDK RC1 - hobbs
		    CC="\"${PATH64}/cl.exe\""
		    CFLAGS="${CFLAGS} -I\"${MSSDK}/Include\" -I\"${MSSDK}/Include/crt\" -I\"${MSSDK}/Include/crt/sys\""
		    RC="\"${MSSDK}/bin/rc.exe\""
		    lflags="-nologo -MACHINE:${MACHINE} -LIBPATH:\"${MSSDK}/Lib/${MACHINE}\""
		    LINKBIN="\"${PATH64}/link.exe\""
		    CFLAGS_DEBUG="-nologo -Zi -Od -W3 ${runtime}d"
		    CFLAGS_OPTIMIZE="-nologo -O2 -W2 ${runtime}"
		    # Avoid 'unresolved external symbol __security_cookie'
		    # errors, c.f. http://support.microsoft.com/?id=894573
		    TEA_ADD_LIBS([bufferoverflowU.lib])
		elif test "$doWince" != "no" ; then
		    CEBINROOT="${WCEROOT}/EVC/${OSVERSION}/bin"
		    if test "${TARGETCPU}" = "X86"; then
			CC="\"${CEBINROOT}/cl.exe\""
		    else
			CC="\"${CEBINROOT}/cl${ARCH}.exe\""
		    fi
		    CFLAGS="$CFLAGS -I\"${CELIB_DIR}/inc\" -I\"${CEINCLUDE}\""
		    RC="\"${WCEROOT}/Common/EVC/bin/rc.exe\""
		    arch=`echo ${ARCH} | awk '{print tolower([$]0)}'`
		    defs="${ARCH} _${ARCH}_ ${arch} PALM_SIZE _MT _WINDOWS"
		    if test "${SHARED_BUILD}" = "1" ; then
			# Static CE builds require static celib as well
		    	defs="${defs} _DLL"
		    fi
		    for i in $defs ; do
			AC_DEFINE_UNQUOTED($i, 1, [WinCE def ]$i)
		    done
		    AC_DEFINE_UNQUOTED(_WIN32_WCE, $CEVERSION, [_WIN32_WCE version])
		    AC_DEFINE_UNQUOTED(UNDER_CE, $CEVERSION, [UNDER_CE version])
		    CFLAGS_DEBUG="-nologo -Zi -Od"
		    CFLAGS_OPTIMIZE="-nologo -Ox"
		    lversion=`echo ${CEVERSION} | sed -e 's/\(.\)\(..\)/\1\.\2/'`
		    lflags="-MACHINE:${ARCH} -LIBPATH:\"${CELIBPATH}\" -subsystem:windowsce,${lversion} -nologo"
		    LINKBIN="\"${CEBINROOT}/link.exe\""
		    AC_SUBST(CELIB_DIR)
		else
		    RC="rc"
		    lflags="-nologo"
		    LINKBIN="link"
		    CFLAGS_DEBUG="-nologo -Z7 -Od -W3 -WX ${runtime}d"
		    CFLAGS_OPTIMIZE="-nologo -O2 -W2 ${runtime}"
		fi
	    fi

	    if test "$GCC" = "yes"; then
		# mingw gcc mode
		AC_CHECK_TOOL(RC, windres)
		CFLAGS_DEBUG="-g"
		CFLAGS_OPTIMIZE="-O2 -fomit-frame-pointer"
		SHLIB_LD='${CC} -shared'
		UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
		LDFLAGS_CONSOLE="-wl,--subsystem,console ${lflags}"
		LDFLAGS_WINDOW="-wl,--subsystem,windows ${lflags}"

		AC_CACHE_CHECK(for cross-compile version of gcc,
			ac_cv_cross,
			AC_TRY_COMPILE([
			    #ifdef _WIN32
				#error cross-compiler
			    #endif
			], [],
			ac_cv_cross=yes,
			ac_cv_cross=no)
		      )
		      if test "$ac_cv_cross" = "yes"; then
			case "$do64bit" in
			    amd64|x64|yes)
				CC="x86_64-w64-mingw32-gcc"
				LD="x86_64-w64-mingw32-ld"
				AR="x86_64-w64-mingw32-ar"
				RANLIB="x86_64-w64-mingw32-ranlib"
				RC="x86_64-w64-mingw32-windres"
			    ;;
			    *)
				CC="i686-w64-mingw32-gcc"
				LD="i686-w64-mingw32-ld"
				AR="i686-w64-mingw32-ar"
				RANLIB="i686-w64-mingw32-ranlib"
				RC="i686-w64-mingw32-windres"
			    ;;
			esac
		fi

	    else
		SHLIB_LD="${LINKBIN} -dll ${lflags}"
		# link -lib only works when -lib is the first arg
		STLIB_LD="${LINKBIN} -lib ${lflags}"
		UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.lib'
		PATHTYPE=-w
		# For information on what debugtype is most useful, see:
		# http://msdn.microsoft.com/library/en-us/dnvc60/html/gendepdebug.asp
		# and also
		# http://msdn2.microsoft.com/en-us/library/y0zzbyt4%28VS.80%29.aspx
		# This essentially turns it all on.
		LDFLAGS_DEBUG="-debug -debugtype:cv"
		LDFLAGS_OPTIMIZE="-release"
		CFLAGS_DEBUG="${CFLAGS_DEBUG} -D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE"
		CFLAGS_OPTIMIZE="${CFLAGS_OPTIMIZE} -D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE"
		CC_OBJNAME="-Fo\[$]@"
		if test "$doWince" != "no" ; then
		    LDFLAGS_CONSOLE="-link ${lflags}"
		    LDFLAGS_WINDOW=${LDFLAGS_CONSOLE}
		else
		    LDFLAGS_CONSOLE="-link -subsystem:console ${lflags}"
		    LDFLAGS_WINDOW="-link -subsystem:windows ${lflags}"
		fi
	    fi

	    SHLIB_SUFFIX=".dll"
	    SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.dll'

	    TCL_LIB_VERSIONS_OK=nodots
    	    ;;
	AIX-*)
	    AS_IF([test "${TCL_THREADS}" = "1" -a "$GCC" != "yes"], [
		# AIX requires the _r compiler when gcc isn't being used
		case "${CC}" in
		    *_r|*_r\ *)
			# ok ...
			;;
		    *)
			# Make sure only first arg gets _r
		    	CC=`echo "$CC" | sed -e 's/^\([[^ ]]*\)/\1_r/'`
			;;
		esac
		AC_MSG_RESULT([Using $CC for compiling with threads])
	    ])
	    LIBS="$LIBS -lc"
	    SHLIB_CFLAGS=""
	    SHLIB_SUFFIX=".so"

	    LD_LIBRARY_PATH_VAR="LIBPATH"

	    # Check to enable 64-bit flags for compiler/linker
	    AS_IF([test "$do64bit" = yes], [
		AS_IF([test "$GCC" = yes], [
		    AC_MSG_WARN([64bit mode not supported with GCC on $system])
		], [
		    do64bit_ok=yes
		    CFLAGS="$CFLAGS -q64"
		    LDFLAGS_ARCH="-q64"
		    RANLIB="${RANLIB} -X64"
		    AR="${AR} -X64"
		    SHLIB_LD_FLAGS="-b64"
		])
	    ])

	    AS_IF([test "`uname -m`" = ia64], [
		# AIX-5 uses ELF style dynamic libraries on IA-64, but not PPC
		SHLIB_LD="/usr/ccs/bin/ld -G -z text"
		AS_IF([test "$GCC" = yes], [
		    CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
		], [
		    CC_SEARCH_FLAGS='-R${LIB_RUNTIME_DIR}'
		])
		LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
	    ], [
		AS_IF([test "$GCC" = yes], [
		    SHLIB_LD='${CC} -shared -Wl,-bexpall'
		], [
		    SHLIB_LD="/bin/ld -bhalt:4 -bM:SRE -bexpall -H512 -T512 -bnoentry"
		    LDFLAGS="$LDFLAGS -brtl"
		])
		SHLIB_LD="${SHLIB_LD} ${SHLIB_LD_FLAGS}"
		CC_SEARCH_FLAGS='-L${LIB_RUNTIME_DIR}'
		LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
	    ])
	    ;;
	BeOS*)
	    SHLIB_CFLAGS="-fPIC"
	    SHLIB_LD='${CC} -nostart'
	    SHLIB_SUFFIX=".so"

	    #-----------------------------------------------------------
	    # Check for inet_ntoa in -lbind, for BeOS (which also needs
	    # -lsocket, even if the network functions are in -lnet which
	    # is always linked to, for compatibility.
	    #-----------------------------------------------------------
	    AC_CHECK_LIB(bind, inet_ntoa, [LIBS="$LIBS -lbind -lsocket"])
	    ;;
	BSD/OS-4.*)
	    SHLIB_CFLAGS="-export-dynamic -fPIC"
	    SHLIB_LD='${CC} -shared'
	    SHLIB_SUFFIX=".so"
	    LDFLAGS="$LDFLAGS -export-dynamic"
	    CC_SEARCH_FLAGS=""
	    LD_SEARCH_FLAGS=""
	    ;;
	CYGWIN_*)
	    SHLIB_CFLAGS=""
	    SHLIB_LD='${CC} -shared'
	    SHLIB_SUFFIX=".dll"
	    EXEEXT=".exe"
	    do64bit_ok=yes
	    CC_SEARCH_FLAGS=""
	    LD_SEARCH_FLAGS=""
	    ;;
	Haiku*)
	    LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
	    SHLIB_CFLAGS="-fPIC"
	    SHLIB_SUFFIX=".so"
	    SHLIB_LD='${CC} -shared ${CFLAGS} ${LDFLAGS}'
	    AC_CHECK_LIB(network, inet_ntoa, [LIBS="$LIBS -lnetwork"])
	    ;;
	HP-UX-*.11.*)
	    # Use updated header definitions where possible
	    AC_DEFINE(_XOPEN_SOURCE_EXTENDED, 1, [Do we want to use the XOPEN network library?])
	    # TEA specific: Needed by Tcl, but not most extensions
	    #AC_DEFINE(_XOPEN_SOURCE, 1, [Do we want to use the XOPEN network library?])
	    #LIBS="$LIBS -lxnet"               # Use the XOPEN network library

	    AS_IF([test "`uname -m`" = ia64], [
		SHLIB_SUFFIX=".so"
		# Use newer C++ library for C++ extensions
		#if test "$GCC" != "yes" ; then
		#   CPPFLAGS="-AA"
		#fi
	    ], [
		SHLIB_SUFFIX=".sl"
	    ])
	    AC_CHECK_LIB(dld, shl_load, tcl_ok=yes, tcl_ok=no)
	    AS_IF([test "$tcl_ok" = yes], [
		LDFLAGS="$LDFLAGS -Wl,-E"
		CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
		LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
		LD_LIBRARY_PATH_VAR="SHLIB_PATH"
	    ])
	    AS_IF([test "$GCC" = yes], [
		SHLIB_LD='${CC} -shared'
		LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
	    ], [
		CFLAGS="$CFLAGS -z"
		# Users may want PA-RISC 1.1/2.0 portable code - needs HP cc
		#CFLAGS="$CFLAGS +DAportable"
		SHLIB_CFLAGS="+z"
		SHLIB_LD="ld -b"
	    ])

	    # Check to enable 64-bit flags for compiler/linker
	    AS_IF([test "$do64bit" = "yes"], [
		AS_IF([test "$GCC" = yes], [
		    case `${CC} -dumpmachine` in
			hppa64*)
			    # 64-bit gcc in use.  Fix flags for GNU ld.
			    do64bit_ok=yes
			    SHLIB_LD='${CC} -shared'
			    AS_IF([test $doRpath = yes], [
				CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
			    LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
			    ;;
			*)
			    AC_MSG_WARN([64bit mode not supported with GCC on $system])
			    ;;
		    esac
		], [
		    do64bit_ok=yes
		    CFLAGS="$CFLAGS +DD64"
		    LDFLAGS_ARCH="+DD64"
		])
	    ]) ;;
	IRIX-6.*)
	    SHLIB_CFLAGS=""
	    SHLIB_LD="ld -n32 -shared -rdata_shared"
	    SHLIB_SUFFIX=".so"
	    AS_IF([test $doRpath = yes], [
		CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
		LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
	    AS_IF([test "$GCC" = yes], [
		CFLAGS="$CFLAGS -mabi=n32"
		LDFLAGS="$LDFLAGS -mabi=n32"
	    ], [
		case $system in
		    IRIX-6.3)
			# Use to build 6.2 compatible binaries on 6.3.
			CFLAGS="$CFLAGS -n32 -D_OLD_TERMIOS"
			;;
		    *)
			CFLAGS="$CFLAGS -n32"
			;;
		esac
		LDFLAGS="$LDFLAGS -n32"
	    ])
	    ;;
	IRIX64-6.*)
	    SHLIB_CFLAGS=""
	    SHLIB_LD="ld -n32 -shared -rdata_shared"
	    SHLIB_SUFFIX=".so"
	    AS_IF([test $doRpath = yes], [
		CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
		LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])

	    # Check to enable 64-bit flags for compiler/linker

	    AS_IF([test "$do64bit" = yes], [
	        AS_IF([test "$GCC" = yes], [
	            AC_MSG_WARN([64bit mode not supported by gcc])
	        ], [
	            do64bit_ok=yes
	            SHLIB_LD="ld -64 -shared -rdata_shared"
	            CFLAGS="$CFLAGS -64"
	            LDFLAGS_ARCH="-64"
	        ])
	    ])
	    ;;
	Linux*|GNU*|NetBSD-Debian)
	    SHLIB_CFLAGS="-fPIC"
	    SHLIB_SUFFIX=".so"

	    # TEA specific:
	    CFLAGS_OPTIMIZE="-O2 -fomit-frame-pointer"

	    # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
	    SHLIB_LD='${CC} -shared ${CFLAGS} ${LDFLAGS_DEFAULT}'
	    # workaround when cross-compiling for Win32: no -fPIC and -Wl,...
	    if test "${TCL_SHLIB_SUFFIX}" = ".dll" ; then
		SHLIB_CFLAGS=""
		SHLIB_SUFFIX=".dll"
		DL_OBJS=""
		DL_LIBS=""
		TCL_LIB_VERSIONS_OK=nodots
		SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.dll'
		UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
	    else	
		LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
	    fi
	    AS_IF([test $doRpath = yes], [
		CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
	    LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
	    AS_IF([test "`uname -m`" = "alpha"], [CFLAGS="$CFLAGS -mieee"])
	    AS_IF([test $do64bit = yes], [
		AC_CACHE_CHECK([if compiler accepts -m64 flag], tcl_cv_cc_m64, [
		    hold_cflags=$CFLAGS
		    CFLAGS="$CFLAGS -m64"
		    AC_TRY_LINK(,, tcl_cv_cc_m64=yes, tcl_cv_cc_m64=no)
		    CFLAGS=$hold_cflags])
		AS_IF([test $tcl_cv_cc_m64 = yes], [
		    CFLAGS="$CFLAGS -m64"
		    do64bit_ok=yes
		])
	   ])

	    # The combo of gcc + glibc has a bug related to inlining of
	    # functions like strtod(). The -fno-builtin flag should address
	    # this problem but it does not work. The -fno-inline flag is kind
	    # of overkill but it works. Disable inlining only when one of the
	    # files in compat/*.c is being linked in.

	    AS_IF([test x"${USE_COMPAT}" != x],[CFLAGS="$CFLAGS -fno-inline"])
	    ;;
	Lynx*)
	    SHLIB_CFLAGS="-fPIC"
	    SHLIB_SUFFIX=".so"
	    CFLAGS_OPTIMIZE=-02
	    SHLIB_LD='${CC} -shared'
	    LD_FLAGS="-Wl,--export-dynamic"
	    AS_IF([test $doRpath = yes], [
		CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
		LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
	    ;;
	OpenBSD-*)
	    arch=`arch -s`
	    case "$arch" in
	    alpha|sparc64)
		SHLIB_CFLAGS="-fPIC"
		;;
	    *)
		SHLIB_CFLAGS="-fpic"
		;;
	    esac
	    SHLIB_LD='${CC} -shared ${SHLIB_CFLAGS}'
	    SHLIB_SUFFIX=".so"
	    AS_IF([test $doRpath = yes], [
		CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
	    LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
	    SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.so${SHLIB_VERSION}'
	    LDFLAGS="-Wl,-export-dynamic"
	    CFLAGS_OPTIMIZE="-O2"
	    AS_IF([test "${TCL_THREADS}" = "1"], [
		# On OpenBSD:	Compile with -pthread
		#		Don't link with -lpthread
		LIBS=`echo $LIBS | sed s/-lpthread//`
		CFLAGS="$CFLAGS -pthread"
	    ])
	    # OpenBSD doesn't do version numbers with dots.
	    UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
	    TCL_LIB_VERSIONS_OK=nodots
	    ;;
	NetBSD-*)
	    # NetBSD has ELF and can use 'cc -shared' to build shared libs
	    SHLIB_CFLAGS="-fPIC"
	    SHLIB_LD='${CC} -shared ${SHLIB_CFLAGS}'
	    SHLIB_SUFFIX=".so"
	    LDFLAGS="$LDFLAGS -export-dynamic"
	    AS_IF([test $doRpath = yes], [
		CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
	    LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
	    AS_IF([test "${TCL_THREADS}" = "1"], [
		# The -pthread needs to go in the CFLAGS, not LIBS
		LIBS=`echo $LIBS | sed s/-pthread//`
		CFLAGS="$CFLAGS -pthread"
	    	LDFLAGS="$LDFLAGS -pthread"
	    ])
	    ;;
	FreeBSD-*)
	    # This configuration from FreeBSD Ports.
	    SHLIB_CFLAGS="-fPIC"
	    SHLIB_LD="${CC} -shared"
	    TCL_SHLIB_LD_EXTRAS="-Wl,-soname=\$[@]"
	    TK_SHLIB_LD_EXTRAS="-Wl,-soname,\$[@]"
	    SHLIB_SUFFIX=".so"
	    LDFLAGS=""
	    AS_IF([test $doRpath = yes], [
		CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
		LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
	    AS_IF([test "${TCL_THREADS}" = "1"], [
		# The -pthread needs to go in the LDFLAGS, not LIBS
		LIBS=`echo $LIBS | sed s/-pthread//`
		CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
		LDFLAGS="$LDFLAGS $PTHREAD_LIBS"])
	    case $system in
	    FreeBSD-3.*)
		# Version numbers are dot-stripped by system policy.
		TCL_TRIM_DOTS=`echo ${VERSION} | tr -d .`
		UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
		SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.so'
		TCL_LIB_VERSIONS_OK=nodots
		;;
	    esac
	    ;;
	Darwin-*)
	    CFLAGS_OPTIMIZE="-Os"
	    SHLIB_CFLAGS="-fno-common"
	    # To avoid discrepancies between what headers configure sees during
	    # preprocessing tests and compiling tests, move any -isysroot and
	    # -mmacosx-version-min flags from CFLAGS to CPPFLAGS:
	    CPPFLAGS="${CPPFLAGS} `echo " ${CFLAGS}" | \
		awk 'BEGIN {FS=" +-";ORS=" "}; {for (i=2;i<=NF;i++) \
		if ([$]i~/^(isysroot|mmacosx-version-min)/) print "-"[$]i}'`"
	    CFLAGS="`echo " ${CFLAGS}" | \
		awk 'BEGIN {FS=" +-";ORS=" "}; {for (i=2;i<=NF;i++) \
		if (!([$]i~/^(isysroot|mmacosx-version-min)/)) print "-"[$]i}'`"
	    AS_IF([test $do64bit = yes], [
		case `arch` in
		    ppc)
			AC_CACHE_CHECK([if compiler accepts -arch ppc64 flag],
				tcl_cv_cc_arch_ppc64, [
			    hold_cflags=$CFLAGS
			    CFLAGS="$CFLAGS -arch ppc64 -mpowerpc64 -mcpu=G5"
			    AC_TRY_LINK(,, tcl_cv_cc_arch_ppc64=yes,
				    tcl_cv_cc_arch_ppc64=no)
			    CFLAGS=$hold_cflags])
			AS_IF([test $tcl_cv_cc_arch_ppc64 = yes], [
			    CFLAGS="$CFLAGS -arch ppc64 -mpowerpc64 -mcpu=G5"
			    do64bit_ok=yes
			]);;
		    i386)
			AC_CACHE_CHECK([if compiler accepts -arch x86_64 flag],
				tcl_cv_cc_arch_x86_64, [
			    hold_cflags=$CFLAGS
			    CFLAGS="$CFLAGS -arch x86_64"
			    AC_TRY_LINK(,, tcl_cv_cc_arch_x86_64=yes,
				    tcl_cv_cc_arch_x86_64=no)
			    CFLAGS=$hold_cflags])
			AS_IF([test $tcl_cv_cc_arch_x86_64 = yes], [
			    CFLAGS="$CFLAGS -arch x86_64"
			    do64bit_ok=yes
			]);;
		    *)
			AC_MSG_WARN([Don't know how enable 64-bit on architecture `arch`]);;
		esac
	    ], [
		# Check for combined 32-bit and 64-bit fat build
		AS_IF([echo "$CFLAGS " |grep -E -q -- '-arch (ppc64|x86_64) ' \
		    && echo "$CFLAGS " |grep -E -q -- '-arch (ppc|i386) '], [
		    fat_32_64=yes])
	    ])
	    # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
	    SHLIB_LD='${CC} -dynamiclib ${CFLAGS} ${LDFLAGS_DEFAULT}'
	    AC_CACHE_CHECK([if ld accepts -single_module flag], tcl_cv_ld_single_module, [
		hold_ldflags=$LDFLAGS
		LDFLAGS="$LDFLAGS -dynamiclib -Wl,-single_module"
		AC_TRY_LINK(, [int i;], tcl_cv_ld_single_module=yes, tcl_cv_ld_single_module=no)
		LDFLAGS=$hold_ldflags])
	    AS_IF([test $tcl_cv_ld_single_module = yes], [
		SHLIB_LD="${SHLIB_LD} -Wl,-single_module"
	    ])
	    # TEA specific: link shlib with current and compatibility version flags
	    vers=`echo ${PACKAGE_VERSION} | sed -e 's/^\([[0-9]]\{1,5\}\)\(\(\.[[0-9]]\{1,3\}\)\{0,2\}\).*$/\1\2/p' -e d`
	    SHLIB_LD="${SHLIB_LD} -current_version ${vers:-0} -compatibility_version ${vers:-0}"
	    SHLIB_SUFFIX=".dylib"
	    # Don't use -prebind when building for Mac OS X 10.4 or later only:
	    AS_IF([test "`echo "${MACOSX_DEPLOYMENT_TARGET}" | awk -F '10\\.' '{print int([$]2)}'`" -lt 4 -a \
		"`echo "${CPPFLAGS}" | awk -F '-mmacosx-version-min=10\\.' '{print int([$]2)}'`" -lt 4], [
		LDFLAGS="$LDFLAGS -prebind"])
	    LDFLAGS="$LDFLAGS -headerpad_max_install_names"
	    AC_CACHE_CHECK([if ld accepts -search_paths_first flag],
		    tcl_cv_ld_search_paths_first, [
		hold_ldflags=$LDFLAGS
		LDFLAGS="$LDFLAGS -Wl,-search_paths_first"
		AC_TRY_LINK(, [int i;], tcl_cv_ld_search_paths_first=yes,
			tcl_cv_ld_search_paths_first=no)
		LDFLAGS=$hold_ldflags])
	    AS_IF([test $tcl_cv_ld_search_paths_first = yes], [
		LDFLAGS="$LDFLAGS -Wl,-search_paths_first"
	    ])
	    AS_IF([test "$tcl_cv_cc_visibility_hidden" != yes], [
		AC_DEFINE(MODULE_SCOPE, [__private_extern__],
		    [Compiler support for module scope symbols])
		tcl_cv_cc_visibility_hidden=yes
	    ])
	    CC_SEARCH_FLAGS=""
	    LD_SEARCH_FLAGS=""
	    LD_LIBRARY_PATH_VAR="DYLD_LIBRARY_PATH"
	    # TEA specific: for combined 32 & 64 bit fat builds of Tk
	    # extensions, verify that 64-bit build is possible.
	    AS_IF([test "$fat_32_64" = yes && test -n "${TK_BIN_DIR}"], [
		AS_IF([test "${TEA_WINDOWINGSYSTEM}" = x11], [
		    AC_CACHE_CHECK([for 64-bit X11], tcl_cv_lib_x11_64, [
			for v in CFLAGS CPPFLAGS LDFLAGS; do
			    eval 'hold_'$v'="$'$v'";'$v'="`echo "$'$v' "|sed -e "s/-arch ppc / /g" -e "s/-arch i386 / /g"`"'
			done
			CPPFLAGS="$CPPFLAGS -I/usr/X11R6/include"
			LDFLAGS="$LDFLAGS -L/usr/X11R6/lib -lX11"
			AC_TRY_LINK([#include <X11/Xlib.h>], [XrmInitialize();],
			    tcl_cv_lib_x11_64=yes, tcl_cv_lib_x11_64=no)
			for v in CFLAGS CPPFLAGS LDFLAGS; do
			    eval $v'="$hold_'$v'"'
			done])
		])
		AS_IF([test "${TEA_WINDOWINGSYSTEM}" = aqua], [
		    AC_CACHE_CHECK([for 64-bit Tk], tcl_cv_lib_tk_64, [
			for v in CFLAGS CPPFLAGS LDFLAGS; do
			    eval 'hold_'$v'="$'$v'";'$v'="`echo "$'$v' "|sed -e "s/-arch ppc / /g" -e "s/-arch i386 / /g"`"'
			done
			CPPFLAGS="$CPPFLAGS -DUSE_TCL_STUBS=1 -DUSE_TK_STUBS=1 ${TCL_INCLUDES} ${TK_INCLUDES}"
			LDFLAGS="$LDFLAGS ${TCL_STUB_LIB_SPEC} ${TK_STUB_LIB_SPEC}"
			AC_TRY_LINK([#include <tk.h>], [Tk_InitStubs(NULL, "", 0);],
			    tcl_cv_lib_tk_64=yes, tcl_cv_lib_tk_64=no)
			for v in CFLAGS CPPFLAGS LDFLAGS; do
			    eval $v'="$hold_'$v'"'
			done])
		])
		# remove 64-bit arch flags from CFLAGS et al. if configuration
		# does not support 64-bit.
		AS_IF([test "$tcl_cv_lib_tk_64" = no -o "$tcl_cv_lib_x11_64" = no], [
		    AC_MSG_NOTICE([Removing 64-bit architectures from compiler & linker flags])
		    for v in CFLAGS CPPFLAGS LDFLAGS; do
			eval $v'="`echo "$'$v' "|sed -e "s/-arch ppc64 / /g" -e "s/-arch x86_64 / /g"`"'
		    done])
	    ])
	    ;;
	OS/390-*)
	    CFLAGS_OPTIMIZE=""		# Optimizer is buggy
	    AC_DEFINE(_OE_SOCKETS, 1,	# needed in sys/socket.h
		[Should OS/390 do the right thing with sockets?])
	    ;;
	OSF1-V*)
	    # Digital OSF/1
	    SHLIB_CFLAGS=""
	    AS_IF([test "$SHARED_BUILD" = 1], [
	        SHLIB_LD='ld -shared -expect_unresolved "*"'
	    ], [
	        SHLIB_LD='ld -non_shared -expect_unresolved "*"'
	    ])
	    SHLIB_SUFFIX=".so"
	    AS_IF([test $doRpath = yes], [
		CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
		LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
	    AS_IF([test "$GCC" = yes], [CFLAGS="$CFLAGS -mieee"], [
		CFLAGS="$CFLAGS -DHAVE_TZSET -std1 -ieee"])
	    # see pthread_intro(3) for pthread support on osf1, k.furukawa
	    AS_IF([test "${TCL_THREADS}" = 1], [
		CFLAGS="$CFLAGS -DHAVE_PTHREAD_ATTR_SETSTACKSIZE"
		CFLAGS="$CFLAGS -DTCL_THREAD_STACK_MIN=PTHREAD_STACK_MIN*64"
		LIBS=`echo $LIBS | sed s/-lpthreads//`
		AS_IF([test "$GCC" = yes], [
		    LIBS="$LIBS -lpthread -lmach -lexc"
		], [
		    CFLAGS="$CFLAGS -pthread"
		    LDFLAGS="$LDFLAGS -pthread"
		])
	    ])
	    ;;
	QNX-6*)
	    # QNX RTP
	    # This may work for all QNX, but it was only reported for v6.
	    SHLIB_CFLAGS="-fPIC"
	    SHLIB_LD="ld -Bshareable -x"
	    SHLIB_LD_LIBS=""
	    SHLIB_SUFFIX=".so"
	    CC_SEARCH_FLAGS=""
	    LD_SEARCH_FLAGS=""
	    ;;
	SCO_SV-3.2*)
	    AS_IF([test "$GCC" = yes], [
		SHLIB_CFLAGS="-fPIC -melf"
		LDFLAGS="$LDFLAGS -melf -Wl,-Bexport"
	    ], [
		SHLIB_CFLAGS="-Kpic -belf"
		LDFLAGS="$LDFLAGS -belf -Wl,-Bexport"
	    ])
	    SHLIB_LD="ld -G"
	    SHLIB_LD_LIBS=""
	    SHLIB_SUFFIX=".so"
	    CC_SEARCH_FLAGS=""
	    LD_SEARCH_FLAGS=""
	    ;;
	SunOS-5.[[0-6]])
	    # Careful to not let 5.10+ fall into this case

	    # Note: If _REENTRANT isn't defined, then Solaris
	    # won't define thread-safe library routines.

	    AC_DEFINE(_REENTRANT, 1, [Do we want the reentrant OS API?])
	    AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1,
		[Do we really want to follow the standard? Yes we do!])

	    SHLIB_CFLAGS="-KPIC"
	    SHLIB_SUFFIX=".so"
	    AS_IF([test "$GCC" = yes], [
		SHLIB_LD='${CC} -shared'
		CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
		LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
	    ], [
		SHLIB_LD="/usr/ccs/bin/ld -G -z text"
		CC_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
		LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
	    ])
	    ;;
	SunOS-5*)
	    # Note: If _REENTRANT isn't defined, then Solaris
	    # won't define thread-safe library routines.

	    AC_DEFINE(_REENTRANT, 1, [Do we want the reentrant OS API?])
	    AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1,
		[Do we really want to follow the standard? Yes we do!])

	    SHLIB_CFLAGS="-KPIC"

	    # Check to enable 64-bit flags for compiler/linker
	    AS_IF([test "$do64bit" = yes], [
		arch=`isainfo`
		AS_IF([test "$arch" = "sparcv9 sparc"], [
		    AS_IF([test "$GCC" = yes], [
			AS_IF([test "`${CC} -dumpversion | awk -F. '{print [$]1}'`" -lt 3], [
			    AC_MSG_WARN([64bit mode not supported with GCC < 3.2 on $system])
			], [
			    do64bit_ok=yes
			    CFLAGS="$CFLAGS -m64 -mcpu=v9"
			    LDFLAGS="$LDFLAGS -m64 -mcpu=v9"
			    SHLIB_CFLAGS="-fPIC"
			])
		    ], [
			do64bit_ok=yes
			AS_IF([test "$do64bitVIS" = yes], [
			    CFLAGS="$CFLAGS -xarch=v9a"
			    LDFLAGS_ARCH="-xarch=v9a"
			], [
			    CFLAGS="$CFLAGS -xarch=v9"
			    LDFLAGS_ARCH="-xarch=v9"
			])
			# Solaris 64 uses this as well
			#LD_LIBRARY_PATH_VAR="LD_LIBRARY_PATH_64"
		    ])
		], [AS_IF([test "$arch" = "amd64 i386"], [
		    AS_IF([test "$GCC" = yes], [
			case $system in
			    SunOS-5.1[[1-9]]*|SunOS-5.[[2-9]][[0-9]]*)
				do64bit_ok=yes
				CFLAGS="$CFLAGS -m64"
				LDFLAGS="$LDFLAGS -m64";;
			    *)
				AC_MSG_WARN([64bit mode not supported with GCC on $system]);;
			esac
		    ], [
			do64bit_ok=yes
			case $system in
			    SunOS-5.1[[1-9]]*|SunOS-5.[[2-9]][[0-9]]*)
				CFLAGS="$CFLAGS -m64"
				LDFLAGS="$LDFLAGS -m64";;
			    *)
				CFLAGS="$CFLAGS -xarch=amd64"
				LDFLAGS="$LDFLAGS -xarch=amd64";;
			esac
		    ])
		], [AC_MSG_WARN([64bit mode not supported for $arch])])])
	    ])

	    SHLIB_SUFFIX=".so"
	    AS_IF([test "$GCC" = yes], [
		SHLIB_LD='${CC} -shared'
		CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
		LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
		AS_IF([test "$do64bit_ok" = yes], [
		    AS_IF([test "$arch" = "sparcv9 sparc"], [
			# We need to specify -static-libgcc or we need to
			# add the path to the sparv9 libgcc.
			# JH: static-libgcc is necessary for core Tcl, but may
			# not be necessary for extensions.
			SHLIB_LD="$SHLIB_LD -m64 -mcpu=v9 -static-libgcc"
			# for finding sparcv9 libgcc, get the regular libgcc
			# path, remove so name and append 'sparcv9'
			#v9gcclibdir="`gcc -print-file-name=libgcc_s.so` | ..."
			#CC_SEARCH_FLAGS="${CC_SEARCH_FLAGS},-R,$v9gcclibdir"
		    ], [AS_IF([test "$arch" = "amd64 i386"], [
			# JH: static-libgcc is necessary for core Tcl, but may
			# not be necessary for extensions.
			SHLIB_LD="$SHLIB_LD -m64 -static-libgcc"
		    ])])
		])
	    ], [
		case $system in
		    SunOS-5.[[1-9]][[0-9]]*)
			# TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
			SHLIB_LD='${CC} -G -z text ${LDFLAGS_DEFAULT}';;
		    *)
			SHLIB_LD='/usr/ccs/bin/ld -G -z text';;
		esac
		CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
		LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
	    ])
	    ;;
	UNIX_SV* | UnixWare-5*)
	    SHLIB_CFLAGS="-KPIC"
	    SHLIB_LD='${CC} -G'
	    SHLIB_LD_LIBS=""
	    SHLIB_SUFFIX=".so"
	    # Some UNIX_SV* systems (unixware 1.1.2 for example) have linkers
	    # that don't grok the -Bexport option.  Test that it does.
	    AC_CACHE_CHECK([for ld accepts -Bexport flag], tcl_cv_ld_Bexport, [
		hold_ldflags=$LDFLAGS
		LDFLAGS="$LDFLAGS -Wl,-Bexport"
		AC_TRY_LINK(, [int i;], tcl_cv_ld_Bexport=yes, tcl_cv_ld_Bexport=no)
	        LDFLAGS=$hold_ldflags])
	    AS_IF([test $tcl_cv_ld_Bexport = yes], [
		LDFLAGS="$LDFLAGS -Wl,-Bexport"
	    ])
	    CC_SEARCH_FLAGS=""
	    LD_SEARCH_FLAGS=""
	    ;;
    esac

    AS_IF([test "$do64bit" = yes -a "$do64bit_ok" = no], [
	AC_MSG_WARN([64bit support being disabled -- don't know magic for this platform])
    ])

dnl # Add any CPPFLAGS set in the environment to our CFLAGS, but delay doing so
dnl # until the end of configure, as configure's compile and link tests use
dnl # both CPPFLAGS and CFLAGS (unlike our compile and link) but configure's
dnl # preprocessing tests use only CPPFLAGS.
    AC_CONFIG_COMMANDS_PRE([CFLAGS="${CFLAGS} ${CPPFLAGS}"; CPPFLAGS=""])

    # Add in the arch flags late to ensure it wasn't removed.
    # Not necessary in TEA, but this is aligned with core
    LDFLAGS="$LDFLAGS $LDFLAGS_ARCH"

    # If we're running gcc, then change the C flags for compiling shared
    # libraries to the right flags for gcc, instead of those for the
    # standard manufacturer compiler.

    AS_IF([test "$GCC" = yes], [
	case $system in
	    AIX-*) ;;
	    BSD/OS*) ;;
	    CYGWIN_*|MINGW32_*) ;;
	    IRIX*) ;;
	    NetBSD-*|FreeBSD-*|OpenBSD-*) ;;
	    Darwin-*) ;;
	    SCO_SV-3.2*) ;;
	    windows) ;;
	    *) SHLIB_CFLAGS="-fPIC" ;;
	esac])

    AS_IF([test "$tcl_cv_cc_visibility_hidden" != yes], [
	AC_DEFINE(MODULE_SCOPE, [extern],
	    [No Compiler support for module scope symbols])
    ])

    AS_IF([test "$SHARED_LIB_SUFFIX" = ""], [
    # TEA specific: use PACKAGE_VERSION instead of VERSION
    SHARED_LIB_SUFFIX='${PACKAGE_VERSION}${SHLIB_SUFFIX}'])
    AS_IF([test "$UNSHARED_LIB_SUFFIX" = ""], [
    # TEA specific: use PACKAGE_VERSION instead of VERSION
    UNSHARED_LIB_SUFFIX='${PACKAGE_VERSION}.a'])

    if test "${GCC}" = "yes" -a ${SHLIB_SUFFIX} = ".dll"; then
	AC_CACHE_CHECK(for SEH support in compiler,
	    tcl_cv_seh,
	AC_TRY_RUN([
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#undef WIN32_LEAN_AND_MEAN

	    int main(int argc, char** argv) {
		int a, b = 0;
		__try {
		    a = 666 / b;
		}
		__except (EXCEPTION_EXECUTE_HANDLER) {
		    return 0;
		}
		return 1;
	    }
	],
	    tcl_cv_seh=yes,
	    tcl_cv_seh=no,
	    tcl_cv_seh=no)
	)
	if test "$tcl_cv_seh" = "no" ; then
	    AC_DEFINE(HAVE_NO_SEH, 1,
		    [Defined when mingw does not support SEH])
	fi

	#
	# Check to see if the excpt.h include file provided contains the
	# definition for EXCEPTION_DISPOSITION; if not, which is the case
	# with Cygwin's version as of 2002-04-10, define it to be int,
	# sufficient for getting the current code to work.
	#
	AC_CACHE_CHECK(for EXCEPTION_DISPOSITION support in include files,
	    tcl_cv_eh_disposition,
	    AC_TRY_COMPILE([
#	    define WIN32_LEAN_AND_MEAN
#	    include <windows.h>
#	    undef WIN32_LEAN_AND_MEAN
	    ],[
		EXCEPTION_DISPOSITION x;
	    ],
		tcl_cv_eh_disposition=yes,
		tcl_cv_eh_disposition=no)
	)
	if test "$tcl_cv_eh_disposition" = "no" ; then
	AC_DEFINE(EXCEPTION_DISPOSITION, int,
		[Defined when cygwin/mingw does not support EXCEPTION DISPOSITION])
	fi

	# Check to see if winnt.h defines CHAR, SHORT, and LONG
	# even if VOID has already been #defined. The win32api
	# used by mingw and cygwin is known to do this.

	AC_CACHE_CHECK(for winnt.h that ignores VOID define,
	    tcl_cv_winnt_ignore_void,
	    AC_TRY_COMPILE([
#define VOID void
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#undef WIN32_LEAN_AND_MEAN
	    ], [
		CHAR c;
		SHORT s;
		LONG l;
	    ],
        tcl_cv_winnt_ignore_void=yes,
        tcl_cv_winnt_ignore_void=no)
	)
	if test "$tcl_cv_winnt_ignore_void" = "yes" ; then
	    AC_DEFINE(HAVE_WINNT_IGNORE_VOID, 1,
		    [Defined when cygwin/mingw ignores VOID define in winnt.h])
	fi
    fi

	# See if the compiler supports casting to a union type.
	# This is used to stop gcc from printing a compiler
	# warning when initializing a union member.

	AC_CACHE_CHECK(for cast to union support,
	    tcl_cv_cast_to_union,
	    AC_TRY_COMPILE([],
	    [
		  union foo { int i; double d; };
		  union foo f = (union foo) (int) 0;
	    ],
	    tcl_cv_cast_to_union=yes,
	    tcl_cv_cast_to_union=no)
	)
	if test "$tcl_cv_cast_to_union" = "yes"; then
	    AC_DEFINE(HAVE_CAST_TO_UNION, 1,
		    [Defined when compiler supports casting to union type.])
	fi

    AC_SUBST(CFLAGS_DEBUG)
    AC_SUBST(CFLAGS_OPTIMIZE)
    AC_SUBST(CFLAGS_WARNING)
    AC_SUBST(CC_OBJNAME)

    AC_SUBST(STLIB_LD)
    AC_SUBST(SHLIB_LD)

    AC_SUBST(SHLIB_LD_LIBS)
    AC_SUBST(SHLIB_CFLAGS)

    AC_SUBST(LD_LIBRARY_PATH_VAR)

    # These must be called after we do the basic CFLAGS checks and
    # verify any possible 64-bit or similar switches are necessary
    TEA_TCL_EARLY_FLAGS
    TEA_TCL_64BIT_FLAGS
])

#--------------------------------------------------------------------
# TEA_SERIAL_PORT
#
#	Determine which interface to use to talk to the serial port.
#	Note that #include lines must begin in leftmost column for
#	some compilers to recognize them as preprocessor directives,
#	and some build environments have stdin not pointing at a
#	pseudo-terminal (usually /dev/null instead.)
#
# Arguments:
#	none
#
# Results:
#
#	Defines only one of the following vars:
#		HAVE_SYS_MODEM_H
#		USE_TERMIOS
#		USE_TERMIO
#		USE_SGTTY
#--------------------------------------------------------------------

AC_DEFUN([TEA_SERIAL_PORT], [
    AC_CHECK_HEADERS(sys/modem.h)
    AC_CACHE_CHECK([termios vs. termio vs. sgtty], tcl_cv_api_serial, [
    AC_TRY_RUN([
#include <termios.h>

int main() {
    struct termios t;
    if (tcgetattr(0, &t) == 0) {
	cfsetospeed(&t, 0);
	t.c_cflag |= PARENB | PARODD | CSIZE | CSTOPB;
	return 0;
    }
    return 1;
}], tcl_cv_api_serial=termios, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
    if test $tcl_cv_api_serial = no ; then
	AC_TRY_RUN([
#include <termio.h>

int main() {
    struct termio t;
    if (ioctl(0, TCGETA, &t) == 0) {
	t.c_cflag |= CBAUD | PARENB | PARODD | CSIZE | CSTOPB;
	return 0;
    }
    return 1;
}], tcl_cv_api_serial=termio, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
    fi
    if test $tcl_cv_api_serial = no ; then
	AC_TRY_RUN([
#include <sgtty.h>

int main() {
    struct sgttyb t;
    if (ioctl(0, TIOCGETP, &t) == 0) {
	t.sg_ospeed = 0;
	t.sg_flags |= ODDP | EVENP | RAW;
	return 0;
    }
    return 1;
}], tcl_cv_api_serial=sgtty, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
    fi
    if test $tcl_cv_api_serial = no ; then
	AC_TRY_RUN([
#include <termios.h>
#include <errno.h>

int main() {
    struct termios t;
    if (tcgetattr(0, &t) == 0
	|| errno == ENOTTY || errno == ENXIO || errno == EINVAL) {
	cfsetospeed(&t, 0);
	t.c_cflag |= PARENB | PARODD | CSIZE | CSTOPB;
	return 0;
    }
    return 1;
}], tcl_cv_api_serial=termios, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
    fi
    if test $tcl_cv_api_serial = no; then
	AC_TRY_RUN([
#include <termio.h>
#include <errno.h>

int main() {
    struct termio t;
    if (ioctl(0, TCGETA, &t) == 0
	|| errno == ENOTTY || errno == ENXIO || errno == EINVAL) {
	t.c_cflag |= CBAUD | PARENB | PARODD | CSIZE | CSTOPB;
	return 0;
    }
    return 1;
    }], tcl_cv_api_serial=termio, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
    fi
    if test $tcl_cv_api_serial = no; then
	AC_TRY_RUN([
#include <sgtty.h>
#include <errno.h>

int main() {
    struct sgttyb t;
    if (ioctl(0, TIOCGETP, &t) == 0
	|| errno == ENOTTY || errno == ENXIO || errno == EINVAL) {
	t.sg_ospeed = 0;
	t.sg_flags |= ODDP | EVENP | RAW;
	return 0;
    }
    return 1;
}], tcl_cv_api_serial=sgtty, tcl_cv_api_serial=none, tcl_cv_api_serial=none)
    fi])
    case $tcl_cv_api_serial in
	termios) AC_DEFINE(USE_TERMIOS, 1, [Use the termios API for serial lines]);;
	termio)  AC_DEFINE(USE_TERMIO, 1, [Use the termio API for serial lines]);;
	sgtty)   AC_DEFINE(USE_SGTTY, 1, [Use the sgtty API for serial lines]);;
    esac
])

#--------------------------------------------------------------------
# TEA_MISSING_POSIX_HEADERS
#
#	Supply substitutes for missing POSIX header files.  Special
#	notes:
#	    - stdlib.h doesn't define strtol, strtoul, or
#	      strtod in some versions of SunOS
#	    - some versions of string.h don't declare procedures such
#	      as strstr
#
# Arguments:
#	none
#
# Results:
#
#	Defines some of the following vars:
#		NO_DIRENT_H
#		NO_ERRNO_H
#		NO_VALUES_H
#		HAVE_LIMITS_H or NO_LIMITS_H
#		NO_STDLIB_H
#		NO_STRING_H
#		NO_SYS_WAIT_H
#		NO_DLFCN_H
#		HAVE_SYS_PARAM_H
#
#		HAVE_STRING_H ?
#
# tkUnixPort.h checks for HAVE_LIMITS_H, so do both HAVE and
# CHECK on limits.h
#--------------------------------------------------------------------

AC_DEFUN([TEA_MISSING_POSIX_HEADERS], [
    AC_CACHE_CHECK([dirent.h], tcl_cv_dirent_h, [
    AC_TRY_LINK([#include <sys/types.h>
#include <dirent.h>], [
#ifndef _POSIX_SOURCE
#   ifdef __Lynx__
	/*
	 * Generate compilation error to make the test fail:  Lynx headers
	 * are only valid if really in the POSIX environment.
	 */

	missing_procedure();
#   endif
#endif
DIR *d;
struct dirent *entryPtr;
char *p;
d = opendir("foobar");
entryPtr = readdir(d);
p = entryPtr->d_name;
closedir(d);
], tcl_cv_dirent_h=yes, tcl_cv_dirent_h=no)])

    if test $tcl_cv_dirent_h = no; then
	AC_DEFINE(NO_DIRENT_H, 1, [Do we have <dirent.h>?])
    fi

    # TEA specific:
    AC_CHECK_HEADER(errno.h, , [AC_DEFINE(NO_ERRNO_H, 1, [Do we have <errno.h>?])])
    AC_CHECK_HEADER(float.h, , [AC_DEFINE(NO_FLOAT_H, 1, [Do we have <float.h>?])])
    AC_CHECK_HEADER(values.h, , [AC_DEFINE(NO_VALUES_H, 1, [Do we have <values.h>?])])
    AC_CHECK_HEADER(limits.h,
	[AC_DEFINE(HAVE_LIMITS_H, 1, [Do we have <limits.h>?])],
	[AC_DEFINE(NO_LIMITS_H, 1, [Do we have <limits.h>?])])
    AC_CHECK_HEADER(stdlib.h, tcl_ok=1, tcl_ok=0)
    AC_EGREP_HEADER(strtol, stdlib.h, , tcl_ok=0)
    AC_EGREP_HEADER(strtoul, stdlib.h, , tcl_ok=0)
    AC_EGREP_HEADER(strtod, stdlib.h, , tcl_ok=0)
    if test $tcl_ok = 0; then
	AC_DEFINE(NO_STDLIB_H, 1, [Do we have <stdlib.h>?])
    fi
    AC_CHECK_HEADER(string.h, tcl_ok=1, tcl_ok=0)
    AC_EGREP_HEADER(strstr, string.h, , tcl_ok=0)
    AC_EGREP_HEADER(strerror, string.h, , tcl_ok=0)

    # See also memmove check below for a place where NO_STRING_H can be
    # set and why.

    if test $tcl_ok = 0; then
	AC_DEFINE(NO_STRING_H, 1, [Do we have <string.h>?])
    fi

    AC_CHECK_HEADER(sys/wait.h, , [AC_DEFINE(NO_SYS_WAIT_H, 1, [Do we have <sys/wait.h>?])])
    AC_CHECK_HEADER(dlfcn.h, , [AC_DEFINE(NO_DLFCN_H, 1, [Do we have <dlfcn.h>?])])

    # OS/390 lacks sys/param.h (and doesn't need it, by chance).
    AC_HAVE_HEADERS(sys/param.h)
])

#--------------------------------------------------------------------
# TEA_PATH_X
#
#	Locate the X11 header files and the X11 library archive.  Try
#	the ac_path_x macro first, but if it doesn't find the X stuff
#	(e.g. because there's no xmkmf program) then check through
#	a list of possible directories.  Under some conditions the
#	autoconf macro will return an include directory that contains
#	no include files, so double-check its result just to be safe.
#
#	This should be called after TEA_CONFIG_CFLAGS as setting the
#	LIBS line can confuse some configure macro magic.
#
# Arguments:
#	none
#
# Results:
#
#	Sets the following vars:
#		XINCLUDES
#		XLIBSW
#		PKG_LIBS (appends to)
#--------------------------------------------------------------------

AC_DEFUN([TEA_PATH_X], [
    if test "${TEA_WINDOWINGSYSTEM}" = "x11" -a "${TEA_USE_SDL}" != "yes" ; then
	TEA_PATH_UNIX_X
    fi
])

AC_DEFUN([TEA_PATH_UNIX_X], [
    AC_PATH_X
    not_really_there=""
    if test "$no_x" = ""; then
	if test "$x_includes" = ""; then
	    AC_TRY_CPP([#include <X11/Xlib.h>], , not_really_there="yes")
	else
	    if test ! -r $x_includes/X11/Xlib.h; then
		not_really_there="yes"
	    fi
	fi
    fi
    if test "$no_x" = "yes" -o "$not_really_there" = "yes"; then
	AC_MSG_CHECKING([for X11 header files])
	found_xincludes="no"
	AC_TRY_CPP([#include <X11/Xlib.h>], found_xincludes="yes", found_xincludes="no")
	if test "$found_xincludes" = "no"; then
	    dirs="/usr/unsupported/include /usr/local/include /usr/X386/include /usr/X11R6/include /usr/X11R5/include /usr/include/X11R5 /usr/include/X11R4 /usr/openwin/include /usr/X11/include /usr/sww/include"
	    for i in $dirs ; do
		if test -r $i/X11/Xlib.h; then
		    AC_MSG_RESULT([$i])
		    XINCLUDES=" -I$i"
		    found_xincludes="yes"
		    break
		fi
	    done
	fi
    else
	if test "$x_includes" != ""; then
	    XINCLUDES="-I$x_includes"
	    found_xincludes="yes"
	fi
    fi
    if test "$found_xincludes" = "no"; then
	AC_MSG_RESULT([couldn't find any!])
    fi

    if test "$no_x" = yes; then
	AC_MSG_CHECKING([for X11 libraries])
	XLIBSW=nope
	dirs="/usr/unsupported/lib /usr/local/lib /usr/X386/lib /usr/X11R6/lib /usr/X11R5/lib /usr/lib/X11R5 /usr/lib/X11R4 /usr/openwin/lib /usr/X11/lib /usr/sww/X11/lib"
	for i in $dirs ; do
	    if test -r $i/libX11.a -o -r $i/libX11.so -o -r $i/libX11.sl -o -r $i/libX11.dylib; then
		AC_MSG_RESULT([$i])
		XLIBSW="-L$i -lX11"
		x_libraries="$i"
		break
	    fi
	done
    else
	if test "$x_libraries" = ""; then
	    XLIBSW=-lX11
	else
	    XLIBSW="-L$x_libraries -lX11"
	fi
    fi
    if test "$XLIBSW" = nope ; then
	AC_CHECK_LIB(Xwindow, XCreateWindow, XLIBSW=-lXwindow)
    fi
    if test "$XLIBSW" = nope ; then
	AC_MSG_RESULT([could not find any!  Using -lX11.])
	XLIBSW=-lX11
    fi
    # TEA specific:
    if test x"${XLIBSW}" != x ; then
	PKG_LIBS="${PKG_LIBS} ${XLIBSW}"
    fi
])

#--------------------------------------------------------------------
# TEA_BLOCKING_STYLE
#
#	The statements below check for systems where POSIX-style
#	non-blocking I/O (O_NONBLOCK) doesn't work or is unimplemented.
#	On these systems (mostly older ones), use the old BSD-style
#	FIONBIO approach instead.
#
# Arguments:
#	none
#
# Results:
#
#	Defines some of the following vars:
#		HAVE_SYS_IOCTL_H
#		HAVE_SYS_FILIO_H
#		USE_FIONBIO
#		O_NONBLOCK
#--------------------------------------------------------------------

AC_DEFUN([TEA_BLOCKING_STYLE], [
    AC_CHECK_HEADERS(sys/ioctl.h)
    AC_CHECK_HEADERS(sys/filio.h)
    TEA_CONFIG_SYSTEM
    AC_MSG_CHECKING([FIONBIO vs. O_NONBLOCK for nonblocking I/O])
    case $system in
	OSF*)
	    AC_DEFINE(USE_FIONBIO, 1, [Should we use FIONBIO?])
	    AC_MSG_RESULT([FIONBIO])
	    ;;
	*)
	    AC_MSG_RESULT([O_NONBLOCK])
	    ;;
    esac
])

#--------------------------------------------------------------------
# TEA_TIME_HANDLER
#
#	Checks how the system deals with time.h, what time structures
#	are used on the system, and what fields the structures have.
#
# Arguments:
#	none
#
# Results:
#
#	Defines some of the following vars:
#		USE_DELTA_FOR_TZ
#		HAVE_TM_GMTOFF
#		HAVE_TM_TZADJ
#		HAVE_TIMEZONE_VAR
#--------------------------------------------------------------------

AC_DEFUN([TEA_TIME_HANDLER], [
    AC_CHECK_HEADERS(sys/time.h)
    AC_HEADER_TIME
    AC_STRUCT_TIMEZONE

    AC_CHECK_FUNCS(gmtime_r localtime_r)

    AC_CACHE_CHECK([tm_tzadj in struct tm], tcl_cv_member_tm_tzadj, [
	AC_TRY_COMPILE([#include <time.h>], [struct tm tm; tm.tm_tzadj;],
	    tcl_cv_member_tm_tzadj=yes, tcl_cv_member_tm_tzadj=no)])
    if test $tcl_cv_member_tm_tzadj = yes ; then
	AC_DEFINE(HAVE_TM_TZADJ, 1, [Should we use the tm_tzadj field of struct tm?])
    fi

    AC_CACHE_CHECK([tm_gmtoff in struct tm], tcl_cv_member_tm_gmtoff, [
	AC_TRY_COMPILE([#include <time.h>], [struct tm tm; tm.tm_gmtoff;],
	    tcl_cv_member_tm_gmtoff=yes, tcl_cv_member_tm_gmtoff=no)])
    if test $tcl_cv_member_tm_gmtoff = yes ; then
	AC_DEFINE(HAVE_TM_GMTOFF, 1, [Should we use the tm_gmtoff field of struct tm?])
    fi

    #
    # Its important to include time.h in this check, as some systems
    # (like convex) have timezone functions, etc.
    #
    AC_CACHE_CHECK([long timezone variable], tcl_cv_timezone_long, [
	AC_TRY_COMPILE([#include <time.h>],
	    [extern long timezone;
	    timezone += 1;
	    exit (0);],
	    tcl_cv_timezone_long=yes, tcl_cv_timezone_long=no)])
    if test $tcl_cv_timezone_long = yes ; then
	AC_DEFINE(HAVE_TIMEZONE_VAR, 1, [Should we use the global timezone variable?])
    else
	#
	# On some systems (eg IRIX 6.2), timezone is a time_t and not a long.
	#
	AC_CACHE_CHECK([time_t timezone variable], tcl_cv_timezone_time, [
	    AC_TRY_COMPILE([#include <time.h>],
		[extern time_t timezone;
		timezone += 1;
		exit (0);],
		tcl_cv_timezone_time=yes, tcl_cv_timezone_time=no)])
	if test $tcl_cv_timezone_time = yes ; then
	    AC_DEFINE(HAVE_TIMEZONE_VAR, 1, [Should we use the global timezone variable?])
	fi
    fi
])

#--------------------------------------------------------------------
# TEA_BUGGY_STRTOD
#
#	Under Solaris 2.4, strtod returns the wrong value for the
#	terminating character under some conditions.  Check for this
#	and if the problem exists use a substitute procedure
#	"fixstrtod" (provided by Tcl) that corrects the error.
#	Also, on Compaq's Tru64 Unix 5.0,
#	strtod(" ") returns 0.0 instead of a failure to convert.
#
# Arguments:
#	none
#
# Results:
#
#	Might defines some of the following vars:
#		strtod (=fixstrtod)
#--------------------------------------------------------------------

AC_DEFUN([TEA_BUGGY_STRTOD], [
    AC_CHECK_FUNC(strtod, tcl_strtod=1, tcl_strtod=0)
    if test "$tcl_strtod" = 1; then
	AC_CACHE_CHECK([for Solaris2.4/Tru64 strtod bugs], tcl_cv_strtod_buggy,[
	    AC_TRY_RUN([
		extern double strtod();
		int main() {
		    char *infString="Inf", *nanString="NaN", *spaceString=" ";
		    char *term;
		    double value;
		    value = strtod(infString, &term);
		    if ((term != infString) && (term[-1] == 0)) {
			exit(1);
		    }
		    value = strtod(nanString, &term);
		    if ((term != nanString) && (term[-1] == 0)) {
			exit(1);
		    }
		    value = strtod(spaceString, &term);
		    if (term == (spaceString+1)) {
			exit(1);
		    }
		    exit(0);
		}], tcl_cv_strtod_buggy=ok, tcl_cv_strtod_buggy=buggy,
		    tcl_cv_strtod_buggy=buggy)])
	if test "$tcl_cv_strtod_buggy" = buggy; then
	    AC_LIBOBJ([fixstrtod])
	    USE_COMPAT=1
	    AC_DEFINE(strtod, fixstrtod, [Do we want to use the strtod() in compat?])
	fi
    fi
])

#--------------------------------------------------------------------
# TEA_TCL_LINK_LIBS
#
#	Search for the libraries needed to link the Tcl shell.
#	Things like the math library (-lm) and socket stuff (-lsocket vs.
#	-lnsl) are dealt with here.
#
# Arguments:
#	Requires the following vars to be set in the Makefile:
#		DL_LIBS (not in TEA, only needed in core)
#		LIBS
#		MATH_LIBS
#
# Results:
#
#	Substitutes the following vars:
#		TCL_LIBS
#		MATH_LIBS
#
#	Might append to the following vars:
#		LIBS
#
#	Might define the following vars:
#		HAVE_NET_ERRNO_H
#--------------------------------------------------------------------

AC_DEFUN([TEA_TCL_LINK_LIBS], [
    #--------------------------------------------------------------------
    # On a few very rare systems, all of the libm.a stuff is
    # already in libc.a.  Set compiler flags accordingly.
    # Also, Linux requires the "ieee" library for math to work
    # right (and it must appear before "-lm").
    #--------------------------------------------------------------------

    AC_CHECK_FUNC(sin, MATH_LIBS="", MATH_LIBS="-lm")
    AC_CHECK_LIB(ieee, main, [MATH_LIBS="-lieee $MATH_LIBS"])

    #--------------------------------------------------------------------
    # Interactive UNIX requires -linet instead of -lsocket, plus it
    # needs net/errno.h to define the socket-related error codes.
    #--------------------------------------------------------------------

    AC_CHECK_LIB(inet, main, [LIBS="$LIBS -linet"])
    AC_CHECK_HEADER(net/errno.h, [
	AC_DEFINE(HAVE_NET_ERRNO_H, 1, [Do we have <net/errno.h>?])])

    #--------------------------------------------------------------------
    #	Check for the existence of the -lsocket and -lnsl libraries.
    #	The order here is important, so that they end up in the right
    #	order in the command line generated by make.  Here are some
    #	special considerations:
    #	1. Use "connect" and "accept" to check for -lsocket, and
    #	   "gethostbyname" to check for -lnsl.
    #	2. Use each function name only once:  can't redo a check because
    #	   autoconf caches the results of the last check and won't redo it.
    #	3. Use -lnsl and -lsocket only if they supply procedures that
    #	   aren't already present in the normal libraries.  This is because
    #	   IRIX 5.2 has libraries, but they aren't needed and they're
    #	   bogus:  they goof up name resolution if used.
    #	4. On some SVR4 systems, can't use -lsocket without -lnsl too.
    #	   To get around this problem, check for both libraries together
    #	   if -lsocket doesn't work by itself.
    #--------------------------------------------------------------------

    tcl_checkBoth=0
    AC_CHECK_FUNC(connect, tcl_checkSocket=0, tcl_checkSocket=1)
    if test "$tcl_checkSocket" = 1; then
	AC_CHECK_FUNC(setsockopt, , [AC_CHECK_LIB(socket, setsockopt,
	    LIBS="$LIBS -lsocket", tcl_checkBoth=1)])
    fi
    if test "$tcl_checkBoth" = 1; then
	tk_oldLibs=$LIBS
	LIBS="$LIBS -lsocket -lnsl"
	AC_CHECK_FUNC(accept, tcl_checkNsl=0, [LIBS=$tk_oldLibs])
    fi
    AC_CHECK_FUNC(gethostbyname, , [AC_CHECK_LIB(nsl, gethostbyname,
	    [LIBS="$LIBS -lnsl"])])

    # TEA specific: Don't perform the eval of the libraries here because
    # DL_LIBS won't be set until we call TEA_CONFIG_CFLAGS

    TCL_LIBS='${DL_LIBS} ${LIBS} ${MATH_LIBS}'
    AC_SUBST(TCL_LIBS)
    AC_SUBST(MATH_LIBS)
])

#--------------------------------------------------------------------
# TEA_TCL_EARLY_FLAGS
#
#	Check for what flags are needed to be passed so the correct OS
#	features are available.
#
# Arguments:
#	None
#
# Results:
#
#	Might define the following vars:
#		_ISOC99_SOURCE
#		_LARGEFILE64_SOURCE
#		_LARGEFILE_SOURCE64
#--------------------------------------------------------------------

AC_DEFUN([TEA_TCL_EARLY_FLAG],[
    AC_CACHE_VAL([tcl_cv_flag_]translit($1,[A-Z],[a-z]),
	AC_TRY_COMPILE([$2], $3, [tcl_cv_flag_]translit($1,[A-Z],[a-z])=no,
	    AC_TRY_COMPILE([[#define ]$1[ 1
]$2], $3,
		[tcl_cv_flag_]translit($1,[A-Z],[a-z])=yes,
		[tcl_cv_flag_]translit($1,[A-Z],[a-z])=no)))
    if test ["x${tcl_cv_flag_]translit($1,[A-Z],[a-z])[}" = "xyes"] ; then
	AC_DEFINE($1, 1, [Add the ]$1[ flag when building])
	tcl_flags="$tcl_flags $1"
    fi
])

AC_DEFUN([TEA_TCL_EARLY_FLAGS],[
    AC_MSG_CHECKING([for required early compiler flags])
    tcl_flags=""
    TEA_TCL_EARLY_FLAG(_ISOC99_SOURCE,[#include <stdlib.h>],
	[char *p = (char *)strtoll; char *q = (char *)strtoull;])
    TEA_TCL_EARLY_FLAG(_LARGEFILE64_SOURCE,[#include <sys/stat.h>],
	[struct stat64 buf; int i = stat64("/", &buf);])
    TEA_TCL_EARLY_FLAG(_LARGEFILE_SOURCE64,[#include <sys/stat.h>],
	[char *p = (char *)open64;])
    if test "x${tcl_flags}" = "x" ; then
	AC_MSG_RESULT([none])
    else
	AC_MSG_RESULT([${tcl_flags}])
    fi
])

#--------------------------------------------------------------------
# TEA_TCL_64BIT_FLAGS
#
#	Check for what is defined in the way of 64-bit features.
#
# Arguments:
#	None
#
# Results:
#
#	Might define the following vars:
#		TCL_WIDE_INT_IS_LONG
#		TCL_WIDE_INT_TYPE
#		HAVE_STRUCT_DIRENT64
#		HAVE_STRUCT_STAT64
#		HAVE_TYPE_OFF64_T
#--------------------------------------------------------------------

AC_DEFUN([TEA_TCL_64BIT_FLAGS], [
    AC_MSG_CHECKING([for 64-bit integer type])
    AC_CACHE_VAL(tcl_cv_type_64bit,[
	tcl_cv_type_64bit=none
	# See if the compiler knows natively about __int64
	AC_TRY_COMPILE(,[__int64 value = (__int64) 0;],
	    tcl_type_64bit=__int64, tcl_type_64bit="long long")
	# See if we should use long anyway  Note that we substitute in the
	# type that is our current guess for a 64-bit type inside this check
	# program, so it should be modified only carefully...
        AC_TRY_COMPILE(,[switch (0) {
            case 1: case (sizeof(]${tcl_type_64bit}[)==sizeof(long)): ;
        }],tcl_cv_type_64bit=${tcl_type_64bit})])
    if test "${tcl_cv_type_64bit}" = none ; then
	AC_DEFINE(TCL_WIDE_INT_IS_LONG, 1, [Are wide integers to be implemented with C 'long's?])
	AC_MSG_RESULT([using long])
    elif test "${tcl_cv_type_64bit}" = "__int64" \
		-a "${TEA_PLATFORM}" = "windows" ; then
	# TEA specific: We actually want to use the default tcl.h checks in
	# this case to handle both TCL_WIDE_INT_TYPE and TCL_LL_MODIFIER*
	AC_MSG_RESULT([using Tcl header defaults])
    else
	AC_DEFINE_UNQUOTED(TCL_WIDE_INT_TYPE,${tcl_cv_type_64bit},
	    [What type should be used to define wide integers?])
	AC_MSG_RESULT([${tcl_cv_type_64bit}])

	# Now check for auxiliary declarations
	AC_CACHE_CHECK([for struct dirent64], tcl_cv_struct_dirent64,[
	    AC_TRY_COMPILE([#include <sys/types.h>
#include <dirent.h>],[struct dirent64 p;],
		tcl_cv_struct_dirent64=yes,tcl_cv_struct_dirent64=no)])
	if test "x${tcl_cv_struct_dirent64}" = "xyes" ; then
	    AC_DEFINE(HAVE_STRUCT_DIRENT64, 1, [Is 'struct dirent64' in <sys/types.h>?])
	fi

	AC_CACHE_CHECK([for struct stat64], tcl_cv_struct_stat64,[
	    AC_TRY_COMPILE([#include <sys/stat.h>],[struct stat64 p;
],
		tcl_cv_struct_stat64=yes,tcl_cv_struct_stat64=no)])
	if test "x${tcl_cv_struct_stat64}" = "xyes" ; then
	    AC_DEFINE(HAVE_STRUCT_STAT64, 1, [Is 'struct stat64' in <sys/stat.h>?])
	fi

	AC_CHECK_FUNCS(open64 lseek64)
	AC_MSG_CHECKING([for off64_t])
	AC_CACHE_VAL(tcl_cv_type_off64_t,[
	    AC_TRY_COMPILE([#include <sys/types.h>],[off64_t offset;
],
		tcl_cv_type_off64_t=yes,tcl_cv_type_off64_t=no)])
	dnl Define HAVE_TYPE_OFF64_T only when the off64_t type and the
	dnl functions lseek64 and open64 are defined.
	if test "x${tcl_cv_type_off64_t}" = "xyes" && \
	        test "x${ac_cv_func_lseek64}" = "xyes" && \
	        test "x${ac_cv_func_open64}" = "xyes" ; then
	    AC_DEFINE(HAVE_TYPE_OFF64_T, 1, [Is off64_t in <sys/types.h>?])
	    AC_MSG_RESULT([yes])
	else
	    AC_MSG_RESULT([no])
	fi
    fi
])

##
## Here ends the standard Tcl configuration bits and starts the
## TEA specific functions
##

#------------------------------------------------------------------------
# TEA_INIT --
#
#	Init various Tcl Extension Architecture (TEA) variables.
#	This should be the first called TEA_* macro.
#
# Arguments:
#	none
#
# Results:
#
#	Defines and substs the following vars:
#		CYGPATH
#		EXEEXT
#	Defines only:
#		TEA_VERSION
#		TEA_INITED
#		TEA_PLATFORM (windows or unix)
#
# "cygpath" is used on windows to generate native path names for include
# files. These variables should only be used with the compiler and linker
# since they generate native path names.
#
# EXEEXT
#	Select the executable extension based on the host type.  This
#	is a lightweight replacement for AC_EXEEXT that doesn't require
#	a compiler.
#------------------------------------------------------------------------

AC_DEFUN([TEA_INIT], [
    # TEA extensions pass this us the version of TEA they think they
    # are compatible with.
    TEA_VERSION="3.9"

    AC_MSG_CHECKING([for correct TEA configuration])
    if test x"${PACKAGE_NAME}" = x ; then
	AC_MSG_ERROR([
The PACKAGE_NAME variable must be defined by your TEA configure.in])
    fi
    if test x"$1" = x ; then
	AC_MSG_ERROR([
TEA version not specified.])
    elif test "$1" != "${TEA_VERSION}" ; then
	AC_MSG_RESULT([warning: requested TEA version "$1", have "${TEA_VERSION}"])
    else
	AC_MSG_RESULT([ok (TEA ${TEA_VERSION})])
    fi

    # If the user did not set CFLAGS, set it now to keep macros
    # like AC_PROG_CC and AC_TRY_COMPILE from adding "-g -O2".
    if test "${CFLAGS+set}" != "set" ; then
	CFLAGS=""
    fi

    case "`uname -s`" in
	*win32*|*WIN32*|*MINGW32_*)
	    AC_CHECK_PROG(CYGPATH, cygpath, cygpath -w, echo)
	    EXEEXT=".exe"
	    TEA_PLATFORM="windows"
	    ;;
	*CYGWIN_*)
	    CYGPATH=echo
	    EXEEXT=".exe"
	    # TEA_PLATFORM is determined later in LOAD_TCLCONFIG
	    ;;
	*)
	    CYGPATH=echo
	    # Maybe we are cross-compiling....
	    case ${host_alias} in
		*mingw32*)
		EXEEXT=".exe"
		TEA_PLATFORM="windows"
		;;
	    *)
		EXEEXT=""
		TEA_PLATFORM="unix"
		;;
	    esac
	    ;;
    esac

    # Check if exec_prefix is set. If not use fall back to prefix.
    # Note when adjusted, so that TEA_PREFIX can correct for this.
    # This is needed for recursive configures, since autoconf propagates
    # $prefix, but not $exec_prefix (doh!).
    if test x$exec_prefix = xNONE ; then
	exec_prefix_default=yes
	exec_prefix=$prefix
    fi

    AC_MSG_NOTICE([configuring ${PACKAGE_NAME} ${PACKAGE_VERSION}])

    AC_SUBST(EXEEXT)
    AC_SUBST(CYGPATH)

    # This package name must be replaced statically for AC_SUBST to work
    AC_SUBST(PKG_LIB_FILE)
    # Substitute STUB_LIB_FILE in case package creates a stub library too.
    AC_SUBST(PKG_STUB_LIB_FILE)

    # We AC_SUBST these here to ensure they are subst'ed,
    # in case the user doesn't call TEA_ADD_...
    AC_SUBST(PKG_STUB_SOURCES)
    AC_SUBST(PKG_STUB_OBJECTS)
    AC_SUBST(PKG_TCL_SOURCES)
    AC_SUBST(PKG_HEADERS)
    AC_SUBST(PKG_INCLUDES)
    AC_SUBST(PKG_LIBS)
    AC_SUBST(PKG_CFLAGS)
])

#------------------------------------------------------------------------
# TEA_ADD_SOURCES --
#
#	Specify one or more source files.  Users should check for
#	the right platform before adding to their list.
#	It is not important to specify the directory, as long as it is
#	in the generic, win or unix subdirectory of $(srcdir).
#
# Arguments:
#	one or more file names
#
# Results:
#
#	Defines and substs the following vars:
#		PKG_SOURCES
#		PKG_OBJECTS
#------------------------------------------------------------------------
AC_DEFUN([TEA_ADD_SOURCES], [
    vars="$@"
    for i in $vars; do
	case $i in
	    [\$]*)
		# allow $-var names
		PKG_SOURCES="$PKG_SOURCES $i"
		PKG_OBJECTS="$PKG_OBJECTS $i"
		;;
	    *)
		# check for existence - allows for generic/win/unix VPATH
		# To add more dirs here (like 'src'), you have to update VPATH
		# in Makefile.in as well
		if test ! -f "${srcdir}/$i" -a ! -f "${srcdir}/generic/$i" \
		    -a ! -f "${srcdir}/win/$i" -a ! -f "${srcdir}/unix/$i" \
		    -a ! -f "${srcdir}/macosx/$i" -a ! -f "${srcdir}/sdl/$i" \
		    ; then
		    AC_MSG_ERROR([could not find source file '$i'])
		fi
		PKG_SOURCES="$PKG_SOURCES $i"
		# this assumes it is in a VPATH dir
		i=`basename $i`
		# handle user calling this before or after TEA_SETUP_COMPILER
		if test x"${OBJEXT}" != x ; then
		    j="`echo $i | sed -e 's/\.[[^.]]*$//'`.${OBJEXT}"
		else
		    j="`echo $i | sed -e 's/\.[[^.]]*$//'`.\${OBJEXT}"
		fi
		PKG_OBJECTS="$PKG_OBJECTS $j"
		;;
	esac
    done
    AC_SUBST(PKG_SOURCES)
    AC_SUBST(PKG_OBJECTS)
])

#------------------------------------------------------------------------
# TEA_ADD_STUB_SOURCES --
#
#	Specify one or more source files.  Users should check for
#	the right platform before adding to their list.
#	It is not important to specify the directory, as long as it is
#	in the generic, win or unix subdirectory of $(srcdir).
#
# Arguments:
#	one or more file names
#
# Results:
#
#	Defines and substs the following vars:
#		PKG_STUB_SOURCES
#		PKG_STUB_OBJECTS
#------------------------------------------------------------------------
AC_DEFUN([TEA_ADD_STUB_SOURCES], [
    vars="$@"
    for i in $vars; do
	# check for existence - allows for generic/win/unix VPATH
	if test ! -f "${srcdir}/$i" -a ! -f "${srcdir}/generic/$i" \
	    -a ! -f "${srcdir}/win/$i" -a ! -f "${srcdir}/unix/$i" \
	    -a ! -f "${srcdir}/macosx/$i" -a ! -f "${srcdir}/sdl/$i" \
	    ; then
	    AC_MSG_ERROR([could not find stub source file '$i'])
	fi
	PKG_STUB_SOURCES="$PKG_STUB_SOURCES $i"
	# this assumes it is in a VPATH dir
	i=`basename $i`
	# handle user calling this before or after TEA_SETUP_COMPILER
	if test x"${OBJEXT}" != x ; then
	    j="`echo $i | sed -e 's/\.[[^.]]*$//'`.${OBJEXT}"
	else
	    j="`echo $i | sed -e 's/\.[[^.]]*$//'`.\${OBJEXT}"
	fi
	PKG_STUB_OBJECTS="$PKG_STUB_OBJECTS $j"
    done
    AC_SUBST(PKG_STUB_SOURCES)
    AC_SUBST(PKG_STUB_OBJECTS)
])

#------------------------------------------------------------------------
# TEA_ADD_TCL_SOURCES --
#
#	Specify one or more Tcl source files.  These should be platform
#	independent runtime files.
#
# Arguments:
#	one or more file names
#
# Results:
#
#	Defines and substs the following vars:
#		PKG_TCL_SOURCES
#------------------------------------------------------------------------
AC_DEFUN([TEA_ADD_TCL_SOURCES], [
    vars="$@"
    for i in $vars; do
	# check for existence, be strict because it is installed
	if test ! -f "${srcdir}/$i" ; then
	    AC_MSG_ERROR([could not find tcl source file '${srcdir}/$i'])
	fi
	PKG_TCL_SOURCES="$PKG_TCL_SOURCES $i"
    done
    AC_SUBST(PKG_TCL_SOURCES)
])

#------------------------------------------------------------------------
# TEA_ADD_HEADERS --
#
#	Specify one or more source headers.  Users should check for
#	the right platform before adding to their list.
#
# Arguments:
#	one or more file names
#
# Results:
#
#	Defines and substs the following vars:
#		PKG_HEADERS
#------------------------------------------------------------------------
AC_DEFUN([TEA_ADD_HEADERS], [
    vars="$@"
    for i in $vars; do
	# check for existence, be strict because it is installed
	if test ! -f "${srcdir}/$i" ; then
	    AC_MSG_ERROR([could not find header file '${srcdir}/$i'])
	fi
	PKG_HEADERS="$PKG_HEADERS $i"
    done
    AC_SUBST(PKG_HEADERS)
])

#------------------------------------------------------------------------
# TEA_ADD_INCLUDES --
#
#	Specify one or more include dirs.  Users should check for
#	the right platform before adding to their list.
#
# Arguments:
#	one or more file names
#
# Results:
#
#	Defines and substs the following vars:
#		PKG_INCLUDES
#------------------------------------------------------------------------
AC_DEFUN([TEA_ADD_INCLUDES], [
    vars="$@"
    for i in $vars; do
	PKG_INCLUDES="$PKG_INCLUDES $i"
    done
    AC_SUBST(PKG_INCLUDES)
])

#------------------------------------------------------------------------
# TEA_ADD_LIBS --
#
#	Specify one or more libraries.  Users should check for
#	the right platform before adding to their list.  For Windows,
#	libraries provided in "foo.lib" format will be converted to
#	"-lfoo" when using GCC (mingw).
#
# Arguments:
#	one or more file names
#
# Results:
#
#	Defines and substs the following vars:
#		PKG_LIBS
#------------------------------------------------------------------------
AC_DEFUN([TEA_ADD_LIBS], [
    vars="$@"
    for i in $vars; do
	if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
	    # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
	    i=`echo "$i" | sed -e 's/^\([[^-]].*\)\.lib[$]/-l\1/i'`
	fi
	PKG_LIBS="$PKG_LIBS $i"
    done
    AC_SUBST(PKG_LIBS)
])

#------------------------------------------------------------------------
# TEA_ADD_CFLAGS --
#
#	Specify one or more CFLAGS.  Users should check for
#	the right platform before adding to their list.
#
# Arguments:
#	one or more file names
#
# Results:
#
#	Defines and substs the following vars:
#		PKG_CFLAGS
#------------------------------------------------------------------------
AC_DEFUN([TEA_ADD_CFLAGS], [
    PKG_CFLAGS="$PKG_CFLAGS $@"
    AC_SUBST(PKG_CFLAGS)
])

#------------------------------------------------------------------------
# TEA_ADD_CLEANFILES --
#
#	Specify one or more CLEANFILES.
#
# Arguments:
#	one or more file names to clean target
#
# Results:
#
#	Appends to CLEANFILES, already defined for subst in LOAD_TCLCONFIG
#------------------------------------------------------------------------
AC_DEFUN([TEA_ADD_CLEANFILES], [
    CLEANFILES="$CLEANFILES $@"
])

#------------------------------------------------------------------------
# TEA_PREFIX --
#
#	Handle the --prefix=... option by defaulting to what Tcl gave
#
# Arguments:
#	none
#
# Results:
#
#	If --prefix or --exec-prefix was not specified, $prefix and
#	$exec_prefix will be set to the values given to Tcl when it was
#	configured.
#------------------------------------------------------------------------
AC_DEFUN([TEA_PREFIX], [
    if test "${prefix}" = "NONE"; then
	prefix_default=yes
	if test x"${TCL_PREFIX}" != x; then
	    AC_MSG_NOTICE([--prefix defaulting to TCL_PREFIX ${TCL_PREFIX}])
	    prefix=${TCL_PREFIX}
	else
	    AC_MSG_NOTICE([--prefix defaulting to /usr/local])
	    prefix=/usr/local
	fi
    fi
    if test "${exec_prefix}" = "NONE" -a x"${prefix_default}" = x"yes" \
	-o x"${exec_prefix_default}" = x"yes" ; then
	if test x"${TCL_EXEC_PREFIX}" != x; then
	    AC_MSG_NOTICE([--exec-prefix defaulting to TCL_EXEC_PREFIX ${TCL_EXEC_PREFIX}])
	    exec_prefix=${TCL_EXEC_PREFIX}
	else
	    AC_MSG_NOTICE([--exec-prefix defaulting to ${prefix}])
	    exec_prefix=$prefix
	fi
    fi
])

#------------------------------------------------------------------------
# TEA_SETUP_COMPILER_CC --
#
#	Do compiler checks the way we want.  This is just a replacement
#	for AC_PROG_CC in TEA configure.in files to make them cleaner.
#
# Arguments:
#	none
#
# Results:
#
#	Sets up CC var and other standard bits we need to make executables.
#------------------------------------------------------------------------
AC_DEFUN([TEA_SETUP_COMPILER_CC], [
    # Don't put any macros that use the compiler (e.g. AC_TRY_COMPILE)
    # in this macro, they need to go into TEA_SETUP_COMPILER instead.

    AC_PROG_CC
    AC_PROG_CPP

    INSTALL="\$(SHELL) \$(srcdir)/tclconfig/install-sh -c"
    AC_SUBST(INSTALL)
    INSTALL_DATA="\${INSTALL} -m 644"
    AC_SUBST(INSTALL_DATA)
    INSTALL_PROGRAM="\${INSTALL}"
    AC_SUBST(INSTALL_PROGRAM)
    INSTALL_SCRIPT="\${INSTALL}"
    AC_SUBST(INSTALL_SCRIPT)

    #--------------------------------------------------------------------
    # Checks to see if the make program sets the $MAKE variable.
    #--------------------------------------------------------------------

    AC_PROG_MAKE_SET

    #--------------------------------------------------------------------
    # Find ranlib
    #--------------------------------------------------------------------

    AC_CHECK_TOOL(RANLIB, ranlib)

    #--------------------------------------------------------------------
    # Determines the correct binary file extension (.o, .obj, .exe etc.)
    #--------------------------------------------------------------------

    AC_OBJEXT
    AC_EXEEXT
])

#------------------------------------------------------------------------
# TEA_SETUP_COMPILER --
#
#	Do compiler checks that use the compiler.  This must go after
#	TEA_SETUP_COMPILER_CC, which does the actual compiler check.
#
# Arguments:
#	none
#
# Results:
#
#	Sets up CC var and other standard bits we need to make executables.
#------------------------------------------------------------------------
AC_DEFUN([TEA_SETUP_COMPILER], [
    # Any macros that use the compiler (e.g. AC_TRY_COMPILE) have to go here.
    AC_REQUIRE([TEA_SETUP_COMPILER_CC])

    #------------------------------------------------------------------------
    # If we're using GCC, see if the compiler understands -pipe. If so, use it.
    # It makes compiling go faster.  (This is only a performance feature.)
    #------------------------------------------------------------------------

    if test -z "$no_pipe" -a -n "$GCC"; then
	AC_CACHE_CHECK([if the compiler understands -pipe],
	    tcl_cv_cc_pipe, [
	    hold_cflags=$CFLAGS; CFLAGS="$CFLAGS -pipe"
	    AC_TRY_COMPILE(,, tcl_cv_cc_pipe=yes, tcl_cv_cc_pipe=no)
	    CFLAGS=$hold_cflags])
	if test $tcl_cv_cc_pipe = yes; then
	    CFLAGS="$CFLAGS -pipe"
	fi
    fi

    #--------------------------------------------------------------------
    # Common compiler flag setup
    #--------------------------------------------------------------------

    AC_C_BIGENDIAN
    if test "${TEA_PLATFORM}" = "unix" ; then
	TEA_TCL_LINK_LIBS
	TEA_MISSING_POSIX_HEADERS
	# Let the user call this, because if it triggers, they will
	# need a compat/strtod.c that is correct.  Users can also
	# use Tcl_GetDouble(FromObj) instead.
	#TEA_BUGGY_STRTOD
    fi
])

#------------------------------------------------------------------------
# TEA_MAKE_LIB --
#
#	Generate a line that can be used to build a shared/unshared library
#	in a platform independent manner.
#
# Arguments:
#	none
#
#	Requires:
#
# Results:
#
#	Defines the following vars:
#	CFLAGS -	Done late here to note disturb other AC macros
#       MAKE_LIB -      Command to execute to build the Tcl library;
#                       differs depending on whether or not Tcl is being
#                       compiled as a shared library.
#	MAKE_SHARED_LIB	Makefile rule for building a shared library
#	MAKE_STATIC_LIB	Makefile rule for building a static library
#	MAKE_STUB_LIB	Makefile rule for building a stub library
#	VC_MANIFEST_EMBED_DLL Makefile rule for embedded VC manifest in DLL
#	VC_MANIFEST_EMBED_EXE Makefile rule for embedded VC manifest in EXE
#------------------------------------------------------------------------

AC_DEFUN([TEA_MAKE_LIB], [
    if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes"; then
	MAKE_STATIC_LIB="\${STLIB_LD} -out:\[$]@ \$(PKG_OBJECTS)"
	MAKE_SHARED_LIB="\${SHLIB_LD} \${SHLIB_LD_LIBS} \${LDFLAGS_DEFAULT} -out:\[$]@ \$(PKG_OBJECTS)"
	AC_EGREP_CPP([manifest needed], [
#if defined(_MSC_VER) && _MSC_VER >= 1400
print("manifest needed")
#endif
	], [
	# Could do a CHECK_PROG for mt, but should always be with MSVC8+
	VC_MANIFEST_EMBED_DLL="if test -f \[$]@.manifest ; then mt.exe -nologo -manifest \[$]@.manifest -outputresource:\[$]@\;2 ; fi"
	VC_MANIFEST_EMBED_EXE="if test -f \[$]@.manifest ; then mt.exe -nologo -manifest \[$]@.manifest -outputresource:\[$]@\;1 ; fi"
	MAKE_SHARED_LIB="${MAKE_SHARED_LIB} ; ${VC_MANIFEST_EMBED_DLL}"

	# Don't clean .manifest provided by the package (see TEA_ADD_MANIFEST)
	# or one created by Makefile or configure.  Could use the /manifest:filename
	# linker option to explicitly set the linker-generated filename.
	eval eval "manifest=${PACKAGE_NAME}${SHARED_LIB_SUFFIX}.manifest"
	TEA_ADD_CLEANFILES([$manifest])
	])
	MAKE_STUB_LIB="\${STLIB_LD} -nodefaultlib -out:\[$]@ \$(PKG_STUB_OBJECTS)"
    else
	MAKE_STATIC_LIB="\${STLIB_LD} \[$]@ \$(PKG_OBJECTS)"
	MAKE_SHARED_LIB="\${SHLIB_LD} -o \[$]@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
	MAKE_STUB_LIB="\${STLIB_LD} \[$]@ \$(PKG_STUB_OBJECTS)"
    fi

    if test "${SHARED_BUILD}" = "1" ; then
	MAKE_LIB="${MAKE_SHARED_LIB} "
    else
	MAKE_LIB="${MAKE_STATIC_LIB} "
    fi

    #--------------------------------------------------------------------
    # Shared libraries and static libraries have different names.
    # Use the double eval to make sure any variables in the suffix is
    # substituted. (@@@ Might not be necessary anymore)
    #--------------------------------------------------------------------

    if test "${TEA_PLATFORM}" = "windows" ; then
	if test "${SHARED_BUILD}" = "1" ; then
	    # We force the unresolved linking of symbols that are really in
	    # the private libraries of Tcl and Tk.
	    if test x"${TK_BIN_DIR}" != x ; then
		SHLIB_LD_LIBS="${SHLIB_LD_LIBS} \"`${CYGPATH} ${TK_BIN_DIR}/${TK_STUB_LIB_FILE}`\""
	    fi
	    SHLIB_LD_LIBS="${SHLIB_LD_LIBS} \"`${CYGPATH} ${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}`\""
	    if test "$GCC" = "yes"; then
		SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -static-libgcc"
	    fi
	    eval eval "PKG_LIB_FILE=${PACKAGE_NAME}${SHARED_LIB_SUFFIX}"
	else
	    eval eval "PKG_LIB_FILE=${PACKAGE_NAME}${UNSHARED_LIB_SUFFIX}"
	    if test "$GCC" = "yes"; then
		PKG_LIB_FILE=lib${PKG_LIB_FILE}
	    fi
	fi
	# Some packages build their own stubs libraries
	eval eval "PKG_STUB_LIB_FILE=${PACKAGE_NAME}stub${UNSHARED_LIB_SUFFIX}"
	if test "$GCC" = "yes"; then
	    PKG_STUB_LIB_FILE=lib${PKG_STUB_LIB_FILE}
	fi
	# These aren't needed on Windows (either MSVC or gcc)
	RANLIB=:
	RANLIB_STUB=:
    else
	RANLIB_STUB="${RANLIB}"
	if test "${SHARED_BUILD}" = "1" ; then
	    SHLIB_LD_LIBS="${SHLIB_LD_LIBS} ${TCL_STUB_LIB_SPEC}"
	    if test x"${TK_BIN_DIR}" != x ; then
		SHLIB_LD_LIBS="${SHLIB_LD_LIBS} ${TK_STUB_LIB_SPEC}"
	    fi
	    eval eval "PKG_LIB_FILE=lib${PACKAGE_NAME}${SHARED_LIB_SUFFIX}"
	    RANLIB=:
	else
	    eval eval "PKG_LIB_FILE=lib${PACKAGE_NAME}${UNSHARED_LIB_SUFFIX}"
	fi
	# Some packages build their own stubs libraries
	eval eval "PKG_STUB_LIB_FILE=lib${PACKAGE_NAME}stub${UNSHARED_LIB_SUFFIX}"
    fi

    # These are escaped so that only CFLAGS is picked up at configure time.
    # The other values will be substituted at make time.
    CFLAGS="${CFLAGS} \${CFLAGS_DEFAULT} \${CFLAGS_WARNING}"
    if test "${SHARED_BUILD}" = "1" ; then
	CFLAGS="${CFLAGS} \${SHLIB_CFLAGS}"
    fi

    AC_SUBST(MAKE_LIB)
    AC_SUBST(MAKE_SHARED_LIB)
    AC_SUBST(MAKE_STATIC_LIB)
    AC_SUBST(MAKE_STUB_LIB)
    AC_SUBST(RANLIB_STUB)
    AC_SUBST(VC_MANIFEST_EMBED_DLL)
    AC_SUBST(VC_MANIFEST_EMBED_EXE)
])

#------------------------------------------------------------------------
# TEA_LIB_SPEC --
#
#	Compute the name of an existing object library located in libdir
#	from the given base name and produce the appropriate linker flags.
#
# Arguments:
#	basename	The base name of the library without version
#			numbers, extensions, or "lib" prefixes.
#	extra_dir	Extra directory in which to search for the
#			library.  This location is used first, then
#			$prefix/$exec-prefix, then some defaults.
#
# Requires:
#	TEA_INIT and TEA_PREFIX must be called first.
#
# Results:
#
#	Defines the following vars:
#		${basename}_LIB_NAME	The computed library name.
#		${basename}_LIB_SPEC	The computed linker flags.
#------------------------------------------------------------------------

AC_DEFUN([TEA_LIB_SPEC], [
    AC_MSG_CHECKING([for $1 library])

    # Look in exec-prefix for the library (defined by TEA_PREFIX).

    tea_lib_name_dir="${exec_prefix}/lib"

    # Or in a user-specified location.

    if test x"$2" != x ; then
	tea_extra_lib_dir=$2
    else
	tea_extra_lib_dir=NONE
    fi

    for i in \
	    `ls -dr ${tea_extra_lib_dir}/$1[[0-9]]*.lib 2>/dev/null ` \
	    `ls -dr ${tea_extra_lib_dir}/lib$1[[0-9]]* 2>/dev/null ` \
	    `ls -dr ${tea_lib_name_dir}/$1[[0-9]]*.lib 2>/dev/null ` \
	    `ls -dr ${tea_lib_name_dir}/lib$1[[0-9]]* 2>/dev/null ` \
	    `ls -dr /usr/lib/$1[[0-9]]*.lib 2>/dev/null ` \
	    `ls -dr /usr/lib/lib$1[[0-9]]* 2>/dev/null ` \
	    `ls -dr /usr/lib64/$1[[0-9]]*.lib 2>/dev/null ` \
	    `ls -dr /usr/lib64/lib$1[[0-9]]* 2>/dev/null ` \
	    `ls -dr /usr/local/lib/$1[[0-9]]*.lib 2>/dev/null ` \
	    `ls -dr /usr/local/lib/lib$1[[0-9]]* 2>/dev/null ` ; do
	if test -f "$i" ; then
	    tea_lib_name_dir=`dirname $i`
	    $1_LIB_NAME=`basename $i`
	    $1_LIB_PATH_NAME=$i
	    break
	fi
    done

    if test "${TEA_PLATFORM}" = "windows"; then
	$1_LIB_SPEC=\"`${CYGPATH} ${$1_LIB_PATH_NAME} 2>/dev/null`\"
    else
	# Strip off the leading "lib" and trailing ".a" or ".so"

	tea_lib_name_lib=`echo ${$1_LIB_NAME}|sed -e 's/^lib//' -e 's/\.[[^.]]*$//' -e 's/\.so.*//'`
	$1_LIB_SPEC="-L${tea_lib_name_dir} -l${tea_lib_name_lib}"
    fi

    if test "x${$1_LIB_NAME}" = x ; then
	AC_MSG_ERROR([not found])
    else
	AC_MSG_RESULT([${$1_LIB_SPEC}])
    fi
])

#------------------------------------------------------------------------
# TEA_PRIVATE_TCL_HEADERS --
#
#	Locate the private Tcl include files
#
# Arguments:
#
#	Requires:
#		TCL_SRC_DIR	Assumes that TEA_LOAD_TCLCONFIG has
#				already been called.
#
# Results:
#
#	Substitutes the following vars:
#		TCL_TOP_DIR_NATIVE
#		TCL_INCLUDES
#------------------------------------------------------------------------

AC_DEFUN([TEA_PRIVATE_TCL_HEADERS], [
    # Allow for --with-tclinclude to take effect and define ${ac_cv_c_tclh}
    AC_REQUIRE([TEA_PUBLIC_TCL_HEADERS])
    AC_MSG_CHECKING([for Tcl private include files])

    TCL_SRC_DIR_NATIVE=`${CYGPATH} ${TCL_SRC_DIR}`
    TCL_TOP_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}\"

    # Check to see if tcl<Plat>Port.h isn't already with the public headers
    # Don't look for tclInt.h because that resides with tcl.h in the core
    # sources, but the <plat>Port headers are in a different directory
    if test "${TEA_PLATFORM}" = "windows" -a \
	-f "${ac_cv_c_tclh}/tclWinPort.h"; then
	result="private headers found with public headers"
    elif test "${TEA_PLATFORM}" = "unix" -a \
	-f "${ac_cv_c_tclh}/tclUnixPort.h"; then
	result="private headers found with public headers"
    else
	TCL_GENERIC_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}/generic\"
	if test "${TEA_PLATFORM}" = "windows"; then
	    TCL_PLATFORM_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}/win\"
	else
	    TCL_PLATFORM_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}/unix\"
	fi
	# Overwrite the previous TCL_INCLUDES as this should capture both
	# public and private headers in the same set.
	# We want to ensure these are substituted so as not to require
	# any *_NATIVE vars be defined in the Makefile
	TCL_INCLUDES="-I${TCL_GENERIC_DIR_NATIVE} -I${TCL_PLATFORM_DIR_NATIVE}"
	if test "`uname -s`" = "Darwin"; then
            # If Tcl was built as a framework, attempt to use
            # the framework's Headers and PrivateHeaders directories
            case ${TCL_DEFS} in
	    	*TCL_FRAMEWORK*)
		    if test -d "${TCL_BIN_DIR}/Headers" -a \
			    -d "${TCL_BIN_DIR}/PrivateHeaders"; then
			TCL_INCLUDES="-I\"${TCL_BIN_DIR}/Headers\" -I\"${TCL_BIN_DIR}/PrivateHeaders\" ${TCL_INCLUDES}"
		    else
			TCL_INCLUDES="${TCL_INCLUDES} ${TCL_INCLUDE_SPEC} `echo "${TCL_INCLUDE_SPEC}" | sed -e 's/Headers/PrivateHeaders/'`"
		    fi
	            ;;
	    esac
	    result="Using ${TCL_INCLUDES}"
	else
	    if test ! -f "${TCL_SRC_DIR}/generic/tclInt.h" ; then
		AC_MSG_ERROR([Cannot find private header tclInt.h in ${TCL_SRC_DIR}])
	    fi
	    result="Using srcdir found in tclConfig.sh: ${TCL_SRC_DIR}"
	fi
    fi

    AC_SUBST(TCL_TOP_DIR_NATIVE)

    AC_SUBST(TCL_INCLUDES)
    AC_MSG_RESULT([${result}])
])

#------------------------------------------------------------------------
# TEA_PUBLIC_TCL_HEADERS --
#
#	Locate the installed public Tcl header files
#
# Arguments:
#	None.
#
# Requires:
#	CYGPATH must be set
#
# Results:
#
#	Adds a --with-tclinclude switch to configure.
#	Result is cached.
#
#	Substitutes the following vars:
#		TCL_INCLUDES
#------------------------------------------------------------------------

AC_DEFUN([TEA_PUBLIC_TCL_HEADERS], [
    AC_MSG_CHECKING([for Tcl public headers])

    AC_ARG_WITH(tclinclude, [  --with-tclinclude       directory containing the public Tcl header files], with_tclinclude=${withval})

    AC_CACHE_VAL(ac_cv_c_tclh, [
	# Use the value from --with-tclinclude, if it was given

	if test x"${with_tclinclude}" != x ; then
	    if test -f "${with_tclinclude}/tcl.h" ; then
		ac_cv_c_tclh=${with_tclinclude}
	    else
		AC_MSG_ERROR([${with_tclinclude} directory does not contain tcl.h])
	    fi
	else
	    list=""
	    if test "`uname -s`" = "Darwin"; then
		# If Tcl was built as a framework, attempt to use
		# the framework's Headers directory
		case ${TCL_DEFS} in
		    *TCL_FRAMEWORK*)
			list="`ls -d ${TCL_BIN_DIR}/Headers 2>/dev/null`"
			;;
		esac
	    fi

	    # Look in the source dir only if Tcl is not installed,
	    # and in that situation, look there before installed locations.
	    if test -f "${TCL_BIN_DIR}/Makefile" ; then
		list="$list `ls -d ${TCL_SRC_DIR}/generic 2>/dev/null`"
	    fi

	    # Check order: pkg --prefix location, Tcl's --prefix location,
	    # relative to directory of tclConfig.sh.

	    eval "temp_includedir=${includedir}"
	    list="$list \
		`ls -d ${temp_includedir}        2>/dev/null` \
		`ls -d ${TCL_PREFIX}/include     2>/dev/null` \
		`ls -d ${TCL_BIN_DIR}/../include 2>/dev/null`"
	    if test "${TEA_PLATFORM}" != "windows" -o "$GCC" = "yes"; then
		list="$list /usr/local/include /usr/include"
		if test x"${TCL_INCLUDE_SPEC}" != x ; then
		    d=`echo "${TCL_INCLUDE_SPEC}" | sed -e 's/^-I//'`
		    list="$list `ls -d ${d} 2>/dev/null`"
		fi
	    fi
	    for i in $list ; do
		if test -f "$i/tcl.h" ; then
		    ac_cv_c_tclh=$i
		    break
		fi
	    done
	fi
    ])

    # Print a message based on how we determined the include path

    if test x"${ac_cv_c_tclh}" = x ; then
	AC_MSG_ERROR([tcl.h not found.  Please specify its location with --with-tclinclude])
    else
	AC_MSG_RESULT([${ac_cv_c_tclh}])
    fi

    # Convert to a native path and substitute into the output files.

    INCLUDE_DIR_NATIVE=`${CYGPATH} ${ac_cv_c_tclh}`

    TCL_INCLUDES=-I\"${INCLUDE_DIR_NATIVE}\"

    AC_SUBST(TCL_INCLUDES)
])

#------------------------------------------------------------------------
# TEA_PRIVATE_TK_HEADERS --
#
#	Locate the private Tk include files
#
# Arguments:
#
#	Requires:
#		TK_SRC_DIR	Assumes that TEA_LOAD_TKCONFIG has
#				 already been called.
#
# Results:
#
#	Substitutes the following vars:
#		TK_INCLUDES
#------------------------------------------------------------------------

AC_DEFUN([TEA_PRIVATE_TK_HEADERS], [
    # Allow for --with-tkinclude to take effect and define ${ac_cv_c_tkh}
    AC_REQUIRE([TEA_PUBLIC_TK_HEADERS])
    AC_MSG_CHECKING([for Tk private include files])

    TK_SRC_DIR_NATIVE=`${CYGPATH} ${TK_SRC_DIR}`
    TK_TOP_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}\"

    # Check to see if tk<Plat>Port.h isn't already with the public headers
    # Don't look for tkInt.h because that resides with tk.h in the core
    # sources, but the <plat>Port headers are in a different directory
    if test -f "${ac_cv_c_tkh}/tkSDLPort.h"; then
	result="private headers found with public headers"
    elif test "${TEA_PLATFORM}" = "windows" -a \
	-f "${ac_cv_c_tkh}/tkWinPort.h"; then
	result="private headers found with public headers"
    elif test "${TEA_PLATFORM}" = "unix" -a \
	-f "${ac_cv_c_tkh}/tkUnixPort.h"; then
	result="private headers found with public headers"
    else
	TK_GENERIC_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/generic\"
	TK_XLIB_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/xlib\"
	if test "${TEA_PLATFORM}" = "windows"; then
	    TK_PLATFORM_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/win\"
	else
	    TK_PLATFORM_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/unix\"
	fi
	case ${TK_DEFS} in
	    *PLATFORM_SDL*)
		TK_PLATFORM_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/sdl\"
		;;
	esac
	# Overwrite the previous TK_INCLUDES as this should capture both
	# public and private headers in the same set.
	# We want to ensure these are substituted so as not to require
	# any *_NATIVE vars be defined in the Makefile
	TK_INCLUDES="-I${TK_GENERIC_DIR_NATIVE} -I${TK_PLATFORM_DIR_NATIVE}"
	# Detect and add ttk subdir
	if test -d "${TK_SRC_DIR}/generic/ttk"; then
	   TK_INCLUDES="${TK_INCLUDES} -I\"${TK_SRC_DIR_NATIVE}/generic/ttk\""
	fi
	if test "${TEA_WINDOWINGSYSTEM}" != "x11" -o "${TEA_USE_SDL}" = "yes" ; then
	   TK_INCLUDES="${TK_INCLUDES} -I${TK_XLIB_DIR_NATIVE}"
	fi
	if test "${TEA_WINDOWINGSYSTEM}" = "aqua"; then
	   TK_INCLUDES="${TK_INCLUDES} -I\"${TK_SRC_DIR_NATIVE}/macosx\""
	fi
	if test "`uname -s`" = "Darwin"; then
	    # If Tk was built as a framework, attempt to use
	    # the framework's Headers and PrivateHeaders directories
	    case ${TK_DEFS} in
		*TK_FRAMEWORK*)
			if test -d "${TK_BIN_DIR}/Headers" -a \
				-d "${TK_BIN_DIR}/PrivateHeaders"; then
			    TK_INCLUDES="-I\"${TK_BIN_DIR}/Headers\" -I\"${TK_BIN_DIR}/PrivateHeaders\" ${TK_INCLUDES}"
			else
			    TK_INCLUDES="${TK_INCLUDES} ${TK_INCLUDE_SPEC} `echo "${TK_INCLUDE_SPEC}" | sed -e 's/Headers/PrivateHeaders/'`"
			fi
			;;
	    esac
	    result="Using ${TK_INCLUDES}"
	else
	    if test ! -f "${TK_SRC_DIR}/generic/tkInt.h" ; then
	       AC_MSG_ERROR([Cannot find private header tkInt.h in ${TK_SRC_DIR}])
	    fi
	    result="Using srcdir found in tkConfig.sh: ${TK_SRC_DIR}"
	fi
    fi

    AC_SUBST(TK_TOP_DIR_NATIVE)
    AC_SUBST(TK_XLIB_DIR_NATIVE)

    AC_SUBST(TK_INCLUDES)
    AC_MSG_RESULT([${result}])
])

#------------------------------------------------------------------------
# TEA_PUBLIC_TK_HEADERS --
#
#	Locate the installed public Tk header files
#
# Arguments:
#	None.
#
# Requires:
#	CYGPATH must be set
#
# Results:
#
#	Adds a --with-tkinclude switch to configure.
#	Result is cached.
#
#	Substitutes the following vars:
#		TK_INCLUDES
#------------------------------------------------------------------------

AC_DEFUN([TEA_PUBLIC_TK_HEADERS], [
    AC_MSG_CHECKING([for Tk public headers])

    AC_ARG_WITH(tkinclude, [  --with-tkinclude        directory containing the public Tk header files], with_tkinclude=${withval})

    AC_CACHE_VAL(ac_cv_c_tkh, [
	# Use the value from --with-tkinclude, if it was given

	if test x"${with_tkinclude}" != x ; then
	    if test -f "${with_tkinclude}/tk.h" ; then
		ac_cv_c_tkh=${with_tkinclude}
	    else
		AC_MSG_ERROR([${with_tkinclude} directory does not contain tk.h])
	    fi
	else
	    list=""
	    if test "`uname -s`" = "Darwin"; then
		# If Tk was built as a framework, attempt to use
		# the framework's Headers directory.
		case ${TK_DEFS} in
		    *TK_FRAMEWORK*)
			list="`ls -d ${TK_BIN_DIR}/Headers 2>/dev/null`"
			;;
		esac
	    fi

	    # Look in the source dir only if Tk is not installed,
	    # and in that situation, look there before installed locations.
	    if test -f "${TK_BIN_DIR}/Makefile" ; then
		list="$list `ls -d ${TK_SRC_DIR}/generic 2>/dev/null`"
	    fi

	    # Check order: pkg --prefix location, Tk's --prefix location,
	    # relative to directory of tkConfig.sh, Tcl's --prefix location,
	    # relative to directory of tclConfig.sh.

	    eval "temp_includedir=${includedir}"
	    list="$list \
		`ls -d ${temp_includedir}        2>/dev/null` \
		`ls -d ${TK_PREFIX}/include      2>/dev/null` \
		`ls -d ${TK_BIN_DIR}/../include  2>/dev/null` \
		`ls -d ${TCL_PREFIX}/include     2>/dev/null` \
		`ls -d ${TCL_BIN_DIR}/../include 2>/dev/null`"
	    if test "${TEA_PLATFORM}" != "windows" -o "$GCC" = "yes"; then
		list="$list /usr/local/include /usr/include"
		if test x"${TK_INCLUDE_SPEC}" != x ; then
		    d=`echo "${TK_INCLUDE_SPEC}" | sed -e 's/^-I//'`
		    list="$list `ls -d ${d} 2>/dev/null`"
		fi
	    fi
	    for i in $list ; do
		if test -f "$i/tk.h" ; then
		    ac_cv_c_tkh=$i
		    break
		fi
	    done
	fi
    ])

    # Print a message based on how we determined the include path

    if test x"${ac_cv_c_tkh}" = x ; then
	AC_MSG_ERROR([tk.h not found.  Please specify its location with --with-tkinclude])
    else
	AC_MSG_RESULT([${ac_cv_c_tkh}])
    fi

    # Convert to a native path and substitute into the output files.

    INCLUDE_DIR_NATIVE=`${CYGPATH} ${ac_cv_c_tkh}`

    TK_INCLUDES=-I\"${INCLUDE_DIR_NATIVE}\"

    AC_SUBST(TK_INCLUDES)

    if test "${TEA_WINDOWINGSYSTEM}" != "x11" -o "${TEA_USE_SDL}" = "yes" ; then
	# On Windows and Aqua, we need the X compat headers
	AC_MSG_CHECKING([for X11 header files])
	if test ! -r "${INCLUDE_DIR_NATIVE}/X11/Xlib.h"; then
	    INCLUDE_DIR_NATIVE="`${CYGPATH} ${TK_SRC_DIR}/xlib`"
	    TK_XINCLUDES=-I\"${INCLUDE_DIR_NATIVE}\"
	    AC_SUBST(TK_XINCLUDES)
	fi
	AC_MSG_RESULT([${INCLUDE_DIR_NATIVE}])
    fi
])

#------------------------------------------------------------------------
# TEA_PATH_CONFIG --
#
#	Locate the ${1}Config.sh file and perform a sanity check on
#	the ${1} compile flags.  These are used by packages like
#	[incr Tk] that load *Config.sh files from more than Tcl and Tk.
#
# Arguments:
#	none
#
# Results:
#
#	Adds the following arguments to configure:
#		--with-$1=...
#
#	Defines the following vars:
#		$1_BIN_DIR	Full path to the directory containing
#				the $1Config.sh file
#------------------------------------------------------------------------

AC_DEFUN([TEA_PATH_CONFIG], [
    #
    # Ok, lets find the $1 configuration
    # First, look for one uninstalled.
    # the alternative search directory is invoked by --with-$1
    #

    if test x"${no_$1}" = x ; then
	# we reset no_$1 in case something fails here
	no_$1=true
	AC_ARG_WITH($1, [  --with-$1              directory containing $1 configuration ($1Config.sh)], with_$1config=${withval})
	AC_MSG_CHECKING([for $1 configuration])
	AC_CACHE_VAL(ac_cv_c_$1config,[

	    # First check to see if --with-$1 was specified.
	    if test x"${with_$1config}" != x ; then
		case ${with_$1config} in
		    */$1Config.sh )
			if test -f ${with_$1config}; then
			    AC_MSG_WARN([--with-$1 argument should refer to directory containing $1Config.sh, not to $1Config.sh itself])
			    with_$1config=`echo ${with_$1config} | sed 's!/$1Config\.sh$!!'`
			fi;;
		esac
		if test -f "${with_$1config}/$1Config.sh" ; then
		    ac_cv_c_$1config=`(cd ${with_$1config}; pwd)`
		else
		    AC_MSG_ERROR([${with_$1config} directory doesn't contain $1Config.sh])
		fi
	    fi

	    # then check for a private $1 installation
	    if test x"${ac_cv_c_$1config}" = x ; then
		for i in \
			../$1 \
			`ls -dr ../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
			`ls -dr ../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
			`ls -dr ../$1*[[0-9]].[[0-9]] 2>/dev/null` \
			`ls -dr ../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
			../../$1 \
			`ls -dr ../../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
			`ls -dr ../../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
			`ls -dr ../../$1*[[0-9]].[[0-9]] 2>/dev/null` \
			`ls -dr ../../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
			../../../$1 \
			`ls -dr ../../../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
			`ls -dr ../../../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
			`ls -dr ../../../$1*[[0-9]].[[0-9]] 2>/dev/null` \
			`ls -dr ../../../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
			${srcdir}/../$1 \
			`ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
			`ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
			`ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]] 2>/dev/null` \
			`ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
			; do
		    if test -f "$i/$1Config.sh" ; then
			ac_cv_c_$1config=`(cd $i; pwd)`
			break
		    fi
		    if test -f "$i/unix/$1Config.sh" ; then
			ac_cv_c_$1config=`(cd $i/unix; pwd)`
			break
		    fi
		done
	    fi

	    # check in a few common install locations
	    if test x"${ac_cv_c_$1config}" = x ; then
		for i in `ls -d ${libdir} 2>/dev/null` \
			`ls -d ${exec_prefix}/lib 2>/dev/null` \
			`ls -d ${prefix}/lib 2>/dev/null` \
			`ls -d /usr/local/lib 2>/dev/null` \
			`ls -d /usr/contrib/lib 2>/dev/null` \
			`ls -d /usr/lib 2>/dev/null` \
			`ls -d /usr/lib64 2>/dev/null` \
			; do
		    if test -f "$i/$1Config.sh" ; then
			ac_cv_c_$1config=`(cd $i; pwd)`
			break
		    fi
		done
	    fi
	])

	if test x"${ac_cv_c_$1config}" = x ; then
	    $1_BIN_DIR="# no $1 configs found"
	    AC_MSG_WARN([Cannot find $1 configuration definitions])
	    exit 0
	else
	    no_$1=
	    $1_BIN_DIR=${ac_cv_c_$1config}
	    AC_MSG_RESULT([found $$1_BIN_DIR/$1Config.sh])
	fi
    fi
])

#------------------------------------------------------------------------
# TEA_LOAD_CONFIG --
#
#	Load the $1Config.sh file
#
# Arguments:
#
#	Requires the following vars to be set:
#		$1_BIN_DIR
#
# Results:
#
#	Substitutes the following vars:
#		$1_SRC_DIR
#		$1_LIB_FILE
#		$1_LIB_SPEC
#------------------------------------------------------------------------

AC_DEFUN([TEA_LOAD_CONFIG], [
    AC_MSG_CHECKING([for existence of ${$1_BIN_DIR}/$1Config.sh])

    if test -f "${$1_BIN_DIR}/$1Config.sh" ; then
        AC_MSG_RESULT([loading])
	. "${$1_BIN_DIR}/$1Config.sh"
    else
        AC_MSG_RESULT([file not found])
    fi

    #
    # If the $1_BIN_DIR is the build directory (not the install directory),
    # then set the common variable name to the value of the build variables.
    # For example, the variable $1_LIB_SPEC will be set to the value
    # of $1_BUILD_LIB_SPEC. An extension should make use of $1_LIB_SPEC
    # instead of $1_BUILD_LIB_SPEC since it will work with both an
    # installed and uninstalled version of Tcl.
    #

    if test -f "${$1_BIN_DIR}/Makefile" ; then
	AC_MSG_WARN([Found Makefile - using build library specs for $1])
        $1_LIB_SPEC=${$1_BUILD_LIB_SPEC}
        $1_STUB_LIB_SPEC=${$1_BUILD_STUB_LIB_SPEC}
        $1_STUB_LIB_PATH=${$1_BUILD_STUB_LIB_PATH}
        $1_INCLUDE_SPEC=${$1_BUILD_INCLUDE_SPEC}
        $1_LIBRARY_PATH=${$1_LIBRARY_PATH}
    fi

    AC_SUBST($1_VERSION)
    AC_SUBST($1_BIN_DIR)
    AC_SUBST($1_SRC_DIR)

    AC_SUBST($1_LIB_FILE)
    AC_SUBST($1_LIB_SPEC)

    AC_SUBST($1_STUB_LIB_FILE)
    AC_SUBST($1_STUB_LIB_SPEC)
    AC_SUBST($1_STUB_LIB_PATH)

    # Allow the caller to prevent this auto-check by specifying any 2nd arg
    AS_IF([test "x$2" = x], [
	# Check both upper and lower-case variants
	# If a dev wanted non-stubs libs, this function could take an option
	# to not use _STUB in the paths below
	AS_IF([test "x${$1_STUB_LIB_SPEC}" = x],
	    [TEA_LOAD_CONFIG_LIB(translit($1,[a-z],[A-Z])_STUB)],
	    [TEA_LOAD_CONFIG_LIB($1_STUB)])
    ])
])

#------------------------------------------------------------------------
# TEA_LOAD_CONFIG_LIB --
#
#	Helper function to load correct library from another extension's
#	${PACKAGE}Config.sh.
#
# Results:
#	Adds to LIBS the appropriate extension library
#------------------------------------------------------------------------
AC_DEFUN([TEA_LOAD_CONFIG_LIB], [
    AC_MSG_CHECKING([For $1 library for LIBS])
    # This simplifies the use of stub libraries by automatically adding
    # the stub lib to your path.  Normally this would add to SHLIB_LD_LIBS,
    # but this is called before CONFIG_CFLAGS.  More importantly, this adds
    # to PKG_LIBS, which becomes LIBS, and that is only used by SHLIB_LD.
    if test "x${$1_LIB_SPEC}" != "x" ; then
	if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes" ; then
	    TEA_ADD_LIBS([\"`${CYGPATH} ${$1_LIB_PATH}`\"])
	    AC_MSG_RESULT([using $1_LIB_PATH ${$1_LIB_PATH}])
	else
	    TEA_ADD_LIBS([${$1_LIB_SPEC}])
	    AC_MSG_RESULT([using $1_LIB_SPEC ${$1_LIB_SPEC}])
	fi
    else
	AC_MSG_RESULT([file not found])
    fi
])

#------------------------------------------------------------------------
# TEA_EXPORT_CONFIG --
#
#	Define the data to insert into the ${PACKAGE}Config.sh file
#
# Arguments:
#
#	Requires the following vars to be set:
#		$1
#
# Results:
#	Substitutes the following vars:
#------------------------------------------------------------------------

AC_DEFUN([TEA_EXPORT_CONFIG], [
    #--------------------------------------------------------------------
    # These are for $1Config.sh
    #--------------------------------------------------------------------

    # pkglibdir must be a fully qualified path and (not ${exec_prefix}/lib)
    eval pkglibdir="[$]{libdir}/$1${PACKAGE_VERSION}"
    if test "${TCL_LIB_VERSIONS_OK}" = "ok"; then
	eval $1_LIB_FLAG="-l$1${PACKAGE_VERSION}${DBGX}"
	eval $1_STUB_LIB_FLAG="-l$1stub${PACKAGE_VERSION}${DBGX}"
    else
	eval $1_LIB_FLAG="-l$1`echo ${PACKAGE_VERSION} | tr -d .`${DBGX}"
	eval $1_STUB_LIB_FLAG="-l$1stub`echo ${PACKAGE_VERSION} | tr -d .`${DBGX}"
    fi
    $1_BUILD_LIB_SPEC="-L`pwd` ${$1_LIB_FLAG}"
    $1_LIB_SPEC="-L${pkglibdir} ${$1_LIB_FLAG}"
    $1_BUILD_STUB_LIB_SPEC="-L`pwd` [$]{$1_STUB_LIB_FLAG}"
    $1_STUB_LIB_SPEC="-L${pkglibdir} [$]{$1_STUB_LIB_FLAG}"
    $1_BUILD_STUB_LIB_PATH="`pwd`/[$]{PKG_STUB_LIB_FILE}"
    $1_STUB_LIB_PATH="${pkglibdir}/[$]{PKG_STUB_LIB_FILE}"

    AC_SUBST($1_BUILD_LIB_SPEC)
    AC_SUBST($1_LIB_SPEC)
    AC_SUBST($1_BUILD_STUB_LIB_SPEC)
    AC_SUBST($1_STUB_LIB_SPEC)
    AC_SUBST($1_BUILD_STUB_LIB_PATH)
    AC_SUBST($1_STUB_LIB_PATH)

    AC_SUBST(MAJOR_VERSION)
    AC_SUBST(MINOR_VERSION)
    AC_SUBST(PATCHLEVEL)
])


#------------------------------------------------------------------------
# TEA_PATH_CELIB --
#
#	Locate Keuchel's celib emulation layer for targeting Win/CE
#
# Arguments:
#	none
#
# Results:
#
#	Adds the following arguments to configure:
#		--with-celib=...
#
#	Defines the following vars:
#		CELIB_DIR	Full path to the directory containing
#				the include and platform lib files
#------------------------------------------------------------------------

AC_DEFUN([TEA_PATH_CELIB], [
    # First, look for one uninstalled.
    # the alternative search directory is invoked by --with-celib

    if test x"${no_celib}" = x ; then
	# we reset no_celib in case something fails here
	no_celib=true
	AC_ARG_WITH(celib,[  --with-celib=DIR        use Windows/CE support library from DIR], with_celibconfig=${withval})
	AC_MSG_CHECKING([for Windows/CE celib directory])
	AC_CACHE_VAL(ac_cv_c_celibconfig,[
	    # First check to see if --with-celibconfig was specified.
	    if test x"${with_celibconfig}" != x ; then
		if test -d "${with_celibconfig}/inc" ; then
		    ac_cv_c_celibconfig=`(cd ${with_celibconfig}; pwd)`
		else
		    AC_MSG_ERROR([${with_celibconfig} directory doesn't contain inc directory])
		fi
	    fi

	    # then check for a celib library
	    if test x"${ac_cv_c_celibconfig}" = x ; then
		for i in \
			../celib-palm-3.0 \
			../celib \
			../../celib-palm-3.0 \
			../../celib \
			`ls -dr ../celib-*3.[[0-9]]* 2>/dev/null` \
			${srcdir}/../celib-palm-3.0 \
			${srcdir}/../celib \
			`ls -dr ${srcdir}/../celib-*3.[[0-9]]* 2>/dev/null` \
			; do
		    if test -d "$i/inc" ; then
			ac_cv_c_celibconfig=`(cd $i; pwd)`
			break
		    fi
		done
	    fi
	])
	if test x"${ac_cv_c_celibconfig}" = x ; then
	    AC_MSG_ERROR([Cannot find celib support library directory])
	else
	    no_celib=
	    CELIB_DIR=${ac_cv_c_celibconfig}
	    CELIB_DIR=`echo "$CELIB_DIR" | sed -e 's!\\\!/!g'`
	    AC_MSG_RESULT([found $CELIB_DIR])
	fi
    fi
])

#--------------------------------------------------------------------
# TEA_EMBED_MANIFEST
#
#	Figure out if we can embed the manifest where necessary
#
# Arguments:
#	An optional manifest to merge into DLL/EXE.
#
# Results:
#	Will define the following vars:
#		VC_MANIFEST_EMBED_DLL
#		VC_MANIFEST_EMBED_EXE
#
#--------------------------------------------------------------------

AC_DEFUN([TEA_EMBED_MANIFEST], [
    AC_MSG_CHECKING(whether to embed manifest)
    AC_ARG_ENABLE(embedded-manifest,
	AC_HELP_STRING([--enable-embedded-manifest],
		[embed manifest if possible (default: yes)]),
	[embed_ok=$enableval], [embed_ok=yes])

    VC_MANIFEST_EMBED_DLL=
    VC_MANIFEST_EMBED_EXE=
    result=no
    if test "$embed_ok" = "yes" -a "${SHARED_BUILD}" = "1" \
       -a "$GCC" != "yes" ; then
	# Add the magic to embed the manifest into the dll/exe
	AC_EGREP_CPP([manifest needed], [
#if defined(_MSC_VER) && _MSC_VER >= 1400
print("manifest needed")
#endif
	], [
	# Could do a CHECK_PROG for mt, but should always be with MSVC8+
	# Could add 'if test -f' check, but manifest should be created
	# in this compiler case
	# Add in a manifest argument that may be specified
	VC_MANIFEST_EMBED_DLL="if test -f \[$]@.manifest ; then mt.exe -nologo -manifest \[$]@.manifest $1 -outputresource:\[$]@\;2 ; fi"
	VC_MANIFEST_EMBED_EXE="if test -f \[$]@.manifest ; then mt.exe -nologo -manifest \[$]@.manifest $1 -outputresource:\[$]@\;1 ; fi"
	result=yes
	if test "x$1" != x ; then
	    result="yes ($1)"
	fi
	])
    fi
    AC_MSG_RESULT([$result])
    AC_SUBST(VC_MANIFEST_EMBED_DLL)
    AC_SUBST(VC_MANIFEST_EMBED_EXE)
])

# Local Variables:
# mode: autoconf
# End:
Added jni/topcua/topcua.c.


































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
/*
 * topcua.c --
 *
 *      This file contains a proof of concept Tcl binding to the
 *	open62541 OPC UA library (client only).
 *
 * Copyright (c) 2018 Christian Werner <chw at ch minus werner dot de>
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include <tcl.h>
#include <string.h>
#include <fcntl.h>
#include <ctype.h>
#include <errno.h>

#include "open62541.h"

/*
 * Structure representing an OPC UA client.
 */

typedef struct {
    int connected;
    UA_Client *client;
    Tcl_Namespace *nsPtr;
} UACL;

/*
 * Per interpreter control structure.
 */

typedef struct {
    int idCount;
    Tcl_HashTable clients;		/* List of UACL instances. */
    Tcl_HashTable types;		/* List of some UA data types. */
    UA_ClientConfig clcfg;		/* Our own default config. */
    char msgBuffer[256];		/* For error messages. */
} UACLI;

/*
 * Forward declarations.
 */

static void		DoNotLog(UA_LogLevel level, UA_LogCategory cat,
				 const char *msg, va_list args);
static UA_NodeId *	ParseNodeId(Tcl_Interp *interp, UA_NodeId *nodein,
				    const char *string);
static UA_QualifiedName *ParseQualifiedName(Tcl_Interp *interp,
					    UA_QualifiedName *namein,
					    const char *string);
static char *		PrintNodeId(UA_NodeId *nodein, Tcl_DString *dsPtr);
static const char *	StatusCodeToString(UACLI *uacli, UA_StatusCode uaret);
static void		ReportError(Tcl_Interp *interp, UACLI *uacli,
				    const char *func, UA_StatusCode uaret);
static void		AddRefDescrToList(Tcl_Obj *list,
					  UA_ReferenceDescription *ref);
static void		SubNamespaceDeleted(ClientData clientData);
static void		NamespaceDeleted(ClientData clientData);
static int		EndpointsObjCmd(ClientData clientData,
					Tcl_Interp *interp,
					int objc, Tcl_Obj * const objv[]);
static int		ServersObjCmd(ClientData clientData,
				      Tcl_Interp *interp,
				      int objc, Tcl_Obj * const objv[]);
static int		NewObjCmd(ClientData clientData, Tcl_Interp *interp,
				  int objc, Tcl_Obj * const objv[]);
static int		DestroyObjCmd(ClientData clientData, Tcl_Interp *interp,
				      int objc, Tcl_Obj * const objv[]);
static int		ConnectObjCmd(ClientData clientData, Tcl_Interp *interp,
				      int objc, Tcl_Obj * const objv[]);
static int		DisconnectObjCmd(ClientData clientData,
					 Tcl_Interp *interp,
					 int objc, Tcl_Obj * const objv[]);
static int		InfoObjCmd(ClientData clientData, Tcl_Interp *interp,
				   int objc, Tcl_Obj * const objv[]);
static int		Sc2StrObjCmd(ClientData clientData, Tcl_Interp *interp,
				     int objc, Tcl_Obj * const objv[]);
static int		BrowseObjCmd(ClientData clientData, Tcl_Interp *interp,
				     int objc, Tcl_Obj * const objv[]);
static int		TranslateObjCmd(ClientData clientData,
					Tcl_Interp *interp,
					int objc, Tcl_Obj * const objv[]);
static int		AttrsObjCmd(ClientData clientData, Tcl_Interp *interp,
				    int objc, Tcl_Obj * const objv[]);
static int		TypesObjCmd(ClientData clientData, Tcl_Interp *interp,
				    int objc, Tcl_Obj * const objv[]);
static int		RefTypeObjCmd(ClientData clientData,
				      Tcl_Interp *interp,
				      int objc, Tcl_Obj * const objv[]);
static int		ReadTypeObjCmd(ClientData clientData,
				       Tcl_Interp *interp, int isType,
				       int objc, Tcl_Obj * const objv[]);
static int		ReadObjCmd(ClientData clientData, Tcl_Interp *interp,
				   int objc, Tcl_Obj * const objv[]);
static int		TypeObjCmd(ClientData clientData, Tcl_Interp *interp,
				   int objc, Tcl_Obj * const objv[]);
static int		WriteObjCmd(ClientData clientData, Tcl_Interp *interp,
				    int objc, Tcl_Obj * const objv[]);
static int		CallObjCmd(ClientData clientData, Tcl_Interp *interp,
				   int objc, Tcl_Obj * const objv[]);

/*
 * Attributes, align with enum UA_AttributeId.
 */

static const char *attrNames[] = {
    "NodeId", "NodeClass", "BrowseName", "DisplayNname",
    "Description", "WriteMask", "UserWriteMask", "IsAbstract",
    "Symmetric", "InverseName", "ContainsNoLoops", "EventNotifier",
    "Value", "DataType", "ValueRank", "ArrayDimensions",
    "AccessLevel", "UserAccessLevel", "MinimumSamplingInterval",
    "Historizing", "Executable", "UserExecutable", NULL
};

/*
 * ReferenceTypes and their NodeIds.
 */

static const struct {
    const char *name;
    int ns0id;
} refTypes[] = {
    { "References", UA_NS0ID_REFERENCES },
    { "NonHierarchicalReferences", UA_NS0ID_NONHIERARCHICALREFERENCES },
    { "HierarchicalReferences", UA_NS0ID_HIERARCHICALREFERENCES },
    { "HasChild", UA_NS0ID_HASCHILD },
    { "Organizes", UA_NS0ID_ORGANIZES },
    { "HasEventSource", UA_NS0ID_HASEVENTSOURCE },
    { "HasModellingRule", UA_NS0ID_HASMODELLINGRULE },
    { "HasEncoding", UA_NS0ID_HASENCODING },
    { "HasDescription", UA_NS0ID_HASDESCRIPTION },
    { "HasTypeDefinition", UA_NS0ID_HASTYPEDEFINITION },
    { "GeneratesEvnet", UA_NS0ID_GENERATESEVENT },
    { "Aggregates", UA_NS0ID_AGGREGATES },
    { "HasSubtype", UA_NS0ID_HASSUBTYPE },
    { "HasProperty", UA_NS0ID_HASPROPERTY },
    { "HasComponent", UA_NS0ID_HASCOMPONENT },
    { "HasNotifier", UA_NS0ID_HASNOTIFIER },
    { "HasOrderedComponent", UA_NS0ID_HASORDEREDCOMPONENT },
    { "FromState", UA_NS0ID_FROMSTATE },
    { "ToState", UA_NS0ID_TOSTATE },
    { "HasCause", UA_NS0ID_HASCAUSE },
    { "HasEffect", UA_NS0ID_HASEFFECT },
    { "HasHistoricalConfiguration", UA_NS0ID_HASHISTORICALCONFIGURATION },
    { "HasSubStateMachine", UA_NS0ID_HASSUBSTATEMACHINE },
    { "AlwaysGeneratesEvent", UA_NS0ID_ALWAYSGENERATESEVENT },
    { "HasTrueSubState", UA_NS0ID_HASTRUESUBSTATE },
    { "HasFalseSubState", UA_NS0ID_HASFALSESUBSTATE },
    { "HasCondition", UA_NS0ID_HASCONDITION },
    { "HasPubSubConnection", 14476 },
    { "DataSetToWriter", 14936 },
    { "HasDataSetWriter", 15296 },
    { "HasDataSetReader", 15297 },
    { "HasAlarmSuppressionGroup", 16361 },
    { "AlarmGroupMember", 16362 },
    { "HasEffectDisable", 17276 },
    { "HasEffectEnable", 17983 },
    { "HasEffectSuppressed", 17984 },
    { "HasEffectUnsuppressed", 17985 }
};

/*
 *-------------------------------------------------------------------------
 *
 * DoNotLog --
 *
 *	Silence log messages.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *-------------------------------------------------------------------------
 */

static void
DoNotLog(UA_LogLevel level, UA_LogCategory cat,
	 const char *msg, va_list args)
{
}

/*
 *-------------------------------------------------------------------------
 *
 * ParseNodeId --
 *
 *	Given string make it into an UA_NodeId struct which the caller
 *	provided.
 *
 * Results:
 *	NULL on error, otherwise a pointer to the UA_NodeId which the
 *	called provided.
 *
 * Side effects:
 *	None.
 *
 *-------------------------------------------------------------------------
 */

static UA_NodeId *
ParseNodeId(Tcl_Interp *interp, UA_NodeId *nodein, const char *string)
{
    int nsindex = 0, len = strlen(string), needtype = 0;
    unsigned id;
    char ch, *errstr = "unknown error";

    if (nodein == NULL) {
	errstr = "no result buffer";
	goto error;
    }
    *nodein = UA_NODEID_NULL;
    nodein->identifierType = UA_NODEIDTYPE_STRING;
    if ((len > 3) && (strncmp(string, "ns=", 3) == 0)) {
	if (sscanf(string, "ns=%d;", &nsindex) != 1) {
	    errstr = "invalid namespace index";
	    goto error;
	}
	string = strchr(string, ';');
	if (string == NULL) {
	    errstr = "invalid nodeid syntax";
	    goto error;
	}
	++string;
	needtype = 1;
    }
    if (!needtype) {
	if ((string[0] != '\0') && (strchr("sbgi", string[0]) != NULL) &&
	    (string[1] == '=')) {
	    needtype = 1;
	}
    }
    if (needtype) {
	switch (string[0]) {
	case 's':
	    nodein->identifierType = UA_NODEIDTYPE_STRING;
	    break;
	case 'b':
	    nodein->identifierType = UA_NODEIDTYPE_BYTESTRING;
	    break;
	case 'g':
	    nodein->identifierType = UA_NODEIDTYPE_GUID;
	    break;
	case 'i':
	    nodein->identifierType = UA_NODEIDTYPE_NUMERIC;
	    break;
	default:
	    nodein->identifierType = UA_NODEIDTYPE_STRING;
	    goto wholeString;
	}
	if (string[1] != '=') {
	    errstr = "missing equal sign in type literal";
	    goto error;
	}
	string += 2;
wholeString:
	;
    }
    nodein->namespaceIndex = nsindex;
    len = 0;
    switch (nodein->identifierType) {
    case UA_NODEIDTYPE_NUMERIC:
	if (sscanf(string, "%u%c", &id, &ch) != 1) {
	    errstr = "invalid numeric identifier";
	    goto error;
	}
	nodein->identifier.numeric = id;
	break;
    case UA_NODEIDTYPE_STRING:
	len = strlen(string);
	nodein->identifier.string = UA_String_fromChars(string);
	break;
    case UA_NODEIDTYPE_GUID: {
	UA_Guid *g = &nodein->identifier.guid;
	int d[11];

	if (sscanf(string,
		   "%8x-%4x-%4x-%2x%2x-%2x%2x%2x%2x%2x%2x",
		   d, d + 1, d + 2, d + 3, d + 4, d + 5,
		   d + 6, d + 7, d + 8, d + 9, d + 10) != 11) {
	    errstr = "invalid GUID";
	    goto error;
	}
	g->data1 = d[0];
	g->data2 = d[1];
	g->data3 = d[2];
	g->data4[0] = d[3];
	g->data4[1] = d[4];
	g->data4[2] = d[5];
	g->data4[3] = d[6];
	g->data4[4] = d[7];
	g->data4[5] = d[8];
	g->data4[6] = d[9];
	g->data4[7] = d[10];
	break;
    }
    case UA_NODEIDTYPE_BYTESTRING:
	errstr = "bytestring identifier unsupported";
	goto error;
    }
    return nodein;
error:
    if (interp != NULL) {
	Tcl_Obj *list[4];
	UA_StatusCode uaret = UA_STATUSCODE_BADINTERNALERROR;

	Tcl_SetResult(interp, errstr, TCL_STATIC);
	list[0] = Tcl_NewStringObj("topcua", -1);
	list[1] = Tcl_NewStringObj("ParseNodeId", -1);
	list[2] = Tcl_NewIntObj((int) uaret);
	list[3] = Tcl_NewStringObj(UA_StatusCode_name(uaret), -1);
	Tcl_SetObjErrorCode(interp, Tcl_NewListObj(4, list));
    }
    return NULL;
}

/*
 *-------------------------------------------------------------------------
 *
 * ParseQualifiedName --
 *
 *	Given string make it into an UA_QualifiedName struct which the caller
 *	provided.
 *
 * Results:
 *	NULL on error, otherwise a pointer to the UA_QualifiedName which the
 *	called provided.
 *
 * Side effects:
 *	None.
 *
 *-------------------------------------------------------------------------
 */

static UA_QualifiedName *
ParseQualifiedName(Tcl_Interp *interp, UA_QualifiedName *namein,
		   const char *string)
{
    int nsindex = 0, len = strlen(string);
    char *errstr = "unknown error";

    if (namein == NULL) {
	errstr = "no result buffer";
	goto error;
    }
    namein->name = UA_STRING_NULL;
    namein->namespaceIndex = nsindex;
    if ((len > 3) && (strncmp(string, "ns=", 3) == 0)) {
	if (sscanf(string, "ns=%d;", &nsindex) != 1) {
	    errstr = "invalid namespace index";
	    goto error;
	}
	string = strchr(string, ';');
	if (string == NULL) {
	    errstr = "invalid nodeid syntax";
	    goto error;
	}
	++string;
    }
    if ((string[0] == 's') && (string[1] == '=')) {
	string += 2;
    }
    namein->namespaceIndex = nsindex;
    len = strlen(string);
    if (len > 0) {
	namein->name = UA_String_fromChars(string);
    }
    return namein;
error:
    if (interp != NULL) {
	Tcl_Obj *list[4];
	UA_StatusCode uaret = UA_STATUSCODE_BADINTERNALERROR;

	Tcl_SetResult(interp, errstr, TCL_STATIC);
	list[0] = Tcl_NewStringObj("topcua", -1);
	list[1] = Tcl_NewStringObj("ParseQualifiedName", -1);
	list[2] = Tcl_NewIntObj((int) uaret);
	list[3] = Tcl_NewStringObj(UA_StatusCode_name(uaret), -1);
	Tcl_SetObjErrorCode(interp, Tcl_NewListObj(4, list));
    }
    return NULL;
}

/*
 *-------------------------------------------------------------------------
 *
 * PrintNodeId --
 *
 *	Given UA_NodeId make a string representation into the
 *	provided Tcl_DString.
 *
 * Results:
 *	String with printed NodeId.
 *
 * Side effects:
 *	None.
 *
 *-------------------------------------------------------------------------
 */

static char *
PrintNodeId(UA_NodeId *nodein, Tcl_DString *dsPtr)
{
    char buffer[64];

    Tcl_DStringInit(dsPtr);
    if (nodein->namespaceIndex) {
	sprintf(buffer, "ns=%d;", nodein->namespaceIndex);
	Tcl_DStringAppend(dsPtr, buffer, -1);
    }
    switch (nodein->identifierType) {
    case UA_NODEIDTYPE_NUMERIC:
	sprintf(buffer, "i=%u", nodein->identifier.numeric);
	Tcl_DStringAppend(dsPtr, buffer, -1);
	break;
    case UA_NODEIDTYPE_STRING:
	Tcl_DStringAppend(dsPtr, "s=", 2);
	Tcl_DStringAppend(dsPtr, (char *) nodein->identifier.string.data,
			  nodein->identifier.string.length);
	break;
    case UA_NODEIDTYPE_GUID:
	sprintf(buffer, "g=%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
                nodein->identifier.guid.data1,
                nodein->identifier.guid.data2,
		nodein->identifier.guid.data3,
                nodein->identifier.guid.data4[0],
		nodein->identifier.guid.data4[1],
                nodein->identifier.guid.data4[2],
		nodein->identifier.guid.data4[3],
                nodein->identifier.guid.data4[4],
		nodein->identifier.guid.data4[5],
                nodein->identifier.guid.data4[6],
		nodein->identifier.guid.data4[7]);
        Tcl_DStringAppend(dsPtr, buffer, -1);
	break;
    case UA_NODEIDTYPE_BYTESTRING:
	/* TBD */
	Tcl_DStringAppend(dsPtr, "b=", 2);
	Tcl_DStringAppend(dsPtr, (char *) nodein->identifier.byteString.data,
			  nodein->identifier.byteString.length);
	break;
    }
    return Tcl_DStringValue(dsPtr);
}

/*
 *-------------------------------------------------------------------------
 *
 * StatusCodeToString --
 *
 *	Given UA_StatusCode return a string representation.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *-------------------------------------------------------------------------
 */

static const char *
StatusCodeToString(UACLI *uacli, UA_StatusCode uaret)
{
    switch (uaret) {
    case UA_STATUSCODE_GOOD:
	return "no error";
    case UA_STATUSCODE_BADUNEXPECTEDERROR:
	return "an unexpected error occurred";
    case UA_STATUSCODE_BADINTERNALERROR:
	return "an internal error occurred as a result "
	    "of a programming or configuration error";
    case UA_STATUSCODE_BADOUTOFMEMORY:
	return "not enough memory to complete the operation";
    case UA_STATUSCODE_BADRESOURCEUNAVAILABLE:
	return "an operating system resource is not available";
    case UA_STATUSCODE_BADCOMMUNICATIONERROR:
	return "a low level communication error occurred";
    case UA_STATUSCODE_BADENCODINGERROR:
	return "encoding halted because of invalid data in the "
	    "objects being serialized";
    case UA_STATUSCODE_BADDECODINGERROR:
	return "decoding halted because of invalid data in the "
	    "stream";
    case UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED:
	return "the message encoding/decoding limits imposed by "
	    "the stack have been exceeded";
    case UA_STATUSCODE_BADREQUESTTOOLARGE:
	return "the request message size exceeds limits set by the server";
    case UA_STATUSCODE_BADRESPONSETOOLARGE:
	return "the response message size exceeds limits set by the client";
    case UA_STATUSCODE_BADUNKNOWNRESPONSE:
	return "an unrecognized response was received from the server";
    case UA_STATUSCODE_BADTIMEOUT:
	return "the operation timed out";
    case UA_STATUSCODE_BADSERVICEUNSUPPORTED:
	return "the server does not support the requested service";
    case UA_STATUSCODE_BADSHUTDOWN:
	return "the operation was cancelled because the application "
	    "is shutting down";
    case UA_STATUSCODE_BADSERVERNOTCONNECTED:
	return "the operation could not complete because the client "
	    "is not connected to the server";
    case UA_STATUSCODE_BADSERVERHALTED:
	return "the server has stopped and cannot process any requests";
    case UA_STATUSCODE_BADNOTHINGTODO:
	return "there was nothing to do because the client passed a "
	    "list of operations with no elements";
    case UA_STATUSCODE_BADTOOMANYOPERATIONS:
	return "the request could not be processed because it "
	    "specified too many operations";
    case UA_STATUSCODE_BADTOOMANYMONITOREDITEMS:
	return "the request could not be processed because there "
	    "are too many monitored items in the subscription";
    case UA_STATUSCODE_BADDATATYPEIDUNKNOWN:
	return "the extension object cannot be (de)serialized "
	    "because the data type id is not recognized";
    case UA_STATUSCODE_BADCERTIFICATEINVALID:
	return "the certificate provided as a parameter is not valid";
    case UA_STATUSCODE_BADSECURITYCHECKSFAILED:
	return "an error occurred verifying security";
    case UA_STATUSCODE_BADCERTIFICATETIMEINVALID:
	return "the Certificate has expired or is not yet valid";
    case UA_STATUSCODE_BADCERTIFICATEISSUERTIMEINVALID:
	return "an Issuer Certificate has expired or is not yet valid";
    case UA_STATUSCODE_BADCERTIFICATEHOSTNAMEINVALID:
	return "the HostName used to connect to a Server does not match "
	    "a HostName in the Certificate";
    case UA_STATUSCODE_BADCERTIFICATEURIINVALID:
	return "the URI specified in the ApplicationDescription does not "
	    "match the URI in the Certificate";
    case UA_STATUSCODE_BADCERTIFICATEUSENOTALLOWED:
	return "the Certificate may not be used for the requested operation";
    case UA_STATUSCODE_BADCERTIFICATEISSUERUSENOTALLOWED:
	return "the Issuer Certificate may not be used for the "
	    "requested operation";
    case UA_STATUSCODE_BADCERTIFICATEUNTRUSTED:
	return "the Certificate is not trusted";
    case UA_STATUSCODE_BADCERTIFICATEREVOCATIONUNKNOWN:
	return "it was not possible to determine if the Certificate "
	    "has been revoked";
    case UA_STATUSCODE_BADCERTIFICATEISSUERREVOCATIONUNKNOWN:
	return "it was not possible to determine if the Issuer "
	    "Certificate has been revoked";
    case UA_STATUSCODE_BADCERTIFICATEREVOKED:
	return "the certificate has been revoked";
    case UA_STATUSCODE_BADCERTIFICATEISSUERREVOKED:
	return "the issuer certificate has been revoked";
    case UA_STATUSCODE_BADCERTIFICATECHAININCOMPLETE:
	return "the certificate chain is incomplete";
    case UA_STATUSCODE_BADUSERACCESSDENIED:
	return "user does not have permission to perform the "
	    "requested operation";
    case UA_STATUSCODE_BADIDENTITYTOKENINVALID:
	return "the user identity token is not valid";
    case UA_STATUSCODE_BADIDENTITYTOKENREJECTED:
	return "the user identity token is valid but the "
	    "server has rejected it";
    case UA_STATUSCODE_BADSECURECHANNELIDINVALID:
	return "the specified secure channel is no longer valid";
    case UA_STATUSCODE_BADINVALIDTIMESTAMP:
	return "The timestamp is outside the range allowed by the server";
    case UA_STATUSCODE_BADNONCEINVALID:
	return "the nonce does appear to be not a random value "
	    "or it is not the correct length";
    case UA_STATUSCODE_BADSESSIONIDINVALID:
	return "the session id is not valid";
    case UA_STATUSCODE_BADSESSIONCLOSED:
	return "the session was closed by the client";
    case UA_STATUSCODE_BADSESSIONNOTACTIVATED:
	return "the session cannot be used because ActivateSession "
	    "has not been called";
    case UA_STATUSCODE_BADSUBSCRIPTIONIDINVALID:
	return "the subscription id is not valid";
    case UA_STATUSCODE_BADREQUESTHEADERINVALID:
	return "the header for the request is missing or invalid";
    case UA_STATUSCODE_BADTIMESTAMPSTORETURNINVALID:
	return "the timestamps to return parameter is invalid";
    case UA_STATUSCODE_BADREQUESTCANCELLEDBYCLIENT:
	return "the request was cancelled by the client";
    case UA_STATUSCODE_BADTOOMANYARGUMENTS:
	return "too many arguments were provided";
    case UA_STATUSCODE_BADLICENSEEXPIRED:
	return "the server requires a license to operate in general "
	    "or to perform a service or operation, but existing "
	    "license is expired";
    case UA_STATUSCODE_BADLICENSELIMITSEXCEEDED:
	return "the server has limits on number of allowed operations "
	    "/ objects, based on installed licenses, and these limits "
	    "where exceeded";
    case UA_STATUSCODE_BADLICENSENOTAVAILABLE:
	return "the server does not have a license which is required "
	    "to operate in general or to perform a service or operation";
    case UA_STATUSCODE_GOODSUBSCRIPTIONTRANSFERRED:
	return "the subscription was transferred to another session";
    case UA_STATUSCODE_GOODCOMPLETESASYNCHRONOUSLY:
	return "the processing will complete asynchronously";
    case UA_STATUSCODE_GOODOVERLOAD:
	return "sampling has slowed down due to resource limitations";
    case UA_STATUSCODE_GOODCLAMPED:
	return "the value written was accepted but was clamped";
    case UA_STATUSCODE_BADNOCOMMUNICATION:
	return "communication with the data source is defined, "
	    "but not established, and there is no last known value available";
    case UA_STATUSCODE_BADWAITINGFORINITIALDATA:
	return "waiting for the server to obtain values from the "
	    "underlying data source";
    case UA_STATUSCODE_BADNODEIDINVALID:
	return "the syntax of the node id is not valid";
    case UA_STATUSCODE_BADNODEIDUNKNOWN:
	return "the node id refers to a node that does not "
	    "exist in the server address space";
    case UA_STATUSCODE_BADATTRIBUTEIDINVALID:
	return "the attribute is not supported for the specified node";
    case UA_STATUSCODE_BADINDEXRANGEINVALID:
	return "the syntax of the index range parameter is invalid";
    case UA_STATUSCODE_BADINDEXRANGENODATA:
	return "no data exists within the range of indexes specified";
    case UA_STATUSCODE_BADDATAENCODINGINVALID:
	return "the data encoding is invalid";
    case UA_STATUSCODE_BADDATAENCODINGUNSUPPORTED:
	return "the server does not support the requested data "
	    "encoding for the node";
    case UA_STATUSCODE_BADNOTREADABLE:
	return "the access level does not allow reading or "
	    "subscribing to the node";
    case UA_STATUSCODE_BADNOTWRITABLE:
	return "the access level does not allow writing to the node";
    case UA_STATUSCODE_BADOUTOFRANGE:
	return "the value was out of range";
    case UA_STATUSCODE_BADNOTSUPPORTED:
	return "the requested operation is not supported";
    case UA_STATUSCODE_BADNOTFOUND:
	return "a requested item was not found or a search "
	    "operation ended without success";
    case UA_STATUSCODE_BADOBJECTDELETED:
	return "the object cannot be used because it has been deleted";
    case UA_STATUSCODE_BADNOTIMPLEMENTED:
	return "requested operation is not implemented";
    case UA_STATUSCODE_BADMONITORINGMODEINVALID:
	return "the monitoring mode is invalid";
    case UA_STATUSCODE_BADMONITOREDITEMIDINVALID:
	return "the monitoring item id does not refer to a valid "
	    "monitored item";
    case UA_STATUSCODE_BADMONITOREDITEMFILTERINVALID:
	return "the monitored item filter parameter is not valid";
    case UA_STATUSCODE_BADMONITOREDITEMFILTERUNSUPPORTED:
	return "the server does not support the requested monitored "
	    "item filter";
    case UA_STATUSCODE_BADFILTERNOTALLOWED:
	return "a monitoring filter cannot be used in combination "
	    "with the attribute specified";
    case UA_STATUSCODE_BADSTRUCTUREMISSING:
	return "a mandatory structured parameter was missing or null";
    case UA_STATUSCODE_BADEVENTFILTERINVALID:
	return "the event filter is not valid";
    case UA_STATUSCODE_BADCONTENTFILTERINVALID:
	return "the content filter is not valid";
    case UA_STATUSCODE_BADFILTEROPERATORINVALID:
	return "an unregognized operator was provided in a filter";
    case UA_STATUSCODE_BADFILTEROPERATORUNSUPPORTED:
	return "a valid operator was provided, but the server does "
	    "not provide support for this filter operator";
    case UA_STATUSCODE_BADFILTEROPERANDCOUNTMISMATCH:
	return "the number of operands provided for the filter "
	    "operator was less then expected for the operand provided";
    case UA_STATUSCODE_BADFILTEROPERANDINVALID:
	return "the operand used in a content filter is not valid";
    case UA_STATUSCODE_BADFILTERELEMENTINVALID:
	return "the referenced element is not a valid element in "
	    "the content filter";
    case UA_STATUSCODE_BADFILTERLITERALINVALID:
	return "the referenced literal is not a valid value";
    case UA_STATUSCODE_BADCONTINUATIONPOINTINVALID:
	return "the continuation point provide is longer valid";
    case UA_STATUSCODE_BADNOCONTINUATIONPOINTS:
	return "the operation could not be processed because all "
	    "continuation points have been allocated";
    case UA_STATUSCODE_BADREFERENCETYPEIDINVALID:
	return "the reference type identifer is not valid";
    case UA_STATUSCODE_BADBROWSEDIRECTIONINVALID:
	return "the browse direction is not valid";
    case UA_STATUSCODE_BADNODENOTINVIEW:
	return "the node is not part of the view";
    case UA_STATUSCODE_BADSERVERURIINVALID:
	return "the ServerUri is not a valid URI";
    case UA_STATUSCODE_BADSERVERNAMEMISSING:
	return "no ServerName was specified";
    case UA_STATUSCODE_BADDISCOVERYURLMISSING:
	return "no DiscoveryUrl was specified";
    case UA_STATUSCODE_BADSEMPAHOREFILEMISSING:
	return "the semaphore file specified by the client is not valid";
    case UA_STATUSCODE_BADREQUESTTYPEINVALID:
	return "the security token request type is not valid";
    case UA_STATUSCODE_BADSECURITYMODEREJECTED:
	return "the security mode does not meet the requirements set "
	    "by the Server";
    case UA_STATUSCODE_BADSECURITYPOLICYREJECTED:
	return "the security policy does not meet the requirements "
	    "set by the Server";
    case UA_STATUSCODE_BADTOOMANYSESSIONS:
	return "the server has reached its maximum number of sessions";
    case UA_STATUSCODE_BADUSERSIGNATUREINVALID:
	return "the user token signature is missing or invalid";
    case UA_STATUSCODE_BADAPPLICATIONSIGNATUREINVALID:
	return "the signature generated with the client certificate "
	    "is missing or invalid";
    case UA_STATUSCODE_BADNOVALIDCERTIFICATES:
	return "the client did not provide at least one software "
	    "certificate that is valid and meets the profile "
	    "requirements for the server";
    case UA_STATUSCODE_BADIDENTITYCHANGENOTSUPPORTED:
	return "the Server does not support changing the user "
	    "identity assigned to the session";
    case UA_STATUSCODE_BADREQUESTCANCELLEDBYREQUEST:
	return "the request was cancelled by the client with "
	    "the Cancel service";
    case UA_STATUSCODE_BADPARENTNODEIDINVALID:
	return "the parent node id does not to refer to a valid node";
    case UA_STATUSCODE_BADREFERENCENOTALLOWED:
	return "the reference could not be created because it "
	    "violates constraints imposed by the data model";
    case UA_STATUSCODE_BADNODEIDREJECTED:
	return "the requested node id was reject because it was "
	    "either invalid or server does not allow node ids to "
	    "be specified by the client";
    case UA_STATUSCODE_BADNODEIDEXISTS:
	return "the requested node id is already used by another node";
    case UA_STATUSCODE_BADNODECLASSINVALID:
	return "the node class is not valid";
    case UA_STATUSCODE_BADBROWSENAMEINVALID:
	return "the browse name is invalid";
    case UA_STATUSCODE_BADBROWSENAMEDUPLICATED:
	return "the browse name is not unique among nodes that "
	    "share the same relationship with the parent";
    case UA_STATUSCODE_BADNODEATTRIBUTESINVALID:
	return "the node attributes are not valid for the node class";
    case UA_STATUSCODE_BADTYPEDEFINITIONINVALID:
	return "the type definition node id does not reference an "
	    "appropriate type node";
    case UA_STATUSCODE_BADSOURCENODEIDINVALID:
	return "the source node id does not reference a valid node";
    case UA_STATUSCODE_BADTARGETNODEIDINVALID:
	return "the target node id does not reference a valid node";
    case UA_STATUSCODE_BADDUPLICATEREFERENCENOTALLOWED:
	return "the reference type between the nodes is already defined";
    case UA_STATUSCODE_BADINVALIDSELFREFERENCE:
	return "the server does not allow this type of self reference "
	    "on this node";
    case UA_STATUSCODE_BADREFERENCELOCALONLY:
	return "the reference type is not valid for a reference "
	    "to a remote server";
    case UA_STATUSCODE_BADNODELETERIGHTS:
	return "the server will not allow the node to be deleted";
    case UA_STATUSCODE_UNCERTAINREFERENCENOTDELETED:
	return "the server was not able to delete all target references";
    case UA_STATUSCODE_BADSERVERINDEXINVALID:
	return "the server index is not valid";
    case UA_STATUSCODE_BADVIEWIDUNKNOWN:
	return "the view id does not refer to a valid view node";
    case UA_STATUSCODE_BADVIEWTIMESTAMPINVALID:
	return "the view timestamp is not available or not supported";
    case UA_STATUSCODE_BADVIEWPARAMETERMISMATCH:
	return "the view parameters are not consistent with each other";
    case UA_STATUSCODE_BADVIEWVERSIONINVALID:
	return "the view version is not available or not supported";
    case UA_STATUSCODE_UNCERTAINNOTALLNODESAVAILABLE:
	return "the list of references may not be complete because "
	    "the underlying system is not available";
    case UA_STATUSCODE_GOODRESULTSMAYBEINCOMPLETE:
	return "the server should have followed a reference to a "
	    "node in a remote server but did not. The result set "
	    "may be incomplete";
    case UA_STATUSCODE_BADNOTTYPEDEFINITION:
	return "the provided Nodeid was not a type definition nodeid";
    case UA_STATUSCODE_UNCERTAINREFERENCEOUTOFSERVER:
	return "one of the references to follow in the relative path "
	    "references to a node in the address space in another server";
    case UA_STATUSCODE_BADTOOMANYMATCHES:
	return "the requested operation has too many matches to return";
    case UA_STATUSCODE_BADQUERYTOOCOMPLEX:
	return "the requested operation requires too many resources "
	    "in the server";
    case UA_STATUSCODE_BADNOMATCH:
	return "the requested operation has no match to return";
    case UA_STATUSCODE_BADMAXAGEINVALID:
	return "the max age parameter is invalid";
    case UA_STATUSCODE_BADSECURITYMODEINSUFFICIENT:
	return "the operation is not permitted over the current secure channel";
    case UA_STATUSCODE_BADHISTORYOPERATIONINVALID:
	return "the history details parameter is not valid";
    case UA_STATUSCODE_BADHISTORYOPERATIONUNSUPPORTED:
	return "the server does not support the requested operation";
    case UA_STATUSCODE_BADINVALIDTIMESTAMPARGUMENT:
	return "the defined timestamp to return was invalid";
    case UA_STATUSCODE_BADWRITENOTSUPPORTED:
	return "the server not does support writing the combination "
	    "of value, status and timestamps provided";
    case UA_STATUSCODE_BADTYPEMISMATCH:
	return "the value supplied for the attribute is not of the "
	    "same type as the attribute's value";
    case UA_STATUSCODE_BADMETHODINVALID:
	return "the method id does not refer to a method for the "
	    "specified object";
    case UA_STATUSCODE_BADARGUMENTSMISSING:
	return "the client did not specify all of the input "
	    "arguments for the method";
    case UA_STATUSCODE_BADTOOMANYSUBSCRIPTIONS:
	return "the server has reached its  maximum number of subscriptions";
    case UA_STATUSCODE_BADTOOMANYPUBLISHREQUESTS:
	return "the server has reached the maximum number of "
	    "queued publish requests";
    case UA_STATUSCODE_BADNOSUBSCRIPTION:
	return "there is no subscription available for this session";
    case UA_STATUSCODE_BADSEQUENCENUMBERUNKNOWN:
	return "the sequence number is unknown to the server";
    case UA_STATUSCODE_BADMESSAGENOTAVAILABLE:
	return "the requested notification message is no longer available";
    case UA_STATUSCODE_BADINSUFFICIENTCLIENTPROFILE:
	return "the Client of the current Session does not support "
	    "one or more Profiles that are necessary for the Subscription";
    case UA_STATUSCODE_BADSTATENOTACTIVE:
	return "the sub-state machine is not currently active";
    case UA_STATUSCODE_BADTCPSERVERTOOBUSY:
	return "the server cannot process the request because it is too busy";
    case UA_STATUSCODE_BADTCPMESSAGETYPEINVALID:
	return "the type of the message specified in the header invalid";
    case UA_STATUSCODE_BADTCPSECURECHANNELUNKNOWN:
	return "the SecureChannelId and/or TokenId are not currently in use";
    case UA_STATUSCODE_BADTCPMESSAGETOOLARGE:
	return "the size of the message specified in the header is too large";
    case UA_STATUSCODE_BADTCPNOTENOUGHRESOURCES:
	return "there are not enough resources to process the request";
    case UA_STATUSCODE_BADTCPINTERNALERROR:
	return "an internal error occurred";
    case UA_STATUSCODE_BADTCPENDPOINTURLINVALID:
	return "the Server does not recognize the QueryString specified";
    case UA_STATUSCODE_BADREQUESTINTERRUPTED:
	return "the request could not be sent because of a "
	    "network interruption";
    case UA_STATUSCODE_BADREQUESTTIMEOUT:
	return "timeout occurred while processing the request";
    case UA_STATUSCODE_BADSECURECHANNELCLOSED:
	return "the secure channel has been closed";
    case UA_STATUSCODE_BADSECURECHANNELTOKENUNKNOWN:
	return "the token has expired or is not recognized";
    case UA_STATUSCODE_BADSEQUENCENUMBERINVALID:
	return "the sequence number is not valid";
    case UA_STATUSCODE_BADPROTOCOLVERSIONUNSUPPORTED:
	return "the applications do not have compatible protocol versions";
    case UA_STATUSCODE_BADCONFIGURATIONERROR:
	return "there is a problem with the configuration that "
	    "affects the usefulness of the value";
    case UA_STATUSCODE_BADNOTCONNECTED:
	return "the variable should receive its value from "
	    "another variable, but has never been configured to do so";
    case UA_STATUSCODE_BADDEVICEFAILURE:
	return "there has been a failure in the device/data source "
	    "that generates the value that has affected the value";
    case UA_STATUSCODE_BADSENSORFAILURE:
	return "there has been a failure in the sensor from which "
	    "the value is derived by the device/data source";
    case UA_STATUSCODE_BADOUTOFSERVICE:
	return "the source of the data is not operational";
    case UA_STATUSCODE_BADDEADBANDFILTERINVALID:
	return "the deadband filter is not valid";
    case UA_STATUSCODE_UNCERTAINNOCOMMUNICATIONLASTUSABLEVALUE:
	return "communication to the data source has failed. "
	    "The variable value is the last value that had a good quality";
    case UA_STATUSCODE_UNCERTAINLASTUSABLEVALUE:
	return "Whatever was updating this value has stopped doing so";
    case UA_STATUSCODE_UNCERTAINSUBSTITUTEVALUE:
	return "the value is an operational value that was "
	    "manually overwritten";
    case UA_STATUSCODE_UNCERTAININITIALVALUE:
	return "the value is an initial value for a variable "
	    "that normally receives its value from another variable";
    case UA_STATUSCODE_UNCERTAINSENSORNOTACCURATE:
	return "the value is at one of the sensor limits";
    case UA_STATUSCODE_UNCERTAINENGINEERINGUNITSEXCEEDED:
	return "the value is outside of the range of values "
	    "defined for this parameter";
    case UA_STATUSCODE_UNCERTAINSUBNORMAL:
	return "the value is derived from multiple sources "
	    "and has less than the required number of Good sources";
    case UA_STATUSCODE_GOODLOCALOVERRIDE:
	return "the value has been overridden";
    case UA_STATUSCODE_BADREFRESHINPROGRESS:
	return "this Condition refresh failed, a Condition refresh "
	    "operation is already in progress";
    case UA_STATUSCODE_BADCONDITIONALREADYDISABLED:
	return "this condition has already been disabled";
    case UA_STATUSCODE_BADCONDITIONALREADYENABLED:
	return "this condition has already been enabled";
    case UA_STATUSCODE_BADCONDITIONDISABLED:
	return "property not available, this condition is disabled";
    case UA_STATUSCODE_BADEVENTIDUNKNOWN:
	return "the specified event id is not recognized";
    case UA_STATUSCODE_BADEVENTNOTACKNOWLEDGEABLE:
	return "the event cannot be acknowledged";
    case UA_STATUSCODE_BADDIALOGNOTACTIVE:
	return "the dialog condition is not active";
    case UA_STATUSCODE_BADDIALOGRESPONSEINVALID:
	return "the response is not valid for the dialog";
    case UA_STATUSCODE_BADCONDITIONBRANCHALREADYACKED:
	return "the condition branch has already been acknowledged";
    case UA_STATUSCODE_BADCONDITIONBRANCHALREADYCONFIRMED:
	return "the condition branch has already been confirmed";
    case UA_STATUSCODE_BADCONDITIONALREADYSHELVED:
	return "the condition has already been shelved";
    case UA_STATUSCODE_BADCONDITIONNOTSHELVED:
	return "the condition is not currently shelved";
    case UA_STATUSCODE_BADSHELVINGTIMEOUTOFRANGE:
	return "the shelving time not within an acceptable range";
    case UA_STATUSCODE_BADNODATA:
	return "no data exists for the requested time range or event filter";
    case UA_STATUSCODE_BADBOUNDNOTFOUND:
	return "no data found to provide upper or lower bound value";
    case UA_STATUSCODE_BADBOUNDNOTSUPPORTED:
	return "the server cannot retrieve a bound for the variable";
    case UA_STATUSCODE_BADDATALOST:
	return "data is missing due to collection started/stopped/lost";
    case UA_STATUSCODE_BADDATAUNAVAILABLE:
	return "expected data is unavailable for the requested time "
	    "range due to an un-mounted volume, an off-line archive "
	    "or tape, or similar reason for temporary unavailability";
    case UA_STATUSCODE_BADENTRYEXISTS:
	return "the data or event was not successfully inserted "
	    "because a matching entry exists";
    case UA_STATUSCODE_BADNOENTRYEXISTS:
	return "the data or event was not successfully updated "
	    "because no matching entry exists";
    case UA_STATUSCODE_BADTIMESTAMPNOTSUPPORTED:
	return "the client requested history using a timestamp "
	    "format the server does not support (i.e requested "
	    "ServerTimestamp when server only supports SourceTimestamp)";
    case UA_STATUSCODE_GOODENTRYINSERTED:
	return "the data or event was successfully inserted into "
	    "the historical database";
    case UA_STATUSCODE_GOODENTRYREPLACED:
	return "the data or event field was successfully replaced "
	    "in the historical database";
    case UA_STATUSCODE_UNCERTAINDATASUBNORMAL:
	return "the value is derived from multiple values and has "
	    "less than the required number of Good values";
    case UA_STATUSCODE_GOODNODATA:
	return "no data exists for the requested time range or event filter";
    case UA_STATUSCODE_GOODMOREDATA:
	return "the data or event field was successfully replaced "
	    "in the historical database";
    case UA_STATUSCODE_BADAGGREGATELISTMISMATCH:
	return "the requested number of Aggregates does not match "
	    "the requested number of NodeIds";
    case UA_STATUSCODE_BADAGGREGATENOTSUPPORTED:
	return "the requested Aggregate is not support by the server";
    case UA_STATUSCODE_BADAGGREGATEINVALIDINPUTS:
	return "the aggregate value could not be derived due to "
	    "invalid data inputs";
    case UA_STATUSCODE_BADAGGREGATECONFIGURATIONREJECTED:
	return "the aggregate configuration is not valid for specified node";
    case UA_STATUSCODE_GOODDATAIGNORED:
	return "the request pecifies fields which are not valid for "
	    "the EventType or cannot be saved by the historian";
    case UA_STATUSCODE_BADREQUESTNOTALLOWED:
	return "the request was rejected by the server because it "
	    "did not meet the criteria set by the server";
    case UA_STATUSCODE_GOODEDITED:
	return "the value does not come from the real source and "
	    "has been edited by the server";
    case UA_STATUSCODE_GOODPOSTACTIONFAILED:
	return "there was an error in execution of these post-actions";
    case UA_STATUSCODE_UNCERTAINDOMINANTVALUECHANGED:
	return "the related EngineeringUnit has been changed but the "
	    "Variable Value is still provided based on the previous unit";
    case UA_STATUSCODE_GOODDEPENDENTVALUECHANGED:
	return "a dependent value has been changed but the change "
	    "has not been applied to the device";
    case UA_STATUSCODE_BADDOMINANTVALUECHANGED:
	return "the related EngineeringUnit has been changed but "
	    "this change has not been applied to the device. The "
	    "Variable Value is still dependent on the previous unit "
	    "but its status is currently Bad";
    case UA_STATUSCODE_UNCERTAINDEPENDENTVALUECHANGED:
	return "a dependent value has been changed but the change "
	    "has not been applied to the device. The quality of the "
	    "dominant variable is uncertain";
    case UA_STATUSCODE_BADDEPENDENTVALUECHANGED:
	return "a dependent value has been changed but the change "
	    "has not been applied to the device. The quality of the "
	    "dominant variable is Bad";
    case UA_STATUSCODE_GOODCOMMUNICATIONEVENT:
	return "the communication layer has raised an event";
    case UA_STATUSCODE_GOODSHUTDOWNEVENT:
	return "the system is shutting down";
    case UA_STATUSCODE_GOODCALLAGAIN:
	return "the operation is not finished and needs to be called again";
    case UA_STATUSCODE_GOODNONCRITICALTIMEOUT:
	return "a non-critical timeout occurred";
    case UA_STATUSCODE_BADINVALIDARGUMENT:
	return "one or more arguments are invalid";
    case UA_STATUSCODE_BADCONNECTIONREJECTED:
	return "could not establish a network connection to remote server";
    case UA_STATUSCODE_BADDISCONNECT:
	return "the server has disconnected from the client";
    case UA_STATUSCODE_BADCONNECTIONCLOSED:
	return "the network connection has been closed";
    case UA_STATUSCODE_BADINVALIDSTATE:
	return "the operation cannot be completed because the "
	    "object is closed, uninitialized or in some other invalid state";
    case UA_STATUSCODE_BADENDOFSTREAM:
	return "cannot move beyond end of the stream";
    case UA_STATUSCODE_BADNODATAAVAILABLE:
	return "no data is currently available for reading from "
	    "a non-blocking stream";
    case UA_STATUSCODE_BADWAITINGFORRESPONSE:
	return "the asynchronous operation is waiting for a response";
    case UA_STATUSCODE_BADOPERATIONABANDONED:
	return "the asynchronous operation was abandoned by the caller";
    case UA_STATUSCODE_BADEXPECTEDSTREAMTOBLOCK:
	return "the stream did not return all data requested "
	    "(possibly because it is a non-blocking stream)";
    case UA_STATUSCODE_BADWOULDBLOCK:
	return "non blocking behaviour is required and the "
	    "operation would block";
    case UA_STATUSCODE_BADSYNTAXERROR:
	return "a value had an invalid syntax";
    case UA_STATUSCODE_BADMAXCONNECTIONSREACHED:
	return "the operation could not be finished because "
	    "all available connections are in use";
    }
    sprintf(uacli->msgBuffer, "error code 0x%08x", uaret);
    return uacli->msgBuffer;
}

/*
 *-------------------------------------------------------------------------
 *
 * ReportError --
 *
 *	Given UA_StatusCode leave an error message in interp.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Error message put into interp.
 *
 *-------------------------------------------------------------------------
 */

static void
ReportError(Tcl_Interp *interp, UACLI *uacli, const char *func,
	    UA_StatusCode uaret)
{
    Tcl_Obj *list[4];

    if (func == NULL) {
	uaret = UA_STATUSCODE_BADINTERNALERROR;
    } else {
	Tcl_SetObjResult(interp,
	    Tcl_NewStringObj(StatusCodeToString(uacli, uaret), -1));
    }
    list[0] = Tcl_NewStringObj("topcua", -1);
    list[1] = Tcl_NewStringObj((func == NULL) ? "Internal" : func, -1);
    list[2] = Tcl_NewIntObj((int) uaret);
    list[3] = Tcl_NewStringObj(UA_StatusCode_name(uaret), -1);
    Tcl_SetObjErrorCode(interp, Tcl_NewListObj(4, list));
}

/*
 *-------------------------------------------------------------------------
 *
 * AddRefDescrToList --
 *
 *	Add browse information from a UA_ReferenceDescription struct
 *	to the given browse result list.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The result list is modified.
 *
 *-------------------------------------------------------------------------
 */

static void
AddRefDescrToList(Tcl_Obj *list, UA_ReferenceDescription *ref)
{
    Tcl_DString ds;
    const char *ncl;

    Tcl_ListObjAppendElement(NULL, list,
	Tcl_NewStringObj(PrintNodeId(&ref->nodeId.nodeId, &ds), -1));
    Tcl_DStringFree(&ds);
    Tcl_ListObjAppendElement(NULL, list,
	Tcl_NewStringObj((char *) ref->browseName.name.data,
			 ref->browseName.name.length));
    Tcl_ListObjAppendElement(NULL, list,
	Tcl_NewStringObj((char *) ref->displayName.text.data,
			 ref->displayName.text.length));
    switch (ref->nodeClass) {
    case UA_NODECLASS_UNSPECIFIED:
	ncl = "Unspecified";
	break;
    case UA_NODECLASS_OBJECT:
	ncl = "Object";
	break;
    case UA_NODECLASS_VARIABLE:
	ncl = "Variable";
	break;
    case UA_NODECLASS_METHOD:
	ncl = "Method";
	break;
    case UA_NODECLASS_OBJECTTYPE:
	ncl = "ObjectType";
	break;
    case UA_NODECLASS_VARIABLETYPE:
	ncl = "VariableType";
	break;
    case UA_NODECLASS_REFERENCETYPE:
	ncl = "ReferenceType";
	break;
    case UA_NODECLASS_DATATYPE:
	ncl = "DataType";
	break;
    case UA_NODECLASS_VIEW:
	ncl = "View";
	break;
    default:
	ncl = "Unknown";
	break;
    }
    Tcl_ListObjAppendElement(NULL, list, Tcl_NewStringObj(ncl, -1));
    Tcl_ListObjAppendElement(NULL, list,
	Tcl_NewStringObj(PrintNodeId(&ref->referenceTypeId, &ds), -1));
    Tcl_DStringFree(&ds);
    Tcl_ListObjAppendElement(NULL, list,
	Tcl_NewStringObj(PrintNodeId(&ref->typeDefinition.nodeId, &ds), -1));
    Tcl_DStringFree(&ds);
}

/*
 *-------------------------------------------------------------------------
 *
 * SubNamespaceDeleted --
 *
 *	Destructor of "::opcua::*" namespace.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Cleanup takes place.
 *
 *-------------------------------------------------------------------------
 */

static void
SubNamespaceDeleted(ClientData clientData)
{
    UACL *uacl = (UACL *) clientData;

    uacl->nsPtr = NULL;
}

/*
 *-------------------------------------------------------------------------
 *
 * NamespaceDeleted --
 *
 *	Destructor of "::opcua" namespace.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	All connections and resources are released.
 *
 *-------------------------------------------------------------------------
 */

static void
NamespaceDeleted(ClientData clientData)
{
    UACLI *uacli = (UACLI *) clientData;
    Tcl_HashEntry *hPtr;
    Tcl_HashSearch search;
    UACL *uacl;

    hPtr = Tcl_FirstHashEntry(&uacli->clients, &search);
    while (hPtr != NULL) {
	uacl = (UACL *) Tcl_GetHashValue(hPtr);
	if (uacl->connected) {
	    UA_Client_disconnect(uacl->client);
	}
	UA_Client_delete(uacl->client);
	ckfree((char *) uacl);
	hPtr = Tcl_NextHashEntry(&search);
    }
    Tcl_DeleteHashTable(&uacli->clients);
    Tcl_DeleteHashTable(&uacli->types);
    ckfree((char *) uacli);
}

/*
 *-------------------------------------------------------------------------
 *
 * EndpointsObjCmd --
 *
 *	Implementation of the "::opcua::endpoints" Tcl command.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *-------------------------------------------------------------------------
 */

static int
EndpointsObjCmd(ClientData clientData, Tcl_Interp *interp,
		int objc, Tcl_Obj * const objv[])
{
    UACLI *uacli = (UACLI *) clientData;
    UA_StatusCode uaret;
    UA_EndpointDescription *eps = NULL;
    size_t i, epsize = 0;
    UA_Client *cl;
    Tcl_Obj *list;

    if (objc > 2) {
	Tcl_WrongNumArgs(interp, 1, objv, "?url?");
	return TCL_ERROR;
    }
    cl = UA_Client_new(uacli->clcfg);
    if (cl == NULL) {
	Tcl_SetResult(interp, "unable to create client", TCL_STATIC);
	ReportError(interp, uacli, NULL, 0);
	return TCL_ERROR;
    }
    uaret = UA_Client_getEndpoints(cl, (objc > 1) ?
				   Tcl_GetString(objv[1]) :
				   "opc.tcp://localhost:4840",
				   &epsize, &eps);
    if (uaret != UA_STATUSCODE_GOOD) {
	UA_Array_delete(eps, epsize,
			&UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]);
	UA_Client_delete(cl);
	ReportError(interp, uacli, "GetEndpoints", uaret);
	return TCL_ERROR;
    }
    list = Tcl_NewListObj(epsize, NULL);
    for (i = 0; i < epsize; i++) {
	Tcl_ListObjAppendElement(NULL, list,
	    Tcl_NewStringObj((char *)eps[i].endpointUrl.data,
			     eps[i].endpointUrl.length));
    }
    UA_Array_delete(eps, epsize,
		    &UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]);
    UA_Client_delete(cl);
    Tcl_SetObjResult(interp, list);
    return TCL_OK;
}

/*
 *-------------------------------------------------------------------------
 *
 * ServersObjCmd --
 *
 *	Implementation of the "::opcua::servers" Tcl command.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *-------------------------------------------------------------------------
 */

static int
ServersObjCmd(ClientData clientData, Tcl_Interp *interp,
	      int objc, Tcl_Obj * const objv[])
{
    UACLI *uacli = (UACLI *) clientData;
    UA_StatusCode uaret;
    UA_ServerOnNetwork *son = NULL;
    size_t i, j, sonsize = 0;
    UA_Client *cl;
    Tcl_Obj *list;

    if (objc > 2) {
	Tcl_WrongNumArgs(interp, 1, objv, "?url?");
	return TCL_ERROR;
    }
    cl = UA_Client_new(uacli->clcfg);
    if (cl == NULL) {
	Tcl_SetResult(interp, "unable to create client", TCL_STATIC);
	ReportError(interp, uacli, NULL, 0);
	return TCL_ERROR;
    }
    uaret = UA_Client_findServersOnNetwork(cl, (objc > 1) ?
					   Tcl_GetString(objv[1]) :
					   "opc.tcp://localhost:4840",
					   0, 0, 0, NULL, &sonsize, &son);
    if (uaret != UA_STATUSCODE_GOOD) {
	UA_Array_delete(son, sonsize,
			&UA_TYPES[UA_TYPES_SERVERONNETWORK]);
	UA_Client_delete(cl);
	ReportError(interp, uacli, "FindServersOnNetwork", uaret);
	return TCL_ERROR;
    }
    list = Tcl_NewListObj(sonsize * 3, NULL);
    for (i = 0; i < sonsize; i++) {
	Tcl_Obj *caps = Tcl_NewListObj(son[i].serverCapabilitiesSize, NULL);

	Tcl_ListObjAppendElement(NULL, list,
	    Tcl_NewStringObj((char *)son[i].serverName.data,
			     son[i].serverName.length));
	Tcl_ListObjAppendElement(NULL, list,
	    Tcl_NewStringObj((char *)son[i].discoveryUrl.data,
			     son[i].discoveryUrl.length));
	for (j = 0; j < son[i].serverCapabilitiesSize; j++) {
	    Tcl_ListObjAppendElement(NULL, caps,
		Tcl_NewStringObj((char *)son[i].serverCapabilities[j].data,
				 son[i].serverCapabilities[j].length));
	}
	Tcl_ListObjAppendElement(NULL, list, caps);
    }
    UA_Array_delete(son, sonsize,
		    &UA_TYPES[UA_TYPES_SERVERONNETWORK]);
    UA_Client_delete(cl);
    Tcl_SetObjResult(interp, list);
    return TCL_OK;
}

/*
 *-------------------------------------------------------------------------
 *
 * NewObjCmd --
 *
 *	Implementation of the "::opcua::new" Tcl command.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *-------------------------------------------------------------------------
 */

static int
NewObjCmd(ClientData clientData, Tcl_Interp *interp,
	  int objc, Tcl_Obj * const objv[])
{
    UACLI *uacli = (UACLI *) clientData;
    UACL *uacl;
    UA_Client *cl;
    Tcl_HashEntry *hPtr = NULL;
    int new;
    char *pname, name[16];
    Tcl_DString ds;

    if (objc > 2) {
	Tcl_WrongNumArgs(interp, 1, objv, "?name?");
	return TCL_ERROR;
    }
    if (objc > 1) {
	hPtr = Tcl_CreateHashEntry(&uacli->clients,
				   Tcl_GetString(objv[1]), &new);
	if (!new) {
	    Tcl_SetResult(interp, "name already in use", TCL_STATIC);
	    ReportError(interp, uacli, NULL, 0);
	    return TCL_ERROR;
	}
    }
    cl = UA_Client_new(uacli->clcfg);
    if (cl == NULL) {
	Tcl_DeleteHashEntry(hPtr);
	Tcl_SetResult(interp, "unable to create client", TCL_STATIC);
	ReportError(interp, uacli, NULL, 0);
	return TCL_ERROR;
    }
    uacl = (UACL *) ckalloc(sizeof(UACL));
    uacl->connected = 0;
    uacl->client = cl;
    if (hPtr == NULL) {
	sprintf(name, "ua%d", uacli->idCount++);
	hPtr = Tcl_CreateHashEntry(&uacli->clients, name, &new);
	if (!new) {
	    UACL *oldcl = (UACL *) Tcl_GetHashValue(hPtr);

	    if (oldcl->connected) {
		UA_Client_disconnect(oldcl->client);
	    }
	    UA_Client_delete(oldcl->client);
	    if (oldcl->nsPtr != NULL) {
		Tcl_DeleteNamespace(oldcl->nsPtr);
	    }
	    ckfree((char *) oldcl);
	}
    }
    Tcl_SetHashValue(hPtr, (ClientData) uacl);
    pname = Tcl_GetHashKey(&uacli->clients, hPtr);
    Tcl_DStringInit(&ds);
    Tcl_DStringAppend(&ds, "::opcua::", -1);
    Tcl_DStringAppend(&ds, pname, -1);
    uacl->nsPtr = Tcl_CreateNamespace(interp, Tcl_DStringValue(&ds),
				      (ClientData) uacl, SubNamespaceDeleted);
    Tcl_DStringFree(&ds);
    Tcl_SetObjResult(interp, Tcl_NewStringObj(pname, -1));
    return TCL_OK;
}

/*
 *-------------------------------------------------------------------------
 *
 * DestroyObjCmd --
 *
 *	Implementation of the "::opcua::destroy" Tcl command.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *-------------------------------------------------------------------------
 */

static int
DestroyObjCmd(ClientData clientData, Tcl_Interp *interp,
	      int objc, Tcl_Obj * const objv[])
{
    UACLI *uacli = (UACLI *) clientData;
    UACL *uacl;
    Tcl_HashEntry *hPtr;

    if (objc != 2) {
	Tcl_WrongNumArgs(interp, 1, objv, "clientid");
	return TCL_ERROR;
    }
    hPtr = Tcl_FindHashEntry(&uacli->clients, Tcl_GetString(objv[1]));
    if (hPtr != NULL) {
	uacl = (UACL *) Tcl_GetHashValue(hPtr);
	if (uacl->connected) {
	    UA_Client_disconnect(uacl->client);
	    uacl->connected = 0;
	}
	UA_Client_delete(uacl->client);
	Tcl_DeleteHashEntry(hPtr);
	if (uacl->nsPtr != NULL) {
	    Tcl_DeleteNamespace(uacl->nsPtr);
	}
	ckfree((char *) uacl);
    } else {
	Tcl_SetResult(interp, "clientid not found", TCL_STATIC);
	ReportError(interp, uacli, NULL, 0);
	return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *-------------------------------------------------------------------------
 *
 * ConnectObjCmd --
 *
 *	Implementation of the "::opcua::connect" Tcl command.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *-------------------------------------------------------------------------
 */

static int
ConnectObjCmd(ClientData clientData, Tcl_Interp *interp,
	      int objc, Tcl_Obj * const objv[])
{
    UACLI *uacli = (UACLI *) clientData;
    UACL *uacl;
    Tcl_HashEntry *hPtr;
    UA_StatusCode uaret;

    if ((objc != 3) && (objc != 5)) {
	Tcl_WrongNumArgs(interp, 1, objv, "clientid url ?user password?");
	return TCL_ERROR;
    }
    hPtr = Tcl_FindHashEntry(&uacli->clients, Tcl_GetString(objv[1]));
    if (hPtr != NULL) {
	uacl = (UACL *) Tcl_GetHashValue(hPtr);
	if (uacl->connected) {
	    UA_Client_disconnect(uacl->client);
	    uacl->connected = 0;
	}
    } else {
	Tcl_SetResult(interp, "clientid not found", TCL_STATIC);
	ReportError(interp, uacli, NULL, 0);
	return TCL_ERROR;
    }
    if (objc == 3) {
	uaret = UA_Client_connect(uacl->client, Tcl_GetString(objv[2]));
    } else {
	uaret = UA_Client_connect_username(uacl->client,
					   Tcl_GetString(objv[2]),
					   Tcl_GetString(objv[3]),
					   Tcl_GetString(objv[4]));
    }
    if (uaret != UA_STATUSCODE_GOOD) {
	ReportError(interp, uacli, "ClientConnect", uaret);
	return TCL_ERROR;
    }
    uacl->connected = 1;
    return TCL_OK;
}

/*
 *-------------------------------------------------------------------------
 *
 * DisconnectObjCmd --
 *
 *	Implementation of the "::opcua::disconnect" Tcl command.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *-------------------------------------------------------------------------
 */

static int
DisconnectObjCmd(ClientData clientData, Tcl_Interp *interp,
		 int objc, Tcl_Obj * const objv[])
{
    UACLI *uacli = (UACLI *) clientData;
    UACL *uacl;
    Tcl_HashEntry *hPtr;

    if (objc != 2) {
	Tcl_WrongNumArgs(interp, 1, objv, "clientid");
	return TCL_ERROR;
    }
    hPtr = Tcl_FindHashEntry(&uacli->clients, Tcl_GetString(objv[1]));
    if (hPtr != NULL) {
	uacl = (UACL *) Tcl_GetHashValue(hPtr);
	if (uacl->connected) {
	    UA_Client_disconnect(uacl->client);
	    uacl->connected = 0;
	}
    } else {
	Tcl_SetResult(interp, "clientid not found", TCL_STATIC);
	ReportError(interp, uacli, NULL, 0);
	return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *-------------------------------------------------------------------------
 *
 * InfoObjCmd --
 *
 *	Implementation of the "::opcua::info" Tcl command.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *-------------------------------------------------------------------------
 */

static int
InfoObjCmd(ClientData clientData, Tcl_Interp *interp,
	   int objc, Tcl_Obj * const objv[])
{
    UACLI *uacli = (UACLI *) clientData;
    Tcl_HashEntry *hPtr;
    Tcl_HashSearch search;
    Tcl_Obj *list;

    if (objc != 1) {
	Tcl_WrongNumArgs(interp, 1, objv, NULL);
	return TCL_ERROR;
    }
    list = Tcl_NewListObj(0, NULL);
    hPtr = Tcl_FirstHashEntry(&uacli->clients, &search);
    while (hPtr != NULL) {
	char *name = Tcl_GetHashKey(&uacli->clients, hPtr);

	Tcl_ListObjAppendElement(NULL, list,
				 Tcl_NewStringObj(name, -1));
	hPtr = Tcl_NextHashEntry(&search);
    }
    Tcl_SetObjResult(interp, list);
    return TCL_OK;
}

/*
 *-------------------------------------------------------------------------
 *
 * Sc2StrObjCmd --
 *
 *	Implementation of the "::opcua::sc2str" Tcl command.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *-------------------------------------------------------------------------
 */

static int
Sc2StrObjCmd(ClientData clientData, Tcl_Interp *interp,
	     int objc, Tcl_Obj * const objv[])
{
    UACLI *uacli = (UACLI *) clientData;
    int sc;

    if (objc != 2) {
	Tcl_WrongNumArgs(interp, 1, objv, "statuscode");
	return TCL_ERROR;
    }
    if (Tcl_GetIntFromObj(interp, objv[1], &sc) != TCL_OK) {
	return TCL_ERROR;
    }
    Tcl_SetObjResult(interp,
	Tcl_NewStringObj(StatusCodeToString(uacli, (UA_StatusCode) sc), -1));
    return TCL_OK;
}

/*
 *-------------------------------------------------------------------------
 *
 * BrowseObjCmd --
 *
 *	Implementation of the "::opcua::browse" Tcl command.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *-------------------------------------------------------------------------
 */

static int
BrowseObjCmd(ClientData clientData, Tcl_Interp *interp,
	     int objc, Tcl_Obj * const objv[])
{
    UACLI *uacli = (UACLI *) clientData;
    UACL *uacl;
    Tcl_HashEntry *hPtr;
    UA_BrowseRequest brq;
    UA_BrowseResponse br;
    UA_ByteString cp = UA_BYTESTRING_NULL;
    UA_NodeId nodeid, refid;
    int dir = UA_BROWSEDIRECTION_FORWARD, ncls = UA_NODECLASS_UNSPECIFIED;
    size_t i, j;
    Tcl_Obj *list;

    /* Align with UA_BrowseDirection. */
    static const char *dirNames[] = {
	"Forward", "Inverse", "Both", NULL
    };

    if (objc < 3) {
	Tcl_WrongNumArgs(interp, 1, objv,
			 "clientid nodeid ?dir refid mask ...?");
	return TCL_ERROR;
    }
    hPtr = Tcl_FindHashEntry(&uacli->clients, Tcl_GetString(objv[1]));
    if (hPtr != NULL) {
	uacl = (UACL *) Tcl_GetHashValue(hPtr);
    } else {
	Tcl_SetResult(interp, "clientid not found", TCL_STATIC);
	ReportError(interp, uacli, NULL, 0);
	return TCL_ERROR;
    }
    if (ParseNodeId(interp, &nodeid, Tcl_GetString(objv[2])) == NULL) {
	return TCL_ERROR;
    }
    if ((objc > 3) && (Tcl_GetIndexFromObj(interp, objv[3], dirNames, "dir",
					   0, &dir) != TCL_OK)) {
	UA_NodeId_deleteMembers(&nodeid);
	return TCL_ERROR;
    }
    refid = UA_NODEID_NULL;
    if (objc > 4) {
	char *ref = Tcl_GetString(objv[4]);

	if ((ref[0] != '\0') && (ParseNodeId(interp, &refid, ref) == NULL)) {
	    UA_NodeId_deleteMembers(&nodeid);
	    return TCL_ERROR;
	}
    }
    for (i = 5; i < objc; i++) {
	char *mask = Tcl_GetString(objv[i]);

	if (strcmp(mask, "Object") == 0) {
	    ncls |= UA_NODECLASS_OBJECT;
	} else if (strcmp(mask, "Variable") == 0) {
	    ncls |= UA_NODECLASS_VARIABLE;
	} else if (strcmp(mask, "Method") == 0) {
	    ncls |= UA_NODECLASS_METHOD;
	} else if (strcmp(mask, "ObjectType") == 0) {
	    ncls |= UA_NODECLASS_OBJECTTYPE;
	} else if (strcmp(mask, "VariableType") == 0) {
	    ncls |=  UA_NODECLASS_VARIABLETYPE;
	} else if (strcmp(mask, "ReferenceType") == 0) {
	    ncls |= UA_NODECLASS_REFERENCETYPE;
	} else if (strcmp(mask, "DataType") == 0) {
	    ncls |= UA_NODECLASS_DATATYPE;
	} else if (strcmp(mask, "View") == 0) {
	    ncls |= UA_NODECLASS_VIEW;
	} else {
	    Tcl_SetResult(interp, "invalid mask", TCL_STATIC);
	    ReportError(interp, uacli, NULL, 0);
	    UA_NodeId_deleteMembers(&nodeid);
	    UA_NodeId_deleteMembers(&refid);
	    return TCL_ERROR;
	}
    }
    UA_BrowseRequest_init(&brq);
    brq.requestedMaxReferencesPerNode = 0;
    brq.nodesToBrowse = UA_BrowseDescription_new();
    brq.nodesToBrowseSize = 1;
    brq.nodesToBrowse[0].nodeId = nodeid;
    brq.nodesToBrowse[0].resultMask = UA_BROWSERESULTMASK_ALL;
    brq.nodesToBrowse[0].browseDirection = dir;
    brq.nodesToBrowse[0].referenceTypeId = refid;
    brq.nodesToBrowse[0].nodeClassMask = ncls;
    brq.nodesToBrowse[0].includeSubtypes = UA_TRUE;
    br = UA_Client_Service_browse(uacl->client, brq);
    list = Tcl_NewListObj(0, NULL);
    for (i = 0; i < br.resultsSize; i++) {
	for (j = 0; j < br.results[i].referencesSize; j++) {
	    AddRefDescrToList(list, &br.results[i].references[j]);
	}
    }
    if (br.resultsSize > 0) {
	cp = br.results[0].continuationPoint;
	br.results[0].continuationPoint = UA_BYTESTRING_NULL;
    }
    UA_BrowseRequest_deleteMembers(&brq);
    UA_BrowseResponse_deleteMembers(&br);
    while (cp.length > 0) {
	UA_BrowseNextRequest bnrq;
	UA_BrowseNextResponse bnr;

	UA_BrowseNextRequest_init(&bnrq);
	bnrq.releaseContinuationPoints = UA_FALSE;
	bnrq.continuationPointsSize = 1;
	bnrq.continuationPoints = &cp;
	bnr = UA_Client_Service_browseNext(uacl->client, bnrq);
	for (i = 0; i < bnr.resultsSize; i++) {
	    for (j = 0; j < bnr.results[i].referencesSize; j++) {
		AddRefDescrToList(list, &bnr.results[i].references[j]);
	    }
	}
	UA_ByteString_deleteMembers(&cp);
	cp = UA_BYTESTRING_NULL;
	if (bnr.resultsSize > 0) {
	    cp = bnr.results[0].continuationPoint;
	    bnr.results[0].continuationPoint = UA_BYTESTRING_NULL;
	}
	UA_BrowseNextRequest_deleteMembers(&bnrq);
	UA_BrowseNextResponse_deleteMembers(&bnr);
    }
    UA_ByteString_deleteMembers(&cp);
    Tcl_SetObjResult(interp, list);
    return TCL_OK;
}

/*
 *-------------------------------------------------------------------------
 *
 * TranslateObjCmd --
 *
 *	Implementation of the "::opcua::translate" Tcl command.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *-------------------------------------------------------------------------
 */

static int
TranslateObjCmd(ClientData clientData, Tcl_Interp *interp,
		int objc, Tcl_Obj * const objv[])
{
    UACLI *uacli = (UACLI *) clientData;
    UACL *uacl;
    Tcl_HashEntry *hPtr;
    UA_BrowsePath bp;
    UA_TranslateBrowsePathsToNodeIdsRequest bprq;
    UA_TranslateBrowsePathsToNodeIdsResponse bpr;
    UA_NodeId nodeid;
    UA_StatusCode uaret;
    char *id;
    int count;
    size_t i;

    if ((objc < 5) || (objc % 2 == 0)) {
	Tcl_WrongNumArgs(interp, 1, objv, "clientid nodeid target reftype ...");
	return TCL_ERROR;
    }
    hPtr = Tcl_FindHashEntry(&uacli->clients, Tcl_GetString(objv[1]));
    if (hPtr != NULL) {
	uacl = (UACL *) Tcl_GetHashValue(hPtr);
    } else {
	Tcl_SetResult(interp, "clientid not found", TCL_STATIC);
	ReportError(interp, uacli, NULL, 0);
	return TCL_ERROR;
    }
    if (ParseNodeId(interp, &nodeid, Tcl_GetString(objv[2])) == NULL) {
	return TCL_ERROR;
    }
    count = (objc - 3) / 2;
    UA_BrowsePath_init(&bp);
    bp.startingNode = nodeid;
    bp.relativePath.elements = (UA_RelativePathElement *)
	UA_Array_new(count, &UA_TYPES[UA_TYPES_RELATIVEPATHELEMENT]);
    bp.relativePath.elementsSize = count;
    for (i = 0; i < count; i++) {
        UA_RelativePathElement *elem = &bp.relativePath.elements[i];

	elem->includeSubtypes = UA_TRUE;
	if (ParseQualifiedName(interp, &elem->targetName,
			       Tcl_GetString(objv[i * 2 + 3])) == NULL) {
	    UA_BrowsePath_deleteMembers(&bp);
	    return TCL_ERROR;
	}
	id = Tcl_GetString(objv[i * 2 + 4]);
	elem->isInverse = (id[0] == '!') ? UA_TRUE : UA_FALSE;
	if (elem->isInverse) {
	    id++;
	}
	if (ParseNodeId(interp, &elem->referenceTypeId, id) == NULL) {
	    UA_BrowsePath_deleteMembers(&bp);
	    return TCL_ERROR;
	}
    }
    UA_TranslateBrowsePathsToNodeIdsRequest_init(&bprq);
    bprq.browsePaths = &bp;
    bprq.browsePathsSize = 1;
    bpr = UA_Client_Service_translateBrowsePathsToNodeIds(uacl->client, bprq);
    uaret = bpr.responseHeader.serviceResult;
    if (uaret != UA_STATUSCODE_GOOD) {
notGood:
	UA_BrowsePath_deleteMembers(&bp);
	UA_TranslateBrowsePathsToNodeIdsResponse_deleteMembers(&bpr);
	ReportError(interp, uacli, "TranslateBrowsePathsToNodeIds", uaret);
	return TCL_ERROR;
    }
    /* Should have zero or one results. */
    if (bpr.resultsSize > 0) {
	UA_BrowsePathResult *r = &bpr.results[0];
	Tcl_Obj *list;

	if (r->statusCode != UA_STATUSCODE_GOOD) {
	    uaret = r->statusCode;
	    goto notGood;
	}
	list = Tcl_NewListObj(0, NULL);
	for (i = 0; i < r->targetsSize; i++) {
	    UA_ExpandedNodeId *e = &r->targets[i].targetId;
	    Tcl_DString ds;
	    char *p;

	    p = PrintNodeId(&e->nodeId, &ds);
	    Tcl_ListObjAppendElement(NULL, list, Tcl_NewStringObj(p, -1));
	    Tcl_DStringFree(&ds);
	    Tcl_ListObjAppendElement(NULL, list,
		Tcl_NewStringObj((char *) e->namespaceUri.data,
				 e->namespaceUri.length));
	    Tcl_ListObjAppendElement(NULL, list, Tcl_NewIntObj(e->serverIndex));
	}
	Tcl_SetObjResult(interp, list);
    }
    UA_BrowsePath_deleteMembers(&bp);
    UA_TranslateBrowsePathsToNodeIdsResponse_deleteMembers(&bpr);
    return TCL_OK;
}

/*
 *-------------------------------------------------------------------------
 *
 * AttrsObjCmd --
 *
 *	Implementation of the "::opcua::attrs" Tcl command.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *-------------------------------------------------------------------------
 */

static int
AttrsObjCmd(ClientData clientData, Tcl_Interp *interp,
	    int objc, Tcl_Obj * const objv[])
{
    Tcl_Obj *list;
    const char **p;

    if (objc != 1) {
	Tcl_WrongNumArgs(interp, 1, objv, NULL);
	return TCL_ERROR;
    }
    list = Tcl_NewListObj(0, NULL);
    p = attrNames;
    while (*p != NULL) {
	Tcl_ListObjAppendElement(NULL, list, Tcl_NewStringObj(*p, -1));
	++p;
    }
    Tcl_SetObjResult(interp, list);
    return TCL_OK;
}

/*
 *-------------------------------------------------------------------------
 *
 * TypesObjCmd --
 *
 *	Implementation of the "::opcua::types" Tcl command.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *-------------------------------------------------------------------------
 */

static int
TypesObjCmd(ClientData clientData, Tcl_Interp *interp,
	    int objc, Tcl_Obj * const objv[])
{
    UACLI *uacli = (UACLI *) clientData;
    Tcl_HashEntry *hPtr;

    if (objc > 2) {
	Tcl_WrongNumArgs(interp, 1, objv, "?name?");
	return TCL_ERROR;
    }
    if (objc == 2) {
	UA_DataType *type;
	Tcl_DString ds;
	char *p;

	hPtr = Tcl_FindHashEntry(&uacli->types, Tcl_GetString(objv[1]));
	if (hPtr == NULL) {
	    Tcl_SetResult(interp, "unknown type", TCL_STATIC);
	    ReportError(interp, uacli, NULL, 0);
	    return TCL_ERROR;
	}
	type = (UA_DataType *) Tcl_GetHashValue(hPtr);
	p = PrintNodeId(&type->typeId, &ds);
	Tcl_SetObjResult(interp, Tcl_NewStringObj(p, -1));
	Tcl_DStringFree(&ds);
    } else {
	Tcl_Obj *list = Tcl_NewListObj(0, NULL);
	Tcl_HashSearch search;

	hPtr = Tcl_FirstHashEntry(&uacli->types, &search);
	while (hPtr != NULL) {
	    Tcl_ListObjAppendElement(NULL, list,
		Tcl_NewStringObj(Tcl_GetHashKey(&uacli->types, hPtr), -1));
	    hPtr = Tcl_NextHashEntry(&search);
	}
	Tcl_SetObjResult(interp, list);
    }
    return TCL_OK;
}

/*
 *-------------------------------------------------------------------------
 *
 * RefTypeObjCmd --
 *
 *	Implementation of the "::opcua::reftype" Tcl command.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *-------------------------------------------------------------------------
 */

static int
RefTypeObjCmd(ClientData clientData, Tcl_Interp *interp,
	      int objc, Tcl_Obj * const objv[])
{
    UACLI *uacli = (UACLI *) clientData;
    int i;

    if (objc > 2) {
	Tcl_WrongNumArgs(interp, 1, objv, "?name?");
	return TCL_ERROR;
    }
    if (objc == 2) {
	const char *name = Tcl_GetString(objv[1]);
	char buffer[16];

	for (i = 0; i < sizeof(refTypes) / sizeof(refTypes[0]); i++) {
	    if (strcmp(name, refTypes[i].name) == 0) {
		break;
	    }
	}
	if (i >= sizeof(refTypes) / sizeof(refTypes[0])) {
	    Tcl_SetResult(interp, "not a reftype", TCL_STATIC);
	    ReportError(interp, uacli, NULL, 0);
	    return TCL_ERROR;
	}
	sprintf(buffer, "i=%d", refTypes[i].ns0id);
	Tcl_SetObjResult(interp, Tcl_NewStringObj(buffer, -1));
    } else {
	Tcl_Obj *list =
	    Tcl_NewListObj(sizeof(refTypes) / sizeof(refTypes[0]), NULL);

	for (i = 0; i < sizeof(refTypes) / sizeof(refTypes[0]); i++) {
	    Tcl_ListObjAppendElement(NULL, list,
		Tcl_NewStringObj(refTypes[i].name, -1));
	}
	Tcl_SetObjResult(interp, list);
    }
    return TCL_OK;
}

/*
 *-------------------------------------------------------------------------
 *
 * ReadTypeObjCmd --
 *
 *	Common code for the "::opcua::read" and "::opcua:type" Tcl commands.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *-------------------------------------------------------------------------
 */

static int
ReadTypeObjCmd(ClientData clientData, Tcl_Interp *interp, int isType,
	       int objc, Tcl_Obj * const objv[])
{
    UACLI *uacli = (UACLI *) clientData;
    UACL *uacl;
    Tcl_HashEntry *hPtr;
    UA_StatusCode uaret;
    UA_NodeId nodeid;
    UA_Variant value;
    int attr;

    if ((objc < 3) || (objc > 4)) {
	Tcl_WrongNumArgs(interp, 1, objv, "clientid nodeid ?attr?");
	return TCL_ERROR;
    }
    hPtr = Tcl_FindHashEntry(&uacli->clients, Tcl_GetString(objv[1]));
    if (hPtr != NULL) {
	uacl = (UACL *) Tcl_GetHashValue(hPtr);
    } else {
	Tcl_SetResult(interp, "clientid not found", TCL_STATIC);
	ReportError(interp, uacli, NULL, 0);
	return TCL_ERROR;
    }
    if (ParseNodeId(interp, &nodeid, Tcl_GetString(objv[2])) == NULL) {
	return TCL_ERROR;
    }
    if (objc > 3) {
	if (Tcl_GetIndexFromObj(interp, objv[3], attrNames, "attr", 0,
				&attr) != TCL_OK) {
	    return TCL_ERROR;
	}
	/* UA_AttributeId is 1-based */
	attr += 1;
    } else {
	/* By default, read the "value" attribute. */
	attr = UA_ATTRIBUTEID_VALUE;
    }
    UA_Variant_init(&value);
    uaret = __UA_Client_readAttribute(uacl->client, &nodeid,
				      (UA_AttributeId) attr, &value,
				      &UA_TYPES[UA_TYPES_VARIANT]);
    UA_NodeId_deleteMembers(&nodeid);
    if (uaret != UA_STATUSCODE_GOOD) {
	UA_Variant_deleteMembers(&value);
	ReportError(interp, uacli, "ReadAttribute", uaret);
	return TCL_ERROR;
    }
    if (isType) {
	if (value.type != NULL) {
	    Tcl_SetObjResult(interp,
		Tcl_NewStringObj(value.type->typeName, -1));
	}
    } else if (!UA_Variant_isEmpty(&value)) {
	if (UA_Variant_isScalar(&value)) {
	    if (value.type == &UA_TYPES[UA_TYPES_BOOLEAN]) {
		int *v = (int *) value.data;

		Tcl_SetObjResult(interp, Tcl_NewIntObj(*v ? 1 : 0));
	    } else if (value.type == &UA_TYPES[UA_TYPES_SBYTE]) {
		Tcl_SetObjResult(interp,
		    Tcl_NewIntObj(((signed char *) value.data)[0]));
	    } else if (value.type == &UA_TYPES[UA_TYPES_BYTE]) {
		Tcl_SetObjResult(interp,
		    Tcl_NewIntObj(((unsigned char *) value.data)[0]));
	    } else if (value.type == &UA_TYPES[UA_TYPES_INT16]) {
		Tcl_SetObjResult(interp,
		    Tcl_NewIntObj(((signed short *) value.data)[0]));
	    } else if (value.type == &UA_TYPES[UA_TYPES_UINT16]) {
		Tcl_SetObjResult(interp,
		    Tcl_NewIntObj(((unsigned short *) value.data)[0]));
	    } else if (value.type == &UA_TYPES[UA_TYPES_INT32]) {
		Tcl_SetObjResult(interp,
		    Tcl_NewIntObj(((signed int *) value.data)[0]));
	    } else if (value.type == &UA_TYPES[UA_TYPES_UINT32]) {
		Tcl_SetObjResult(interp,
		    Tcl_NewWideIntObj(((unsigned int *) value.data)[0]));
	    } else if (value.type == &UA_TYPES[UA_TYPES_INT64]) {
		Tcl_SetObjResult(interp,
		    Tcl_NewWideIntObj(((Tcl_WideInt *) value.data)[0]));
	    } else if (value.type == &UA_TYPES[UA_TYPES_UINT64]) {
		Tcl_SetObjResult(interp,
		    Tcl_NewWideIntObj(((Tcl_WideInt *) value.data)[0]));
	    } else if (value.type == &UA_TYPES[UA_TYPES_FLOAT]) {
		Tcl_SetObjResult(interp,
		    Tcl_NewDoubleObj(((float *) value.data)[0]));
	    } else if (value.type == &UA_TYPES[UA_TYPES_DOUBLE]) {
		Tcl_SetObjResult(interp,
		    Tcl_NewDoubleObj(((double *) value.data)[0]));
	    } else if (value.type == &UA_TYPES[UA_TYPES_STRING]) {
		UA_String *v = (UA_String *) value.data;

		Tcl_SetObjResult(interp,
		    Tcl_NewStringObj((char *) v->data, v->length));
	    } else if (value.type == &UA_TYPES[UA_TYPES_DATETIME]) {
		UA_DateTime t = ((UA_DateTime *) value.data)[0];

		Tcl_SetObjResult(interp,
		    Tcl_NewWideIntObj((Tcl_WideInt) t));
	    } else if (value.type == &UA_TYPES[UA_TYPES_GUID]) {
		UA_Guid *v = (UA_Guid *) value.data;
		char buffer[64];

		sprintf(buffer,
			"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
			v->data1, v->data2, v->data3,
			v->data4[0], v->data4[1],
			v->data4[2], v->data4[3],
			v->data4[4], v->data4[5],
			v->data4[6], v->data4[7]);
		Tcl_SetObjResult(interp, Tcl_NewStringObj(buffer, -1));
	    } else if (value.type == &UA_TYPES[UA_TYPES_BYTESTRING]) {
		UA_ByteString *v = (UA_ByteString *) value.data;

		Tcl_SetObjResult(interp,
		    Tcl_NewByteArrayObj(v->data, v->length));
	    } else if (value.type == &UA_TYPES[UA_TYPES_XMLELEMENT]) {
		UA_String *v = (UA_String *) value.data;

		Tcl_SetObjResult(interp,
		    Tcl_NewStringObj((char *) v->data, v->length));
	    } else if (value.type == &UA_TYPES[UA_TYPES_NODEID]) {
		UA_NodeId *v = (UA_NodeId *) value.data;
		Tcl_DString ds;

		Tcl_SetObjResult(interp,
		    Tcl_NewStringObj(PrintNodeId(v, &ds), -1));
		Tcl_DStringFree(&ds);
	    } else if (value.type == &UA_TYPES[UA_TYPES_EXPANDEDNODEID]) {
		UA_ExpandedNodeId *v = (UA_ExpandedNodeId *) value.data;
		Tcl_DString ds;
		Tcl_Obj *list[3];

		list[0] = Tcl_NewStringObj(PrintNodeId(&v->nodeId, &ds), -1);
		list[1] = Tcl_NewStringObj((char * ) v->namespaceUri.data,
					   v->namespaceUri.length);
		list[2] = Tcl_NewWideIntObj(v->serverIndex);
		Tcl_DStringFree(&ds);
		Tcl_SetObjResult(interp, Tcl_NewListObj(3, list));
	    } else if (value.type == &UA_TYPES[UA_TYPES_STATUSCODE]) {
		Tcl_SetObjResult(interp,
		    Tcl_NewIntObj(((int *) value.data)[0]));
	    } else if (value.type == &UA_TYPES[UA_TYPES_QUALIFIEDNAME]) {
		UA_QualifiedName *v = (UA_QualifiedName *) value.data;
		Tcl_Obj *list[2];

		list[0] = Tcl_NewWideIntObj(v->namespaceIndex);
		list[1] = Tcl_NewStringObj((char * ) v->name.data,
					   v->name.length);
		Tcl_SetObjResult(interp, Tcl_NewListObj(2, list));
	    } else if (value.type == &UA_TYPES[UA_TYPES_LOCALIZEDTEXT]) {
		UA_LocalizedText *v = (UA_LocalizedText *) value.data;
		Tcl_Obj *list[2];

		list[0] = Tcl_NewStringObj((char * ) v->locale.data,
					   v->locale.length);
		list[1] = Tcl_NewStringObj((char * ) v->text.data,
					   v->text.length);
		Tcl_SetObjResult(interp, Tcl_NewListObj(2, list));
	    } else if (value.type == &UA_TYPES[UA_TYPES_EXTENSIONOBJECT]) {
		/* TBD */
	    } else if (value.type == &UA_TYPES[UA_TYPES_DATAVALUE]) {
		/* TBD */
	    } else {
		/* TBD */
	    }
	} else if ((value.data == NULL) ||
		   (value.data == UA_EMPTY_ARRAY_SENTINEL)) {
	    /* An empty array. */
	} else {
	    if (value.type == &UA_TYPES[UA_TYPES_BOOLEAN]) {
		int i, *v = (int *) value.data;
		Tcl_Obj *a = Tcl_NewListObj(value.arrayLength, NULL);

		for (i = 0; i < value.arrayLength; i++) {
		    Tcl_ListObjAppendElement(NULL, a,
			Tcl_NewIntObj(v[i] ? 1 : 0));
		}
		Tcl_SetObjResult(interp, a);
	    } else if (value.type == &UA_TYPES[UA_TYPES_SBYTE]) {
		int i;
		signed char *v = (signed char *) value.data;
		Tcl_Obj *a = Tcl_NewListObj(value.arrayLength, NULL);

		for (i = 0; i < value.arrayLength; i++) {
		    Tcl_ListObjAppendElement(NULL, a,
			Tcl_NewIntObj(v[i]));
		}
		Tcl_SetObjResult(interp, a);
	    } else if (value.type == &UA_TYPES[UA_TYPES_BYTE]) {
		int i;
		unsigned char *v = (unsigned char *) value.data;
		Tcl_Obj *a = Tcl_NewListObj(value.arrayLength, NULL);

		for (i = 0; i < value.arrayLength; i++) {
		    Tcl_ListObjAppendElement(NULL, a,
			Tcl_NewIntObj(v[i]));
		}
		Tcl_SetObjResult(interp, a);
	    } else if (value.type == &UA_TYPES[UA_TYPES_INT16]) {
		int i;
		signed short *v = (signed short *) value.data;
		Tcl_Obj *a = Tcl_NewListObj(value.arrayLength, NULL);

		for (i = 0; i < value.arrayLength; i++) {
		    Tcl_ListObjAppendElement(NULL, a,
			Tcl_NewIntObj(v[i]));
		}
		Tcl_SetObjResult(interp, a);
	    } else if (value.type == &UA_TYPES[UA_TYPES_UINT16]) {
		int i;
		unsigned short *v = (unsigned short *) value.data;
		Tcl_Obj *a = Tcl_NewListObj(value.arrayLength, NULL);

		for (i = 0; i < value.arrayLength; i++) {
		    Tcl_ListObjAppendElement(NULL, a,
			Tcl_NewIntObj(v[i]));
		}
		Tcl_SetObjResult(interp, a);
	    } else if (value.type == &UA_TYPES[UA_TYPES_INT32]) {
		int i;
		signed int *v = (signed int *) value.data;
		Tcl_Obj *a = Tcl_NewListObj(value.arrayLength, NULL);

		for (i = 0; i < value.arrayLength; i++) {
		    Tcl_ListObjAppendElement(NULL, a,
			Tcl_NewIntObj(v[i]));
		}
		Tcl_SetObjResult(interp, a);
	    } else if (value.type == &UA_TYPES[UA_TYPES_UINT32]) {
		int i;
		unsigned int *v = (unsigned int *) value.data;
		Tcl_Obj *a = Tcl_NewListObj(value.arrayLength, NULL);

		for (i = 0; i < value.arrayLength; i++) {
		    Tcl_ListObjAppendElement(NULL, a,
			Tcl_NewWideIntObj(v[i]));
		}
		Tcl_SetObjResult(interp, a);
	    } else if (value.type == &UA_TYPES[UA_TYPES_INT64]) {
		int i;
		Tcl_WideInt *v = (Tcl_WideInt *) value.data;
		Tcl_Obj *a = Tcl_NewListObj(value.arrayLength, NULL);

		for (i = 0; i < value.arrayLength; i++) {
		    Tcl_ListObjAppendElement(NULL, a,
			Tcl_NewWideIntObj(v[i]));
		}
		Tcl_SetObjResult(interp, a);
	    } else if (value.type == &UA_TYPES[UA_TYPES_UINT64]) {
		int i;
		Tcl_WideInt *v = (Tcl_WideInt *) value.data;
		Tcl_Obj *a = Tcl_NewListObj(value.arrayLength, NULL);

		for (i = 0; i < value.arrayLength; i++) {
		    Tcl_ListObjAppendElement(NULL, a,
			Tcl_NewWideIntObj(v[i]));
		}
		Tcl_SetObjResult(interp, a);
	    } else if (value.type == &UA_TYPES[UA_TYPES_FLOAT]) {
		int i;
		float *v = (float *) value.data;
		Tcl_Obj *a = Tcl_NewListObj(value.arrayLength, NULL);

		for (i = 0; i < value.arrayLength; i++) {
		    Tcl_ListObjAppendElement(NULL, a,
			Tcl_NewDoubleObj(v[i]));
		}
		Tcl_SetObjResult(interp, a);
	    } else if (value.type == &UA_TYPES[UA_TYPES_DOUBLE]) {
		int i;
		double *v = (double *) value.data;
		Tcl_Obj *a = Tcl_NewListObj(value.arrayLength, NULL);

		for (i = 0; i < value.arrayLength; i++) {
		    Tcl_ListObjAppendElement(NULL, a,
			Tcl_NewDoubleObj(v[i]));
		}
		Tcl_SetObjResult(interp, a);
	    } else if (value.type == &UA_TYPES[UA_TYPES_STRING]) {
		int i;
		UA_String *v = (UA_String *) value.data;
		Tcl_Obj *a = Tcl_NewListObj(value.arrayLength, NULL);

		for (i = 0; i < value.arrayLength; i++, v++) {
		    Tcl_ListObjAppendElement(NULL, a,
			Tcl_NewStringObj((char *) v->data, v->length));
		}
		Tcl_SetObjResult(interp, a);
	    } else if (value.type == &UA_TYPES[UA_TYPES_DATETIME]) {
		int i;
		UA_DateTime *t = (UA_DateTime *) value.data;
		Tcl_Obj *a = Tcl_NewListObj(value.arrayLength, NULL);

		for (i = 0; i < value.arrayLength; i++) {
		    Tcl_ListObjAppendElement(NULL, a,
			Tcl_NewWideIntObj((Tcl_WideInt) t[i]));
		}
		Tcl_SetObjResult(interp, a);
	    } else {
		/* TBD */
	    }
	}
    }
    UA_Variant_deleteMembers(&value);
    return TCL_OK;
}

/*
 *-------------------------------------------------------------------------
 *
 * ReadObjCmd --
 *
 *	Implementation of the "::opcua::read" Tcl command.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *-------------------------------------------------------------------------
 */

static int
ReadObjCmd(ClientData clientData, Tcl_Interp *interp,
	   int objc, Tcl_Obj * const objv[])
{
    return ReadTypeObjCmd(clientData, interp, 0, objc, objv);
}

/*
 *-------------------------------------------------------------------------
 *
 * TypeObjCmd --
 *
 *	Implementation of the "::opcua::type" Tcl command.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *-------------------------------------------------------------------------
 */

static int
TypeObjCmd(ClientData clientData, Tcl_Interp *interp,
	   int objc, Tcl_Obj * const objv[])
{
    return ReadTypeObjCmd(clientData, interp, 1, objc, objv);
}

/*
 *-------------------------------------------------------------------------
 *
 * WriteObjCmd --
 *
 *	Implementation of the "::opcua::write" Tcl command.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *-------------------------------------------------------------------------
 */

static int
WriteObjCmd(ClientData clientData, Tcl_Interp *interp,
	    int objc, Tcl_Obj * const objv[])
{
    UACLI *uacli = (UACLI *) clientData;
    UACL *uacl;
    Tcl_HashEntry *hPtr;
    UA_StatusCode uaret;
    UA_NodeId nodeid;
    UA_DataType *type;
    void *value;
    int attr, idx;

    if ((objc < 5) || (objc > 6)) {
	Tcl_WrongNumArgs(interp, 1, objv,
			 "clientid nodeid ?attr? type value");
	return TCL_ERROR;
    }
    hPtr = Tcl_FindHashEntry(&uacli->clients, Tcl_GetString(objv[1]));
    if (hPtr != NULL) {
	uacl = (UACL *) Tcl_GetHashValue(hPtr);
    } else {
	Tcl_SetResult(interp, "clientid not found", TCL_STATIC);
	ReportError(interp, uacli, NULL, 0);
	return TCL_ERROR;
    }
    if (ParseNodeId(interp, &nodeid, Tcl_GetString(objv[2])) == NULL) {
	return TCL_ERROR;
    }
    if (objc > 5) {
	if (Tcl_GetIndexFromObj(interp, objv[3], attrNames, "attr", 0,
				&attr) != TCL_OK) {
	    return TCL_ERROR;
	}
	/* UA_AttributeId is 1-based */
	attr += 1;
	idx = 4;
    } else {
	/* By default, write the "value" attribute. */
	attr = UA_ATTRIBUTEID_VALUE;
	idx = 3;
    }
    hPtr = Tcl_FindHashEntry(&uacli->types, Tcl_GetString(objv[idx]));
    if (hPtr == NULL) {
	Tcl_SetResult(interp, "unsupported type", TCL_STATIC);
	goto error;
    }
    idx++;
    type = (UA_DataType *) Tcl_GetHashValue(hPtr);
    if (type == &UA_TYPES[UA_TYPES_BOOLEAN]) {
	int v;

	if (Tcl_GetBooleanFromObj(interp, objv[idx], &v) != TCL_OK) {
	    goto error;
	}
	value = UA_new(type);
	((UA_Boolean *) value)[0] = v ? UA_TRUE : UA_FALSE;
    } else if (type == &UA_TYPES[UA_TYPES_SBYTE]) {
	int v;

	if (Tcl_GetIntFromObj(interp, objv[idx], &v) != TCL_OK) {
	    goto error;
	}
	value = UA_new(type);
	((UA_SByte *) value)[0] = v;
    } else if (type == &UA_TYPES[UA_TYPES_BYTE]) {
	int v;

	if (Tcl_GetIntFromObj(interp, objv[idx], &v) != TCL_OK) {
	    goto error;
	}
	value = UA_new(type);
	((UA_Byte *) value)[0] = v;
    } else if (type == &UA_TYPES[UA_TYPES_INT16]) {
	int v;

	if (Tcl_GetIntFromObj(interp, objv[idx], &v) != TCL_OK) {
	    goto error;
	}
	value = UA_new(type);
	((UA_Int16 *) value)[0] = v;
    } else if (type == &UA_TYPES[UA_TYPES_UINT16]) {
	int v;

	if (Tcl_GetIntFromObj(interp, objv[idx], &v) != TCL_OK) {
	    goto error;
	}
	value = UA_new(type);
	((UA_UInt16 *) value)[0] = v;
    } else if (type == &UA_TYPES[UA_TYPES_INT32]) {
	int v;

	if (Tcl_GetIntFromObj(interp, objv[idx], &v) != TCL_OK) {
	    goto error;
	}
	value = UA_new(type);
	((UA_Int32 *) value)[0] = v;
    } else if (type == &UA_TYPES[UA_TYPES_UINT32]) {
	Tcl_WideInt v;

	if (Tcl_GetWideIntFromObj(interp, objv[idx], &v) != TCL_OK) {
	    goto error;
	}
	value = UA_new(type);
	((UA_UInt32 *) value)[0] = v;
    } else if (type == &UA_TYPES[UA_TYPES_INT64]) {
	Tcl_WideInt v;

	if (Tcl_GetWideIntFromObj(interp, objv[idx], &v) != TCL_OK) {
	    goto error;
	}
	value = UA_new(type);
	((UA_Int64 *) value)[0] = v;
    } else if (type == &UA_TYPES[UA_TYPES_UINT64]) {
	Tcl_WideInt v;

	if (Tcl_GetWideIntFromObj(interp, objv[idx], &v) != TCL_OK) {
	    goto error;
	}
	value = UA_new(type);
	((UA_UInt64 *) value)[0] = v;
    } else if (type == &UA_TYPES[UA_TYPES_FLOAT]) {
	double v;

	if (Tcl_GetDoubleFromObj(interp, objv[idx], &v) != TCL_OK) {
	    goto error;
	}
	value = UA_new(type);
	((UA_Float *) value)[0] = v;
    } else if (type == &UA_TYPES[UA_TYPES_DOUBLE]) {
	double v;

	if (Tcl_GetDoubleFromObj(interp, objv[idx], &v) != TCL_OK) {
	    goto error;
	}
	value = UA_new(type);
	((UA_Double *) value)[0] = v;
    } else if (type == &UA_TYPES[UA_TYPES_STRING]) {
	UA_String s = UA_String_fromChars(Tcl_GetString(objv[idx]));

	value = UA_new(type);
	UA_String_copy(&s, (UA_String *) value);
	UA_String_delete(&s);
    } else if (type == &UA_TYPES[UA_TYPES_DATETIME]) {
	Tcl_WideInt v;

	if (Tcl_GetWideIntFromObj(interp, objv[idx], &v) != TCL_OK) {
	    goto error;
	}
	value = UA_new(type);
	((UA_DateTime *) value)[0] = (UA_DateTime) v;
    } else if (type == &UA_TYPES[UA_TYPES_GUID]) {
	UA_Guid *g;
	int d[11];

	if (sscanf(Tcl_GetString(objv[idx]),
		   "%8x-%4x-%4x-%2x%2x-%2x%2x%2x%2x%2x%2x",
		   d, d + 1, d + 2, d + 3, d + 4, d + 5,
		   d + 6, d + 7, d + 8, d + 9, d + 10) != 11) {
	    Tcl_SetResult(interp, "invalid GUID", TCL_STATIC);
	    goto error;
	}
	value = UA_new(type);
	g = (UA_Guid *) value;
	g->data1 = d[0];
	g->data2 = d[1];
	g->data3 = d[2];
	g->data4[0] = d[3];
	g->data4[1] = d[4];
	g->data4[2] = d[5];
	g->data4[3] = d[6];
	g->data4[4] = d[7];
	g->data4[5] = d[8];
	g->data4[6] = d[9];
	g->data4[7] = d[10];
    } else if (type == &UA_TYPES[UA_TYPES_BYTESTRING]) {
	UA_String s = UA_String_fromChars(Tcl_GetString(objv[idx]));

	value = UA_new(type);
	UA_String_copy(&s, (UA_String *) value);
	UA_String_delete(&s);
    } else if (type == &UA_TYPES[UA_TYPES_XMLELEMENT]) {
	UA_String s = UA_String_fromChars(Tcl_GetString(objv[idx]));

	value = UA_new(type);
	UA_String_copy(&s, (UA_String *) value);
	UA_String_delete(&s);
    } else if (type == &UA_TYPES[UA_TYPES_NODEID]) {
	value = UA_new(type);
	if (ParseNodeId(interp, (UA_NodeId *) value,
			Tcl_GetString(objv[idx])) == NULL) {
	    UA_delete(value, type);
	    goto error;
	}
    } else if (type == &UA_TYPES[UA_TYPES_QUALIFIEDNAME]) {
	/* TBD */
	Tcl_SetResult(interp, "unsupported type", TCL_STATIC);
	goto error;
    } else if (type == &UA_TYPES[UA_TYPES_LOCALIZEDTEXT]) {
	/* TBD */
	Tcl_SetResult(interp, "unsupported type", TCL_STATIC);
	goto error;
    } else {
	Tcl_SetResult(interp, "unsupported type", TCL_STATIC);
error:
	ReportError(interp, uacli, NULL, 0);
	UA_NodeId_deleteMembers(&nodeid);
	return TCL_ERROR;
    }
    uaret = __UA_Client_writeAttribute(uacl->client, &nodeid,
				       (UA_AttributeId) attr,
				       value, type);
    UA_NodeId_deleteMembers(&nodeid);
    if (uaret != UA_STATUSCODE_GOOD) {
	ReportError(interp, uacli, "WriteAttribute", uaret);
	return TCL_ERROR;
    }
    UA_delete(value, type);
    return TCL_OK;
}

/*
 *-------------------------------------------------------------------------
 *
 * CallObjCmd --
 *
 *	Implementation of the "::opcua::call" Tcl command.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *-------------------------------------------------------------------------
 */

static int
CallObjCmd(ClientData clientData, Tcl_Interp *interp,
	   int objc, Tcl_Obj * const objv[])
{
    UACLI *uacli = (UACLI *) clientData;
    UACL *uacl;
    Tcl_HashEntry *hPtr;
    UA_StatusCode uaret;
    UA_NodeId nodeid, methid;
    UA_DataType *type;
    UA_Variant *inArgs, *outArgs;
    size_t i, nInArgs, nOutArgs;
    Tcl_Obj *list;

    if ((objc < 4) || (objc %2 != 0)) {
	Tcl_WrongNumArgs(interp, 1, objv,
			 "clientid nodeid methid ?type value ...?");
	return TCL_ERROR;
    }
    hPtr = Tcl_FindHashEntry(&uacli->clients, Tcl_GetString(objv[1]));
    if (hPtr != NULL) {
	uacl = (UACL *) Tcl_GetHashValue(hPtr);
    } else {
	Tcl_SetResult(interp, "clientid not found", TCL_STATIC);
	ReportError(interp, uacli, NULL, 0);
	return TCL_ERROR;
    }
    if (ParseNodeId(interp, &nodeid, Tcl_GetString(objv[2])) == NULL) {
	return TCL_ERROR;
    }
    if (ParseNodeId(interp, &methid, Tcl_GetString(objv[3])) == NULL) {
	return TCL_ERROR;
    }
    nInArgs = (objc - 4) / 2;
    inArgs = (UA_Variant *) UA_Array_new(nInArgs, &UA_TYPES[UA_TYPES_VARIANT]);
    for (i = 0; i < nInArgs; i++) {
	int idx = i * 2 + 4;
	void *value;

	hPtr = Tcl_FindHashEntry(&uacli->types, Tcl_GetString(objv[idx]));
	if (hPtr == NULL) {
	    Tcl_SetResult(interp, "unsupported type", TCL_STATIC);
	    goto argsError;
	}
	type = (UA_DataType *) Tcl_GetHashValue(hPtr);
	idx++;
	if (type == &UA_TYPES[UA_TYPES_BOOLEAN]) {
	    int v;

	    if (Tcl_GetBooleanFromObj(interp, objv[idx], &v) != TCL_OK) {
		goto argsError;
	    }
	    value = UA_new(type);
	    ((UA_Boolean *) value)[0] = v ? UA_TRUE : UA_FALSE;
	} else if (type == &UA_TYPES[UA_TYPES_SBYTE]) {
	    int v;

	    if (Tcl_GetIntFromObj(interp, objv[idx], &v) != TCL_OK) {
		goto argsError;
	    }
	    value = UA_new(type);
	    ((UA_SByte *) value)[0] = v;
	} else if (type == &UA_TYPES[UA_TYPES_BYTE]) {
	    int v;

	    if (Tcl_GetIntFromObj(interp, objv[idx], &v) != TCL_OK) {
		goto argsError;
	    }
	    value = UA_new(type);
	    ((UA_Byte *) value)[0] = v;
	} else if (type == &UA_TYPES[UA_TYPES_INT16]) {
	    int v;

	    if (Tcl_GetIntFromObj(interp, objv[idx], &v) != TCL_OK) {
		goto argsError;
	    }
	    value = UA_new(type);
	    ((UA_Int16 *) value)[0] = v;
	} else if (type == &UA_TYPES[UA_TYPES_UINT16]) {
	    int v;

	    if (Tcl_GetIntFromObj(interp, objv[idx], &v) != TCL_OK) {
		goto argsError;
	    }
	    value = UA_new(type);
	    ((UA_UInt16 *) value)[0] = v;
	} else if (type == &UA_TYPES[UA_TYPES_INT32]) {
	    int v;

	    if (Tcl_GetIntFromObj(interp, objv[idx], &v) != TCL_OK) {
		goto argsError;
	    }
	    value = UA_new(type);
	    ((UA_Int32 *) value)[0] = v;
	} else if (type == &UA_TYPES[UA_TYPES_UINT32]) {
	    Tcl_WideInt v;

	    if (Tcl_GetWideIntFromObj(interp, objv[idx], &v) != TCL_OK) {
		goto argsError;
	    }
	    value = UA_new(type);
	    ((UA_UInt32 *) value)[0] = v;
	} else if (type == &UA_TYPES[UA_TYPES_INT64]) {
	    Tcl_WideInt v;

	    if (Tcl_GetWideIntFromObj(interp, objv[idx], &v) != TCL_OK) {
		goto argsError;
	    }
	    value = UA_new(type);
	    ((UA_Int64 *) value)[0] = v;
	} else if (type == &UA_TYPES[UA_TYPES_UINT64]) {
	    Tcl_WideInt v;

	    if (Tcl_GetWideIntFromObj(interp, objv[idx], &v) != TCL_OK) {
		goto argsError;
	    }
	    value = UA_new(type);
	    ((UA_UInt64 *) value)[0] = v;
	} else if (type == &UA_TYPES[UA_TYPES_FLOAT]) {
	    double v;

	    if (Tcl_GetDoubleFromObj(interp, objv[idx], &v) != TCL_OK) {
		goto argsError;
	    }
	    value = UA_new(type);
	    ((UA_Float *) value)[0] = v;
	} else if (type == &UA_TYPES[UA_TYPES_DOUBLE]) {
	    double v;

	    if (Tcl_GetDoubleFromObj(interp, objv[idx], &v) != TCL_OK) {
		goto argsError;
	    }
	    value = UA_new(type);
	    ((UA_Double *) value)[0] = v;
	} else if (type == &UA_TYPES[UA_TYPES_STRING]) {
	    UA_String s = UA_String_fromChars(Tcl_GetString(objv[idx]));

	    value = UA_new(type);
	    UA_String_copy(&s, (UA_String *) value);
	    UA_String_delete(&s);
	} else if (type == &UA_TYPES[UA_TYPES_DATETIME]) {
	    Tcl_WideInt v;

	    if (Tcl_GetWideIntFromObj(interp, objv[idx], &v) != TCL_OK) {
		goto argsError;
	    }
	    value = UA_new(type);
	    ((UA_DateTime *) value)[0] = (UA_DateTime) v;
	} else if (type == &UA_TYPES[UA_TYPES_GUID]) {
	    UA_Guid *g;
	    int d[11];

	    if (sscanf(Tcl_GetString(objv[idx]),
		       "%8x-%4x-%4x-%2x%2x-%2x%2x%2x%2x%2x%2x",
		       d, d + 1, d + 2, d + 3, d + 4, d + 5,
		       d + 6, d + 7, d + 8, d + 9, d + 10) != 11) {
		Tcl_SetResult(interp, "invalid GUID", TCL_STATIC);
		goto argsError;
	    }
	    value = UA_new(type);
	    g = (UA_Guid *) value;
	    g->data1 = d[0];
	    g->data2 = d[1];
	    g->data3 = d[2];
	    g->data4[0] = d[3];
	    g->data4[1] = d[4];
	    g->data4[2] = d[5];
	    g->data4[3] = d[6];
	    g->data4[4] = d[7];
	    g->data4[5] = d[8];
	    g->data4[6] = d[9];
	    g->data4[7] = d[10];
	} else if (type == &UA_TYPES[UA_TYPES_BYTESTRING]) {
	    UA_String s = UA_String_fromChars(Tcl_GetString(objv[idx]));

	    value = UA_new(type);
	    UA_String_copy(&s, (UA_String *) value);
	    UA_String_delete(&s);
	} else if (type == &UA_TYPES[UA_TYPES_XMLELEMENT]) {
	    UA_String s = UA_String_fromChars(Tcl_GetString(objv[idx]));

	    value = UA_new(type);
	    UA_String_copy(&s, (UA_String *) value);
	    UA_String_delete(&s);
	} else if (type == &UA_TYPES[UA_TYPES_NODEID]) {
	    value = UA_new(type);
	    if (ParseNodeId(interp, (UA_NodeId *) value,
			    Tcl_GetString(objv[idx])) == NULL) {
		UA_delete(value, type);
		goto argsError;
	    }
	} else if (type == &UA_TYPES[UA_TYPES_QUALIFIEDNAME]) {
	    /* TBD */
	    Tcl_SetResult(interp, "unsupported type", TCL_STATIC);
	    goto argsError;
	} else if (type == &UA_TYPES[UA_TYPES_LOCALIZEDTEXT]) {
	    /* TBD */
	    Tcl_SetResult(interp, "unsupported type", TCL_STATIC);
	    goto argsError;
	} else {
	    Tcl_SetResult(interp, "unsupported type", TCL_STATIC);
argsError:
	    ReportError(interp, uacli, NULL, 0);
	    UA_NodeId_deleteMembers(&nodeid);
	    UA_NodeId_deleteMembers(&methid);
	    UA_Array_delete(inArgs, nInArgs, &UA_TYPES[UA_TYPES_VARIANT]);
	    return TCL_ERROR;
	}
	UA_Variant_setScalarCopy(inArgs + i, value, type);
    }
    uaret = UA_Client_call(uacl->client, nodeid, methid,
			   nInArgs, inArgs, &nOutArgs, &outArgs);
    UA_NodeId_deleteMembers(&nodeid);
    UA_NodeId_deleteMembers(&methid);
    UA_Array_delete(inArgs, nInArgs, &UA_TYPES[UA_TYPES_VARIANT]);
    if (uaret != UA_STATUSCODE_GOOD) {
	UA_Array_delete(outArgs, nOutArgs, &UA_TYPES[UA_TYPES_VARIANT]);
	ReportError(interp, uacli, "Call", uaret);
	return TCL_ERROR;
    }
    list = Tcl_NewListObj(nOutArgs, NULL);
    for (i = 0; i < nOutArgs; i++) {
	UA_Variant *value = &outArgs[i];

	if (!UA_Variant_isEmpty(value)) {
	    if (UA_Variant_isScalar(value)) {
		if (value->type == &UA_TYPES[UA_TYPES_BOOLEAN]) {
		    int *v = (int *) value->data;

		    Tcl_ListObjAppendElement(NULL, list,
			Tcl_NewIntObj(*v ? 1 : 0));
		} else if (value->type == &UA_TYPES[UA_TYPES_SBYTE]) {
		    Tcl_ListObjAppendElement(NULL, list,
			Tcl_NewIntObj(((signed char *) value->data)[0]));
		} else if (value->type == &UA_TYPES[UA_TYPES_BYTE]) {
		    Tcl_ListObjAppendElement(NULL, list,
			Tcl_NewIntObj(((unsigned char *) value->data)[0]));
		} else if (value->type == &UA_TYPES[UA_TYPES_INT16]) {
		    Tcl_ListObjAppendElement(NULL, list,
			Tcl_NewIntObj(((signed short *) value->data)[0]));
		} else if (value->type == &UA_TYPES[UA_TYPES_UINT16]) {
		    Tcl_ListObjAppendElement(NULL, list,
			Tcl_NewIntObj(((unsigned short *) value->data)[0]));
		} else if (value->type == &UA_TYPES[UA_TYPES_INT32]) {
		    Tcl_ListObjAppendElement(NULL, list,
			Tcl_NewIntObj(((signed int *) value->data)[0]));
		} else if (value->type == &UA_TYPES[UA_TYPES_UINT32]) {
		    Tcl_ListObjAppendElement(NULL, list,
			Tcl_NewWideIntObj(((unsigned int *) value->data)[0]));
		} else if (value->type == &UA_TYPES[UA_TYPES_INT64]) {
		    Tcl_ListObjAppendElement(NULL, list,
			Tcl_NewWideIntObj(((Tcl_WideInt *) value->data)[0]));
		} else if (value->type == &UA_TYPES[UA_TYPES_UINT64]) {
		    Tcl_ListObjAppendElement(NULL, list,
			Tcl_NewWideIntObj(((Tcl_WideInt *) value->data)[0]));
		} else if (value->type == &UA_TYPES[UA_TYPES_FLOAT]) {
		    Tcl_ListObjAppendElement(NULL, list,
			Tcl_NewDoubleObj(((float *) value->data)[0]));
		} else if (value->type == &UA_TYPES[UA_TYPES_DOUBLE]) {
		    Tcl_ListObjAppendElement(NULL, list,
			Tcl_NewDoubleObj(((double *) value->data)[0]));
		} else if (value->type == &UA_TYPES[UA_TYPES_STRING]) {
		    UA_String *v = (UA_String *) value->data;

		    Tcl_ListObjAppendElement(NULL, list,
			Tcl_NewStringObj((char *) v->data, v->length));
		} else if (value->type == &UA_TYPES[UA_TYPES_DATETIME]) {
		    UA_DateTime t = ((UA_DateTime *) value->data)[0];

		    Tcl_ListObjAppendElement(NULL, list,
			Tcl_NewWideIntObj((Tcl_WideInt) t));
		} else if (value->type == &UA_TYPES[UA_TYPES_GUID]) {
		    UA_Guid *v = (UA_Guid *) value->data;
		    char buffer[64];

		    sprintf(buffer,
			    "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
			    v->data1, v->data2, v->data3,
			    v->data4[0], v->data4[1],
			    v->data4[2], v->data4[3],
			    v->data4[4], v->data4[5],
			    v->data4[6], v->data4[7]);
		    Tcl_ListObjAppendElement(NULL, list,
			Tcl_NewStringObj(buffer, -1));
		} else if (value->type == &UA_TYPES[UA_TYPES_BYTESTRING]) {
		    UA_ByteString *v = (UA_ByteString *) value->data;

		    Tcl_ListObjAppendElement(NULL, list,
			Tcl_NewByteArrayObj(v->data, v->length));
		} else if (value->type == &UA_TYPES[UA_TYPES_XMLELEMENT]) {
		    UA_String *v = (UA_String *) value->data;

		    Tcl_ListObjAppendElement(NULL, list,
			Tcl_NewStringObj((char *) v->data, v->length));
		} else if (value->type == &UA_TYPES[UA_TYPES_NODEID]) {
		    UA_NodeId *v = (UA_NodeId *) value->data;
		    Tcl_DString ds;

		    Tcl_ListObjAppendElement(NULL, list,
			Tcl_NewStringObj(PrintNodeId(v, &ds), -1));
		    Tcl_DStringFree(&ds);
		} else if (value->type == &UA_TYPES[UA_TYPES_EXPANDEDNODEID]) {
		    UA_ExpandedNodeId *v = (UA_ExpandedNodeId *) value->data;
		    Tcl_DString ds;
		    Tcl_Obj *slist[3];

		    slist[0] = Tcl_NewStringObj(PrintNodeId(&v->nodeId, &ds),
						  -1);
		    slist[1] = Tcl_NewStringObj((char * ) v->namespaceUri.data,
						v->namespaceUri.length);
		    slist[2] = Tcl_NewWideIntObj(v->serverIndex);
		    Tcl_DStringFree(&ds);
		    Tcl_ListObjAppendElement(NULL, list,
			Tcl_NewListObj(3, slist));
		} else if (value->type == &UA_TYPES[UA_TYPES_STATUSCODE]) {
		    Tcl_ListObjAppendElement(NULL, list,
			Tcl_NewIntObj(((int *) value->data)[0]));
		} else if (value->type == &UA_TYPES[UA_TYPES_QUALIFIEDNAME]) {
		    UA_QualifiedName *v = (UA_QualifiedName *) value->data;
		    Tcl_Obj *slist[2];

		    slist[0] = Tcl_NewWideIntObj(v->namespaceIndex);
		    slist[1] = Tcl_NewStringObj((char * ) v->name.data,
						v->name.length);
		    Tcl_ListObjAppendElement(NULL, list,
			Tcl_NewListObj(2, slist));
		} else if (value->type == &UA_TYPES[UA_TYPES_LOCALIZEDTEXT]) {
		    UA_LocalizedText *v = (UA_LocalizedText *) value->data;
		    Tcl_Obj *slist[2];

		    slist[0] = Tcl_NewStringObj((char * ) v->locale.data,
						v->locale.length);
		    slist[1] = Tcl_NewStringObj((char * ) v->text.data,
					       v->text.length);
		    Tcl_ListObjAppendElement(NULL, list,
			Tcl_NewListObj(2, slist));
		} else if (value->type == &UA_TYPES[UA_TYPES_EXTENSIONOBJECT]) {
		    /* TBD */
		} else if (value->type == &UA_TYPES[UA_TYPES_DATAVALUE]) {
		    /* TBD */
		} else {
		    /* TBD */
		}
	    } else if ((value->data == NULL) ||
		       (value->data == UA_EMPTY_ARRAY_SENTINEL)) {
		/* An empty array. */
	    } else {
		if (value->type == &UA_TYPES[UA_TYPES_BOOLEAN]) {
		    int i, *v = (int *) value->data;
		    Tcl_Obj *a = Tcl_NewListObj(value->arrayLength, NULL);

		    for (i = 0; i < value->arrayLength; i++) {
			Tcl_ListObjAppendElement(NULL, a,
			    Tcl_NewIntObj(v[i] ? 1 : 0));
		    }
		    Tcl_ListObjAppendElement(NULL, list, a);
		} else if (value->type == &UA_TYPES[UA_TYPES_SBYTE]) {
		    int i;
		    signed char *v = (signed char *) value->data;
		    Tcl_Obj *a = Tcl_NewListObj(value->arrayLength, NULL);

		    for (i = 0; i < value->arrayLength; i++) {
			Tcl_ListObjAppendElement(NULL, a,
			    Tcl_NewIntObj(v[i]));
		    }
		    Tcl_ListObjAppendElement(NULL, list, a);
		} else if (value->type == &UA_TYPES[UA_TYPES_BYTE]) {
		    int i;
		    unsigned char *v = (unsigned char *) value->data;
		    Tcl_Obj *a = Tcl_NewListObj(value->arrayLength, NULL);

		    for (i = 0; i < value->arrayLength; i++) {
			Tcl_ListObjAppendElement(NULL, a,
			    Tcl_NewIntObj(v[i]));
		    }
		    Tcl_ListObjAppendElement(NULL, list, a);
		} else if (value->type == &UA_TYPES[UA_TYPES_INT16]) {
		    int i;
		    signed short *v = (signed short *) value->data;
		    Tcl_Obj *a = Tcl_NewListObj(value->arrayLength, NULL);

		    for (i = 0; i < value->arrayLength; i++) {
			Tcl_ListObjAppendElement(NULL, a,
			    Tcl_NewIntObj(v[i]));
		    }
		    Tcl_ListObjAppendElement(NULL, list, a);
		} else if (value->type == &UA_TYPES[UA_TYPES_UINT16]) {
		    int i;
		    unsigned short *v = (unsigned short *) value->data;
		    Tcl_Obj *a = Tcl_NewListObj(value->arrayLength, NULL);

		    for (i = 0; i < value->arrayLength; i++) {
			Tcl_ListObjAppendElement(NULL, a,
			    Tcl_NewIntObj(v[i]));
		    }
		    Tcl_ListObjAppendElement(NULL, list, a);
		} else if (value->type == &UA_TYPES[UA_TYPES_INT32]) {
		    int i;
		    signed int *v = (signed int *) value->data;
		    Tcl_Obj *a = Tcl_NewListObj(value->arrayLength, NULL);

		    for (i = 0; i < value->arrayLength; i++) {
			Tcl_ListObjAppendElement(NULL, a,
			    Tcl_NewIntObj(v[i]));
		    }
		    Tcl_ListObjAppendElement(NULL, list, a);
		} else if (value->type == &UA_TYPES[UA_TYPES_UINT32]) {
		    int i;
		    unsigned int *v = (unsigned int *) value->data;
		    Tcl_Obj *a = Tcl_NewListObj(value->arrayLength, NULL);

		    for (i = 0; i < value->arrayLength; i++) {
			Tcl_ListObjAppendElement(NULL, a,
			    Tcl_NewWideIntObj(v[i]));
		    }
		    Tcl_ListObjAppendElement(NULL, list, a);
		} else if (value->type == &UA_TYPES[UA_TYPES_INT64]) {
		    int i;
		    Tcl_WideInt *v = (Tcl_WideInt *) value->data;
		    Tcl_Obj *a = Tcl_NewListObj(value->arrayLength, NULL);

		    for (i = 0; i < value->arrayLength; i++) {
			Tcl_ListObjAppendElement(NULL, a,
			    Tcl_NewWideIntObj(v[i]));
		    }
		    Tcl_ListObjAppendElement(NULL, list, a);
		} else if (value->type == &UA_TYPES[UA_TYPES_UINT64]) {
		    int i;
		    Tcl_WideInt *v = (Tcl_WideInt *) value->data;
		    Tcl_Obj *a = Tcl_NewListObj(value->arrayLength, NULL);

		    for (i = 0; i < value->arrayLength; i++) {
			Tcl_ListObjAppendElement(NULL, a,
			    Tcl_NewWideIntObj(v[i]));
		    }
		    Tcl_ListObjAppendElement(NULL, list, a);
		} else if (value->type == &UA_TYPES[UA_TYPES_FLOAT]) {
		    int i;
		    float *v = (float *) value->data;
		    Tcl_Obj *a = Tcl_NewListObj(value->arrayLength, NULL);

		    for (i = 0; i < value->arrayLength; i++) {
			Tcl_ListObjAppendElement(NULL, a,
			    Tcl_NewDoubleObj(v[i]));
		    }
		    Tcl_ListObjAppendElement(NULL, list, a);
		} else if (value->type == &UA_TYPES[UA_TYPES_DOUBLE]) {
		    int i;
		    double *v = (double *) value->data;
		    Tcl_Obj *a = Tcl_NewListObj(value->arrayLength, NULL);

		    for (i = 0; i < value->arrayLength; i++) {
			Tcl_ListObjAppendElement(NULL, a,
			    Tcl_NewDoubleObj(v[i]));
		    }
		    Tcl_ListObjAppendElement(NULL, list, a);
		} else if (value->type == &UA_TYPES[UA_TYPES_STRING]) {
		    int i;
		    UA_String *v = (UA_String *) value->data;
		    Tcl_Obj *a = Tcl_NewListObj(value->arrayLength, NULL);

		    for (i = 0; i < value->arrayLength; i++, v++) {
			Tcl_ListObjAppendElement(NULL, a,
			    Tcl_NewStringObj((char *) v->data, v->length));
		    }
		    Tcl_ListObjAppendElement(NULL, list, a);
		} else if (value->type == &UA_TYPES[UA_TYPES_DATETIME]) {
		    int i;
		    UA_DateTime *t = (UA_DateTime *) value->data;
		    Tcl_Obj *a = Tcl_NewListObj(value->arrayLength, NULL);

		    for (i = 0; i < value->arrayLength; i++) {
			Tcl_ListObjAppendElement(NULL, a,
			    Tcl_NewWideIntObj((Tcl_WideInt) t[i]));
		    }
		    Tcl_ListObjAppendElement(NULL, list, a);
		} else {
		    /* TBD */
		}
	    }
	}
    }
    UA_Array_delete(outArgs, nOutArgs, &UA_TYPES[UA_TYPES_VARIANT]);
    Tcl_SetObjResult(interp, list);
    return TCL_OK;
}

/*
 *-------------------------------------------------------------------------
 *
 * Topcua_Init --
 *
 *	Module initializer:
 *	  - require Tcl infrastructure
 *	  - initialize module data structures
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *-------------------------------------------------------------------------
 */

int DLLEXPORT
Topcua_Init(Tcl_Interp *interp)
{
    UACLI *uacli;
    int i, skip, new;
    Tcl_HashEntry *hPtr;
    Tcl_Namespace *nsPtr;
    Tcl_Obj *cmdList;
    Tcl_Command cmd;

    /*
     * UA data types for which a mapping is provided.
     */
    static const int types[] = {
	UA_TYPES_BOOLEAN, UA_TYPES_SBYTE, UA_TYPES_BYTE,
	UA_TYPES_INT16, UA_TYPES_UINT16, UA_TYPES_INT32,
	UA_TYPES_UINT32, UA_TYPES_INT64, UA_TYPES_UINT64,
	UA_TYPES_FLOAT, UA_TYPES_DOUBLE, UA_TYPES_STRING,
	UA_TYPES_DATETIME, UA_TYPES_GUID, UA_TYPES_BYTESTRING,
	UA_TYPES_XMLELEMENT, UA_TYPES_NODEID, UA_TYPES_EXPANDEDNODEID,
	UA_TYPES_STATUSCODE, UA_TYPES_QUALIFIEDNAME,
	UA_TYPES_LOCALIZEDTEXT, UA_TYPES_EXTENSIONOBJECT,
	UA_TYPES_DATAVALUE
    };

    /*
     * Aliased types as found with
     *   grep "#define.*UA_TYPES_.*UA_TYPES_" open62541/open62541.h
     */
    static const struct {
	const char *name;
	int type;
    } typeAliases[] = {
	{ "UtcTime", UA_TYPES_DATETIME },
	{ "LocaleId", UA_TYPES_STRING },
	{ "Duration", UA_TYPES_DOUBLE }
    };

    /*
     * Namespace commands to create.
     */
    static const struct {
	const char *name;
	Tcl_ObjCmdProc *proc;
    } nsCmds[] = {
	{ "::opcua::endpoints", EndpointsObjCmd },
	{ "::opcua::servers", ServersObjCmd },
	{ "::opcua::new", NewObjCmd },
	{ "::opcua::destroy", DestroyObjCmd },
	{ "::opcua::connect", ConnectObjCmd },
	{ "::opcua::disconnect", DisconnectObjCmd },
	{ "::opcua::info", InfoObjCmd },
	{ "::opcua::sc2str", Sc2StrObjCmd },
	{ "::opcua::browse", BrowseObjCmd },
	{ "::opcua::translate", TranslateObjCmd },
	{ "::opcua::attrs", AttrsObjCmd },
	{ "::opcua::types", TypesObjCmd },
	{ "::opcua::reftype", RefTypeObjCmd },
	{ "::opcua::read", ReadObjCmd },
	{ "::opcua::type", TypeObjCmd },
	{ "::opcua::write", WriteObjCmd },
	{ "::opcua::call", CallObjCmd }
    };

#ifdef USE_TCL_STUBS
    if (Tcl_InitStubs(interp, "8.5", 0) == NULL) {
	return TCL_ERROR;
    }
#else
    if (Tcl_PkgRequire(interp, "Tcl", "8.5", 0) == NULL) {
	return TCL_ERROR;
    }
#endif
    if (Tcl_PkgProvide(interp, PACKAGE_NAME, PACKAGE_VERSION) != TCL_OK) {
	return TCL_ERROR;
    }
    uacli = (UACLI *) ckalloc(sizeof(UACLI));
    memset(uacli, 0, sizeof(UACLI));
    uacli->idCount = 0;
    Tcl_InitHashTable(&uacli->clients, TCL_STRING_KEYS);

    /*
     * Basic (scalar) types we can map.
     */
    Tcl_InitHashTable(&uacli->types, TCL_STRING_KEYS);
    for (i = 0; i < sizeof(types) / sizeof(types[0]); i++) {
	hPtr = Tcl_CreateHashEntry(&uacli->types,
				   UA_TYPES[types[i]].typeName, &new);
	Tcl_SetHashValue(hPtr, &UA_TYPES[i]);
    }
    for (i = 0; i < sizeof(typeAliases) / sizeof(typeAliases[0]); i++) {
	hPtr = Tcl_CreateHashEntry(&uacli->types,
				   typeAliases[i].name, &new);
	Tcl_SetHashValue(hPtr, &UA_TYPES[typeAliases[i].type]);
    }

    /*
     * UA_Client configuration overriden with logging silenced.
     */
    uacli->clcfg = UA_ClientConfig_default;
    uacli->clcfg.logger = DoNotLog;

    /*
     * Create and populate "::opcua" namespace with module commands.
     */
    nsPtr = Tcl_CreateNamespace(interp, "::opcua", (ClientData) uacli,
				NamespaceDeleted);
    cmdList = Tcl_NewListObj(sizeof(nsCmds) / sizeof(nsCmds[0]), NULL);
    skip = strlen("::opcua::");
    for (i = 0; i < sizeof(nsCmds) / sizeof(nsCmds[0]); i++) {
	Tcl_ListObjAppendElement(NULL, cmdList,
	    Tcl_NewStringObj(nsCmds[i].name + skip, -1));
    }
    cmd = Tcl_CreateEnsemble(interp, "::opcua", nsPtr, TCL_ENSEMBLE_PREFIX);
    Tcl_SetEnsembleSubcommandList(interp, cmd, cmdList);
    for (i = 0; i < sizeof(nsCmds) / sizeof(nsCmds[0]); i++) {
	Tcl_CreateObjCommand(interp, nsCmds[i].name, nsCmds[i].proc,
			     (ClientData) uacli, (Tcl_CmdDeleteProc *) NULL);
    }
    return TCL_OK;
}

/*
 * Local Variables:
 * mode: c
 * c-basic-offset: 4
 * fill-column: 78
 * tab-width: 8
 * End:
 */
Changes to undroid/build-undroidwish-generic.sh.
96
97
98
99
100
101
102


103
104
105
106
107
108
109
    aarch*)
      SUBDIRS="${SUBDIRS} piio"
      ;;
  esac
  SUBDIRS="${SUBDIRS} libsocketcan tclcan fswatch tserialport"
fi



ACTION="$1"
if test -z "$ACTION" ; then
  ACTION=build
fi

clean_build_stamps() {
  for i in $@ ; do







>
>







96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
    aarch*)
      SUBDIRS="${SUBDIRS} piio"
      ;;
  esac
  SUBDIRS="${SUBDIRS} libsocketcan tclcan fswatch tserialport"
fi

SUBDIRS="${SUBDIRS} topcua"

ACTION="$1"
if test -z "$ACTION" ; then
  ACTION=build
fi

clean_build_stamps() {
  for i in $@ ; do
1377
1378
1379
1380
1381
1382
1383














1384
1385
1386
1387
1388
1389
1390
    make prerequisite || exit 1
    make || exit 1
    make install-binaries install-libraries DESTDIR=${HERE} || exit 1
    touch build-stamp
    echo >&3 "done"
  ) || fail
fi















echo -n "strip binaries ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  set -x
  $STRIP ${PFX_HERE}/bin/tclsh* ${PFX_HERE}/bin/sdl2wish* \







>
>
>
>
>
>
>
>
>
>
>
>
>
>







1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
    make prerequisite || exit 1
    make || exit 1
    make install-binaries install-libraries DESTDIR=${HERE} || exit 1
    touch build-stamp
    echo >&3 "done"
  ) || fail
fi

echo -n "build topcua ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  cd topcua
  test -e build-stamp && echo >&3 "already done" && exit 0
  CFLAGS="-std=c99" DESTDIR=${HERE} ./configure --prefix=${PFX} \
      --with-tcl=${HERE}/tcl/unix --enable-threads || exit 1
  make || exit 1
  make install-binaries install-libraries DESTDIR=${HERE} || exit 1
  touch build-stamp
  echo >&3 "done"
) || fail

echo -n "strip binaries ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  set -x
  $STRIP ${PFX_HERE}/bin/tclsh* ${PFX_HERE}/bin/sdl2wish* \
1519
1520
1521
1522
1523
1524
1525

1526
1527
1528
1529
1530
1531
1532
  cp -rp ${PFX_HERE}/lib/tclcompiler* assets
  if test -d ${PFX_HERE}/lib/fswatch* ; then
    cp -rp ${PFX_HERE}/lib/fswatch* assets
  fi
  if test -d ${PFX_HERE}/lib/tserialport* ; then
    cp -rp ${PFX_HERE}/lib/tserialport* assets
  fi

  # add shortcuts providing builtin:widget, builtin:tksqlite, etc.
  (
    cd assets
    echo > widget \
      'source [file dirname [info script]]/'$(echo sdl2tk*)'/demos/widget'
    echo > tksqlite \
      'source [file dirname [info script]]/'$(echo tksqlite*)'/tksqlite.tcl'







>







1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
  cp -rp ${PFX_HERE}/lib/tclcompiler* assets
  if test -d ${PFX_HERE}/lib/fswatch* ; then
    cp -rp ${PFX_HERE}/lib/fswatch* assets
  fi
  if test -d ${PFX_HERE}/lib/tserialport* ; then
    cp -rp ${PFX_HERE}/lib/tserialport* assets
  fi
  cp -rp ${PFX_HERE}/lib/topcua* assets
  # add shortcuts providing builtin:widget, builtin:tksqlite, etc.
  (
    cd assets
    echo > widget \
      'source [file dirname [info script]]/'$(echo sdl2tk*)'/demos/widget'
    echo > tksqlite \
      'source [file dirname [info script]]/'$(echo tksqlite*)'/tksqlite.tcl'
Changes to undroid/build-undroidwish-kmsdrm.sh.
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
SUBDIRS="${SUBDIRS} 3dcanvas tkimg trf tktable tktreectrl tkpath itk v4l2"
SUBDIRS="${SUBDIRS} tkhtml dbus-tcl dbus-intf tclx libdmtx ZBar zint"
SUBDIRS="${SUBDIRS} tcl-augeas snack tkvnc tksvg VecTcl tclral"
SUBDIRS="${SUBDIRS} tclepeg tcluvc xotcl nsf libsocketcan tclcan vu"
SUBDIRS="${SUBDIRS} rl_json mpexpr"
SUBDIRS="${SUBDIRS} tclcsv tkzinc libffi ffidl tcl-lmdb DiffUtilTcl"
SUBDIRS="${SUBDIRS} tclparser tclcompiler snap7 libmodbus fswatch"
SUBDIRS="${SUBDIRS} tserialport"

ACTION="$1"
if test -z "$ACTION" ; then
  ACTION=build
fi

clean_build_stamps() {







|







84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
SUBDIRS="${SUBDIRS} 3dcanvas tkimg trf tktable tktreectrl tkpath itk v4l2"
SUBDIRS="${SUBDIRS} tkhtml dbus-tcl dbus-intf tclx libdmtx ZBar zint"
SUBDIRS="${SUBDIRS} tcl-augeas snack tkvnc tksvg VecTcl tclral"
SUBDIRS="${SUBDIRS} tclepeg tcluvc xotcl nsf libsocketcan tclcan vu"
SUBDIRS="${SUBDIRS} rl_json mpexpr"
SUBDIRS="${SUBDIRS} tclcsv tkzinc libffi ffidl tcl-lmdb DiffUtilTcl"
SUBDIRS="${SUBDIRS} tclparser tclcompiler snap7 libmodbus fswatch"
SUBDIRS="${SUBDIRS} tserialport topcua"

ACTION="$1"
if test -z "$ACTION" ; then
  ACTION=build
fi

clean_build_stamps() {
1336
1337
1338
1339
1340
1341
1342














1343
1344
1345
1346
1347
1348
1349
    --with-tcl=${HERE}/tcl/unix --enable-threads || exit 1
  make prerequisite || exit 1
  make || exit 1
  make install-binaries install-libraries DESTDIR=${HERE} || exit 1
  touch build-stamp
  echo >&3 "done"
) || fail















echo -n "strip binaries ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  set -x
  $STRIP ${PFX_HERE}/bin/tclsh* ${PFX_HERE}/bin/sdl2wish* \







>
>
>
>
>
>
>
>
>
>
>
>
>
>







1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
    --with-tcl=${HERE}/tcl/unix --enable-threads || exit 1
  make prerequisite || exit 1
  make || exit 1
  make install-binaries install-libraries DESTDIR=${HERE} || exit 1
  touch build-stamp
  echo >&3 "done"
) || fail

echo -n "build topcua ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  cd topcua
  test -e build-stamp && echo >&3 "already done" && exit 0
  CFLAGS="-std=c99" DESTDIR=${HERE} ./configure --prefix=${PFX} \
      --with-tcl=${HERE}/tcl/unix --enable-threads || exit 1
  make || exit 1
  make install-binaries install-libraries DESTDIR=${HERE} || exit 1
  touch build-stamp
  echo >&3 "done"
) || fail

echo -n "strip binaries ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  set -x
  $STRIP ${PFX_HERE}/bin/tclsh* ${PFX_HERE}/bin/sdl2wish* \
1467
1468
1469
1470
1471
1472
1473

1474
1475
1476
1477
1478
1479
1480
  cp -rp ${PFX_HERE}/lib/Ffidl* assets
  cp -rp ${PFX_HERE}/lib/lmdb* assets
  cp -rp ${PFX_HERE}/lib/DiffUtil* assets
  cp -rp ${PFX_HERE}/lib/parser* assets
  cp -rp ${PFX_HERE}/lib/tclcompiler* assets
  cp -rp ${PFX_HERE}/lib/fswatch* assets
  cp -rp ${PFX_HERE}/lib/tserialport* assets

  # add shortcuts providing builtin:widget, builtin:tksqlite, etc.
  (
    cd assets
    echo > widget \
      'source [file dirname [info script]]/'$(echo sdl2tk*)'/demos/widget'
    echo > tksqlite \
      'source [file dirname [info script]]/'$(echo tksqlite*)'/tksqlite.tcl'







>







1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
  cp -rp ${PFX_HERE}/lib/Ffidl* assets
  cp -rp ${PFX_HERE}/lib/lmdb* assets
  cp -rp ${PFX_HERE}/lib/DiffUtil* assets
  cp -rp ${PFX_HERE}/lib/parser* assets
  cp -rp ${PFX_HERE}/lib/tclcompiler* assets
  cp -rp ${PFX_HERE}/lib/fswatch* assets
  cp -rp ${PFX_HERE}/lib/tserialport* assets
  cp -rp ${PFX_HERE}/lib/topcua* assets
  # add shortcuts providing builtin:widget, builtin:tksqlite, etc.
  (
    cd assets
    echo > widget \
      'source [file dirname [info script]]/'$(echo sdl2tk*)'/demos/widget'
    echo > tksqlite \
      'source [file dirname [info script]]/'$(echo tksqlite*)'/tksqlite.tcl'
Changes to undroid/build-undroidwish-linux32.sh.
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
SUBDIRS="${SUBDIRS} 3dcanvas tkimg trf tktable tktreectrl tkpath itk v4l2"
SUBDIRS="${SUBDIRS} tkhtml dbus-tcl dbus-intf tclx libdmtx ZBar zint"
SUBDIRS="${SUBDIRS} tcl-augeas snack tkvnc tksvg VecTcl tclral"
SUBDIRS="${SUBDIRS} tclepeg tcluvc xotcl nsf libsocketcan tclcan vu"
SUBDIRS="${SUBDIRS} rl_json mpexpr"
SUBDIRS="${SUBDIRS} tclcsv tkzinc libffi ffidl tcl-lmdb DiffUtilTcl"
SUBDIRS="${SUBDIRS} tclparser tclcompiler snap7 libmodbus fswatch"
SUBDIRS="${SUBDIRS} tserialport"

ACTION="$1"
if test -z "$ACTION" ; then
  ACTION=build
fi

clean_build_stamps() {







|







85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
SUBDIRS="${SUBDIRS} 3dcanvas tkimg trf tktable tktreectrl tkpath itk v4l2"
SUBDIRS="${SUBDIRS} tkhtml dbus-tcl dbus-intf tclx libdmtx ZBar zint"
SUBDIRS="${SUBDIRS} tcl-augeas snack tkvnc tksvg VecTcl tclral"
SUBDIRS="${SUBDIRS} tclepeg tcluvc xotcl nsf libsocketcan tclcan vu"
SUBDIRS="${SUBDIRS} rl_json mpexpr"
SUBDIRS="${SUBDIRS} tclcsv tkzinc libffi ffidl tcl-lmdb DiffUtilTcl"
SUBDIRS="${SUBDIRS} tclparser tclcompiler snap7 libmodbus fswatch"
SUBDIRS="${SUBDIRS} tserialport topcua"

ACTION="$1"
if test -z "$ACTION" ; then
  ACTION=build
fi

clean_build_stamps() {
1135
1136
1137
1138
1139
1140
1141



1142
1143




1144
1145
1146
1147
1148
1149
1150

echo -n "build libsocketcan ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  cd libsocketcan
  test -e build-stamp && echo >&3 "already done" && exit 0



  ./configure --build=i586-linux-gnu --prefix=${PFX} \
    --disable-static || exit 1




  make || exit 1
  make install DESTDIR=${HERE} || exit 1
  touch build-stamp
  echo >&3 "done"
) || fail

echo -n "build tclcan ... "







>
>
>
|
|
>
>
>
>







1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157

echo -n "build libsocketcan ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  cd libsocketcan
  test -e build-stamp && echo >&3 "already done" && exit 0
  # CentOS 5 lacks some stuff in rtnetlink.h, so need to cheat here
  if ! grep -q IFLA_INFO_MAX /usr/include/linux/rtnetlink.h ; then
    CFLAGS="-I${SCRIPTDIR}/compat" \
      ./configure --build=i586-linux-gnu --prefix=${PFX} \
        --disable-static || exit 1
  else
    ./configure --build=i586-linux-gnu --prefix=${PFX} \
      --disable-static || exit 1
  fi
  make || exit 1
  make install DESTDIR=${HERE} || exit 1
  touch build-stamp
  echo >&3 "done"
) || fail

echo -n "build tclcan ... "
1358
1359
1360
1361
1362
1363
1364














1365
1366
1367
1368
1369
1370
1371
  make prerequisite || exit 1
  make || exit 1
  make install-binaries install-libraries DESTDIR=${HERE} || exit 1
  touch build-stamp
  echo >&3 "done"
) || fail
















echo -n "strip binaries ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  set -x
  $STRIP ${PFX_HERE}/bin/tclsh* ${PFX_HERE}/bin/sdl2wish* \







>
>
>
>
>
>
>
>
>
>
>
>
>
>







1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
  make prerequisite || exit 1
  make || exit 1
  make install-binaries install-libraries DESTDIR=${HERE} || exit 1
  touch build-stamp
  echo >&3 "done"
) || fail

echo -n "build topcua ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  cd topcua
  test -e build-stamp && echo >&3 "already done" && exit 0
  CFLAGS="-std=c99" DESTDIR=${HERE} \
    ./configure --build=i586-linux-gnu --prefix=${PFX} \
      --with-tcl=${HERE}/tcl/unix --enable-threads || exit 1
  make || exit 1
  make install-binaries install-libraries DESTDIR=${HERE} || exit 1
  touch build-stamp
  echo >&3 "done"
) || fail

echo -n "strip binaries ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  set -x
  $STRIP ${PFX_HERE}/bin/tclsh* ${PFX_HERE}/bin/sdl2wish* \
1489
1490
1491
1492
1493
1494
1495

1496
1497
1498
1499
1500
1501
1502
  cp -rp ${PFX_HERE}/lib/Ffidl* assets
  cp -rp ${PFX_HERE}/lib/lmdb* assets
  cp -rp ${PFX_HERE}/lib/DiffUtil* assets
  cp -rp ${PFX_HERE}/lib/parser* assets
  cp -rp ${PFX_HERE}/lib/tclcompiler* assets
  cp -rp ${PFX_HERE}/lib/fswatch* assets
  cp -rp ${PFX_HERE}/lib/tserialport* assets

  # add shortcuts providing builtin:widget, builtin:tksqlite, etc.
  (
    cd assets
    echo > widget \
      'source [file dirname [info script]]/'$(echo sdl2tk*)'/demos/widget'
    echo > tksqlite \
      'source [file dirname [info script]]/'$(echo tksqlite*)'/tksqlite.tcl'







>







1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
  cp -rp ${PFX_HERE}/lib/Ffidl* assets
  cp -rp ${PFX_HERE}/lib/lmdb* assets
  cp -rp ${PFX_HERE}/lib/DiffUtil* assets
  cp -rp ${PFX_HERE}/lib/parser* assets
  cp -rp ${PFX_HERE}/lib/tclcompiler* assets
  cp -rp ${PFX_HERE}/lib/fswatch* assets
  cp -rp ${PFX_HERE}/lib/tserialport* assets
  cp -rp ${PFX_HERE}/lib/topcua* assets
  # add shortcuts providing builtin:widget, builtin:tksqlite, etc.
  (
    cd assets
    echo > widget \
      'source [file dirname [info script]]/'$(echo sdl2tk*)'/demos/widget'
    echo > tksqlite \
      'source [file dirname [info script]]/'$(echo tksqlite*)'/tksqlite.tcl'
Changes to undroid/build-undroidwish-linux64.sh.
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
SUBDIRS="${SUBDIRS} 3dcanvas tkimg trf tktable tktreectrl tkpath itk v4l2"
SUBDIRS="${SUBDIRS} tkhtml dbus-tcl dbus-intf tclx libdmtx ZBar zint"
SUBDIRS="${SUBDIRS} tcl-augeas snack tkvnc tksvg VecTcl tclral"
SUBDIRS="${SUBDIRS} tclepeg tcluvc xotcl nsf libsocketcan tclcan vu"
SUBDIRS="${SUBDIRS} rl_json mpexpr"
SUBDIRS="${SUBDIRS} tclcsv tkzinc libffi ffidl tcl-lmdb DiffUtilTcl"
SUBDIRS="${SUBDIRS} tclparser tclcompiler snap7 libmodbus fswatch"
SUBDIRS="${SUBDIRS} tserialport"

ACTION="$1"
if test -z "$ACTION" ; then
  ACTION=build
fi

clean_build_stamps() {







|







85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
SUBDIRS="${SUBDIRS} 3dcanvas tkimg trf tktable tktreectrl tkpath itk v4l2"
SUBDIRS="${SUBDIRS} tkhtml dbus-tcl dbus-intf tclx libdmtx ZBar zint"
SUBDIRS="${SUBDIRS} tcl-augeas snack tkvnc tksvg VecTcl tclral"
SUBDIRS="${SUBDIRS} tclepeg tcluvc xotcl nsf libsocketcan tclcan vu"
SUBDIRS="${SUBDIRS} rl_json mpexpr"
SUBDIRS="${SUBDIRS} tclcsv tkzinc libffi ffidl tcl-lmdb DiffUtilTcl"
SUBDIRS="${SUBDIRS} tclparser tclcompiler snap7 libmodbus fswatch"
SUBDIRS="${SUBDIRS} tserialport topcua"

ACTION="$1"
if test -z "$ACTION" ; then
  ACTION=build
fi

clean_build_stamps() {
1135
1136
1137
1138
1139
1140
1141



1142
1143




1144
1145
1146
1147
1148
1149
1150

echo -n "build libsocketcan ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  cd libsocketcan
  test -e build-stamp && echo >&3 "already done" && exit 0



  ./configure --build=x86_64-linux-gnu --prefix=${PFX} \
    --disable-static || exit 1




  make || exit 1
  make install DESTDIR=${HERE} || exit 1
  touch build-stamp
  echo >&3 "done"
) || fail

echo -n "build tclcan ... "







>
>
>
|
|
>
>
>
>







1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157

echo -n "build libsocketcan ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  cd libsocketcan
  test -e build-stamp && echo >&3 "already done" && exit 0
  # CentOS 5 lacks some stuff in rtnetlink.h, so need to cheat here
  if ! grep -q IFLA_INFO_MAX /usr/include/linux/rtnetlink.h ; then
    CFLAGS="-I${SCRIPTDIR}/compat" \
      ./configure --build=x86_64-linux-gnu --prefix=${PFX} \
        --disable-static || exit 1
  else
    ./configure --build=x86_64-linux-gnu --prefix=${PFX} \
      --disable-static || exit 1
  fi
  make || exit 1
  make install DESTDIR=${HERE} || exit 1
  touch build-stamp
  echo >&3 "done"
) || fail

echo -n "build tclcan ... "
1358
1359
1360
1361
1362
1363
1364














1365
1366
1367
1368
1369
1370
1371
  make prerequisite || exit 1
  make || exit 1
  make install-binaries install-libraries DESTDIR=${HERE} || exit 1
  touch build-stamp
  echo >&3 "done"
) || fail
















echo -n "strip binaries ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  set -x
  $STRIP ${PFX_HERE}/bin/tclsh* ${PFX_HERE}/bin/sdl2wish* \







>
>
>
>
>
>
>
>
>
>
>
>
>
>







1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
  make prerequisite || exit 1
  make || exit 1
  make install-binaries install-libraries DESTDIR=${HERE} || exit 1
  touch build-stamp
  echo >&3 "done"
) || fail

echo -n "build topcua ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  cd topcua
  test -e build-stamp && echo >&3 "already done" && exit 0
  CFLAGS="-std=c99" DESTDIR=${HERE} \
    ./configure --build=x86_64-linux-gnu --prefix=${PFX} \
      --with-tcl=${HERE}/tcl/unix --enable-threads || exit 1
  make || exit 1
  make install-binaries install-libraries DESTDIR=${HERE} || exit 1
  touch build-stamp
  echo >&3 "done"
) || fail

echo -n "strip binaries ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  set -x
  $STRIP ${PFX_HERE}/bin/tclsh* ${PFX_HERE}/bin/sdl2wish* \
1489
1490
1491
1492
1493
1494
1495

1496
1497
1498
1499
1500
1501
1502
  cp -rp ${PFX_HERE}/lib/Ffidl* assets
  cp -rp ${PFX_HERE}/lib/lmdb* assets
  cp -rp ${PFX_HERE}/lib/DiffUtil* assets
  cp -rp ${PFX_HERE}/lib/parser* assets
  cp -rp ${PFX_HERE}/lib/tclcompiler* assets
  cp -rp ${PFX_HERE}/lib/fswatch* assets
  cp -rp ${PFX_HERE}/lib/tserialport* assets

  # add shortcuts providing builtin:widget, builtin:tksqlite, etc.
  (
    cd assets
    echo > widget \
      'source [file dirname [info script]]/'$(echo sdl2tk*)'/demos/widget'
    echo > tksqlite \
      'source [file dirname [info script]]/'$(echo tksqlite*)'/tksqlite.tcl'







>







1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
  cp -rp ${PFX_HERE}/lib/Ffidl* assets
  cp -rp ${PFX_HERE}/lib/lmdb* assets
  cp -rp ${PFX_HERE}/lib/DiffUtil* assets
  cp -rp ${PFX_HERE}/lib/parser* assets
  cp -rp ${PFX_HERE}/lib/tclcompiler* assets
  cp -rp ${PFX_HERE}/lib/fswatch* assets
  cp -rp ${PFX_HERE}/lib/tserialport* assets
  cp -rp ${PFX_HERE}/lib/topcua* assets
  # add shortcuts providing builtin:widget, builtin:tksqlite, etc.
  (
    cd assets
    echo > widget \
      'source [file dirname [info script]]/'$(echo sdl2tk*)'/demos/widget'
    echo > tksqlite \
      'source [file dirname [info script]]/'$(echo tksqlite*)'/tksqlite.tcl'
Changes to undroid/build-undroidwish-wayland.sh.
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
SUBDIRS="${SUBDIRS} 3dcanvas tkimg trf tktable tktreectrl tkpath itk v4l2"
SUBDIRS="${SUBDIRS} tkhtml dbus-tcl dbus-intf tclx libdmtx ZBar zint"
SUBDIRS="${SUBDIRS} tcl-augeas snack tkvnc tksvg VecTcl tclral"
SUBDIRS="${SUBDIRS} tclepeg tcluvc xotcl nsf libsocketcan tclcan vu"
SUBDIRS="${SUBDIRS} rl_json mpexpr"
SUBDIRS="${SUBDIRS} tclcsv tkzinc libffi ffidl tcl-lmdb DiffUtilTcl"
SUBDIRS="${SUBDIRS} tclparser tclcompiler snap7 libmodbus fswatch"
SUBDIRS="${SUBDIRS} tserialport"

ACTION="$1"
if test -z "$ACTION" ; then
  ACTION=build
fi

clean_build_stamps() {







|







84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
SUBDIRS="${SUBDIRS} 3dcanvas tkimg trf tktable tktreectrl tkpath itk v4l2"
SUBDIRS="${SUBDIRS} tkhtml dbus-tcl dbus-intf tclx libdmtx ZBar zint"
SUBDIRS="${SUBDIRS} tcl-augeas snack tkvnc tksvg VecTcl tclral"
SUBDIRS="${SUBDIRS} tclepeg tcluvc xotcl nsf libsocketcan tclcan vu"
SUBDIRS="${SUBDIRS} rl_json mpexpr"
SUBDIRS="${SUBDIRS} tclcsv tkzinc libffi ffidl tcl-lmdb DiffUtilTcl"
SUBDIRS="${SUBDIRS} tclparser tclcompiler snap7 libmodbus fswatch"
SUBDIRS="${SUBDIRS} tserialport topcua"

ACTION="$1"
if test -z "$ACTION" ; then
  ACTION=build
fi

clean_build_stamps() {
1336
1337
1338
1339
1340
1341
1342














1343
1344
1345
1346
1347
1348
1349
    --with-tcl=${HERE}/tcl/unix --enable-threads || exit 1
  make prerequisite || exit 1
  make || exit 1
  make install-binaries install-libraries DESTDIR=${HERE} || exit 1
  touch build-stamp
  echo >&3 "done"
) || fail















echo -n "strip binaries ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  set -x
  $STRIP ${PFX_HERE}/bin/tclsh* ${PFX_HERE}/bin/sdl2wish* \







>
>
>
>
>
>
>
>
>
>
>
>
>
>







1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
    --with-tcl=${HERE}/tcl/unix --enable-threads || exit 1
  make prerequisite || exit 1
  make || exit 1
  make install-binaries install-libraries DESTDIR=${HERE} || exit 1
  touch build-stamp
  echo >&3 "done"
) || fail

echo -n "build topcua ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  cd topcua
  test -e build-stamp && echo >&3 "already done" && exit 0
  CFLAGS="-std=c99" DESTDIR=${HERE} ./configure --prefix=${PFX} \
      --with-tcl=${HERE}/tcl/unix --enable-threads || exit 1
  make || exit 1
  make install-binaries install-libraries DESTDIR=${HERE} || exit 1
  touch build-stamp
  echo >&3 "done"
) || fail

echo -n "strip binaries ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  set -x
  $STRIP ${PFX_HERE}/bin/tclsh* ${PFX_HERE}/bin/sdl2wish* \
1467
1468
1469
1470
1471
1472
1473

1474
1475
1476
1477
1478
1479
1480
  cp -rp ${PFX_HERE}/lib/Ffidl* assets
  cp -rp ${PFX_HERE}/lib/lmdb* assets
  cp -rp ${PFX_HERE}/lib/DiffUtil* assets
  cp -rp ${PFX_HERE}/lib/parser* assets
  cp -rp ${PFX_HERE}/lib/tclcompiler* assets
  cp -rp ${PFX_HERE}/lib/fswatch* assets
  cp -rp ${PFX_HERE}/lib/tserialport* assets

  # add shortcuts providing builtin:widget, builtin:tksqlite, etc.
  (
    cd assets
    echo > widget \
      'source [file dirname [info script]]/'$(echo sdl2tk*)'/demos/widget'
    echo > tksqlite \
      'source [file dirname [info script]]/'$(echo tksqlite*)'/tksqlite.tcl'







>







1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
  cp -rp ${PFX_HERE}/lib/Ffidl* assets
  cp -rp ${PFX_HERE}/lib/lmdb* assets
  cp -rp ${PFX_HERE}/lib/DiffUtil* assets
  cp -rp ${PFX_HERE}/lib/parser* assets
  cp -rp ${PFX_HERE}/lib/tclcompiler* assets
  cp -rp ${PFX_HERE}/lib/fswatch* assets
  cp -rp ${PFX_HERE}/lib/tserialport* assets
  cp -rp ${PFX_HERE}/lib/topcua* assets
  # add shortcuts providing builtin:widget, builtin:tksqlite, etc.
  (
    cd assets
    echo > widget \
      'source [file dirname [info script]]/'$(echo sdl2tk*)'/demos/widget'
    echo > tksqlite \
      'source [file dirname [info script]]/'$(echo tksqlite*)'/tksqlite.tcl'
Changes to undroid/build-vanilla-generic.sh.
97
98
99
100
101
102
103


104
105
106
107
108
109
110
    aarch*)
      SUBDIRS="${SUBDIRS} piio"
      ;;
  esac
  SUBDIRS="${SUBDIRS} libsocketcan tclcan fswatch tserialport"
fi



ACTION="$1"
if test -z "$ACTION" ; then
  ACTION=build
fi

clean_build_stamps() {
  for i in $@ ; do







>
>







97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
    aarch*)
      SUBDIRS="${SUBDIRS} piio"
      ;;
  esac
  SUBDIRS="${SUBDIRS} libsocketcan tclcan fswatch tserialport"
fi

SUBDIRS="${SUBDIRS} topcua"

ACTION="$1"
if test -z "$ACTION" ; then
  ACTION=build
fi

clean_build_stamps() {
  for i in $@ ; do
1351
1352
1353
1354
1355
1356
1357














1358
1359
1360
1361
1362
1363
1364
    make prerequisite || exit 1
    make || exit 1
    make install-binaries install-libraries DESTDIR=${HERE} || exit 1
    touch build-stamp
    echo >&3 "done"
  ) || fail
fi















echo -n "strip binaries ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  set -x
  $STRIP ${PFX_HERE}/bin/tclsh* ${PFX_HERE}/bin/wish* ${PFX_HERE}/lib/*.so \







>
>
>
>
>
>
>
>
>
>
>
>
>
>







1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
    make prerequisite || exit 1
    make || exit 1
    make install-binaries install-libraries DESTDIR=${HERE} || exit 1
    touch build-stamp
    echo >&3 "done"
  ) || fail
fi

echo -n "build topcua ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  cd topcua
  test -e build-stamp && echo >&3 "already done" && exit 0
  CFLAGS="-std=c99" DESTDIR=${HERE} ./configure --prefix=${PFX} \
      --with-tcl=${HERE}/tcl/unix --enable-threads || exit 1
  make || exit 1
  make install-binaries install-libraries DESTDIR=${HERE} || exit 1
  touch build-stamp
  echo >&3 "done"
) || fail

echo -n "strip binaries ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  set -x
  $STRIP ${PFX_HERE}/bin/tclsh* ${PFX_HERE}/bin/wish* ${PFX_HERE}/lib/*.so \
1495
1496
1497
1498
1499
1500
1501

1502
1503
1504
1505
1506
1507
1508
  cp -rp ${PFX_HERE}/lib/tclcompiler* assets
  if test -d ${PFX_HERE}/lib/fswatch* ; then
    cp -rp ${PFX_HERE}/lib/fswatch* assets
  fi
  if test -d ${PFX_HERE}/lib/tserialport* ; then
    cp -rp ${PFX_HERE}/lib/tserialport* assets
  fi

  # add stripped down TDK
  cp -rp ${AWDIR}/undroid/TDK assets
  # add shortcuts providing builtin:widget, builtin:tksqlite, etc.
  (
    cd assets
    echo > widget \
      'source [file dirname [info script]]/'$(echo tk8*)'/demos/widget'







>







1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
  cp -rp ${PFX_HERE}/lib/tclcompiler* assets
  if test -d ${PFX_HERE}/lib/fswatch* ; then
    cp -rp ${PFX_HERE}/lib/fswatch* assets
  fi
  if test -d ${PFX_HERE}/lib/tserialport* ; then
    cp -rp ${PFX_HERE}/lib/tserialport* assets
  fi
  cp -rp ${PFX_HERE}/lib/topcua* assets
  # add stripped down TDK
  cp -rp ${AWDIR}/undroid/TDK assets
  # add shortcuts providing builtin:widget, builtin:tksqlite, etc.
  (
    cd assets
    echo > widget \
      'source [file dirname [info script]]/'$(echo tk8*)'/demos/widget'
Changes to undroid/build-vanilla-linux32.sh.
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
SUBDIRS="${SUBDIRS} tkimg trf tktable tktreectrl tkpath itk v4l2 tkhtml"
SUBDIRS="${SUBDIRS} dbus-tcl dbus-intf tclx libdmtx ZBar zint"
SUBDIRS="${SUBDIRS} tcl-augeas tktray snack tkvnc tksvg VecTcl tclral"
SUBDIRS="${SUBDIRS} tclepeg tcluvc xotcl nsf libsocketcan tclcan vu"
SUBDIRS="${SUBDIRS} rl_json tkdnd mpexpr"
SUBDIRS="${SUBDIRS} tclcsv tkzinc libffi ffidl tcl-lmdb DiffUtilTcl"
SUBDIRS="${SUBDIRS} tclparser tclcompiler snap7 libmodbus fswatch"
SUBDIRS="${SUBDIRS} tserialport"

ACTION="$1"
if test -z "$ACTION" ; then
  ACTION=build
fi

clean_build_stamps() {







|







85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
SUBDIRS="${SUBDIRS} tkimg trf tktable tktreectrl tkpath itk v4l2 tkhtml"
SUBDIRS="${SUBDIRS} dbus-tcl dbus-intf tclx libdmtx ZBar zint"
SUBDIRS="${SUBDIRS} tcl-augeas tktray snack tkvnc tksvg VecTcl tclral"
SUBDIRS="${SUBDIRS} tclepeg tcluvc xotcl nsf libsocketcan tclcan vu"
SUBDIRS="${SUBDIRS} rl_json tkdnd mpexpr"
SUBDIRS="${SUBDIRS} tclcsv tkzinc libffi ffidl tcl-lmdb DiffUtilTcl"
SUBDIRS="${SUBDIRS} tclparser tclcompiler snap7 libmodbus fswatch"
SUBDIRS="${SUBDIRS} tserialport topcua"

ACTION="$1"
if test -z "$ACTION" ; then
  ACTION=build
fi

clean_build_stamps() {
1097
1098
1099
1100
1101
1102
1103



1104
1105




1106
1107
1108
1109
1110
1111
1112

echo -n "build libsocketcan ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  cd libsocketcan
  test -e build-stamp && echo >&3 "already done" && exit 0



  ./configure --build=i586-linux-gnu --prefix=${PFX} \
    --disable-static || exit 1




  make || exit 1
  make install DESTDIR=${HERE} || exit 1
  touch build-stamp
  echo >&3 "done"
) || fail

echo -n "build tclcan ... "







>
>
>
|
|
>
>
>
>







1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119

echo -n "build libsocketcan ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  cd libsocketcan
  test -e build-stamp && echo >&3 "already done" && exit 0
  # CentOS 5 lacks some stuff in rtnetlink.h, so need to cheat here
  if ! grep -q IFLA_INFO_MAX /usr/include/linux/rtnetlink.h ; then
    CFLAGS="-I${SCRIPTDIR}/compat" \
      ./configure --build=i586-linux-gnu --prefix=${PFX} \
        --disable-static || exit 1
  else
    ./configure --build=i586-linux-gnu --prefix=${PFX} \
      --disable-static || exit 1
  fi
  make || exit 1
  make install DESTDIR=${HERE} || exit 1
  touch build-stamp
  echo >&3 "done"
) || fail

echo -n "build tclcan ... "
1334
1335
1336
1337
1338
1339
1340















1341
1342
1343
1344
1345
1346
1347
    --with-tcl=${HERE}/tcl/unix --enable-threads || exit 1
  make prerequisite || exit 1
  make || exit 1
  make install-binaries install-libraries DESTDIR=${HERE} || exit 1
  touch build-stamp
  echo >&3 "done"
) || fail
















echo -n "strip binaries ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  set -x
  $STRIP ${PFX_HERE}/bin/tclsh* ${PFX_HERE}/bin/wish* ${PFX_HERE}/lib/*.so \







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
    --with-tcl=${HERE}/tcl/unix --enable-threads || exit 1
  make prerequisite || exit 1
  make || exit 1
  make install-binaries install-libraries DESTDIR=${HERE} || exit 1
  touch build-stamp
  echo >&3 "done"
) || fail

echo -n "build topcua ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  cd topcua
  test -e build-stamp && echo >&3 "already done" && exit 0
  CFLAGS="-std=c99" DESTDIR=${HERE} \
    ./configure --build=i586-linux-gnu --prefix=${PFX} \
      --with-tcl=${HERE}/tcl/unix --enable-threads || exit 1
  make || exit 1
  make install-binaries install-libraries DESTDIR=${HERE} || exit 1
  touch build-stamp
  echo >&3 "done"
) || fail

echo -n "strip binaries ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  set -x
  $STRIP ${PFX_HERE}/bin/tclsh* ${PFX_HERE}/bin/wish* ${PFX_HERE}/lib/*.so \
1467
1468
1469
1470
1471
1472
1473

1474
1475
1476
1477
1478
1479
1480
  cp -rp ${PFX_HERE}/lib/Ffidl* assets
  cp -rp ${PFX_HERE}/lib/lmdb* assets
  cp -rp ${PFX_HERE}/lib/DiffUtil* assets
  cp -rp ${PFX_HERE}/lib/parser* assets
  cp -rp ${PFX_HERE}/lib/tclcompiler* assets
  cp -rp ${PFX_HERE}/lib/fswatch* assets
  cp -rp ${PFX_HERE}/lib/tserialport* assets

  # add stripped down TDK
  cp -rp ${AWDIR}/undroid/TDK assets
  # add shortcuts providing builtin:widget, builtin:tksqlite, etc.
  (
    cd assets
    echo > widget \
      'source [file dirname [info script]]/'$(echo tk8*)'/demos/widget'







>







1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
  cp -rp ${PFX_HERE}/lib/Ffidl* assets
  cp -rp ${PFX_HERE}/lib/lmdb* assets
  cp -rp ${PFX_HERE}/lib/DiffUtil* assets
  cp -rp ${PFX_HERE}/lib/parser* assets
  cp -rp ${PFX_HERE}/lib/tclcompiler* assets
  cp -rp ${PFX_HERE}/lib/fswatch* assets
  cp -rp ${PFX_HERE}/lib/tserialport* assets
  cp -rp ${PFX_HERE}/lib/topcua* assets
  # add stripped down TDK
  cp -rp ${AWDIR}/undroid/TDK assets
  # add shortcuts providing builtin:widget, builtin:tksqlite, etc.
  (
    cd assets
    echo > widget \
      'source [file dirname [info script]]/'$(echo tk8*)'/demos/widget'
Changes to undroid/build-vanilla-linux64.sh.
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
SUBDIRS="${SUBDIRS} tkimg trf tktable tktreectrl tkpath itk v4l2 tkhtml"
SUBDIRS="${SUBDIRS} dbus-tcl dbus-intf tclx libdmtx ZBar zint"
SUBDIRS="${SUBDIRS} tcl-augeas tktray snack tkvnc tksvg VecTcl tclral"
SUBDIRS="${SUBDIRS} tclepeg tcluvc xotcl nsf libsocketcan tclcan vu"
SUBDIRS="${SUBDIRS} rl_json tkdnd mpexpr"
SUBDIRS="${SUBDIRS} tclcsv tkzinc libffi ffidl tcl-lmdb DiffUtilTcl"
SUBDIRS="${SUBDIRS} tclparser tclcompiler snap7 libmodbus fswatch"
SUBDIRS="${SUBDIRS} tserialport"

ACTION="$1"
if test -z "$ACTION" ; then
  ACTION=build
fi

clean_build_stamps() {







|







85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
SUBDIRS="${SUBDIRS} tkimg trf tktable tktreectrl tkpath itk v4l2 tkhtml"
SUBDIRS="${SUBDIRS} dbus-tcl dbus-intf tclx libdmtx ZBar zint"
SUBDIRS="${SUBDIRS} tcl-augeas tktray snack tkvnc tksvg VecTcl tclral"
SUBDIRS="${SUBDIRS} tclepeg tcluvc xotcl nsf libsocketcan tclcan vu"
SUBDIRS="${SUBDIRS} rl_json tkdnd mpexpr"
SUBDIRS="${SUBDIRS} tclcsv tkzinc libffi ffidl tcl-lmdb DiffUtilTcl"
SUBDIRS="${SUBDIRS} tclparser tclcompiler snap7 libmodbus fswatch"
SUBDIRS="${SUBDIRS} tserialport topcua"

ACTION="$1"
if test -z "$ACTION" ; then
  ACTION=build
fi

clean_build_stamps() {
1097
1098
1099
1100
1101
1102
1103



1104
1105




1106
1107
1108
1109
1110
1111
1112

echo -n "build libsocketcan ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  cd libsocketcan
  test -e build-stamp && echo >&3 "already done" && exit 0



  ./configure --build=x86_64-linux-gnu --prefix=${PFX} \
    --disable-static || exit 1




  make || exit 1
  make install DESTDIR=${HERE} || exit 1
  touch build-stamp
  echo >&3 "done"
) || fail

echo -n "build tclcan ... "







>
>
>
|
|
>
>
>
>







1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119

echo -n "build libsocketcan ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  cd libsocketcan
  test -e build-stamp && echo >&3 "already done" && exit 0
  # CentOS 5 lacks some stuff in rtnetlink.h, so need to cheat here
  if ! grep -q IFLA_INFO_MAX /usr/include/linux/rtnetlink.h ; then
    CFLAGS="-I${SCRIPTDIR}/compat" \
      ./configure --build=x86_64-linux-gnu --prefix=${PFX} \
        --disable-static || exit 1
  else
    ./configure --build=x86_64-linux-gnu --prefix=${PFX} \
      --disable-static || exit 1
  fi
  make || exit 1
  make install DESTDIR=${HERE} || exit 1
  touch build-stamp
  echo >&3 "done"
) || fail

echo -n "build tclcan ... "
1334
1335
1336
1337
1338
1339
1340















1341
1342
1343
1344
1345
1346
1347
    --with-tcl=${HERE}/tcl/unix --enable-threads || exit 1
  make prerequisite || exit 1
  make || exit 1
  make install-binaries install-libraries DESTDIR=${HERE} || exit 1
  touch build-stamp
  echo >&3 "done"
) || fail
















echo -n "strip binaries ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  set -x
  $STRIP ${PFX_HERE}/bin/tclsh* ${PFX_HERE}/bin/wish* ${PFX_HERE}/lib/*.so \







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
    --with-tcl=${HERE}/tcl/unix --enable-threads || exit 1
  make prerequisite || exit 1
  make || exit 1
  make install-binaries install-libraries DESTDIR=${HERE} || exit 1
  touch build-stamp
  echo >&3 "done"
) || fail

echo -n "build topcua ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  cd topcua
  test -e build-stamp && echo >&3 "already done" && exit 0
  CFLAGS="-std=c99" DESTDIR=${HERE} \
    ./configure --build=x86_64-linux-gnu --prefix=${PFX} \
      --with-tcl=${HERE}/tcl/unix --enable-threads || exit 1
  make || exit 1
  make install-binaries install-libraries DESTDIR=${HERE} || exit 1
  touch build-stamp
  echo >&3 "done"
) || fail

echo -n "strip binaries ... "
(
  exec 3>&1
  exec >> build.log 2>&1
  set -x
  $STRIP ${PFX_HERE}/bin/tclsh* ${PFX_HERE}/bin/wish* ${PFX_HERE}/lib/*.so \
1467
1468
1469
1470
1471
1472
1473

1474
1475
1476
1477
1478
1479
1480
  cp -rp ${PFX_HERE}/lib/Ffidl* assets
  cp -rp ${PFX_HERE}/lib/lmdb* assets
  cp -rp ${PFX_HERE}/lib/DiffUtil* assets
  cp -rp ${PFX_HERE}/lib/parser* assets
  cp -rp ${PFX_HERE}/lib/tclcompiler* assets
  cp -rp ${PFX_HERE}/lib/fswatch* assets
  cp -rp ${PFX_HERE}/lib/tserialport* assets

  # add stripped down TDK
  cp -rp ${AWDIR}/undroid/TDK assets
  # add shortcuts providing builtin:widget, builtin:tksqlite, etc.
  (
    cd assets
    echo > widget \
      'source [file dirname [info script]]/'$(echo tk8*)'/demos/widget'







>







1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
  cp -rp ${PFX_HERE}/lib/Ffidl* assets
  cp -rp ${PFX_HERE}/lib/lmdb* assets
  cp -rp ${PFX_HERE}/lib/DiffUtil* assets
  cp -rp ${PFX_HERE}/lib/parser* assets
  cp -rp ${PFX_HERE}/lib/tclcompiler* assets
  cp -rp ${PFX_HERE}/lib/fswatch* assets
  cp -rp ${PFX_HERE}/lib/tserialport* assets
  cp -rp ${PFX_HERE}/lib/topcua* assets
  # add stripped down TDK
  cp -rp ${AWDIR}/undroid/TDK assets
  # add shortcuts providing builtin:widget, builtin:tksqlite, etc.
  (
    cd assets
    echo > widget \
      'source [file dirname [info script]]/'$(echo tk8*)'/demos/widget'
Added undroid/compat/linux/if_link.h.






















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
#ifndef _LINUX_IF_LINK_H
#define _LINUX_IF_LINK_H

#include <linux/types.h>
#include <linux/netlink.h>

/* This struct should be in sync with struct rtnl_link_stats64 */
struct rtnl_link_stats {
	__u32	rx_packets;		/* total packets received	*/
	__u32	tx_packets;		/* total packets transmitted	*/
	__u32	rx_bytes;		/* total bytes received 	*/
	__u32	tx_bytes;		/* total bytes transmitted	*/
	__u32	rx_errors;		/* bad packets received		*/
	__u32	tx_errors;		/* packet transmit problems	*/
	__u32	rx_dropped;		/* no space in linux buffers	*/
	__u32	tx_dropped;		/* no space available in linux	*/
	__u32	multicast;		/* multicast packets received	*/
	__u32	collisions;

	/* detailed rx_errors: */
	__u32	rx_length_errors;
	__u32	rx_over_errors;		/* receiver ring buff overflow	*/
	__u32	rx_crc_errors;		/* recved pkt with crc error	*/
	__u32	rx_frame_errors;	/* recv'd frame alignment error */
	__u32	rx_fifo_errors;		/* recv'r fifo overrun		*/
	__u32	rx_missed_errors;	/* receiver missed packet	*/

	/* detailed tx_errors */
	__u32	tx_aborted_errors;
	__u32	tx_carrier_errors;
	__u32	tx_fifo_errors;
	__u32	tx_heartbeat_errors;
	__u32	tx_window_errors;

	/* for cslip etc */
	__u32	rx_compressed;
	__u32	tx_compressed;
};

/* The main device statistics structure */
struct rtnl_link_stats64 {
	__u64	rx_packets;		/* total packets received	*/
	__u64	tx_packets;		/* total packets transmitted	*/
	__u64	rx_bytes;		/* total bytes received 	*/
	__u64	tx_bytes;		/* total bytes transmitted	*/
	__u64	rx_errors;		/* bad packets received		*/
	__u64	tx_errors;		/* packet transmit problems	*/
	__u64	rx_dropped;		/* no space in linux buffers	*/
	__u64	tx_dropped;		/* no space available in linux	*/
	__u64	multicast;		/* multicast packets received	*/
	__u64	collisions;

	/* detailed rx_errors: */
	__u64	rx_length_errors;
	__u64	rx_over_errors;		/* receiver ring buff overflow	*/
	__u64	rx_crc_errors;		/* recved pkt with crc error	*/
	__u64	rx_frame_errors;	/* recv'd frame alignment error */
	__u64	rx_fifo_errors;		/* recv'r fifo overrun		*/
	__u64	rx_missed_errors;	/* receiver missed packet	*/

	/* detailed tx_errors */
	__u64	tx_aborted_errors;
	__u64	tx_carrier_errors;
	__u64	tx_fifo_errors;
	__u64	tx_heartbeat_errors;
	__u64	tx_window_errors;

	/* for cslip etc */
	__u64	rx_compressed;
	__u64	tx_compressed;
};

/* The struct should be in sync with struct ifmap */
struct rtnl_link_ifmap
{
	__u64	mem_start;
	__u64	mem_end;
	__u64	base_addr;
	__u16	irq;
	__u8	dma;
	__u8	port;
};

/*
 * IFLA_AF_SPEC
 *   Contains nested attributes for address family specific attributes.
 *   Each address family may create a attribute with the address family
 *   number as type and create its own attribute structure in it.
 *
 *   Example:
 *   [IFLA_AF_SPEC] = {
 *       [AF_INET] = {
 *           [IFLA_INET_CONF] = ...,
 *       },
 *       [AF_INET6] = {
 *           [IFLA_INET6_FLAGS] = ...,
 *           [IFLA_INET6_CONF] = ...,
 *       }
 *   }
 */

enum {
	IFLA_UNSPEC,
	IFLA_ADDRESS,
	IFLA_BROADCAST,
	IFLA_IFNAME,
	IFLA_MTU,
	IFLA_LINK,
	IFLA_QDISC,
	IFLA_STATS,
	IFLA_COST,
#define IFLA_COST IFLA_COST
	IFLA_PRIORITY,
#define IFLA_PRIORITY IFLA_PRIORITY
	IFLA_MASTER,
#define IFLA_MASTER IFLA_MASTER
	IFLA_WIRELESS,		/* Wireless Extension event - see wireless.h */
#define IFLA_WIRELESS IFLA_WIRELESS
	IFLA_PROTINFO,		/* Protocol specific information for a link */
#define IFLA_PROTINFO IFLA_PROTINFO
	IFLA_TXQLEN,
#define IFLA_TXQLEN IFLA_TXQLEN
	IFLA_MAP,
#define IFLA_MAP IFLA_MAP
	IFLA_WEIGHT,
#define IFLA_WEIGHT IFLA_WEIGHT
	IFLA_OPERSTATE,
	IFLA_LINKMODE,
	IFLA_LINKINFO,
#define IFLA_LINKINFO IFLA_LINKINFO
	IFLA_NET_NS_PID,
	IFLA_IFALIAS,
	IFLA_NUM_VF,		/* Number of VFs if device is SR-IOV PF */
	IFLA_VFINFO_LIST,
	IFLA_STATS64,
	IFLA_VF_PORTS,
	IFLA_PORT_SELF,
	IFLA_AF_SPEC,
	IFLA_GROUP,		/* Group the device belongs to */
	IFLA_NET_NS_FD,
	IFLA_EXT_MASK,		/* Extended info mask, VFs, etc */
	IFLA_PROMISCUITY,       /* Promiscuity count: > 0 means acts PROMISC */
#define IFLA_PROMISCUITY IFLA_PROMISCUITY
	IFLA_NUM_TX_QUEUES,
	IFLA_NUM_RX_QUEUES,
	IFLA_CARRIER,
	IFLA_PHYS_PORT_ID,
	__IFLA_MAX
};


#define IFLA_MAX (__IFLA_MAX - 1)

/* backwards compatibility for userspace */
#define IFLA_RTA(r)  ((struct rtattr*)(((char*)(r)) + NLMSG_ALIGN(sizeof(struct ifinfomsg))))
#define IFLA_PAYLOAD(n) NLMSG_PAYLOAD(n,sizeof(struct ifinfomsg))

enum {
	IFLA_INET_UNSPEC,
	IFLA_INET_CONF,
	__IFLA_INET_MAX,
};

#define IFLA_INET_MAX (__IFLA_INET_MAX - 1)

/* ifi_flags.

   IFF_* flags.

   The only change is:
   IFF_LOOPBACK, IFF_BROADCAST and IFF_POINTOPOINT are
   more not changeable by user. They describe link media
   characteristics and set by device driver.

   Comments:
   - Combination IFF_BROADCAST|IFF_POINTOPOINT is invalid
   - If neither of these three flags are set;
     the interface is NBMA.

   - IFF_MULTICAST does not mean anything special:
   multicasts can be used on all not-NBMA links.
   IFF_MULTICAST means that this media uses special encapsulation
   for multicast frames. Apparently, all IFF_POINTOPOINT and
   IFF_BROADCAST devices are able to use multicasts too.
 */

/* IFLA_LINK.
   For usual devices it is equal ifi_index.
   If it is a "virtual interface" (f.e. tunnel), ifi_link
   can point to real physical interface (f.e. for bandwidth calculations),
   or maybe 0, what means, that real media is unknown (usual
   for IPIP tunnels, when route to endpoint is allowed to change)
 */

/* Subtype attributes for IFLA_PROTINFO */
enum
{
	IFLA_INET6_UNSPEC,
	IFLA_INET6_FLAGS,	/* link flags			*/
	IFLA_INET6_CONF,	/* sysctl parameters		*/
	IFLA_INET6_STATS,	/* statistics			*/
	IFLA_INET6_MCAST,	/* MC things. What of them?	*/
	IFLA_INET6_CACHEINFO,	/* time values and max reasm size */
	IFLA_INET6_ICMP6STATS,	/* statistics (icmpv6)		*/
	IFLA_INET6_TOKEN,	/* device token			*/
	__IFLA_INET6_MAX
};

#define IFLA_INET6_MAX	(__IFLA_INET6_MAX - 1)

/* Bridge section */

enum {
	IFLA_BR_UNSPEC,
	IFLA_BR_FORWARD_DELAY,
	IFLA_BR_HELLO_TIME,
	IFLA_BR_MAX_AGE,
	__IFLA_BR_MAX,
};

#define IFLA_BR_MAX	(__IFLA_BR_MAX - 1)

enum {
	BRIDGE_MODE_UNSPEC,
	BRIDGE_MODE_HAIRPIN,
};

enum {
	IFLA_BRPORT_UNSPEC,
	IFLA_BRPORT_STATE,	/* Spanning tree state     */
	IFLA_BRPORT_PRIORITY,	/* "             priority  */
	IFLA_BRPORT_COST,	/* "             cost      */
	IFLA_BRPORT_MODE,	/* mode (hairpin)          */
	__IFLA_BRPORT_MAX
};
#define IFLA_BRPORT_MAX (__IFLA_BRPORT_MAX - 1)

struct ifla_cacheinfo
{
	__u32	max_reasm_len;
	__u32	tstamp;		/* ipv6InterfaceTable updated timestamp */
	__u32	reachable_time;
	__u32	retrans_time;
};

enum
{
	IFLA_INFO_UNSPEC,
	IFLA_INFO_KIND,
	IFLA_INFO_DATA,
	IFLA_INFO_XSTATS,
	__IFLA_INFO_MAX,
};

#define IFLA_INFO_MAX	(__IFLA_INFO_MAX - 1)

/* VLAN section */

enum
{
	IFLA_VLAN_UNSPEC,
	IFLA_VLAN_ID,
	IFLA_VLAN_FLAGS,
	IFLA_VLAN_EGRESS_QOS,
	IFLA_VLAN_INGRESS_QOS,
	__IFLA_VLAN_MAX,
};

#define IFLA_VLAN_MAX	(__IFLA_VLAN_MAX - 1)

struct ifla_vlan_flags {
	__u32	flags;
	__u32	mask;
};

enum
{
	IFLA_VLAN_QOS_UNSPEC,
	IFLA_VLAN_QOS_MAPPING,
	__IFLA_VLAN_QOS_MAX
};

#define IFLA_VLAN_QOS_MAX	(__IFLA_VLAN_QOS_MAX - 1)

struct ifla_vlan_qos_mapping
{
	__u32 from;
	__u32 to;
};

/* MACVLAN section */
enum {
	IFLA_MACVLAN_UNSPEC,
	IFLA_MACVLAN_MODE,
	__IFLA_MACVLAN_MAX,
};

#define IFLA_MACVLAN_MAX (__IFLA_MACVLAN_MAX - 1)

enum macvlan_mode {
	MACVLAN_MODE_PRIVATE = 1, /* don't talk to other macvlans */
	MACVLAN_MODE_VEPA    = 2, /* talk to other ports through ext bridge */
	MACVLAN_MODE_BRIDGE  = 4, /* talk to bridge ports directly */
	MACVLAN_MODE_PASSTHRU = 8, /* take over the underlying device */
};

/* VXLAN section */
enum {
	IFLA_VXLAN_UNSPEC,
	IFLA_VXLAN_ID,
	IFLA_VXLAN_GROUP,	/* group or remote address */
	IFLA_VXLAN_LINK,
	IFLA_VXLAN_LOCAL,
	IFLA_VXLAN_TTL,
	IFLA_VXLAN_TOS,
	IFLA_VXLAN_LEARNING,
	IFLA_VXLAN_AGEING,
	IFLA_VXLAN_LIMIT,
	IFLA_VXLAN_PORT_RANGE,	/* source port */
	IFLA_VXLAN_PROXY,
	IFLA_VXLAN_RSC,
	IFLA_VXLAN_L2MISS,
	IFLA_VXLAN_L3MISS,
	IFLA_VXLAN_PORT,	/* destination port */
	__IFLA_VXLAN_MAX
};
#define IFLA_VXLAN_MAX	(__IFLA_VXLAN_MAX - 1)

struct ifla_vxlan_port_range {
	__be16	low;
	__be16	high;
};

/* Bonding section */

enum {
	IFLA_BOND_UNSPEC,
	IFLA_BOND_MODE,
	IFLA_BOND_ACTIVE_SLAVE,
	IFLA_BOND_MIIMON,
	IFLA_BOND_UPDELAY,
	IFLA_BOND_DOWNDELAY,
	IFLA_BOND_USE_CARRIER,
	IFLA_BOND_ARP_INTERVAL,
	IFLA_BOND_ARP_IP_TARGET,
	IFLA_BOND_ARP_VALIDATE,
	IFLA_BOND_ARP_ALL_TARGETS,
	IFLA_BOND_PRIMARY,
	IFLA_BOND_PRIMARY_RESELECT,
	IFLA_BOND_FAIL_OVER_MAC,
	IFLA_BOND_XMIT_HASH_POLICY,
	IFLA_BOND_RESEND_IGMP,
	IFLA_BOND_NUM_PEER_NOTIF,
	IFLA_BOND_ALL_SLAVES_ACTIVE,
	IFLA_BOND_MIN_LINKS,
	IFLA_BOND_LP_INTERVAL,
	IFLA_BOND_PACKETS_PER_SLAVE,
	IFLA_BOND_AD_LACP_RATE,
	IFLA_BOND_AD_SELECT,
	IFLA_BOND_AD_INFO,
	__IFLA_BOND_MAX,
};

#define IFLA_BOND_MAX	(__IFLA_BOND_MAX - 1)

enum {
	IFLA_BOND_AD_INFO_AGGREGATOR,
	IFLA_BOND_AD_INFO_NUM_PORTS,
	IFLA_BOND_AD_INFO_ACTOR_KEY,
	IFLA_BOND_AD_INFO_PARTNER_KEY,
	IFLA_BOND_AD_INFO_PARTNER_MAC,
	__IFLA_BOND_AD_INFO_MAX,
};

#define IFLA_BOND_AD_INFO_MAX	(__IFLA_BOND_AD_INFO_MAX - 1)

/* SR-IOV virtual function management section */

enum {
	IFLA_VF_INFO_UNSPEC,
	IFLA_VF_INFO,
	__IFLA_VF_INFO_MAX,
};

#define IFLA_VF_INFO_MAX (__IFLA_VF_INFO_MAX - 1)

enum {
	IFLA_VF_UNSPEC,
	IFLA_VF_MAC,		/* Hardware queue specific attributes */
	IFLA_VF_VLAN,
	IFLA_VF_TX_RATE,	/* TX Bandwidth Allocation */
	IFLA_VF_SPOOFCHK,	/* Spoof Checking on/off switch */
	IFLA_VF_LINK_STATE,	/* link state enable/disable/auto switch */
	__IFLA_VF_MAX,
};

#define IFLA_VF_MAX (__IFLA_VF_MAX - 1)

struct ifla_vf_mac {
	__u32 vf;
	__u8 mac[32]; /* MAX_ADDR_LEN */
};

struct ifla_vf_vlan {
	__u32 vf;
	__u32 vlan; /* 0 - 4095, 0 disables VLAN filter */
	__u32 qos;
};

struct ifla_vf_tx_rate {
	__u32 vf;
	__u32 rate; /* Max TX bandwidth in Mbps, 0 disables throttling */
};

struct ifla_vf_spoofchk {
	__u32 vf;
	__u32 setting;
};

enum {
	IFLA_VF_LINK_STATE_AUTO,	/* link state of the uplink */
	IFLA_VF_LINK_STATE_ENABLE,	/* link always up */
	IFLA_VF_LINK_STATE_DISABLE,	/* link always down */
	__IFLA_VF_LINK_STATE_MAX,
};

struct ifla_vf_link_state {
	__u32 vf;
	__u32 link_state;
};


/* VF ports management section
 *
 *	Nested layout of set/get msg is:
 *
 *		[IFLA_NUM_VF]
 *		[IFLA_VF_PORTS]
 *			[IFLA_VF_PORT]
 *				[IFLA_PORT_*], ...
 *			[IFLA_VF_PORT]
 *				[IFLA_PORT_*], ...
 *			...
 *		[IFLA_PORT_SELF]
 *			[IFLA_PORT_*], ...
 */

enum {
	IFLA_VF_PORT_UNSPEC,
	IFLA_VF_PORT,			/* nest */
	__IFLA_VF_PORT_MAX,
};

#define IFLA_VF_PORT_MAX (__IFLA_VF_PORT_MAX - 1)

enum {
	IFLA_PORT_UNSPEC,
	IFLA_PORT_VF,			/* __u32 */
	IFLA_PORT_PROFILE,		/* string */
	IFLA_PORT_VSI_TYPE,		/* 802.1Qbg (pre-)standard VDP */
	IFLA_PORT_INSTANCE_UUID,	/* binary UUID */
	IFLA_PORT_HOST_UUID,		/* binary UUID */
	IFLA_PORT_REQUEST,		/* __u8 */
	IFLA_PORT_RESPONSE,		/* __u16, output only */
	__IFLA_PORT_MAX,
};

#define IFLA_PORT_MAX (__IFLA_PORT_MAX - 1)

#define PORT_PROFILE_MAX	40
#define PORT_UUID_MAX		16
#define PORT_SELF_VF		-1

enum {
	PORT_REQUEST_PREASSOCIATE = 0,
	PORT_REQUEST_PREASSOCIATE_RR,
	PORT_REQUEST_ASSOCIATE,
	PORT_REQUEST_DISASSOCIATE,
};

enum {
	PORT_VDP_RESPONSE_SUCCESS = 0,
	PORT_VDP_RESPONSE_INVALID_FORMAT,
	PORT_VDP_RESPONSE_INSUFFICIENT_RESOURCES,
	PORT_VDP_RESPONSE_UNUSED_VTID,
	PORT_VDP_RESPONSE_VTID_VIOLATION,
	PORT_VDP_RESPONSE_VTID_VERSION_VIOALTION,
	PORT_VDP_RESPONSE_OUT_OF_SYNC,
	/* 0x08-0xFF reserved for future VDP use */
	PORT_PROFILE_RESPONSE_SUCCESS = 0x100,
	PORT_PROFILE_RESPONSE_INPROGRESS,
	PORT_PROFILE_RESPONSE_INVALID,
	PORT_PROFILE_RESPONSE_BADSTATE,
	PORT_PROFILE_RESPONSE_INSUFFICIENT_RESOURCES,
	PORT_PROFILE_RESPONSE_ERROR,
};

struct ifla_port_vsi {
	__u8 vsi_mgr_id;
	__u8 vsi_type_id[3];
	__u8 vsi_type_version;
	__u8 pad[3];
};


/* IPoIB section */

enum {
	IFLA_IPOIB_UNSPEC,
	IFLA_IPOIB_PKEY,
	IFLA_IPOIB_MODE,
	IFLA_IPOIB_UMCAST,
	__IFLA_IPOIB_MAX
};

enum {
	IPOIB_MODE_DATAGRAM  = 0, /* using unreliable datagram QPs */
	IPOIB_MODE_CONNECTED = 1, /* using connected QPs */
};

#define IFLA_IPOIB_MAX (__IFLA_IPOIB_MAX - 1)

#endif /* _LINUX_IF_LINK_H */
Added undroid/compat/linux/neighbour.h.
















































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
#ifndef __LINUX_NEIGHBOUR_H
#define __LINUX_NEIGHBOUR_H

#include <linux/types.h>
#include <linux/netlink.h>

struct ndmsg
{
	__u8		ndm_family;
	__u8		ndm_pad1;
	__u16		ndm_pad2;
	__s32		ndm_ifindex;
	__u16		ndm_state;
	__u8		ndm_flags;
	__u8		ndm_type;
};

enum
{
	NDA_UNSPEC,
	NDA_DST,
	NDA_LLADDR,
	NDA_CACHEINFO,
	NDA_PROBES,
	NDA_VLAN,
	NDA_PORT,
	NDA_VNI,
	NDA_IFINDEX,
	__NDA_MAX
};

#define NDA_MAX (__NDA_MAX - 1)

/*
 *	Neighbor Cache Entry Flags
 */

#define NTF_USE		0x01
#define NTF_PROXY	0x08	/* == ATF_PUBL */
#define NTF_ROUTER	0x80

#define NTF_SELF	0x02
#define NTF_MASTER	0x04

/*
 *	Neighbor Cache Entry States.
 */

#define NUD_INCOMPLETE	0x01
#define NUD_REACHABLE	0x02
#define NUD_STALE	0x04
#define NUD_DELAY	0x08
#define NUD_PROBE	0x10
#define NUD_FAILED	0x20

/* Dummy states */
#define NUD_NOARP	0x40
#define NUD_PERMANENT	0x80
#define NUD_NONE	0x00

/* NUD_NOARP & NUD_PERMANENT are pseudostates, they never change
   and make no address resolution or NUD.
   NUD_PERMANENT is also cannot be deleted by garbage collectors.
 */

struct nda_cacheinfo
{
	__u32		ndm_confirmed;
	__u32		ndm_used;
	__u32		ndm_updated;
	__u32		ndm_refcnt;
};

/*****************************************************************
 *		Neighbour tables specific messages.
 *
 * To retrieve the neighbour tables send RTM_GETNEIGHTBL with the
 * NLM_F_DUMP flag set. Every neighbour table configuration is
 * spread over multiple messages to avoid running into message
 * size limits on systems with many interfaces. The first message
 * in the sequence transports all not device specific data such as
 * statistics, configuration, and the default parameter set.
 * This message is followed by 0..n messages carrying device
 * specific parameter sets.
 * Although the ordering should be sufficient, NDTA_NAME can be
 * used to identify sequences. The initial message can be identified
 * by checking for NDTA_CONFIG. The device specific messages do
 * not contain this TLV but have NDTPA_IFINDEX set to the
 * corresponding interface index.
 *
 * To change neighbour table attributes, send RTM_SETNEIGHTBL
 * with NDTA_NAME set. Changeable attribute include NDTA_THRESH[1-3],
 * NDTA_GC_INTERVAL, and all TLVs in NDTA_PARMS unless marked
 * otherwise. Device specific parameter sets can be changed by
 * setting NDTPA_IFINDEX to the interface index of the corresponding
 * device.
 ****/

struct ndt_stats
{
	__u64		ndts_allocs;
	__u64		ndts_destroys;
	__u64		ndts_hash_grows;
	__u64		ndts_res_failed;
	__u64		ndts_lookups;
	__u64		ndts_hits;
	__u64		ndts_rcv_probes_mcast;
	__u64		ndts_rcv_probes_ucast;
	__u64		ndts_periodic_gc_runs;
	__u64		ndts_forced_gc_runs;
};

enum {
	NDTPA_UNSPEC,
	NDTPA_IFINDEX,			/* u32, unchangeable */
	NDTPA_REFCNT,			/* u32, read-only */
	NDTPA_REACHABLE_TIME,		/* u64, read-only, msecs */
	NDTPA_BASE_REACHABLE_TIME,	/* u64, msecs */
	NDTPA_RETRANS_TIME,		/* u64, msecs */
	NDTPA_GC_STALETIME,		/* u64, msecs */
	NDTPA_DELAY_PROBE_TIME,		/* u64, msecs */
	NDTPA_QUEUE_LEN,		/* u32 */
	NDTPA_APP_PROBES,		/* u32 */
	NDTPA_UCAST_PROBES,		/* u32 */
	NDTPA_MCAST_PROBES,		/* u32 */
	NDTPA_ANYCAST_DELAY,		/* u64, msecs */
	NDTPA_PROXY_DELAY,		/* u64, msecs */
	NDTPA_PROXY_QLEN,		/* u32 */
	NDTPA_LOCKTIME,			/* u64, msecs */
	__NDTPA_MAX
};
#define NDTPA_MAX (__NDTPA_MAX - 1)

struct ndtmsg
{
	__u8		ndtm_family;
	__u8		ndtm_pad1;
	__u16		ndtm_pad2;
};

struct ndt_config
{
	__u16		ndtc_key_len;
	__u16		ndtc_entry_size;
	__u32		ndtc_entries;
	__u32		ndtc_last_flush;	/* delta to now in msecs */
	__u32		ndtc_last_rand;		/* delta to now in msecs */
	__u32		ndtc_hash_rnd;
	__u32		ndtc_hash_mask;
	__u32		ndtc_hash_chain_gc;
	__u32		ndtc_proxy_qlen;
};

enum {
	NDTA_UNSPEC,
	NDTA_NAME,			/* char *, unchangeable */
	NDTA_THRESH1,			/* u32 */
	NDTA_THRESH2,			/* u32 */
	NDTA_THRESH3,			/* u32 */
	NDTA_CONFIG,			/* struct ndt_config, read-only */
	NDTA_PARMS,			/* nested TLV NDTPA_* */
	NDTA_STATS,			/* struct ndt_stats, read-only */
	NDTA_GC_INTERVAL,		/* u64, msecs */
	__NDTA_MAX
};
#define NDTA_MAX (__NDTA_MAX - 1)

#endif
Added undroid/compat/linux/rtnetlink.h.
























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
#ifndef __LINUX_RTNETLINK_H
#define __LINUX_RTNETLINK_H

#include <linux/types.h>
#include <linux/netlink.h>
#include <linux/if_link.h>
#include <linux/if_addr.h>
#include <linux/neighbour.h>

/* rtnetlink families. Values up to 127 are reserved for real address
 * families, values above 128 may be used arbitrarily.
 */
#define RTNL_FAMILY_IPMR		128
#define RTNL_FAMILY_MAX			128

/****
 *		Routing/neighbour discovery messages.
 ****/

/* Types of messages */

enum {
	RTM_BASE	= 16,
#define RTM_BASE	RTM_BASE

	RTM_NEWLINK	= 16,
#define RTM_NEWLINK	RTM_NEWLINK
	RTM_DELLINK,
#define RTM_DELLINK	RTM_DELLINK
	RTM_GETLINK,
#define RTM_GETLINK	RTM_GETLINK
	RTM_SETLINK,
#define RTM_SETLINK	RTM_SETLINK

	RTM_NEWADDR	= 20,
#define RTM_NEWADDR	RTM_NEWADDR
	RTM_DELADDR,
#define RTM_DELADDR	RTM_DELADDR
	RTM_GETADDR,
#define RTM_GETADDR	RTM_GETADDR

	RTM_NEWROUTE	= 24,
#define RTM_NEWROUTE	RTM_NEWROUTE
	RTM_DELROUTE,
#define RTM_DELROUTE	RTM_DELROUTE
	RTM_GETROUTE,
#define RTM_GETROUTE	RTM_GETROUTE

	RTM_NEWNEIGH	= 28,
#define RTM_NEWNEIGH	RTM_NEWNEIGH
	RTM_DELNEIGH,
#define RTM_DELNEIGH	RTM_DELNEIGH
	RTM_GETNEIGH,
#define RTM_GETNEIGH	RTM_GETNEIGH

	RTM_NEWRULE	= 32,
#define RTM_NEWRULE	RTM_NEWRULE
	RTM_DELRULE,
#define RTM_DELRULE	RTM_DELRULE
	RTM_GETRULE,
#define RTM_GETRULE	RTM_GETRULE

	RTM_NEWQDISC	= 36,
#define RTM_NEWQDISC	RTM_NEWQDISC
	RTM_DELQDISC,
#define RTM_DELQDISC	RTM_DELQDISC
	RTM_GETQDISC,
#define RTM_GETQDISC	RTM_GETQDISC

	RTM_NEWTCLASS	= 40,
#define RTM_NEWTCLASS	RTM_NEWTCLASS
	RTM_DELTCLASS,
#define RTM_DELTCLASS	RTM_DELTCLASS
	RTM_GETTCLASS,
#define RTM_GETTCLASS	RTM_GETTCLASS

	RTM_NEWTFILTER	= 44,
#define RTM_NEWTFILTER	RTM_NEWTFILTER
	RTM_DELTFILTER,
#define RTM_DELTFILTER	RTM_DELTFILTER
	RTM_GETTFILTER,
#define RTM_GETTFILTER	RTM_GETTFILTER

	RTM_NEWACTION	= 48,
#define RTM_NEWACTION   RTM_NEWACTION
	RTM_DELACTION,
#define RTM_DELACTION   RTM_DELACTION
	RTM_GETACTION,
#define RTM_GETACTION   RTM_GETACTION

	RTM_NEWPREFIX	= 52,
#define RTM_NEWPREFIX	RTM_NEWPREFIX

	RTM_GETMULTICAST = 58,
#define RTM_GETMULTICAST RTM_GETMULTICAST

	RTM_GETANYCAST	= 62,
#define RTM_GETANYCAST	RTM_GETANYCAST

	RTM_NEWNEIGHTBL	= 64,
#define RTM_NEWNEIGHTBL	RTM_NEWNEIGHTBL
	RTM_GETNEIGHTBL	= 66,
#define RTM_GETNEIGHTBL	RTM_GETNEIGHTBL
	RTM_SETNEIGHTBL,
#define RTM_SETNEIGHTBL	RTM_SETNEIGHTBL

	RTM_NEWNDUSEROPT = 68,
#define RTM_NEWNDUSEROPT RTM_NEWNDUSEROPT

	RTM_NEWADDRLABEL = 72,
#define RTM_NEWADDRLABEL RTM_NEWADDRLABEL
	RTM_DELADDRLABEL,
#define RTM_DELADDRLABEL RTM_DELADDRLABEL
	RTM_GETADDRLABEL,
#define RTM_GETADDRLABEL RTM_GETADDRLABEL

	RTM_GETDCB = 78,
#define RTM_GETDCB RTM_GETDCB
	RTM_SETDCB,
#define RTM_SETDCB RTM_SETDCB

	RTM_GETMDB = 86,
#define RTM_GETMDB RTM_GETMDB

	__RTM_MAX,
#define RTM_MAX		(((__RTM_MAX + 3) & ~3) - 1)
};

#define RTM_NR_MSGTYPES	(RTM_MAX + 1 - RTM_BASE)
#define RTM_NR_FAMILIES	(RTM_NR_MSGTYPES >> 2)
#define RTM_FAM(cmd)	(((cmd) - RTM_BASE) >> 2)

/* 
   Generic structure for encapsulation of optional route information.
   It is reminiscent of sockaddr, but with sa_family replaced
   with attribute type.
 */

struct rtattr
{
	unsigned short	rta_len;
	unsigned short	rta_type;
};

/* Macros to handle rtattributes */

#define RTA_ALIGNTO	4
#define RTA_ALIGN(len) ( ((len)+RTA_ALIGNTO-1) & ~(RTA_ALIGNTO-1) )
#define RTA_OK(rta,len) ((len) >= (int)sizeof(struct rtattr) && \
			 (rta)->rta_len >= sizeof(struct rtattr) && \
			 (rta)->rta_len <= (len))
#define RTA_NEXT(rta,attrlen)	((attrlen) -= RTA_ALIGN((rta)->rta_len), \
				 (struct rtattr*)(((char*)(rta)) + RTA_ALIGN((rta)->rta_len)))
#define RTA_LENGTH(len)	(RTA_ALIGN(sizeof(struct rtattr)) + (len))
#define RTA_SPACE(len)	RTA_ALIGN(RTA_LENGTH(len))
#define RTA_DATA(rta)   ((void*)(((char*)(rta)) + RTA_LENGTH(0)))
#define RTA_PAYLOAD(rta) ((int)((rta)->rta_len) - RTA_LENGTH(0))




/******************************************************************************
 *		Definitions used in routing table administration.
 ****/

struct rtmsg
{
	unsigned char		rtm_family;
	unsigned char		rtm_dst_len;
	unsigned char		rtm_src_len;
	unsigned char		rtm_tos;

	unsigned char		rtm_table;	/* Routing table id */
	unsigned char		rtm_protocol;	/* Routing protocol; see below	*/
	unsigned char		rtm_scope;	/* See below */	
	unsigned char		rtm_type;	/* See below	*/

	unsigned		rtm_flags;
};

/* rtm_type */

enum
{
	RTN_UNSPEC,
	RTN_UNICAST,		/* Gateway or direct route	*/
	RTN_LOCAL,		/* Accept locally		*/
	RTN_BROADCAST,		/* Accept locally as broadcast,
				   send as broadcast */
	RTN_ANYCAST,		/* Accept locally as broadcast,
				   but send as unicast */
	RTN_MULTICAST,		/* Multicast route		*/
	RTN_BLACKHOLE,		/* Drop				*/
	RTN_UNREACHABLE,	/* Destination is unreachable   */
	RTN_PROHIBIT,		/* Administratively prohibited	*/
	RTN_THROW,		/* Not in this table		*/
	RTN_NAT,		/* Translate this address	*/
	RTN_XRESOLVE,		/* Use external resolver	*/
	__RTN_MAX
};

#define RTN_MAX (__RTN_MAX - 1)


/* rtm_protocol */

#define RTPROT_UNSPEC	0
#define RTPROT_REDIRECT	1	/* Route installed by ICMP redirects;
				   not used by current IPv4 */
#define RTPROT_KERNEL	2	/* Route installed by kernel		*/
#define RTPROT_BOOT	3	/* Route installed during boot		*/
#define RTPROT_STATIC	4	/* Route installed by administrator	*/

/* Values of protocol >= RTPROT_STATIC are not interpreted by kernel;
   they are just passed from user and back as is.
   It will be used by hypothetical multiple routing daemons.
   Note that protocol values should be standardized in order to
   avoid conflicts.
 */

#define RTPROT_GATED	8	/* Apparently, GateD */
#define RTPROT_RA	9	/* RDISC/ND router advertisements */
#define RTPROT_MRT	10	/* Merit MRT */
#define RTPROT_ZEBRA	11	/* Zebra */
#define RTPROT_BIRD	12	/* BIRD */
#define RTPROT_DNROUTED	13	/* DECnet routing daemon */
#define RTPROT_XORP	14	/* XORP */
#define RTPROT_NTK	15	/* Netsukuku */
#define RTPROT_DHCP	16      /* DHCP client */

/* rtm_scope

   Really it is not scope, but sort of distance to the destination.
   NOWHERE are reserved for not existing destinations, HOST is our
   local addresses, LINK are destinations, located on directly attached
   link and UNIVERSE is everywhere in the Universe.

   Intermediate values are also possible f.e. interior routes
   could be assigned a value between UNIVERSE and LINK.
*/

enum rt_scope_t
{
	RT_SCOPE_UNIVERSE=0,
/* User defined values  */
	RT_SCOPE_SITE=200,
	RT_SCOPE_LINK=253,
	RT_SCOPE_HOST=254,
	RT_SCOPE_NOWHERE=255
};

/* rtm_flags */

#define RTM_F_NOTIFY		0x100	/* Notify user of route change	*/
#define RTM_F_CLONED		0x200	/* This route is cloned		*/
#define RTM_F_EQUALIZE		0x400	/* Multipath equalizer: NI	*/
#define RTM_F_PREFIX		0x800	/* Prefix addresses		*/

/* Reserved table identifiers */

enum rt_class_t
{
	RT_TABLE_UNSPEC=0,
/* User defined values */
	RT_TABLE_COMPAT=252,
	RT_TABLE_DEFAULT=253,
	RT_TABLE_MAIN=254,
	RT_TABLE_LOCAL=255,
	RT_TABLE_MAX=0xFFFFFFFF
};


/* Routing message attributes */

enum rtattr_type_t
{
	RTA_UNSPEC,
	RTA_DST,
	RTA_SRC,
	RTA_IIF,
	RTA_OIF,
	RTA_GATEWAY,
	RTA_PRIORITY,
	RTA_PREFSRC,
	RTA_METRICS,
	RTA_MULTIPATH,
	RTA_PROTOINFO, /* no longer used */
	RTA_FLOW,
	RTA_CACHEINFO,
	RTA_SESSION, /* no longer used */
	RTA_MP_ALGO, /* no longer used */
	RTA_TABLE,
	__RTA_MAX
};

#define RTA_MAX (__RTA_MAX - 1)

#define RTM_RTA(r)  ((struct rtattr*)(((char*)(r)) + NLMSG_ALIGN(sizeof(struct rtmsg))))
#define RTM_PAYLOAD(n) NLMSG_PAYLOAD(n,sizeof(struct rtmsg))

/* RTM_MULTIPATH --- array of struct rtnexthop.
 *
 * "struct rtnexthop" describes all necessary nexthop information,
 * i.e. parameters of path to a destination via this nexthop.
 *
 * At the moment it is impossible to set different prefsrc, mtu, window
 * and rtt for different paths from multipath.
 */

struct rtnexthop
{
	unsigned short		rtnh_len;
	unsigned char		rtnh_flags;
	unsigned char		rtnh_hops;
	int			rtnh_ifindex;
};

/* rtnh_flags */

#define RTNH_F_DEAD		1	/* Nexthop is dead (used by multipath)	*/
#define RTNH_F_PERVASIVE	2	/* Do recursive gateway lookup	*/
#define RTNH_F_ONLINK		4	/* Gateway is forced on link	*/

/* Macros to handle hexthops */

#define RTNH_ALIGNTO	4
#define RTNH_ALIGN(len) ( ((len)+RTNH_ALIGNTO-1) & ~(RTNH_ALIGNTO-1) )
#define RTNH_OK(rtnh,len) ((rtnh)->rtnh_len >= sizeof(struct rtnexthop) && \
			   ((int)(rtnh)->rtnh_len) <= (len))
#define RTNH_NEXT(rtnh)	((struct rtnexthop*)(((char*)(rtnh)) + RTNH_ALIGN((rtnh)->rtnh_len)))
#define RTNH_LENGTH(len) (RTNH_ALIGN(sizeof(struct rtnexthop)) + (len))
#define RTNH_SPACE(len)	RTNH_ALIGN(RTNH_LENGTH(len))
#define RTNH_DATA(rtnh)   ((struct rtattr*)(((char*)(rtnh)) + RTNH_LENGTH(0)))

/* RTM_CACHEINFO */

struct rta_cacheinfo
{
	__u32	rta_clntref;
	__u32	rta_lastuse;
	__s32	rta_expires;
	__u32	rta_error;
	__u32	rta_used;

#define RTNETLINK_HAVE_PEERINFO 1
	__u32	rta_id;
	__u32	rta_ts;
	__u32	rta_tsage;
};

/* RTM_METRICS --- array of struct rtattr with types of RTAX_* */

enum
{
	RTAX_UNSPEC,
#define RTAX_UNSPEC RTAX_UNSPEC
	RTAX_LOCK,
#define RTAX_LOCK RTAX_LOCK
	RTAX_MTU,
#define RTAX_MTU RTAX_MTU
	RTAX_WINDOW,
#define RTAX_WINDOW RTAX_WINDOW
	RTAX_RTT,
#define RTAX_RTT RTAX_RTT
	RTAX_RTTVAR,
#define RTAX_RTTVAR RTAX_RTTVAR
	RTAX_SSTHRESH,
#define RTAX_SSTHRESH RTAX_SSTHRESH
	RTAX_CWND,
#define RTAX_CWND RTAX_CWND
	RTAX_ADVMSS,
#define RTAX_ADVMSS RTAX_ADVMSS
	RTAX_REORDERING,
#define RTAX_REORDERING RTAX_REORDERING
	RTAX_HOPLIMIT,
#define RTAX_HOPLIMIT RTAX_HOPLIMIT
	RTAX_INITCWND,
#define RTAX_INITCWND RTAX_INITCWND
	RTAX_FEATURES,
#define RTAX_FEATURES RTAX_FEATURES
	RTAX_RTO_MIN,
#define RTAX_RTO_MIN RTAX_RTO_MIN
	__RTAX_MAX,
#define RTAX_INITRWND __RTAX_MAX /* Red Hat kABI workaround for dst_entry */
	__RTAX_NEW_MAX
};

/* This Red Hat kABI workaround, requires some subtle details to understand.
 * We MUST keep the exact string expansion "(__RTAX_MAX - 1)" else the kABI
 * checker will miss-fire, as its based on gcc's preprocessor and it keeps
 * the enum literals (not like real defines that gets macro expanded).
 */
#define RTAX_MAX_ORIG (__RTAX_MAX - 1)
#define RTAX_MAX (__RTAX_NEW_MAX - 1)

#define RTAX_FEATURE_ECN	0x00000001
#define RTAX_FEATURE_SACK	0x00000002
#define RTAX_FEATURE_TIMESTAMP	0x00000004
#define RTAX_FEATURE_ALLFRAG	0x00000008

struct rta_session
{
	__u8	proto;
	__u8	pad1;
	__u16	pad2;

	union {
		struct {
			__u16	sport;
			__u16	dport;
		} ports;

		struct {
			__u8	type;
			__u8	code;
			__u16	ident;
		} icmpt;

		__u32		spi;
	} u;
};

/****
 *		General form of address family dependent message.
 ****/

struct rtgenmsg
{
	unsigned char		rtgen_family;
};

/*****************************************************************
 *		Link layer specific messages.
 ****/

/* struct ifinfomsg
 * passes link level specific information, not dependent
 * on network protocol.
 */

struct ifinfomsg
{
	unsigned char	ifi_family;
	unsigned char	__ifi_pad;
	unsigned short	ifi_type;		/* ARPHRD_* */
	int		ifi_index;		/* Link index	*/
	unsigned	ifi_flags;		/* IFF_* flags	*/
	unsigned	ifi_change;		/* IFF_* change mask */
};

/********************************************************************
 *		prefix information 
 ****/

struct prefixmsg
{
	unsigned char	prefix_family;
	unsigned char	prefix_pad1;
	unsigned short	prefix_pad2;
	int		prefix_ifindex;
	unsigned char	prefix_type;
	unsigned char	prefix_len;
	unsigned char	prefix_flags;
	unsigned char	prefix_pad3;
};

enum 
{
	PREFIX_UNSPEC,
	PREFIX_ADDRESS,
	PREFIX_CACHEINFO,
	__PREFIX_MAX
};

#define PREFIX_MAX	(__PREFIX_MAX - 1)

struct prefix_cacheinfo
{
	__u32	preferred_time;
	__u32	valid_time;
};


/*****************************************************************
 *		Traffic control messages.
 ****/

struct tcmsg
{
	unsigned char	tcm_family;
	unsigned char	tcm__pad1;
	unsigned short	tcm__pad2;
	int		tcm_ifindex;
	__u32		tcm_handle;
	__u32		tcm_parent;
	__u32		tcm_info;
};

enum
{
	TCA_UNSPEC,
	TCA_KIND,
	TCA_OPTIONS,
	TCA_STATS,
	TCA_XSTATS,
	TCA_RATE,
	TCA_FCNT,
	TCA_STATS2,
	TCA_STAB,
	__TCA_MAX
};

#define TCA_MAX (__TCA_MAX - 1)

#define TCA_RTA(r)  ((struct rtattr*)(((char*)(r)) + NLMSG_ALIGN(sizeof(struct tcmsg))))
#define TCA_PAYLOAD(n) NLMSG_PAYLOAD(n,sizeof(struct tcmsg))

/********************************************************************
 *		Neighbor Discovery userland options
 ****/

struct nduseroptmsg
{
	unsigned char	nduseropt_family;
	unsigned char	nduseropt_pad1;
	unsigned short	nduseropt_opts_len;	/* Total length of options */
	int		nduseropt_ifindex;
	__u8		nduseropt_icmp_type;
	__u8		nduseropt_icmp_code;
	unsigned short	nduseropt_pad2;
	unsigned int	nduseropt_pad3;
	/* Followed by one or more ND options */
};

enum
{
	NDUSEROPT_UNSPEC,
	NDUSEROPT_SRCADDR,
	__NDUSEROPT_MAX
};

#define NDUSEROPT_MAX	(__NDUSEROPT_MAX - 1)

/* RTnetlink multicast groups - backwards compatibility for userspace */
#define RTMGRP_LINK		1
#define RTMGRP_NOTIFY		2
#define RTMGRP_NEIGH		4
#define RTMGRP_TC		8

#define RTMGRP_IPV4_IFADDR	0x10
#define RTMGRP_IPV4_MROUTE	0x20
#define RTMGRP_IPV4_ROUTE	0x40
#define RTMGRP_IPV4_RULE	0x80

#define RTMGRP_IPV6_IFADDR	0x100
#define RTMGRP_IPV6_MROUTE	0x200
#define RTMGRP_IPV6_ROUTE	0x400
#define RTMGRP_IPV6_IFINFO	0x800

#define RTMGRP_DECnet_IFADDR    0x1000
#define RTMGRP_DECnet_ROUTE     0x4000

#define RTMGRP_IPV6_PREFIX	0x20000

/* RTnetlink multicast groups */
enum rtnetlink_groups {
	RTNLGRP_NONE,
#define RTNLGRP_NONE		RTNLGRP_NONE
	RTNLGRP_LINK,
#define RTNLGRP_LINK		RTNLGRP_LINK
	RTNLGRP_NOTIFY,
#define RTNLGRP_NOTIFY		RTNLGRP_NOTIFY
	RTNLGRP_NEIGH,
#define RTNLGRP_NEIGH		RTNLGRP_NEIGH
	RTNLGRP_TC,
#define RTNLGRP_TC		RTNLGRP_TC
	RTNLGRP_IPV4_IFADDR,
#define RTNLGRP_IPV4_IFADDR	RTNLGRP_IPV4_IFADDR
	RTNLGRP_IPV4_MROUTE,
#define	RTNLGRP_IPV4_MROUTE	RTNLGRP_IPV4_MROUTE
	RTNLGRP_IPV4_ROUTE,
#define RTNLGRP_IPV4_ROUTE	RTNLGRP_IPV4_ROUTE
	RTNLGRP_IPV4_RULE,
#define RTNLGRP_IPV4_RULE	RTNLGRP_IPV4_RULE
	RTNLGRP_IPV6_IFADDR,
#define RTNLGRP_IPV6_IFADDR	RTNLGRP_IPV6_IFADDR
	RTNLGRP_IPV6_MROUTE,
#define RTNLGRP_IPV6_MROUTE	RTNLGRP_IPV6_MROUTE
	RTNLGRP_IPV6_ROUTE,
#define RTNLGRP_IPV6_ROUTE	RTNLGRP_IPV6_ROUTE
	RTNLGRP_IPV6_IFINFO,
#define RTNLGRP_IPV6_IFINFO	RTNLGRP_IPV6_IFINFO
	RTNLGRP_DECnet_IFADDR,
#define RTNLGRP_DECnet_IFADDR	RTNLGRP_DECnet_IFADDR
	RTNLGRP_NOP2,
	RTNLGRP_DECnet_ROUTE,
#define RTNLGRP_DECnet_ROUTE	RTNLGRP_DECnet_ROUTE
	RTNLGRP_DECnet_RULE,
#define RTNLGRP_DECnet_RULE	RTNLGRP_DECnet_RULE
	RTNLGRP_NOP4,
	RTNLGRP_IPV6_PREFIX,
#define RTNLGRP_IPV6_PREFIX	RTNLGRP_IPV6_PREFIX
	RTNLGRP_IPV6_RULE,
#define RTNLGRP_IPV6_RULE	RTNLGRP_IPV6_RULE
	RTNLGRP_ND_USEROPT,
#define RTNLGRP_ND_USEROPT	RTNLGRP_ND_USEROPT
	RTNLGRP_PHONET_IFADDR,
#define RTNLGRP_PHONET_IFADDR	RTNLGRP_PHONET_IFADDR
	RTNLGRP_PHONET_ROUTE,
#define RTNLGRP_PHONET_ROUTE	RTNLGRP_PHONET_ROUTE
	RTNLGRP_DCB,
#define RTNLGRP_DCB		RTNLGRP_DCB
	__RTNLGRP_MAX
};
#define RTNLGRP_MAX	(__RTNLGRP_MAX - 1)

/* TC action piece */
struct tcamsg
{
	unsigned char	tca_family;
	unsigned char	tca__pad1;
	unsigned short	tca__pad2;
};
#define TA_RTA(r)  ((struct rtattr*)(((char*)(r)) + NLMSG_ALIGN(sizeof(struct tcamsg))))
#define TA_PAYLOAD(n) NLMSG_PAYLOAD(n,sizeof(struct tcamsg))
#define TCA_ACT_TAB 1 /* attr type must be >=1 */	
#define TCAA_MAX 1

/* New extended info filters for IFLA_EXT_MASK */
#define RTEXT_FILTER_VF		(1 << 0)

/* End of information exported to user level */



#endif	/* __LINUX_RTNETLINK_H */
Changes to undroid/tclcan/doc/can.n.
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324


325
326
327
328
329
330
331
.\" ---- man.macros end ----
.BS
'\" Note:  do not modify the .SH NAME line immediately below!
.SH NAME
can \- Tcl interface to Linux SocketCAN
.SH SYNOPSIS
package require \fBTcl 8.6\fR
.sp
package require \fBtclcan\fR
.sp
\fBcan bcmopen\fR \fIifname\fR
.sp
\fBcan bitrate\fR \fIifname\fR ?\fIrate\fR? ?\fIsample_point\fR?
.sp
\fBcan bittiming\fR \fIifname\fR
.sp
\fBcan bittiming_const\fR \fIifname\fR
.sp
\fBcan berr\fR \fIifname\fR
.sp
\fBcan clock\fR \fIifname\fR
.sp
\fBcan close\fR \fIchan\fR
.sp
\fBcan ctrlmode\fR \fIifname\fR ?\fImode ...\fR?
.sp
\fBcan devstat\fR \fIifname\fR
.sp
\fBcan dump\fR \fIchan\fR
.sp
\fBcan interfaces\fR
.sp
\fBcan open\fR \fIifname\fR
.sp
\fBcan read\fR \fIchan\fR
.sp
\fBcan restart\fR \fIifname\fR
.sp
\fBcan restart_ms\fR \fIifname\fR ?\fIms\fR?
.sp
\fBcan start\fR \fIifname\fR
.sp
\fBcan state\fR \fIifname\fR
.sp
\fBcan stop\fR \fIifname\fR
.sp
\fBcan write\fR \fIchan canid data\fR ?\fIifindex\fR?


.sp
.BE
.SH DESCRIPTION
This package provides Tcl support for Linux SocketCAN CAN_RAW and
CAN_BCM socket types.
The package implements a new channel type and a Tcl command to perform
operations on these channels. The standard \fBgets\fR, \fBputs\fR,







|



|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

>
>







278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
.\" ---- man.macros end ----
.BS
'\" Note:  do not modify the .SH NAME line immediately below!
.SH NAME
can \- Tcl interface to Linux SocketCAN
.SH SYNOPSIS
package require \fBTcl 8.6\fR
.br
package require \fBtclcan\fR
.sp
\fBcan bcmopen\fR \fIifname\fR
.br
\fBcan bitrate\fR \fIifname\fR ?\fIrate\fR? ?\fIsample_point\fR?
.br
\fBcan bittiming\fR \fIifname\fR
.br
\fBcan bittiming_const\fR \fIifname\fR
.br
\fBcan berr\fR \fIifname\fR
.br
\fBcan clock\fR \fIifname\fR
.br
\fBcan close\fR \fIchan\fR
.br
\fBcan ctrlmode\fR \fIifname\fR ?\fImode ...\fR?
.br
\fBcan devstat\fR \fIifname\fR
.br
\fBcan dump\fR \fIchan\fR
.br
\fBcan interfaces\fR
.br
\fBcan open\fR \fIifname\fR
.br
\fBcan read\fR \fIchan\fR
.br
\fBcan restart\fR \fIifname\fR
.br
\fBcan restart_ms\fR \fIifname\fR ?\fIms\fR?
.br
\fBcan start\fR \fIifname\fR
.br
\fBcan state\fR \fIifname\fR
.br
\fBcan stop\fR \fIifname\fR
.br
\fBcan write\fR \fIchan canid data\fR ?\fIifindex\fR?
.br
\fBcan write\fR \fIchan opcode flags count time1 time2 canId ?\fIifindex\fR ...?
.sp
.BE
.SH DESCRIPTION
This package provides Tcl support for Linux SocketCAN CAN_RAW and
CAN_BCM socket types.
The package implements a new channel type and a Tcl command to perform
operations on these channels. The standard \fBgets\fR, \fBputs\fR,
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
\fBbittiming_const\fR, \fBberr\fR, \fBclock\fR, \fBctlrmode\fR,
\fBdevstat\fR, \fBrestart\fR, \fBrestart_ms\fR, \fBstart\fR,
\fBstate\fR, and \fBstop\fR depend on an installed \fBlibsocketcan\fR
shared library for proper operation. Otherwise they report
"function not implemented". All changes of link state by these
commands usually require administrative rights.
Either the calling process must have super user privileges or the
\fBCAP_NET_ADMIN\fR capability must be effective. The later can be
achieved by a command similar to:
.sp
    setcap cap_net_admin+eip binary-package-requiring-tclcan
.sp
Furthermore, retrieving link information depends on CAN driver support.
Usually, the virtual CAN driver \fBvcan\fR and drivers attached through
a serial line discipline (using the \fBslcan_attach\fR or







|







541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
\fBbittiming_const\fR, \fBberr\fR, \fBclock\fR, \fBctlrmode\fR,
\fBdevstat\fR, \fBrestart\fR, \fBrestart_ms\fR, \fBstart\fR,
\fBstate\fR, and \fBstop\fR depend on an installed \fBlibsocketcan\fR
shared library for proper operation. Otherwise they report
"function not implemented". All changes of link state by these
commands usually require administrative rights.
Either the calling process must have super user privileges or the
\fBCAP_NET_ADMIN\fR capability must be effective. The latter can be
achieved by a command similar to:
.sp
    setcap cap_net_admin+eip binary-package-requiring-tclcan
.sp
Furthermore, retrieving link information depends on CAN driver support.
Usually, the virtual CAN driver \fBvcan\fR and drivers attached through
a serial line discipline (using the \fBslcan_attach\fR or