#!/apps/perl/PRO/bin/perl
#!/apps/perl/bin/perl

#########################################################################################
# This is the prestart script for the PrimEx DAQ system. It is run during the
# CODA "prestart" transition and is responsible for filling certain entries
# in the online database.
# 
# 8/12/02  D. Lawrence
#########################################################################################


### perl modules built for PrimEx use on clon cluster
use Pezca;
Pezca::SetTimeout(1);
Pezca::SetRetryCount(0);

### Set database access parameters
$msql_host = "clon10";
$mysql_host = "clas-sc0";
$mysql_user = "primex";
$mysql_db = "primex_online";

### Make sure the EPICS_CA_ADDR_LIST environment variable is defined
if(length($ENV{"EPICS_CA_ADDR_LIST"})<1) {
	$ENV{"EPICS_CA_ADDR_LIST"} = "129.57.255.4 129.57.163.255 129.57.96.7 129.57.57.188";
}

########################## Collect values to insert in database ####################
### Get Current run number (Geez, it's ridiculous what we havce to do to get the run number)
$sql = "SELECT runNumber FROM sessions WHERE name='primex'\\g";
$result = `echo \"$sql\" | msql -h $msql_host primex | grep \"|\" | grep -v runNumber`;
@tmp = split(/\s+/, $result);
$runNumber =  $tmp[2];

# Dummy check on run number
if($runNumber<1000){
	print "Run Number is less than 1000!. This just can't be right.\n";
	exit(0);
}


### Get Beam energy in Hall-B
($err,$beamEnergy) = Pezca::GetDouble("MMSHLBE");

### Get values from BPMs
$BPM2C21I=$BPM2C21X=$BPM2C21Y=$BPM2C24I=$BPM2C24X=$BPM2C24Y=0;
($err,$BPM2C21I) = Pezca::GetDouble("hallb_IPM2C21A_CUR");
($err,$BPM2C21X) = Pezca::GetDouble("hallb_IPM2C21A_XPOS");
($err,$BPM2C21Y) = Pezca::GetDouble("hallb_IPM2C21A_YPOS");
($err,$BPM2C24I) = Pezca::GetDouble("hallb_IPM2C24A_CUR");
($err,$BPM2C24X) = Pezca::GetDouble("hallb_IPM2C24A_XPOS");
($err,$BPM2C24Y) = Pezca::GetDouble("hallb_IPM2C24A_YPOS");

### Get Magnet currents
($err,$PS_Current) = Pezca::GetDouble("PSPECIRBCK");
# The following was commented out fro the low Q2 test run
#($err,$PS_NMR) = Pezca::GetDouble("PAIR_SPEC:NMRFIELDRBCK");
($err,$Tagger_Current) = Pezca::GetDouble("TMIRBCK");
if($PS_Current eq ""){$PS_Current = 0;}
if($PS_NMR eq ""){$PS_NMR = 0;}
if($Tagger_Current eq ""){$Tagger_Current = 0;}

### Get Radiator/Convertor positions
($err,$Radiator_pos) = Pezca::GetDouble("harp_tagger.VAL");
($err,$Convertor_pos) = Pezca::GetDouble("harp_2h00.VAL");
#($err,$Target_pos) = Pezca::GetDouble("harp_tagger.VAL");
#($err,$TAC_status) = Pezca::GetDouble("harp_tagger.VAL");

$Radiator="'UNKNOWN'";
if(abs($Radiator_pos-0.0	)<10.0){$Radiator="'OUT'";}
if(abs($Radiator_pos-70.485	)< 5.0){$Radiator="'A'";}
if(abs($Radiator_pos-86.804	)< 5.0){$Radiator="'B'";}
if(abs($Radiator_pos-100.77	)< 5.0){$Radiator="'C'";}
if(abs($Radiator_pos-115.2	)< 5.0){$Radiator="'D'";}

$Convertor="'UNKNOWN'";
if(abs($Convertor_pos-0.0	)<10.0){$Convertor="'OUT'";}
if(abs($Convertor_pos-75)< 5.0){$Convertor="'-4'";}
if(abs($Convertor_pos-107)< 5.0){$Convertor="'-3'";}
if(abs($Convertor_pos-134)< 5.0){$Convertor="'-2'";}

############################ Insert values into database #############################
### Form SQL INSERT query for "Beam" table
push(@vals,("Run_Number","$runNumber"));
push(@vals,("Beam_Energy","$beamEnergy"));
push(@vals,"BPM2C21I","$BPM2C21I");
push(@vals,"BPM2C21X","$BPM2C21X");
push(@vals,"BPM2C21Y","$BPM2C21Y");
push(@vals,"BPM2C24I","$BPM2C24I");
push(@vals,"BPM2C24X","$BPM2C24X");
push(@vals,"BPM2C24Y","$BPM2C24Y");
&FillFieldsAndValues;
$query = "INSERT INTO Beam ($fields) VALUES ($values)";
print"$query\n";
print `mysql -e \"$query\" -h $mysql_host -u $mysql_user $mysql_db`;
#$dbh_mysql->do($query) or die $DBI::errstr;

### Form SQL INSERT query for "Magnets" table
push(@vals,("Run_Number","$runNumber"));
push(@vals,"PS_Current","$PS_Current");
push(@vals,"PS_NMR","$PS_NMR");
push(@vals,"Tagger_Current","$Tagger_Current");
&FillFieldsAndValues;
$query = "INSERT INTO Magnets ($fields) VALUES ($values)";
print"$query\n";
print `mysql -e \"$query\" -h $mysql_host -u $mysql_user $mysql_db`;
#$dbh_mysql->do($query) or die $DBI::errstr;

### Form SQL INSERT query for "RunID" table
push(@vals,("Run_Number","$runNumber"));
push(@vals,("Run_Type","$runType"));
push(@vals,("Run_Status","'UNKNOWN'"));
push(@vals,("Run_Comment","$runComment"));
push(@vals,("Operators","$operators"));
push(@vals,("Beam_Current_requested","$beamCurrentRequest"));
push(@vals,"Radiator","$Radiator");
push(@vals,"Converter","$Convertor");
push(@vals,"Begin_Run_Time","NOW()");
&FillFieldsAndValues;
$query = "UPDATE RunID SET Radiator=$Radiator,Converter=$Convertor,Begin_Run_Time=NOW() WHERE Run_Number=$runNumber";
print"$query\n";
print `mysql -e \"$query\" -h $mysql_host -u $mysql_user $mysql_db`;
#$dbh_mysql->do($query) or die $DBI::errstr;



#### This subroutine uses the values in @vals to create comma separated lists
#### in $fields and $values for use in an SQL query
sub FillFieldsAndValues{

	$fields = "";
	$values = "";

	$length = @vals;
	for($i=0; $i<$length/2; $i++)
	{
		$val	= pop(@vals);
		$name	= pop(@vals);
		if( length($val)<1 ){$val=0;}
		$fields .= "$name,";
		$values .= "$val,";
	}
	chop $fields; # remove last comma
	chop $values; # remove last comma

}

