#!/usr/local/bin/ruby
#
# pdfgraph.rb : A micro language for drawing PDF graphics
#     original C version by Thomas Merz
#     rewritten in Ruby by TAKAHASHI Hitoshi
#

require 'pdflib'
require 'getopts'


def usage
  STDERR.print <<EOS
pdfgraph.rb - draw PDF graph. (C) Thomas Merz 1997-99
rewritten in Ruby by TAKAHASHI Hitoshi 1999
usage: ruby #{$0} [options] [datafile]
Available options:
-o filename	PDF output file name
EOS
  exit(1)
end


result = getopts(nil, "o:")
usage unless result
usage unless pdffile = $OPT_o

pdf = PDF.new(pdffile)

pdf.set_info(PDF::INFO_TITLE, "Converted graphics")
pdf.set_info(PDF::INFO_CREATOR, "pdfgraph.rb")

pdf.begin_page(PDF::A4_WIDTH, PDF::A4_HEIGHT)

while ARGF.gets
  data = $_.chop!.split
  next if data.size == 0 || data[0][0] == ?%
  case data[0]
  when 'M'
    if data.size < 3
      STDERR << "Error in line: #{$_}\n"
    else
      pdf.moveto(data[1].to_f, data[2].to_f)
    end
  when 'L'
    if data.size < 3
      STDERR << "Error in line: #{$_}\n"
    else
      pdf.lineto(data[1].to_f, data[2].to_f)
    end
  when 'S'
    pdf.stroke
  when 'f'
    pdf.fill
  when 'F'
    pdf.fill_stroke
  when 'g'
    if data.size < 2
      STDERR << "Error in line: #($_}\n"
    else
      pdf.set_gray(data[1].to_f)
    end
  when 'C'
    if data.size < 4
      STDERR << "Error in line: #{$_}\n"
    else
      pdf.set_rgbcolor(data[1].to_f, data[2].to_f, data[3].to_f)
    end
  else
    STDERR << "Error in line: #{$_}\n"
  end
end

pdf.end_page
pdf.close
