BUILD_DIR := ./build
CC := gcc
CFLAGS := -Wno-unused-but-set-variable -Wno-unused-parameter -Wno-unused-variable -Wall -g -std=c90
LDFLAGS := -lm

LIB_DIR := ./lib/nr/ansi
LIB_INCLUDE := -I$(LIB_DIR)/other


HW_DIR := ./hws

ifeq ($(strip $(hw)),)
	
else
	TARGET_NAME := hw$(hw)
	SRC_DIR := $(HW_DIR)/hw$(hw)
	ifeq ($(strip $(hw)),1)
		LIB_SRCS := $(LIB_DIR)/recipes/machar.c
	else ifeq ($(strip $(hw)),2)
		LIB_SRCS := $(LIB_DIR)/other/nrutil.c $(LIB_DIR)/recipes/rtflsp.c $(LIB_DIR)/recipes/rtbis.c $(LIB_DIR)/recipes/rtsec.c $(LIB_DIR)/recipes/rtnewt.c $(LIB_DIR)/recipes/rtsafe.c $(LIB_DIR)/recipes/zbrak.c $(LIB_DIR)/recipes/bessj0.c $(LIB_DIR)/recipes/bessj1.c
	else ifeq ($(strip $(hw)),3)
		LIB_SRCS := $(LIB_DIR)/other/nrutil.c $(LIB_DIR)/recipes/gaussj.c $(LIB_DIR)/recipes/ludcmp.c $(LIB_DIR)/recipes/svdcmp.c $(LIB_DIR)/recipes/mprove.c $(LIB_DIR)/recipes/lubksb.c $(LIB_DIR)/recipes/pythag.c
	endif
	LIB_OBJS := $(patsubst %.c,$(BUILD_DIR)/lib/%.o,$(notdir $(LIB_SRCS)))

endif

ifeq ($(strip $(TARGET_NAME)),)
all:
	@echo "에러: 'target'을 지정해주세요."
else
    TARGET_EXEC := $(BUILD_DIR)/$(TARGET_NAME).out
    TARGET_SRCS := $(wildcard $(SRC_DIR)/*.c)
    TARGET_OBJS := $(patsubst %.c,$(BUILD_DIR)/hw$(hw)/%.o,$(notdir $(TARGET_SRCS)))
	TARGET_INCLUDE := -I$(SRC_DIR)
	OBJS := $(TARGET_OBJS) $(LIB_OBJS)
	SRCS := $(TARGET_SRCS) $(LIB_SRCS)
	INCLUDE := $(TARGET_INCLUDE) $(LIB_INCLUDE)
all: run
endif

init:
	@mkdir -p $(BUILD_DIR)
	@mkdir -p $(BUILD_DIR)/lib
	@mkdir -p $(BUILD_DIR)/$(TARGET_NAME)

clean:
	@echo "빌드 결과물을 삭제합니다..."
	@rm -rf $(BUILD_DIR)
	@rm -rf ./out/**

build: init $(TARGET_EXEC)
	@echo "빌드 완료"

$(TARGET_EXEC): $(OBJS)
	@echo "링킹 중: $@"
	$(CC) $(CFLAGS) $^ -o $@ $(LDFLAGS)

$(OBJS): %.o:
	@echo "컴파일 중: $@"
	$(eval TARGET_C_BASENAME := $(patsubst %.o,%.c,$(notdir $@)))
	$(eval FOUND_SRC := $(foreach src,$(SRCS),$(if $(filter $(TARGET_C_BASENAME),$(notdir $(src))),$(src))))
	$(CC) $(CFLAGS) $(INCLUDE) $(LDFLAGS) -c $(FOUND_SRC) -o $@ 

run: clean build
	@echo "실행 시작"
	@echo "============"
	@if ls $(SRC_DIR)/*.dat >/dev/null 2>&1; then \
		cp -f $(SRC_DIR)/*.dat build/; \
	fi
	@cd build && ./$(TARGET_NAME).out

dist: clean
	mkdir -p out
	(cd $(SRC_DIR) && zip -9 $(TARGET_NAME).zip ./**)
	mv $(SRC_DIR)/$(TARGET_NAME).zip out