GRAPH_WIDTH = 800
GRAPH_HEIGHT = 400

# Returns the filename for a given plot for the given task. If the plot does not
# exist, it is generated by yielding to a given block and piping its output to
# gnuplot. The block can either pass data directly to gnuplot or write a data
# file and call plot on it. The filename of the image is given as an argument to
# the block. 
#
# The image will currently always be saved as png, but its name should not have
# the .png extension.
#
# The return value is the path of the image relative to ../html.
def get_plot(trace, plot_name, format = "png", &block)
  task = trace.taskid
  graph_file = "../html/graphs/#{task}/#{plot_name}.#{format}"
  # Only regenerate the plot if the file does not exist, or it is older
  # than the end of the trace plus 5 seconds, or debug mode is on.
  if not File.exist? graph_file or DEBUG or 
      File.new(graph_file).ctime.to_f < trace.end_time.to_f + 5
    puts "Generating graph #{graph_file}"
    Dir.mkdir "../html/graphs" unless File.exist? "../html/graphs"
    Dir.mkdir "../html/graphs/#{task}" unless File.exist? "../html/graphs/#{task}"
    IO.popen("gnuplot", "w") do |io|
      io << "set terminal #{format} size #{GRAPH_WIDTH}, #{GRAPH_HEIGHT}\n"
      io << "set output '#{graph_file}'\n"
      io << yield(graph_file)
    end
  end
  return "graphs/#{task}/#{plot_name}.#{format}"
end

def get_plot_2(job, plot_name, format = "png", &block)
  task = job
  graph_file = "../html/graphs/#{task}/#{plot_name}.#{format}"
  puts "Generating graph #{graph_file}"
  Dir.mkdir "../html/graphs" unless File.exist? "../html/graphs"
  Dir.mkdir "../html/graphs/#{task}" unless File.exist? "../html/graphs/#{task}"
  IO.popen("gnuplot", "w") do |io|
    io << "set terminal #{format} size #{GRAPH_WIDTH}, #{GRAPH_HEIGHT}\n"
    io << "set output '#{graph_file}'\n"
    io << yield(graph_file)
  end
  return "graphs/#{task}/#{plot_name}.#{format}"
end
