#!/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 usage {usage: outsf72sdds -input <filename> -output <filename>}
set input OUTSF7.TXT
set output ""
set args $argv
if {[APSStrictParseArguments {input output}] ||  ![string length $input] || ![string length $output]} {
    return -code error "$usage"
}
if ![file exists $input] {
    return -code error "not found: $input"
}
if [file exists $output] {
    return -code error "in use: $output"
}

set fdi [open $input r]
set ready 0
while {![eof $fdi]} {
    gets $fdi data
    if [string match "Number of increments*" $data] {
	set ready 1
	break
    }
}

if $ready {
    foreach i {1 2 3} {gets $fdi data}
    set sddsdata(ColumnNames) [list x y Bx By B Az dBydy dBydx dBxdy]
    set sddsdata(ColumnInfo.x) "type SDDS_DOUBLE units m"
    set sddsdata(ColumnInfo.y) "type SDDS_DOUBLE units m"
    set sddsdata(ColumnInfo.Bx) "type SDDS_DOUBLE units T"
    set sddsdata(ColumnInfo.By) "type SDDS_DOUBLE units T"
    set sddsdata(ColumnInfo.B)  "type SDDS_DOUBLE units T"
    set sddsdata(ColumnInfo.Az)  "type SDDS_DOUBLE units T*m"
    set sddsdata(ColumnInfo.dBydy) "type SDDS_DOUBLE units T/m"
    set sddsdata(ColumnInfo.dBydx) "type SDDS_DOUBLE units T/m"
    set sddsdata(ColumnInfo.dBxdy) "type SDDS_DOUBLE units T/m"
    while {![eof $fdi]} {
	gets $fdi data
	if [scan $data "%f %f %f %f %f %f %f %f %f" x y Bx By B Az dBydy dBydx dBxdy]!=9 break
	foreach item {x y Bx By B Az dBydy dBydx dBxdy} conversion {.01 .01 1e-4 1e-4 1e-4 1e-6 .01 .01 .01} {
	    lappend ${item}List [expr $conversion*[set $item]]
	}
    }
    foreach item {x y Bx By B Az dBydy dBydx dBxdy} {
	set sddsdata(Column.$item) [list [set ${item}List]]
    }
    if [catch {sdds save $output sddsdata} result] {
	puts stderr "Problem saving $output: $result"
    }
} else {
    puts stderr "Invalid file: $input"
}
