
module LaTeX
  
  class FileSearchFailed < Exception
    attr_accessor :searched_paths
  end

  # Array of paths to search for LaTeX files
  def self.texinputs
    (ENV['TEXINPUTS'] or ".").split(":").reject { |x| x.empty? }
  end

  def self.find_in_paths(file_name,paths, extensions=['.tex'])
    paths.each do |path|
      f = File.join(path,file_name)
      return f if File.exist?(f)
      extensions.each do |ext|
        return f + ext if File.exist?(f + ext)
      end
    end
    exc = FileSearchFailed.new(file_name)
    exc.searched_paths = paths
    raise exc
  end

  def self.flatten(file, paths = nil)
    text = File.read(file)
    if not paths then
      paths = texinputs + [File.dirname(file)]
    end

    text.gsub!(/^\\input\{([^}]+)\}/) do
      "%#{$&}\n" + flatten(find_in_paths($1,paths),paths)
    end
    text
  end

end

