###############################################################################
# Makefile for the project PortableVinegar
###############################################################################

## General Flags
PROJECT = PortableVinegar
MCU = atmega644p
TARGET = PortableVinegar.elf
CC = avr-gcc
AVRDUDE = avrdude -c siprog -P COM2 -p $(MCU) -V

## Options common to compile, link and assembly rules
COMMON = -mmcu=$(MCU)

## Compile options common for all C compilation units.
CFLAGS = $(COMMON)
CFLAGS += -Wall -gdwarf-2 -std=gnu99 -DF_CPU=8000000UL -Os -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums
CFLAGS += -MD -MP -MT $(*F).o -MF dep/$(@F).d 

## Assembly specific flags
ASMFLAGS = $(COMMON)
ASMFLAGS += $(CFLAGS)
ASMFLAGS += -x assembler-with-cpp -Wa,-gdwarf2

## Linker flags
LDFLAGS = $(COMMON)
LDFLAGS +=  -Wl,-Map=PortableVinegar.map

## Intel Hex file production flags
HEX_FLASH_FLAGS = -R .eeprom -R .fuse -R .lock -R .signature

HEX_EEPROM_FLAGS = -j .eeprom
HEX_EEPROM_FLAGS += --set-section-flags=.eeprom="alloc,load"
HEX_EEPROM_FLAGS += --change-section-lma .eeprom=0 --no-change-warnings

## Objects that must be built in order to link
OBJECTS = main.o interpreter.o pg12864lrs-ann-h.o keypad_4x4.o ui.o

## Build
all: $(TARGET) PortableVinegar.elf PortableVinegar.hex size

## Compile
main.o: main.c
	$(CC) $(INCLUDES) $(CFLAGS) -c  $<

interpreter.o: interpreter.c
	$(CC) $(INCLUDES) $(CFLAGS) -c  $<

pg12864lrs-ann-h.o: pg12864lrs-ann-h.c
	$(CC) $(INCLUDES) $(CFLAGS) -c  $<

keypad_4x4.o: keypad_4x4.c
	$(CC) $(INCLUDES) $(CFLAGS) -c  $<

ui.o: ui.c
	$(CC) $(INCLUDES) $(CFLAGS) -c  $<

##Link
$(TARGET): $(OBJECTS)
	 $(CC) $(LDFLAGS) $(OBJECTS) $(LINKONLYOBJECTS) $(LIBDIRS) $(LIBS) -o $(TARGET)

%.hex: $(TARGET)
	avr-objcopy -O ihex $(HEX_FLASH_FLAGS)  $< $@

%.eep: $(TARGET)
	-avr-objcopy $(HEX_EEPROM_FLAGS) -O ihex $< $@ || exit 0

%.lss: $(TARGET)
	avr-objdump -h -S $< > $@

size: ${TARGET}
	@echo
	@avr-size -C --mcu=${MCU} ${TARGET}

## Clean target
.PHONY: clean
clean:
	-rm -rf $(OBJECTS) PortableVinegar.elf dep PortableVinegar.hex PortableVinegar.eep PortableVinegar.lss PortableVinegar.map

flash: all
	$(AVRDUDE) -U flash:w:PortableVinegar.hex:i

fuses:
	$(AVRDUDE) -U lfuse:w:0xe2:m -U hfuse:w:0xd9:m -U efuse:w:0xff:m

## Other dependencies
-include $(shell mkdir dep 2>/dev/null) $(wildcard dep/*)

