Lib         := libulm.a

CC := ulmcc
AS := ulmas
LD := ulmld
LDFLAGS := $(Lib)
RANLIB := ulmranlib

# files of form x*.s or x*.c are test programs and an executable x* gets
# created.
TestTargets := $(patsubst %.s,%,$(wildcard x*.s)) \
               $(patsubst %.c,%,$(wildcard x*.c))
# machinery to cleanup the directory if test programs were renamed or deleted
XObjRemoves := $(filter-out $(patsubst %,%.o,$(TestTargets)),$(wildcard x*.o))
XTstRemoves := $(patsubst %.o,%,$(XObjRemoves))
XSrcRemoves := $(if $(XObjRemoves),xsrcRemoves)

# all other files of form *.s or *.c are part of the library
LibSources  := $(filter-out x%.s,$(wildcard *.s)) \
               $(filter-out x%.c,$(wildcard *.c))
LibObjects  := $(patsubst %.c,%.o,$(patsubst %.s,%.o,$(LibSources)))

# machinery to cleanup the archive if source files for the library were renamed
# or deleted
LibContent  := $(if $(wildcard $(Lib)),$(shell ar t $(Lib) | grep -v "^__"),)
LibRemoves  := $(filter-out $(LibObjects),$(LibContent))
SrcRemoves  := $(if $(LibRemoves),srcRemoves)
ArDelete    := $(if $(LibRemoves),ar d $(Lib) $(LibRemoves),)

.PHONY: all clean srcRemoves xsrcRemoves

all:    $(TestTargets) $(Lib) $(XSrcRemoves)

clean:
        $(RM) $(TestTargets) *.o $(Lib)

$(TestTargets): % : %.o $(Lib)
        $(LD) -o $@ $^

$(XSrcRemoves) :
        $(RM) $(XObjRemoves) $(XTstRemoves)

%.o : %.c
        $(CC) -o $*.s $^
        $(AS) -o $*.o $*.s
        $(RM) $*.s

# $(Lib)(%) : %
#       $(AR) cr $@ $^

$(SrcRemoves) :
        $(ArDelete)

$(Lib) : $(Lib)($(LibObjects)) $(SrcRemoves)
        $(RANLIB) $(Lib)
