#include <cstdlib>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <vector>
#include "PadMap.h"
PadMap::PadMap(const char *fname):
_nx(0), _ny(0), _ntot(0),
_pad2chan(0), _chan2pad(0), _connected(0)
{
read_map(fname);
}
void PadMap::read_map(const char *fname)
{
clear();
std::ifstream ifile(fname);
if (!ifile)
{
std::cout << "**** PadMap: cannot open file " << fname << std::endl;
exit(1);
}
ifile >> _nx >> std::ws >> _ny >> std::ws;
_ntot = _nx * _ny;
int i, k, kmx = -1;
std::vector<int> iv;
std::vector<int>::iterator ip;
while (1)
{
ifile >> k;
if (!ifile || ifile.eof())
break;
if (kmx < k)
kmx = k;
if (k>=0)
iv.push_back(k);
}
kmx++;
if (kmx > _ntot)
_ntot = kmx;
init();
for (i = 0, ip = iv.begin();ip != iv.end();++ip, i++)
{
k = *ip;
if (k<0)
continue;
_pad2chan[i] = k;
_chan2pad[ k ] = i;
_connected[k] = 1;
}
}
PadMap::PadMap(int n, int *m, int nx, int ny):
_nx(nx), _ny(ny), _ntot(nx*ny),
_pad2chan(0), _chan2pad(0), _connected(0)
{
if (n > _ntot)
_ntot = n;
int i;
init();
for (i = 0;i < n;i++)
{
_pad2chan[i] = m[i];
_chan2pad[ m[i] ] = i;
_connected[ m[i] ] = 1;
}
}
PadMap::PadMap(int nx, int ny, int ntot):
_nx(nx), _ny(ny), _ntot(ntot),
_pad2chan(0), _chan2pad(0), _connected(0)
{
if (_ntot < 0)
_ntot = _nx * _ny;
init();
}
PadMap::PadMap(const PadMap &m) :
_pad2chan(0), _chan2pad(0), _connected(0)
{
cpy(m);
}
PadMap &PadMap::operator=(const PadMap &m)
{
if (&m!=this)
cpy(m);
return *this;
}
void PadMap::cpy(const PadMap &m)
{
int i;
clear();
_nx = m._nx;
_ny = m._ny;
_ntot = m._ntot;
_pad2chan = new int[_ntot];
_chan2pad = new int[_ntot];
_connected = new char[_ntot];
for (i = 0;i < _ntot;i++)
{
_pad2chan[i] = m._pad2chan[i];
_chan2pad[i] = m._chan2pad[i];
_connected[i] = m._connected[i];
}
}
void PadMap::clear()
{
if (_pad2chan)
delete [] _pad2chan;
if (_chan2pad )
delete [] _chan2pad;
if (_connected)
delete [] _connected;
}
void PadMap::init()
{
int i;
_pad2chan = new int[_ntot];
_chan2pad = new int[_ntot];
_connected = new char[_ntot];
for (i = 0;i < _ntot;i++)
{
_pad2chan[i] = -1;
_chan2pad[i] = -1;
_connected[i] = 0;
}
}
PadMap::~PadMap()
{
clear();
}
void PadMap::print(std::ostream &os) const
{
int ix, iy;
for (iy = 0;iy < ny();iy++)
{
for (ix = 0;ix < nx();ix++)
{
os << std::setw(5) << channel(ix, iy);
}
os << std::endl;
}
}
void PadMap::print_unconnected() const
{
int i, j;
std::cout << "Unconnected channels" << std::endl;
for (i = j = 0;i < _ntot;i++)
{
if (! _connected[i] )
{
if (!(j % 8))
std::cout << std::endl;
std::cout << std::setw(8) << i;
j++;
}
}
std::cout << std::endl;
}
void PadMap::set(int channel, int x, int y)
{
if (channel<0 || channel >_ntot)
return;
int ipad = x + _nx * y;
if (ipad>=0 && ipad<_ntot)
{
_pad2chan[ ipad ] = channel;
_chan2pad[ channel ] = ipad;
_connected[ channel ] = 1;
}
}