# Set up MATLAB paths
include mexargs/Makefile.mex

# Type of build
BUILD?=optimized
# Type of link
LINK?=dynamic
# Enable local access
LOCAL?=no
# Timeout support
TIMEOUT?=no

# Checks
ifeq ($(CLEAN_ONLY),no)
  ifeq ($(BUILD),$(filter-out optimized debug,$(BUILD)))
    $(error Possible values for BUILD are optimized and debug, received BUILD="$(BUILD)")
  endif
  
  ifeq ($(LINK),$(filter-out static shared dynamic,$(LINK)))
    $(error Possible values for LINK are static, shared and dynamic, received LINK="$(LINK)")
  endif
  
  ifeq ($(LOCAL),$(filter-out yes no,$(LOCAL)))
    $(error Possible values for LOCAL are yes and no, received LOCAL="$(LOCAL)")
  endif
  
  ifeq ($(TIMEOUT),$(filter-out yes no,$(TIMEOUT)))
    $(error Possible values for TIMEOUT are yes and no, received TIMEOUT="$(TIMEOUT)")
  endif
endif


# MDSplus install dir
MDSPLUS?=$(MDSPLUS_DIR)
ifeq ($(MDSPLUS),)
  MDSPLUS:=mdsplus
  MDSPLUSLIBDIR=
else
  ifeq ($(OS),Windows)
    MDSPLUSLIBDIR=$(MDSPLUS)/devtools/mingw/lib64
  else
    MDSPLUSLIBDIR=$(MDSPLUS)/lib
  endif
endif

# Enable debug
ifeq ($(BUILD),debug)
  MEXOPTS+= -DDEBUG -g -v
endif

# Source files
SOURCE=mdsipmex.c
ifeq ($(MDSPLUS),mdsplus)
  # Add minimal MDSplus files
  SOURCE+= $(wildcard mdsplus/mdstcpip/*.c)
endif

ifeq ($(LINK),static)
endif
ifeq ($(LINK),shared)
  MEXOPTS+= -DSHARED -L"$(MDSPLUSLIBDIR)" -lMdsIpShr
endif
ifeq ($(LINK),dynamic)
  MEXOPTS+= -DSHARED -DDYNAMICLINK -ldl
endif

ifeq ($(LOCAL),yes)
  MEXOPTS+= -DLOCAL_CONNECT
  ifeq ($(LINK),shared)
    MEXOPTS+= -lTdiShr -lMdsShr
  endif
endif

ifeq ($(TIMEOUT),yes)
  MEXOPTS+= -DTIMEOUT
  ifneq ($(LINK),static)
    MEXOPTS+= -ldl
  endif
endif

MEXOPTS+= -DPASSWD CFLAGS='$$CFLAGS -std=c99'

ifeq ($(OS),Windows)
  MEXOPTS+= -lws2_32
endif

all: mdsipmex.$(MEXEXT)

mdsipmex.$(MEXEXT): $(SOURCE)
	$(MEXCMD) $^ -output $@ -I"$(MDSPLUS)/include" -I"$(MDSPLUS)/mdstcpip" $(MEXOPTS)
	
clean:
	rm -f mdsipmex.mex*
