#!/bin/sh  
# \
exec oagtclsh "$0" "$@"



# set the path to pick up OAG libraries
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)]
set CVSRevisionAuthor "\$Revision: 1.1 $ \$Author: soliday $"

#########################################################################
#
#  ConvertSDDS2AVI is used to take an SDDS file and convert it to a 
#  series of TIFF image files using sdds2tiff. These TIFF images are then
#  converted to PGM images using tifftopnm. Then these
#  PGM images are converted into an AVI file using ffmpeg.
#
#########################################################################
proc ConvertSDDS2AVI {args} {
    APSParseArguments {input output}
    if {![file exists $input]} {
	puts stderr "input file $input does not exist"
	exit 1
    }

    set tmpFiles /tmp/[APSTmpString]


    if {[catch {eval exec sdds2tiff $input ${tmpFiles}.tiff} results]} {
        puts stderr "Error: $results"
        exit 1
    }
    set tiffFiles ""
    set pgmFiles ""
    for {set i 1} {$i < 10000} {incr i} {
        set j [format %04d $i]
        set k [format %d $i]
        if {![file exists ${tmpFiles}.tiff.$j]} {
            break
        }
        lappend tiffFiles ${tmpFiles}.tiff.$j
        lappend pgmFiles ${tmpFiles}${k}.pgm
    }
    set numImages [expr {$i - 1}]

    foreach tiffFile $tiffFiles pgmFile $pgmFiles {
        file delete -force $pgmFile
        if {[catch {exec tifftopnm $tiffFile > $pgmFile} results]} {
        }
    }
    eval file delete -force $tiffFiles
    if {[catch {eval exec ffmpeg_beta \
                  -y -i ${tmpFiles}%d.pgm $output} result]} {
    }
    eval file delete -force $pgmFiles

    return
}


set input ""
set output ""
set args $argv
APSStrictParseArguments {input output}
if {(![llength $input]) || (![llength $output])} {
    puts stderr "usage: avi2sdds -input <input> -output <output>
        [join [split $CVSRevisionAuthor $] ""]"
    exit 1
}
ConvertSDDS2AVI -input $input -output $output


