PRG            = uBlink
OBJ            = ublink-main.o ublink-irq.o sd-reader/sd_raw.o sd-reader/partition.o sd-reader/fat.o
#OBJ            = ublink-main.o timer.c uart.c motor.c

BOOTPRG        = uSDBoot
BOOTOBJ        = usd-boot.o sd-reader/sd_raw_boot.o
BOOTLOADERSTARTADR = 0xf800
BOOTLDRSIZE = 0x0800


MCU_TARGET     = atmega644p
OPTIMIZE       = -O2

# DEFS           =  -std=c99 -mcall-prologues  -DUSE_UART0_SPI -DBOOTLDRSIZE=$(BOOTLDRSIZE)
DEFS           =  -std=c99 -DUSE_UART0_SPI -DBOOTLDRSIZE=$(BOOTLDRSIZE) -DUSE_DEBUG

LIBS           = -lm

# You should not have to change anything below here.

CC             = avr-gcc
SIZE           = avr-size

# Output format. (can be srec, ihex, binary)
FORMAT         = ihex

# Override is only needed by avr-lib build system.

#CFLAGS        = -g -Wall $(OPTIMIZE) -gdwarf-2 -mmcu=$(MCU_TARGET) $(DEFS)
CFLAGS        = -g -save-temps -Wall $(OPTIMIZE) -ffunction-sections -mmcu=$(MCU_TARGET) $(DEFS)
LDFLAGS       = -Wl,--section-start=.framebuffer=0x800600,--check-sections --gc-sections

BOOTLDFLAGS = -Wl,--section-start=.text=$(BOOTLOADERSTARTADR) --gc-sections
BOOTCFLAGS  = -DBOOTLDRSIZE=$(BOOTLDRSIZE)

OBJCOPY        = avr-objcopy
OBJDUMP        = avr-objdump

all: $(PRG).elf $(PRG).uSD $(BOOTPRG).elf text

$(PRG).elf: $(OBJ)
	$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^ $(LIBS)

$(BOOTPRG).elf: $(BOOTOBJ)
	$(CC) $(CFLAGS) $(BOOTCFLAGS) $(BOOTLDFLAGS) -o $@ $^ $(LIBS)

clean:
	rm -rf *.o *.i *.s *.d $(OBJ) $(BOOTOBJ) $(BOOTPRG).elf $(PRG).elf *.bak *~
	rm -rf *.srec *.bin *.hex *.eep *.map
	rm -rf *.lst *.map $(EXTRA_CLEAN_FILES)

lst:  $(PRG).lst

%.lst: %.elf
	$(OBJDUMP) -h -S $< > $@

# Rules for building the .text rom images

text: hex bin

hex:  $(PRG).hex $(BOOTPRG).hex
bin:  $(PRG).bin $(BOOTPRG).bin

%.hex: %.elf
	$(OBJCOPY) -j .text -j .data -O ihex $< $@
	$(SIZE) $<

%.bin: %.elf
	$(OBJCOPY) -j .text -j .data -O binary $< $@

sd-reader/sd_raw_boot.o: sd-reader/sd_raw.c
	$(CC) -c $(CFLAGS) -DBOOTLOADER_SD_RAW -o $@ $^

ublink-irq.o: ublink-irq.S
	$(CC) -c $(CFLAGS) -o $@ $^

%.uSD: %.bin
	./gen_update.py $< $@
