
proc APSClipROIHelp {} {
    return "Usage: APSClipROI\n\[-input <inputfile>\]\n\[-output <outputfile>\]\n\[-imageColumns <string>\]\n\[-plot <0|1>\]\n\[-formatString <string>\]\n\[-xSpotMin <number>\]\n\[-xSpotMax <number>\]\n\[-ySpotMin <number>\]\n\[-ySpotMax <number>\]\nClips the region of interest from an image file."
}

proc APSClipROI {args} {
    set input ""
    set output ""
    set imageColumns ""
    set plot 0
    set formatString "%03d"
    set xSpotMin ""
    set xSpotMax ""
    set ySpotMin ""
    set ySpotMax ""

    APSStrictParseArguments {input output imageColumns plot formatString xSpotMin xSpotMax ySpotMin ySpotMax}

    set tmpOutput /tmp/[APSTmpString]
    APSAddToTempFileList $tmpOutput
    if {[catch {exec sddsspotanalysis \
		    $input $tmpOutput \
		    "-imageColumns=${imageColumns}*"} results]} {
	return -code error "APSClipROI: $results"
    }

    if {[catch {sdds load $tmpOutput data} results]} {
	return -code error "APSClipROI: $results"
    }
    
    if {![llength $xSpotMin]} {
	set xSpotMin [lindex $data(Column.xSpotROILower) 0]
    }
    if {![llength $xSpotMax]} {
	set xSpotMax [lindex $data(Column.xSpotROIUpper) 0]
    }
    if {![llength $ySpotMin]} {
	set ySpotMin [lindex $data(Column.ySpotROILower) 0]
    }
    if {![llength $ySpotMax]} {
	set ySpotMax [lindex $data(Column.ySpotROIUpper) 0]
    }
    
    set unusedColumns ""
    for {set n [lindex $data(Column.yROILower) 0]} \
	{$n < $ySpotMin} \
	{incr n} {
	    lappend unusedColumns ${imageColumns}[format $formatString $n]
	}
    for {set n [lindex $data(Column.yROIUpper) 0]} \
	{$n > $ySpotMax} \
	{incr n -1} {
	    lappend unusedColumns ${imageColumns}[format $formatString $n]
	}
    
    
    if {[catch {exec sddsprocess $input $output \
		    -delete=column,[join $unusedColumns ","] \
		    -clip=[expr {$xSpotMin - [lindex $data(Column.xROILower) 0]}],[expr {[lindex $data(Column.xROIUpper) 0] - $xSpotMax}]} results]} {
	return -code error "APSClipROI: $results"
    }
    
    if {$plot} {
	if {[catch {exec sddscontour $output -column=Index,${imageColumns}* -shade &} results]} {
	    return -code error "APSClipROI: $results"
	}
    }
}
