#-----------------------------------------------------------------------------#
# This Makefile contains rules are creating DLLs on Windows using gnu-win32.
#-----------------------------------------------------------------------------#

# This rule creates a `.def' file, which lists the symbols that are exported
# from the DLL.  We use `nm' to get a list of all the exported text (`T')
# symbols.  Note that exporting data symbols -- including uninitialized
# data (`B'), initialized data (`D'), read-only data (`R'), and
# common blocks (`C') -- does not work, so we only grep for symbols whose
# type is `T'.
%.def: %.a
	@echo "	Generation of $@"
	@echo EXPORTS > $@
	@nm $< | grep '^........ [T] _' | sed 's/[^_]*_//' >> $@


# The following rule generates proper path for libraries 
# contained in LIBNAME 
# if the gcc path has been changed for examle for mingwin32
# it won't work 
# add for example echo "-L/softs/GCWIN32/win32/lib" >> libs_path
# at the end

LIBNAME=libgcc.a libcygwin.a libkernel32.a
# for mingw32 
LIBNAME=libgcc.a libkernel32.a


# use libs_path_cygwin for cygwin 
# and next for mingwin 

libs_path_cygwin	:
	@echo "using gcc to find libs'path"
	@rm -f libs_path ; \
	for x in $(LIBNAME) ; \
	do ( \
	$(CC) -print-file-name="$$x" |sed -e "s/^[a-zA-Z]://" -e 's+\\+/+g' > lib_path ;\
	dirname `cat lib_path` | sed -e "s/^/-L/"  lib_path>> libs_path )  ;\
	done ; \
	rm -f lib_path 


libs_path	: 
	@echo "using gcc to find libs'path"
	@rm -f libs_path ; \
	for x in $(LIBNAME) ; \
	do ( \
	$(CC) -print-file-name="$$x"  > lib_path ;\
	sed -e "s/^/-L/" -e "s+\\$$x++" lib_path >> libs_path )  ;\
	done ; \
	rm -f lib_path 


%.dll:	%.def  dll_fixup.o libs_path $(OBJS) 
	@echo "Calling linker first pass"
	@$(LD) $(LDFLAGS)  $(LDFLAGS-$*) --base-file $*.base --dll -o $*.dll \
		$(OBJS) dll_fixup.o \
		`cat libs_path` $(CYGWIN32_LIBS) -e _DllMain@12 
	@echo "Calling dlltool"
	@$(DLLTOOL)  --dllname $*.dll --def $*.def --base-file $*.base --output-exp $*.exp 
	@echo "Calling linker second pass"
	@$(LD) $(LDFLAGS)  $(LDFLAGS-$*) --base-file $*.base $*.exp --dll -o $*.dll \
		$(OBJS) dll_fixup.o \
		`cat libs_path` $(CYGWIN32_LIBS) -e _DllMain@12 
	@echo "Calling dlltool"
	@$(DLLTOOL)  --dllname $*.dll --def $*.def --base-file $*.base --output-exp $*.exp 
	@echo "Calling linker third pass"
	@$(LD) $(LDFLAGS)  $(LDFLAGS-$*) $*.exp --dll -o $*.dll $(OBJS) dll_fixup.o \
		`cat libs_path` $(CYGWIN32_LIBS) -e _DllMain@12
	@echo "Calling dlltool"
	@$(DLLTOOL)  --dllname $*.dll --def $*.def --output-lib $*.stubs.a


# This black magic piece of assembler needs to be linked in in order to
# properly terminate the list of imported DLLs.
dll_fixup.s:
	echo '.section .idata$$3' 	> dll_fixup.s
	echo '.long 0,0,0,0, 0,0,0,0'	>> dll_fixup.s




