#!/bin/sh  
# \
exec oagtclsh "$0" "$@"
set auto_path [linsert $auto_path 0  /usr/local/oag/apps/lib/$env(HOST_ARCH)]
set auto_path [linsert $auto_path 0 /usr/local/oag/lib_patch/$env(HOST_ARCH)]

APSStandardSetup
set args $argv
set input ""
set output ""
APSStrictParseArguments {input output}
if {([llength $input] != 1) || ([llength $output] != 1)} {
    puts "Usage: isf2sdds -input <filename> -output <filename>"
    exit
}

proc getValue {name} {
    global data
    set i [string first "$name " $data]
    if {$i > -1} {
        incr i [expr [string length $name] + 1]
        set j [string first \; [string range $data $i end]]
        return [string range $data $i [expr $i + $j - 1]]
    } else {
        puts "$input is not a valid Tektronix .ISF file"
        exit
    }
}

set fid [open $input r]
fconfigure $fid -translation binary
set data [read $fid]
close $fid

set byt [getValue BYT_NR]
set byteOrder [getValue BYT_OR]
set xzero [getValue XZERO]
set xincr [getValue XINCR]
set nrpt [getValue NR_PT]
set yoff [getValue YOFF]
set ymult [getValue YMULT]
set xunit [getValue XUNIT]
set yunit [getValue YUNIT]

set x $xzero
set xList $x
for {set n 1} {$n < $nrpt} {incr n} {
    set x [expr $x + $xincr]
    lappend xList $x
}

set i [string first ";:CURVE \#" $data]
if {$i == -1} {
    puts "$input is not a valid Tektronix .ISF file"
    exit
}

incr i 9

set X [string index $data $i]
incr i
set YYY [string range $data $i [expr {$i + $X - 1}]]
incr i $X

if {$byt == 1} {
    binary scan [string range $data $i end] c* values
} elseif {$byt == 2} {
    if {$byteOrder == "MSB"} {
        binary scan [string range $data $i end] S* values
    } else {
        binary scan [string range $data $i end] s* values
    }
} elseif {$byt == 4} {
    if {$byteOrder == "MSB"} {
        binary scan [string range $data $i end] I* values
    } else {
        binary scan [string range $data $i end] i* values
    }
} elseif {$byt == 8} {
    if {$byteOrder == "MSB"} {
        binary scan [string range $data $i end] W* values
    } else {
        binary scan [string range $data $i end] w* values
    }
}

set valueList ""
foreach value $values {
    lappend valueList [expr $ymult * ( $value - $yoff )]
}

set outputData(ColumnNames) "X Y"
set outputData(ColumnInfo.X) "type SDDS_DOUBLE units $xunit"
set outputData(ColumnInfo.Y) "type SDDS_DOUBLE units $yunit"
set outputData(Column.X) [list $xList]
set outputData(Column.Y) [list $valueList]
sdds save $output outputData

