#!/usr/bin/perl

use charger_lib;


$cl = charger_lib->new(0x0F);


$cl->set_unit(shift || 1);
$cl->set_baud(shift || 9600);
$cl->set_delay(0.05);
$cl->open_bus();


print "This routine will calibrate the high voltage section!\n";
print "BE VERY VERY CAREFUL WHEN USING THIS ROUTINE! 300 VOLTS CAN KILL!\n";
print "Press enter when ready>";
$junk = <>;

if($cl->write_with_verify(0x1FF3,42)) {
	die "Failed to open software lock";
}

	print "1)Connect the charger to a high voltage power supply with\n";
	print "\tbig caps like lee's silver box\n";
	print "2)Connect the charger to a battery also to provide power for the last step\n";
	print "3)Make sure the HV supply is OFF!\n";
	print "4)Connect the RS232 voltmeter COM(-) to the - output of the HV supply\n";
	print "5)Connect the RS232 voltmeter Volt/Ohm(+) to the + output of the HV supply\n";
	print "6)Set the RS232 voltmeter on Volts, and then\n";
	print "\tturn on the HV supply. \n";
	print "7)Press the Range Hold (r-h) button until there are NO decimal points in the display\n";
	print "\t(the meter is on it's highest range)\n";
	print "\n";
	print "Press enter when ready>";
	$junk = <>;

	$avg = $cl->read_eeprom(0x1FF4);

	$cl->write_eeprom(0x1FF4,2);

	print "We will log the voltage as the caps drain\n";
	print "This will take a while\n";
	print "If you're using a variac, instead of turning off the HV supply \n";
	print "slowly turn down the variac knob.\n";
	print "Now press enter, and then turn off the HV supply>";

	$junk = <>;

	@x_array = ();
	@y_array = ();

	$vfin = 256;

	while($vfin > 0) {
#		$realvolts = `./poll`;
		$realvolts = $cl->vm_read_data();
		if($cl->show_inputs()) {
			#timeout occured
		} else {
	

			$last_vfin = $vfin;
			$vfin = $cl->{read_d5};
		


			($rvolts) = $realvolts =~ /\D*(\d*.\d*)\D*/;
	#		$rvolts -= 20; # calibrated for speed of fall
					# on lee's silver box


			$rxvolts = int($rvolts * 10); 
	
			if((abs($vfin - $last_vfin) > 3) && ($vfin != 256)) {
				if($vfin > 15) {
					push(@x_array,$vfin); 
					push(@y_array,$rxvolts);
					print "$vfin -> $rxvolts\n";	
				}
			}
		}

	}

	push(@x_array,0);
	push(@y_array,0);


	print "Supply fell to zero! (this is good)\n";

	$cl->write_eeprom(0x1FF4, $avg);
	
	$href = $cl->solve("x_array" => \@x_array,
			   "y_array" => \@y_array);

	$cl->print_mcb_error(%{$href});

	$best_c = $href->{best_c};
	$best_b = $href->{best_b};
	$best_m = $href->{best_m};
	$best_error = $href->{best_error};
	$max_count = $href->{max_count};
	
	print "HV B: $best_b C: $best_c M: $best_m error: $best_error \n";
	print "max count: $max_count\n";

	open(LOG,">>calresults.log");
	$ltime = localtime();
	print LOG "$ltime HV B: $best_b C: $best_c M: $best_m E: $best_error MC: $max_count\n";
	close(LOG);
	

	while($cl->write_eeprom_int(0x1FB0,$best_m)) {}
	while($cl->write_eeprom_int(0x1FB2,$best_c)) {}
	while($cl->write_eeprom_int(0x1FB4,$best_b)) {}

	print "Okay! High voltage calibrated!\n";
		

	$cl->force_on_charger(0,0);





