PRG			= voltmeter
PROGRAMMER		= usbasp
PORT			= usb
MCU_TARGET		= atmega8
AVRDUDE_TARGET	= $(MCU_TARGET)
DEFS			= -I. -Imcucpp -Imcucpp/AVR
LIBS			= 
 
HZ          = 1000000

OPTS		= -combine  -fwhole-program -ffreestanding  -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums

OPTS 		+= -ffunction-sections -fdata-sections -Wl,--relax,--gc-sections  -g

#!OPTS		+= -fgcse-las
#!OPTS		+= -fgcse-sm
#!OPTS		+= -fmodulo-sched
#!OPTS		+= -fmodulo-sched-allow-regmoves 
#OPTS		+= -freorder-blocks
#OPTS		+= -freorder-blocks-and-partition 
#OPTS		+= -freschedule-modulo-scheduled-loops 
#OPTS		+= -fsched-spec-load-dangerous 
#OPTS		+= -fsched-stalled-insns=0 
#OPTS		+= -mcall-prologues
#OPTS		+= --param inline-call-cost=1  
#OPTS		+= -finline-limit=3 
#OPTS		+= -fno-inline-small-functions
#OPTS		+= -fpredictive-commoning
#OPTS		+= -Wunsafe-loop-optimizations
#OPTS		+= -fcse-skip-blocks
#OPTS		+= -fomit-frame-pointer 

OBJCOPY        = avr-objcopy
OBJDUMP        = avr-objdump
CC			   = avr-gcc

all: crtm8.o $(PRG).elf lst text size eeprom

$(PRG).elf: $(PRG).cc 
		$(CC) -Wa,-ahlms=v.lst -L/usr/avr/lib/avr4 $(OPTS) -DF_CPU=$(HZ)L -Os -mmcu=$(MCU_TARGET) -Wall -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums $(DEFS)  $^ -o $@

crtm8.o:
		ln -s /usr/avr/lib/avr4/crtm8.o .

size:
#		avr-size -C -d $(PRG).elf --mcu=$(MCU_TARGET)
		avr-size  -d $(PRG).elf


clean:
		rm -rf *.o $(PRG).elf *.eps *.png *.pdf *.bak *.hex *.bin *.srec *~ *.i *.s *.ii
		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 srec

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

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

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

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

# Rules for building the .eeprom rom images

eeprom: ehex ebin esrec


ehex:  $(PRG)_eeprom.hex
ebin:  $(PRG)_eeprom.bin
esrec: $(PRG)_eeprom.srec

%_eeprom.hex: %.elf
		$(OBJCOPY) -j .eeprom --change-section-lma .eeprom=0 -O ihex $< $@

%_eeprom.srec: %.elf
		$(OBJCOPY) -j .eeprom --change-section-lma .eeprom=0 -O srec $< $@

%_eeprom.bin: %.elf
		$(OBJCOPY) -j .eeprom --change-section-lma .eeprom=0 -O binary $< $@


# command to program chip (invoked by running "make install")
install:  $(PRG).hex
		avrdude -p $(AVRDUDE_TARGET) -c $(PROGRAMMER) -P $(PORT)  \
         -U flash:w:$(PRG).hex

install_eeprom:  $(PRG).hex
		avrdude -p $(AVRDUDE_TARGET) -c $(PROGRAMMER) -P $(PORT)  \
         -U eeprom:w:$(PRG)_eeprom.hex
        
fuse:
		avrdude -p $(AVRDUDE_TARGET) -c $(PROGRAMMER) -P $(PORT) -v \
        -U lfuse:w:0xc6:m -U hfuse:w:0xd9:m

