# mpfit-parser/lex Makefile
################################################################################

# Macros
MV         = mv
RM         = rm -f
SED        = sed
CP         = cp

ifeq ($(PLATFORM), WIN)
   # didn't manage to do this as onliner like in the unix-case, pipe doesn't work...
   ARCH := $(shell wmic os get osarchitecture)
   $(shell @echo $(ARCH) > _bbb.txt)
   ARCH := $(shell sed  -e "s/OSArchitecture//g" -e "s/ //g" -e "s/-bit//g" -e "s/-Bit//g" _bbb.txt)
   $(shell del _bbb.txt)

   YACC           = ..\..\bin\WIN$(ARCH)\yacc.exe
   LEX            = ..\..\bin\WIN$(ARCH)\flex.exe -i
   SED_INPLACE    = ..\..\bin\WIN$(ARCH)\sed.exe -i''
   MV             = ren
   RM             = del
	 CP             = copy /Y
  SED_STRING = $(SED_INPLACE) 's/file ? (isatty/0;\/\/file ? (isatty/g' lex.mpfit.cpp
else
   ifeq ($(shell uname -m), x86_64)
      ARCH = 64
   else
      ARCH = 32
   endif

   ifeq ($(PLATFORM), LINUX)
      YACC        = ../../bin/LINUX$(ARCH)/yacc
      LEX         = flex -l -i
      SED_INPLACE = sed -i''
   endif
   ifeq ($(PLATFORM), MACOSX)
      YACC        = yacc
      LEX         = flex -l -i
      SED_INPLACE = sed -i ''
   endif
   SED_STRING = $(SED_INPLACE) 's/extern int isatty/\/\/extern int isatty/g' lex.mpfit.cpp
endif

################################################################################
##### creates parser and lexer #####

mpfit-parser: y.mpfit.cpp lex.mpfit.cpp

y.mpfit.cpp: mpfit.y
	$(YACC) -d $<
	$(MV) y.tab.c y.mpfit.cpp

lex.mpfit.cpp: mpfit.l
	$(LEX) $<
	$(MV) lex.yy.c lex.mpfit.cpp

# all occurences of yy and YY are replaced with mpfit and MPFIT, because the lex.yy.cpp uses the same names -> error when linking
	$(SED_INPLACE) 's/yy/mpfit/g' y.mpfit.cpp lex.mpfit.cpp y.tab.h
	$(SED_INPLACE) 's/YY/MPFIT/g' y.mpfit.cpp lex.mpfit.cpp y.tab.h
# resolve the isatty problem (then-part= LINUX/MAC, else-part: WIN)
	$(SED_INPLACE) 's/extern int isatty/\/\/extern int isatty/g' lex.mpfit.cpp
	$(SED_STRING)
	
	$(MV) y.tab.h mpfitParser.h
#	$(CP) mpfitParser.h ..

clean:
	$(RM) y.mpfit.cpp lex.mpfit.cpp mpfitParser.h y.tab.c lex.yy.c
