# Rules to construct a binary from .o files

ALLOFILES := $(ALLOFILES) $(OFILES)

ifeq (,$(USE_DEFERRED))
  LIBS := $(WHEN_NO_DEFER_LIBS) $(LIBS)
else
  LIBS := $(WHEN_DEFER_LIBS) $(LIBS)
endif

# Eliminate -lm and -ldl on NT because they don't exist
WINLIBS := $(filter-out -lm -ldl,$(SYSLIBS))
# On NT -l<library> needs to map to lib<library>.lib
WINLIBS := $(LIBS:-l%=lib%$(DEBUGNAME).lib) $(WINLIBS:-l%=lib%.lib)

ifeq (PS2,$(PENV))
  LDFLAGS += -lm -nostartfiles
endif  # (PS2,$(PENV))

ifneq (,$(strip $(ALLOFILES)))
$(TARGET): $(OFILES)  # *not* ALLOFILES

# PS2 MODIFICATION ###################

ifeq (PS2, $(PENV))
	$(LD) $(LDFLAGS) $(ALLOFILES) $(LPATH) $(LIBS) $(SYSLIBS) -T /for/program/sce/ee/lib/app.cmd -o a.out.$@
	mv a.out.$@ $@.elf
else

# END PS2 MOD ########################

ifeq (WIN32_VC,$(PENV_COMPILER))
	$(LD) $(LDFLAGS) $(LPATH) $(LINKFLAGS) $(ALLOFILES) $(WINLIBS) -OUT:a.out.$@
	mv a.out.$@ $@
else # NON-WIN32_VC
	$(LD) $(LDFLAGS) $(LPATH) $(LINKFLAGS) $(ALLOFILES) $(LIBS) $(SYSLIBS) -o a.out.$@
	mv a.out.$@ $@
endif # WIN32_VC
endif # PS2

ifeq (4,$(OPTIMIZE))
	strip $@
endif
endif

EXPBIN =
ILKBIN =
PDBBIN =
LIBBIN =
VCFILES =
ifeq (WIN32_VC,$(PENV_COMPILER))
  EXPBIN := $(BASETARGET:%=a.out.%.exp)
  ILKBIN := $(BASETARGET:%=a.out.%.ilk)
  PDBBIN := $(BASETARGET:%=a.out.%.pdb)
  LIBBIN := $(BASETARGET:%=a.out.%.lib)
  VCFILES := vc60.idb vc60.pdb
endif # WIN32_VC

clean::
	@rm -f a.out.$(TARGET) $(EXPBIN) $(ILKBIN) $(PDBBIN) $(LIBBIN) \
		$(VCFILES)

cleanall: clean
	rm -rf ii_files
	rm -f $(TARGET) $(EXPBIN) $(ILKBIN) $(PDBBIN) $(LIBBIN) \
		$(VCFILES)

list:
	@echo $(TARGET)
