CC 		?= clang
RELEASE ?= 0 # Optimize.
DEBUG 	?= 1 # Emit debug info.
SQUEEZE ?= 0 # Nuclear option to save space.
BITS 	?= 64
RUN 	?= 0

CFLAGS 	= -Wall -std=gnu99 -ffast-math -fno-ident -fvisibility=hidden

# Set cosmopolitan toolchain.
ifeq ($(MAKECMDGOALS),cosmo)
	CC = ./Cosmo/bin/cosmocc -mclang
	ifeq ($(DEBUG), 1)
	    CFLAGS += -mdbg
	else
	    CFLAGS += -mtiny
	endif
endif

# Provide LTO where it's applicable.
ifeq ($(CC),clang)
	ISCLANG = 1
	CFLAGS += -flto=thin -fuse-ld=lld
else
	ifneq ($(MAKECMDGOALS),cosmo)
		CFLAGS += -flto
	endif
endif

# Linux specific options.
ifeq ($(MAKECMDGOALS),linux)
	CFLAGS += -fno-pic -fno-pie
	ifeq ($(RELEASE), 1)
# 	    CFLAGS += -Wl,--ignore-data-address-equality -Wl,--ignore-function-address-equality \
	    		  -Wl,--optimize-bb-jumps
	endif
	ifeq ($(SQUEEZE), 1)
		ifeq ($(DEBUG), 0)
			CFLAGS += -Wl,-T,tiny.ld 
		endif
	    CFLAGS += -Wl,--icf=all -Wl,--bp-compression-sort=both \
	    		  -Wl,--nmagic
	endif
	ifeq ($(BITS), 64)
		CFLAGS += -m64 -march=x86-64-v3 -mpopcnt
	else
		CFLAGS += -m32 -msse2
	endif
endif

# WASM specific options.
ifeq ($(MAKECMDGOALS),wasm)
	ifeq ($(RELEASE), 1)
	    CFLAGS += -Wl,--compress-relocations
	endif
endif

# Separate debug and release switches.
ifeq ($(DEBUG), 1)
    CFLAGS += -g3
else
    CFLAGS += -DNDEBUG -s
endif
ifeq ($(RELEASE), 1)
    CFLAGS += -O3 -fmerge-all-constants -Wl,-O3 \
    		  -ffunction-sections -fdata-sections -Wl,--gc-sections
	ifeq ($(CC),clang)
		CFLAGS += -Wl,-mllvm,--vectorize-slp=true \
    		  	  -Wl,-mllvm,--enable-gvn-hoist=true
	endif
endif

linux: CFLAGS += -static -mbmi2 -nostdlib
linux: ./amalgam.c
	$(CC) -o player $^ $(CFLAGS)

# Note: lld package might need to be downloaded.
wasm: CFLAGS += --target=wasm32 -nostdlib -Wl,--no-entry -msimd128 -mbulk-memory
wasm:
	$(CC) -o player.wasm ./amalgam.c $(CFLAGS)

# todo: Add -mtiny for release without debug
cosmo: CFLAGS += -I /usr/include/X11
cosmo: ./amalgam.c
	$(CC) $(CFLAGS) -o ./Out/Cosmo/player $^
ifeq ($(RUN), 1)
ifeq ($(DEBUG), 1)
	gdb ./Out/Cosmo/player.com.dbg
else 
	./Out/Cosmo/player
endif
endif

# https://tippach.hier-im-netz.de/wdosx
dos: CFLAGS += -ffreestanding -m32 -fno-PIC -fno-PIE -nostdlib -nodefaultlibs
dos: 
	$(CC) -c ./Main/dos.s -o ./Main/dos.o -m32
	$(CC) -c ./Display/dos.c -o ./Display/dos.o $(CFLAGS)
	ld.lld -m elf_i386 -T dos.ld ./Main/dos.o ./Display/dos.o -o dos.elf
	objcopy -O binary --strip-all dos.elf dos.bin
	cat WDosX/WDOSX.DX dos.bin > DOS.EXE
ifeq ($(RUN), 1)
ifeq ($(DEBUG), 1)
	dosbox -c "mount c $(PWD)" -c "c:" -c "WDOSX\WUDEBUG.EXE DOS.EXE"
else 
	dosbox -c "mount c $(PWD)" -c "c:" -c "DOS.EXE"
endif
endif

clean:
	rm -r *.o ../*.o
