#!/usr/bin/tclsh
# Author: Jeff Comer <jeffcomer at gmail>

if {$argc != 1 && $argc != 3} {
    puts "Usage: tclsh getColvarHistory.tcl colvarHistFile \[frame outFile\]"
    puts "If 'frame', the frame number is not given, returns the number of frames."
    exit
}


# Input:
set colvarHistFile [lindex $argv 0]
if {$argc == 3} {
    set frame [lindex $argv 1]
    puts "Looking for frame $frame."
    # Output:
    set outFile [lindex $argv end]
} else {
    set frame -1
    set outFile ""
}

# We assume that the frames have a header of two comment lines.
set count 0
set writing 0
set in [open $colvarHistFile r]
set data {}
while {[gets $in lin] >= 0} {
    if {$writing} {
	if {[string match "#*" $lin]} {
	    # We have reached the end of this frame.
	    set writing 0
	    break
	} else {
	    # Add to the data.
	    if {[string length [string trim $lin]] > 0} {
		#puts $lin
		lappend data [concat $lin]
	    }
	}
    } elseif {[string match "#*" $lin]} {
	# Keep track of how many headers we've seen.

	# Are we at the requested frame.
	if {$frame >= 0 && $frame == $count} {
	    puts "Found frame $frame." 
	    # This is the frame that we want.
	    set writing 1
	}
	# Get the next comment line as well so it doesn't get counted.
	set lin1 [gets $in lin]
	# We are on the next frame.
	incr count
    }
}
close $in

if {[llength $data] > 0} {
    # Write the extracted data.
    puts "Writing frame $frame"
    set out [open $outFile w]
    foreach item $data {
	puts $out $item
    }
    close $out
} else {
    if {$frame >= 0} {
	puts "WARNING: Desired frame was not found."
    }
    puts "Total frames: $count"
}
