#!/usr/bin/ruby

require 'optparse'

keep_going = false
cauchy_options = ""

optparse = OptionParser.new do|opts|
  opts.banner = "Usage: cauchymake [options] src dst"
  opts.on( '-k', '--keep-going', 'continue the conversion even after an error' ) do
    keep_going = true
  end  
  opts.on( '-I', '--include-dir directory', 'add an include directory for finding functions definition' ) do|file|
    cauchy_options += "-I #{file} "
  end
  opts.on( '-i', '--include-file file', 'load a specific function definition' ) do|file|
    cauchy_options += "-i #{file} "
  end
  opts.on( '-h', '--help', 'print this message' ) do
    puts opts
    exit
  end
  opts.on( '-v', '--version', 'print the version information' ) do
puts <<END
Cauchy - Cauchy Make - 0.9.0
Copyright (c) 2010 Cyrille Berger (cberger@cberger.net)
END
    exit
  end
end

optparse.parse!

if ARGV.size != 2
  puts optparse
  exit
end

src = ARGV[0]
dst = ARGV[1]

unless File.exist?(dst)
  Dir.mkdir(dst)
end

Dir["#{src}/**/*.m"].each{|s|
  s["#{src}/"] = ""
  prefix = s[0,s.size-2]
  puts "Converting #{s}"
  
  # Create the directory if needed
  ss = s.split("/")
  ss.delete_at(ss.size - 1) # remove the file name
  currentdir = dst
  ss.each() { |subdir|
    currentdir += "/" + subdir
    unless File.exist?(currentdir)
      Dir.mkdir(currentdir)
    end
  }
  
  # Do the conversion
  cmd = "cauchymc #{cauchy_options} -o #{dst}/#{prefix}.cpp #{src}/#{s}"
  puts cmd
  if(not system(cmd) and not keep_going)
    exit -1
  end
}

