###############################################################################
# Maklefile for build firmware of SECU-3 project using IAR
# Created by Alexey A. Shabelnikov, Kiev 17 July 2011. 
#
# Note: It requires IAR compiler and linker
# Also: Before using of this Makefile you must define environment variable IAR_HOME.
#       For instance "C:\Program Files\IAR Systems\Embedded Workbench 5.4"
#       Additionaly make sure CC, LD and LIBS variables in this Makefile are correct.

#include platform-specific options from another file
include platform_cfg

TARGET = secu-3_app
OBJDIR = ./output
CC = $(IAR_HOME)/avr/bin/iccavr.exe
LD = $(IAR_HOME)/avr/bin/xlink.exe
#LD = $(IAR_HOME)/common/bin/xlink.exe

# Compile options common for all C compilation units.
CFLAGS = --cpu $(MCU)
CFLAGS += -DREALTIME_TABLES -DBL_BAUD_RATE=9600 -DSECU3T -DTHERMISTOR_CS -DCOOLINGFAN_PWM -DDIAGNOSTICS -DHALL_OUTPUT -DFUEL_PUMP
CFLAGS += -DLITTLE_ENDIAN_DATA_FORMAT -DENABLE_BIT_DEFINITIONS
CFLAGS += -ms -e --initializers_in_flash
CFLAGS += -s9
#CFLAGS += --cross_call_passes=1 --do_cross_call
CFLAGS += --lock_regs 1
CFLAGS += --eeprom_size $(EE_SIZE)
CFLAGS += --dlib_config $(IAR_HOME)/avr/lib/dlib/dlAVR-3s-ec_mul-sf-n.h

# Linker flags
LDFLAGS = -Fintel-standard -xs -s main
LDFLAGS += -f $(IAR_HOME)/avr/config/$(LNKXCL)
LDFLAGS += -l $(OBJDIR)/secu3.map
LDFLAGS += -Z.boot_loader=$(BL_START) -Z.firmware_data=$(FWD_START)
LIBS = $(IAR_HOME)/avr/lib/dlib/dlAVR-3s-ec_mul-sf-n.r90
#LIBS = $(IAR_HOME)/avr/lib/dlib/dl3s-ec-sf.r90

# Include Directories
INCLUDES = -I $(IAR_HOME)/avr/inc/dlib -I $(IAR_HOME)/avr/inc

# Define all source files.
SRC = adc.c bootldr.c ce_errors.c ckps.c crc16.c \
	eeprom.c fuelecon.c funconv.c idlecon.c ignlogic.c \
	jumper.c knklogic.c knock.c measure.c params.c \
	procuart.c secu3.c starter.c suspendop.c tables.c \
	uart.c ventilator.c vstimer.c camsens.c fuelpump.c \
	diagnost.c wdt.c ioconfig.c

# Define all object files and dependencies
OBJECTS = $(SRC:%.c=$(OBJDIR)/%.r90)
DEPS = $(OBJECTS:$(OBJDIR)/%.r90=$(OBJDIR)/%.d)

# Define all listing files.
LST = $(SRC:%.c=$(OBJDIR)/%.lst)

#Thanks to guys from Microsoft we have to deal with spaces...
SPAT=$(shell echo $(IAR_HOME) | sed -e 's/\\\/\\\\\\\\\\\/g')
RPAT=$(shell echo $(IAR_HOME) | sed -e 's/\\\/\\\\\\\\\\\/g' -e 's/ /\\\\\\\\\\\ /g')

# Build
all: OBJ_DIRS $(TARGET).a90

#Include make files containing dependencies
-include $(DEPS)

#Create directory for object files
OBJ_DIRS :
	@mkdir -p $(OBJDIR)

# Compile
$(OBJDIR)/%.r90 : sources/%.c 
	$(CC) $(INCLUDES) $(CFLAGS) $< -o $@ -lC $(OBJDIR:%.r90=$(OBJDIR)/%.lst) --dependencies=m $(OBJDIR:%.r90=$(OBJDIR)/%.d)
	@sed -e 's/$(SPAT)/$(RPAT)/' $(patsubst %.r90, %.d, $@) > tmpfile; mv tmpfile $(patsubst %.r90, %.d, $@)

#Link
$(TARGET).a90: $(OBJECTS)
	$(LD) $(LDFLAGS) $(OBJECTS) $(LIBDIRS) $(LIBS) -o $(TARGET).a90

# Clean target
clean:
	@rm -f $(OBJECTS) $(LST) $(TARGET).a90 $(OBJDIR)/*.map $(DEPS)
