#!/usr/bin/ruby
# need to define the R_HOME
ENV['R_HOME'] = "/usr/lib/R"
require 'rubygems'
require 'rsruby'

# adds a library silently and restores $stderr
def add_R_lib(rObj, libname)
  begin
    errCopy = $stderr.dup
    $stderr.reopen("/dev/null", "w")   # PROBLEM LINE
    rObj.library(libname)
    $stderr.sync = true                # PROBLEM LINE
  ensure
    $stderr = errCopy.dup
  end
end

########################################################

puts "\n\n#################### QUANTILE REGRESSION ##########################\n"
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]             # input
y = [13, 27, 38, 42, 50, 69, 71, 83, 92, 105]   # output
puts "x: #{x.inspect}"
puts "y: #{y.inspect}"

r = RSRuby.instance
add_R_lib(r, "quantreg")
degree = 2                                      # polynomial degree
vtau = 0.25                                     # quantile
puts "Degree: #{degree}"
puts "Quantile (tau): #{vtau}"
model = "poly(x, #{degree}, raw = T)"
qfit = r.rq("y ~ #{model}", tau = vtau, :data=>{'x'=>x,'y'=>y})
puts "Fit: #{qfit.inspect}"                   # this is all the data returned