#
# Makefile - Makefile of cameo
#
# Written 2010, 2012, 2013, 2015 by Werner Almesberger
# Copyright 2010, 2012, 2013, 2015 by Werner Almesberger
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#

PREFIX ?= /usr/local

SHELL=/bin/bash

MAIN=cameo
OBJS=cameo.o excellon.o area-poly2d.o gerber.o gnuplot.o ops.o path.o \
     connect.o poly2d.o shape.o stl.o lex.yy.o y.tab.o

CFLAGS_WARN=-Wall -Wshadow -Wmissing-prototypes \
            -Wmissing-declarations -Wno-format-zero-length
SLOPPY = -Wno-unused -Wno-implicit-function-declaration

# An older version of SLOPPY (seems that bison and flex got tidier):
#
#SLOPPY = -Wno-unused -Wno-implicit-function-declaration \
#         -Wno-missing-prototypes -Wno-missing-declarations
#

CFLAGS=$(CFLAGS_WARN) -g -I../poly2d
LDFLAGS=-L../poly2d
LDLIBS=-lpoly2d -lCGAL -lCGAL_Core -lboost_thread \
       -lstdc++ -lmpfr -lgmp -lm -lfl
YACC = bison -y
YYFLAGS = -v

# ----- Verbosity control -----------------------------------------------------

CC_normal	:= $(CC)
YACC_normal	:= $(YACC)
LEX_normal	:= $(LEX)
DEPEND_normal	:= $(CPP) $(CFLAGS) -MM -MG

CC_quiet	= @echo "  CC       " $@ && $(CC_normal)
YACC_quiet	= @echo "  YACC     " $@ && $(YACC_normal)
LEX_quiet	= @echo "  LEX      " $@ && $(LEX_normal)
DEPEND_quiet	= @$(DEPEND_normal)

ifeq ($(V),1)
    CC		= $(CC_normal)
    LEX		= $(LEX_normal)
    YACC	= $(YACC_normal)
    DEPEND	= $(DEPEND_normal)
else
    CC		= $(CC_quiet)
    LEX		= $(LEX_quiet)
    YACC	= $(YACC_quiet)
    DEPEND	= $(DEPEND_quiet)
endif

# ----- Rules -----------------------------------------------------------------

.PHONY:		all clean spotless

all:		$(MAIN)

$(MAIN):	$(OBJS)

lex.yy.c:	lang.l y.tab.h
		$(LEX) lang.l

lex.yy.o:	lex.yy.c y.tab.h
		$(CC) -c $(CFLAGS) $(SLOPPY) lex.yy.c

y.tab.c y.tab.h: lang.y
		$(YACC) $(YYFLAGS) -d lang.y

y.tab.o:	y.tab.c y.tab.h
		$(CC) -c $(CFLAGS) $(SLOPPY) y.tab.c

clean:
		rm -f $(OBJS) $(OBJS:.o=.d)
		rm -f lex.yy.c y.output y.tab.c y.tab.h

spotless:	clean
		rm -f $(MAIN)

# ----- Install / uninstall ---------------------------------------------------

install:	all
		mkdir -p $(DESTDIR)/$(PREFIX)/bin/
		install -m 755 $(MAIN) $(DESTDIR)/$(PREFIX)/bin/

uninstall:
		rm -f $(DESTDIR)/$(PREFIX)/bin/$(MAIN)

# ----- Dependencies ----------------------------------------------------------

# compile and generate dependencies, from fped, based on
# http://scottmcpeak.com/autodepend/autodepend.html

%.o:		%.c
		$(CC) -c $(CFLAGS) $*.c -o $*.o
		$(DEPEND) $*.c | \
		  sed -e \
		    '/^\(.*:\)\? */{p;s///;s/ *\\\?$$/ /;s/  */:\n/g;H;}' \
		    -e '$${g;p;}' -e d >$*.d; \
		  [ "$${PIPESTATUS[*]}" = "0 0" ] || { rm -f $*.d; exit 1; }

-include $(OBJS:.o=.d)