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

narray_dir = nil
if s = ( Gem::Specification.find_all_by_name("narray")[0] || Gem::Specification.find_all_by_name("narray-bigmem")[0] )
  if s.respond_to?(:exts_dir)
    narray_dir = s.exts_dir + "/narray"
    narray_dir = s.gem_dir+"/lib/narray" unless File.exist?(narray_dir)
  else
    narray_dir = s.extension_dir + "/narray"
  end
  narray_include = narray_dir
  narray_lib = narray_dir
end

unless narray_dir && File.exist?(narray_dir)
  if Gem.respond_to?(:find_files)
    require "rbconfig"
    so = RbConfig::CONFIG["DLEXT"]
    narray_include = File.expand_path(File.dirname(Gem.find_files("narray.h")[0]))
    narray_lib = File.expand_path(File.dirname(Gem.find_files("narray." + so)[0]))
  else
    gem_home=(`gem environment GEM_HOME`).chomp
    narray_dir = Dir.glob("#{gem_home}/gems/narray-*").sort[-1]
    if narray_dir
      narray_include = narray_lib = narray_dir
    else
      sitearchdir = RbConfig::CONFIG["sitearchdir"]
      narray_include = narray_lib = [$sitearchdir, $sitearchdir]
    end
  end
end
dir_config('narray', narray_include, narray_lib)

create_makefile("numru/lapack")
