# This program asks for the board serial number, assembles it's cal file, puts it in the eeprom
# along with an oscillator calibration program, It then runs the calibration 
# routine, which modifies the eeprom with the new value. It then checks to make
# sure that the eeprom has been modified, and if so, it programs in the final
# program.

# Make sure your programs are located here, or change these lines appropriately!
$avrasm2 = qq("c:\\Program Files\\Atmel\\AVR Tools\\AvrAssembler2\\avrasm2");
$stk500 = qq("c:\\Program Files\\Atmel\\AVR Tools\\STK500\\stk500.exe");
$COMPORT = "USB";
$finalcode = "..\\software\\BRMK3.hex";
my $voltcal = 2504;
my $tempcal = 500;
my $vplus;

printf "BrassRatMK3 Recalibrate Program\n\n";
printf "Serial Number? ";
$serialnum = <>;
chomp $serialnum;

$asmfile = sprintf "P%04d.asm", $serialnum;
$eepfile = sprintf "P%04d.eep", $serialnum;
$hexfile = sprintf "P%04d.eep", $serialnum;

my $returncode = 0;
$asm = qq($avrasm2 -e $eepfile $asmfile);
$returncode = (system $asm) >> 8;
if ($returncode != 0) {
	die "Cal file assembly failed :$returncode";
}

# allow erasure of eeprom
$prog = qq($stk500 -c$COMPORT -I125000 -dATMEGA168 -e -fdcc2 -EFD);
$returncode = (system $prog) >> 8;
if ($returncode != 0) {
	die "Allowing eeprom erase failed :$returncode";
}

# Pour in the Oscillator calibration program...
$prog = qq($stk500 -c$COMPORT -I1000000 -dATMEGA168 -ifRC_Calibration.hex -ie$hexfile -e -fd4c2 -EFD -pf -pe);
$returncode = (system $prog) >> 8;
if ($returncode != 0) {
	die "Initial programming failed :$returncode";
}

# And calibrate the oscillator
$prog = qq($stk500 -c$COMPORT -dATMEGA168 -Y);
$returncode = (system $prog) >> 8;
if ($returncode != 0) {
	die "Oscillator calibration failed :$returncode";
}

# make sure we did change the osccal byte
printf " vv IGNORE errors below vv\n\n";
$prog = qq($stk500 -c$COMPORT -I1000000 -dATMEGA168 -ae01b,01b -ve -ie$hexfile);
$returncode = (system $prog) >> 8;
if ($returncode == 0) {
	die "EEProm wasn't modified! :$returncode";
}
printf " ^^ IGNORE errors above ^^\n\n";

# Now put in the real bits...
$prog = qq($stk500 -c$COMPORT -I1000000 -dATMEGA168 -if$finalcode -e -pf);
$returncode = (system $prog) >> 8;
if ($returncode != 0) {
	die "Final programming failed :$returncode";
}

printf "\n\n Final Programming SUCCEEDED! YIPPEE!\n";

