require "rubygems"
require "mkmf"


def header_not_found(name)
  warn <<EOF
 #{name}.h was not found.
 If you have #{name}.h, try the following:
   % ruby extconf.rb --with-#{name}-include=path
EOF
  exit 1
end

def library_not_found(lname, fname=nil)
  if fname
    warn <<EOF
  #{fname} was not found.
  If you have #{lname} library, try the following:
    % ruby extconf.rb --with-#{lname}-lib=path --with-#{lname}-name=name
  e.g.
    If you have /usr/local/#{lname}/#{fname},
     % ruby extconf.rb --with-#{lname}-lib=/usr/local/#{lname} --with-#{lname}-name=#{fname}
EOF
    exit 1
  else
    warn <<EOF
  lib#{lname}.{a|so} was not found.
  If you have lib#{lname}.{a|so}, try the following:
    % ruby extconf.rb --with-#{lname}-lib=path
EOF
    exit 1
  end
end



dir_config("lapack")
unless find_library("lapack", nil)
  library_not_found("lapack",nil)

  warn "LAPACK will be tried to find"

  name = with_config("blas-name","blas_LINUX.a")
  unless have_library(name)
    lib_path = with_config("blas-lib","/usr/local/lib")
    _libarg = LIBARG
    LIBARG.replace "#{lib_path}/%s"
    unless have_library(name)
      library_not_found("blas",name)
    end
    LIBARG.replace _libarg
  end
  name = with_config("lapack-name","lapack_LINUX.a")
  unless have_library(name)
    lib_path = with_config("lapack-lib","/usr/local/lib")
    _libarg = LIBARG
    LIBARG.replace "#{lib_path}/%s"
    unless have_library(name)
      library_not_found("lapack",name)
    end
    LIBARG.replace _libarg
  end
end

na_path = RbConfig::CONFIG["sitearchdir"]
begin
  require "rubygems"
  gem = true
rescue LoadError
  gem = false
end
if gem
  if ( na_type = ENV["NARRAY_TYPE"] )
    nas = [na_type]
  else
    nas = %w(narray numru-narray)
  end
  if Gem::Specification.respond_to?(:find_by_name)
    nas.each do |na|
      begin
        if ( spec = Gem::Specification.find_by_name(na) )
          na_type = na
          na_path = spec.full_gem_path
          case na_type
          when "narray"
            na_path = File.join(na_path, "src")
          when "numru-narray"
            na_path = File.join(na_path, "ext", "numru", "narray")
          end
          break
        end
      rescue LoadError
      end
    end
  else
    nas.each do |na|
      if ( spec = Gem.source_index.find_name(na) ).any?
        na_type = na
        na_path = spec[0].full_gem_path
        case na_type
        when "narray"
          na_path = File.join(na_path, "src")
        when "numru-narray"
          na_path = File.join(na_path, "ext", "numru", "narray")
        end
        break
      end
    end
  end
end

dir_config("narray", na_path, na_path)
unless have_header("narray.h")
  $stderr.print "narray.h does not found. Specify the path.\n"
  $stderr.print "e.g., gem install ruby-lapack -- --with-narray-include=path\n"
  exit(-1)
end

if have_func("zposvxx_")
  $defs.each{|d| d.sub!("HAVE_ZPOSVXX_", "USEXBLAS")}
end

create_makefile("numru/lapack")
