# Makefile to build libblosc for Julia Blosc.jl.  I'd rather use their
# cmake stuff, but we need support for cross-compiling that they lack.
# ... We compile with:
#           make -f make.blosc clean
#           make -f make.blosc CC=compiler LIB=libfile
# Note: to cross-compile for Windows, use CFLAGS=-O3, and edit
#       the blosc.c source file to force the inclusion of win32/pthread.*

CC = gcc
CFLAGS = -fPIC -O3 -pthread -std=gnu99
CPPFLAGS = -I. -DBLOSC_SHARED_LIBRARY

LIB = libblosc.so

AVX2_OBJ = bitshuffle-avx2.o shuffle-avx2.o
SSE2_OBJ = bitshuffle-sse2.o shuffle-sse2.o
OTHER_OBJ = bitshuffle-generic.o shuffle-generic.o shuffle.o blosclz.o blosc.o

# Check whether the option -mavx2 is supported
CHECK_AVX2 = $(shell if $(CC) $(CPPFLAGS) $(CFLAGS) -mavx2 -c -o shuffle-avx2.tmp shuffle-avx2.c; then echo 1; else echo 0; fi; rm -f shuffle-avx2.tmp)

# include internal LZ4
# there will only be one LZ4 dir
LZ4_DIR = $(wildcard ../internal-complibs/lz4-*)
OTHER_OBJ += $(LZ4_DIR)/lz4.o $(LZ4_DIR)/lz4hc.o
CFLAGS += -DHAVE_LZ4 -I$(LZ4_DIR)

ifeq ($(shell uname -m), x86_64)
HAVE_AVX=$(CHECK_AVX2)
HAVE_SSE=1
else ifeq ($(shell uname -m), i686)
HAVE_AVX=$(CHECK_AVX2)
HAVE_SSE=1
else ifeq ($(shell uname -m), i386)
HAVE_AVX=$(CHECK_AVX2)
HAVE_SSE=1
else
HAVE_AVX=0
HAVE_SSE=0
endif

ifeq ($(HAVE_SSE),0)
OBJ = $(OTHER_OBJ)
else ifeq ($(HAVE_AVX),0)
OBJ = $(OTHER_OBJ) $(SSE2_OBJ)
CPPFLAGS += -DSHUFFLE_SSE2_ENABLED
else
OBJ = $(OTHER_OBJ) $(AVX2_OBJ) $(SSE2_OBJ)
CPPFLAGS += -DSHUFFLE_AVX2_ENABLED -DSHUFFLE_SSE2_ENABLED
endif

$(LIB): $(OBJ)
	$(CC) $(CFLAGS) -shared $(OBJ) -o $(LIB)

clean:
	rm -f $(OBJ) $(LIB)

bitshuffle-avx2.o: bitshuffle-avx2.c
	echo "building with AVX2"
	$(CC) $(CPPFLAGS) $(CFLAGS) -mavx2 -c -o $@ bitshuffle-avx2.c

shuffle-avx2.o: shuffle-avx2.c
	$(CC) $(CPPFLAGS) $(CFLAGS) -mavx2 -c -o $@ shuffle-avx2.c

bitshuffle-sse2.o: bitshuffle-sse2.c
	echo "building without AVX2"
	$(CC) $(CPPFLAGS) $(CFLAGS) -msse2 -c -o $@ bitshuffle-sse2.c

shuffle-sse2.o: shuffle-sse2.c
	$(CC) $(CPPFLAGS) $(CFLAGS) -msse2 -c -o $@ shuffle-sse2.c

bitshuffle-generic.o: bitshuffle-generic.c
	$(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ bitshuffle-generic.c

shuffle-generic.o: shuffle-generic.c
	$(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ shuffle-generic.c

shuffle.o: shuffle.c
	$(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ shuffle.c

blosclz.o: blosclz.c
	$(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ blosclz.c

blosc.o: blosc.c
	$(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ blosc.c

$(LZ4_DIR)/lz4.o: $(LZ4_DIR)/lz4.c
	$(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $(LZ4_DIR)/lz4.c

$(LZ4_DIR)/lz4hc.o: $(LZ4_DIR)/lz4hc.c
	$(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $(LZ4_DIR)/lz4hc.c
