#!/usr/bin/env ruby
"""Program to show cdtext, similar to examples/cdtext.c"""
#
#  Copyright (C) 2006, 2008, 2009 Rocky Bernstein <rocky@gnu.org>
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.

# require 'rubygems'; require 'ruby-debug'; Debugger.start

mypath = File.dirname(__FILE__)

if (File::exists?(mypath + "/../lib/cdio.rb"))
  $: << File.dirname(__FILE__) + '/../lib'
  $: << File.dirname(__FILE__) + '/../ext/cdio'
else
  require 'rubygems'
end
require "cdio"

def print_cdtext_track_info(device, track, message)
  print message
  t = device.track(track)
  cdt = t.cdtext()
  
  for i in 0.upto(Rubycdio::MAX_CDTEXT_FIELDS) do
    value = cdt.get(i)
    # value can be empty but exist, compared to NULL values
    if value.nil?
      puts "\t%s: %s" % [Rubycdio::cdtext_field2str(i), value]
    end
  end
end

if ARGV[0]
  begin
    drive_name = sys.argv[1]
    d = Cdio::Device(sys.argv[1])
  rescue IOError
    puts "Problem opening CD-ROM: %s" % drive_name
   exit 1
  end
else
  begin
    d = Cdio::Device.new(nil, Rubycdio::DRIVER_UNKNOWN)
    drive_name = d.device()
  rescue IOError
    puts "Problem finding a CD-ROM"
    exit 1
  end
end

i_tracks = d.num_tracks()
t = d.first_track()
i_first_track = t.track

print_cdtext_track_info(d, 0, 'CD-Text for Disc:')
for i in i_first_track.upto(i_tracks + i_first_track) do
  print_cdtext_track_info(d, i, 'CD-Text for Track %d:' % i)
end
