require "mkmf"

dir_config('narray',$sitearchdir,$sitearchdir)
dir_config('netcdf','/usr/local')

if ( ! ( have_header("narray.h") && have_header("narray_config.h") ) ) then
print <<EOS
** configure error **  
   Header narray.h or narray_config.h is not found. If you have these files in 
   /narraydir/include, try the following:

   % ruby extconf.rb --with-narray-include=/narraydir/include

EOS
   exit(-1)
end

if ( ! ( have_header("netcdf.h") && have_library("netcdf") ) )then
print <<EOS
** configure error **  
   Header netcdf.h or the compiled netcdf library is not found. 
   If you have the library installed under /netcdfdir (that is, netcdf.h is
   in /netcdfdir/include and the library in /netcdfdir/lib/),
   try the following:

   % ruby extconf.rb --with-netcdf-dir=/netcdfdir

   Alternatively, you can specify the two directory separately
   with --with-netcdf-include and --with-netcdf-lib.
EOS
   exit(-1)
end

if /cygwin|mingw/ =~ RUBY_PLATFORM
   have_library("narray") || raise("ERROR: narray library is not found")
end

create_makefile "numru/netcdfraw"

######  Modify Makefile: #######
File.rename("Makefile","Makefile.orig")
oldmkfl = File.open("Makefile.orig")
newmkfl = File.open("Makefile","w")
oldmkfl.each_line{ |line|
   case(line)
   when /^distclean:/
      newmkfl.puts(line)
      newmkfl.puts("\t\t@$(RM) *.nc demo/*.nc demo/*~ lib/*~ doc/*~ test/*.nc test/*~ Makefile.orig")
   when /^all:/
      newmkfl.puts(line)
      newmkfl.puts("")         
      newmkfl.puts("test: all")            # insert the "test" target
      newmkfl.puts("\t\t@cd test && ruby test.rb && echo 'test did not fail :-p (please ignore the warnings)' && cd ..") 
   when /lib\/netcdf/
      line = line.chomp! + "/"
      newmkfl.puts(line)
   else
      newmkfl.puts(line)
   end
}
newmkfl.close
