def makefile(swig_lib)
  return <<END
##################################################################
#####                     SWIG RUBY                         ######
##################################################################

# Build swigruby
TARGET = swigruby
SRCS   = ruby.cxx main.cxx
OBJS   = ruby.o main.o
HDRS   = swigruby.h

SWIG_LIB      = #{swig_lib}
SWIG_LIB_RUBY = $(SWIG_LIB)/ruby

.SUFFIXES: .cxx
.cxx.o: 
	$(CXX) $(CFLAGS) $(SWIGINCLUDE) $(INCLUDE) -c -o $*.o $<

$(OBJS): $(HDRS)

$(TARGET): $(OBJS)
	$(CXX) $(OBJS) $(SWIGLIB) $(LIBS) -lswig -o $(TARGET)

RUBY_SHARED = libswigrb$(SO)
RUBY_LIB    = libswigrb.a

runtime: $(RUBY_SHARED) $(RUBY_LIB)

$(RUBY_SHARED):
	cp $(SWIG_LIB)/swigptr.swg librb.c
	$(CC) $(CCSHARED) -c -DSWIG_GLOBAL librb.c
	$(LDSHARED) librb.o -o $(RUBY_SHARED)

$(RUBY_LIB):
	cp $(SWIG_LIB)/swigptr.swg librb.c
	$(CC) -c -DSWIG_GLOBAL librb.c
	$(AR) cr $(RUBY_LIB) librb.o

clean:
	rm -f *.o $(TARGET) $(RUBY_SHARED) $(RUBY_LIB)

distclean: clean
	rm -f Makefile librb.c

INSTALL         = ./install-sh -c
INSTALL_DATA    = ${INSTALL} -m 644
INSTALL_PROGRAM = ${INSTALL} -m 755

install: $(TARGET) runtime
	@echo "Installing $(TARGET)..."
	@$(INSTALL_PROGRAM) $(TARGET) $(exec_prefix)/bin
	@if [ ! -d $(SWIG_LIB_RUBY) ] ; then \\
	    echo "Making directory $(SWIG_LIB_RUBY)"; \\
	    mkdir $(SWIG_LIB_RUBY); \\
	fi
	@cd swig_lib; for f in *; \\
	    do \\
	    echo "Installing swig_lib/$$f.."; \\
	    ../$(INSTALL_DATA) $$f $(SWIG_LIB_RUBY); \\
	    done;
	@echo "Installing $(RUBY_SHARED)..."
	@$(INSTALL_PROGRAM) $(RUBY_SHARED) $(exec_prefix)/lib
	@echo "Installing $(RUBY_LIB)..."
	@$(INSTALL_DATA) $(RUBY_LIB) $(exec_prefix)/lib

END
end

def usage
  $stderr.print <<END
Usage: #{$0}: [options]
Options:
  --with-swig=SWIG         Set name of swig executable [default=swig]
END
  exit 1
end

swig = nil

while (arg = ARGV.shift)
  case arg
  when /^--with-swig=(.*)$/
    unless swig
      swig = $1
    else
      usage
    end
  else
    usage
  end
end

swig = 'swig' unless swig

begin
  print 'checking for swig... '
  path = `which #{swig}`
  path.chomp!
  if File.executable? path
    puts swig
  else
    puts 'no'
    raise 'no swig found'
  end

  print 'checking for swig_lib... '
  swig_lib = `#{swig} -swiglib`
  swig_lib.chomp!
  if File.directory? swig_lib
    puts swig_lib
  else
    puts 'no'
    raise 'no swig_lib found'
  end

  print 'checking for swig_lib/Makefile... '
  template = swig_lib + '/Makefile'
  template.chomp!
  if File.exists? template
    puts 'yes'
  else
    puts 'no'
    raise 'no swig_lib/Makefile found'
  end

  puts 'creating Makefile'
  out = File.open('Makefile', 'w')
  out.print <<END
# Makefile for swigruby
# Generated automatically by configure.rb

all: swigruby runtime

END
  File.open(template).each_line {|line|
    out.print line
  }
  out.print makefile(swig_lib)
rescue
  puts "** #{$!} **"
end
