#!/usr/bin/env perl

# This script is used to convert the tagger B-field map from
# an ascii format that contains only Bx, By, and Bz into
# one that also contains the x,y,z position information and
# is compatible with the Hall-D calibration DB.
#
# Run it by passing the input file as a single argument on
# the command line and redirecting stdout to a new file:
#
# convert_fieldmap.pl taggerBfield-quad-map > taggerBfield-quad
#

$Nx = 351;
$Ny = 16;
$Nz = 1611;

$xmin = 10.0;
$xmax = -340.0;

$ymin= 0.0;
$ymax = 1.5;

$zmin = -10.0;
$zmax = 1600.0;


print "# \n";
print "# This file was generated from the original tagger map found\n";
print "# at http://zeus.phys.uconn.edu/halld/tagger/simulation/taggerBfield-quad-map.gz.\n";
print "# The file was listed with a date of \"15-Jan-2006 15:19\" when grabbed.\n";
print "# \n";
print "# The original file was a gzipped ASCII and contained only 3 columns\n";
print "# and no header. The coordinates of the points were calculated using\n";
print "# parameters in the gxtwist/hdds/Regions.xml file. In addition to adding\n";
print "# the coordinates, the units were converted to Tesla (from Gauss).\n";
print "# \n";
print "# \n";
print "# x        y            z          Bx               By            Bz\n";

$ix = $iy = $iz = 0;

open(FD,$ARGV[0]);
while (<FD>)
{
   if (/[^-.Ee0-9]$/)
   {
      @B = split(" ");
      next if (@B != 3);
      $B[0]=0 if (abs($B[0])<1e-10);
      $B[1]=0 if (abs($B[1])<1e-10);
      $B[2]=0 if (abs($B[2])<1e-10);
		
		# Convert from Gauss to Telsa
		for($i=0; $i<3; $i++){$B[$i]/=10000.0;}
		
		# Calculate position from indexes
		$x = $xmin + $ix*($xmax-$xmin)/($Nx-1);
		$y = $ymin + $iy*($ymax-$ymin)/($Ny-1);
		$z = $zmin + $iz*($zmax-$zmin)/($Nz-1);
		
      print "$x\t$y\t\t$z\t$B[0]\t$B[1]\t$B[2]\n";

		# Increment indexes
		$iy++;
		if($iy>=$Ny){ $iy=0; $iz++;}
		if($iz>=$Nz){ $iz=0; $ix++;}
   }
}

