/*
 * QtGl.cpp
 *
 *  Created on: Jul 19, 2011
 *      Author: lyard
 */


#include "RawEventsViewer.h"
#include "viewer.h"
#include <math.h>
#include <fstream>

#ifdef LOAD_RAW
int16_t eventsData[NUM_STORED_EVENTS][ACTUAL_NUM_PIXELS][1024];
#include </home/lyard/Code/display.C>
#endif

#define VALUES_SPAN 4096

#include <QFileDialog>

#include <qwt_plot_grid.h>
#include <qwt_symbol.h>

#include "src/Configuration.h"
#include "externals/fits.h"

using namespace std;

#undef ACTUAL_NUM_PIXELS
#define ACTUAL_NUM_PIXELS 1440

//bounding box for diplaying the impulse curve
float bboxMin[2] = {-0.8,-0.9};
float bboxMax[2] = {0.8,-0.3};
/************************************************************
 * CALC BLUR COLOR if in blur display mode, calculate the interpolated
 * colour for a given vertex
 ************************************************************/
void RawDataViewer::calcBlurColor(int pixel,  int vertex)
{
    GLfloat color[3];
    int first, second;
    first = vertex-1;
    second = vertex;
    if (first < 0)
        first = 5;
    first = neighbors[pixel][first];
    second = neighbors[pixel][second];
    for (int i=0;i<3;i++)
        color[i] = pixelsColor[pixel][i];
    float divide = 1;
    if (first != -1)
    {
        divide++;
        for (int i=0;i<3;i++)
            color[i] += pixelsColor[first][i];
    }
    if (second != -1)
    {
        divide++;
        for (int i=0;i<3;i++)
            color[i] += pixelsColor[second][i];
    }
    for (int i=0;i<3;i++)
        color[i] /= divide;
    glColor3fv(color);
}
/************************************************************
 * DRAW BLURRY HEXAGON. draws a solid hexagon, with interpolated colours
 ************************************************************/
void RawDataViewer::drawBlurryHexagon(int index)
{
    GLfloat color[3];
    for (int i=0;i<3;i++)
        color[i] = pixelsColor[index][i];
    glBegin(GL_TRIANGLES);
    calcBlurColor(index, 0);
    glVertex2fv(verticesList[verticesIndices[index][0]]);
    glColor3fv(color);
    glVertex2fv(pixelsCoords[index]);
    calcBlurColor(index, 1);
    glVertex2fv(verticesList[verticesIndices[index][1]]);

    glVertex2fv(verticesList[verticesIndices[index][1]]);
    glColor3fv(color);
    glVertex2fv(pixelsCoords[index]);
    calcBlurColor(index, 2);
    glVertex2fv(verticesList[verticesIndices[index][2]]);

    glVertex2fv(verticesList[verticesIndices[index][2]]);
    glColor3fv(color);
    glVertex2fv(pixelsCoords[index]);
    calcBlurColor(index, 3);
    glVertex2fv(verticesList[verticesIndices[index][3]]);

    glVertex2fv(verticesList[verticesIndices[index][3]]);
    glColor3fv(color);
    glVertex2fv(pixelsCoords[index]);
    calcBlurColor(index, 4);
    glVertex2fv(verticesList[verticesIndices[index][4]]);

    glVertex2fv(verticesList[verticesIndices[index][4]]);
    glColor3fv(color);
    glVertex2fv(pixelsCoords[index]);
    calcBlurColor(index, 5);
    glVertex2fv(verticesList[verticesIndices[index][5]]);

    glVertex2fv(verticesList[verticesIndices[index][5]]);
    glColor3fv(color);
    glVertex2fv(pixelsCoords[index]);
    calcBlurColor(index, 0);
    glVertex2fv(verticesList[verticesIndices[index][0]]);
    glEnd();

    return;
}

/************************************************************
 * DRAW CAMERA draws all the camera pixels
 ************************************************************/
void RawDataViewer::drawCamera(bool alsoWire)
{
    glLoadIdentity();
    if (!drawImpulse)
    {
        glTranslatef(0,-0.44,0);
        glRotatef(cameraRotation, 0,0,-1);
        if (cameraRotation == 90)
        {
            glTranslatef(-0.45,-0.45,0);
 //           cout << "correction" << endl;
        }
        if (cameraRotation == -90)
        {
            glTranslatef(0.45,-0.45,0);
        }
        glScalef(1.5,1.5,1);
    }
    else
    {
        glRotatef(cameraRotation, 0,0,-1);
          if (cameraRotation == 90)
        {
            glTranslatef(-0.45/1.5,-0.45/1.5,0);
 //           cout << "correction" << endl;
        }
        if (cameraRotation == -90)
        {
            glTranslatef(0.45/1.5,-0.45/1.5,0);
        }
  }
    glColor3f(0.5,0.5,0.5);
    glLineWidth(1.0);
    float color;
//cout << "Actual num pixels: " << ACTUAL_NUM_PIXELS << endl;
    for (int i=0;i<ACTUAL_NUM_PIXELS;i++)
    {
        if (!nRoi)
          color = (float)(i)/(float)(ACTUAL_NUM_PIXELS);
        else
#ifdef LOAD_RAW
        color = float(eventsData[eventNum][i][whichSlice]+(VALUES_SPAN/2))/(float)(VALUES_SPAN-1);
#else
        color = float(eventData[nRoi*i + whichSlice]+(VALUES_SPAN/2))/(float)(VALUES_SPAN-1);
        if (logScale)
        {
            color *= 9;
            color += 1;
            color = log10(color);
        }
#endif
        if (color < 0)
        {
            pixelsColor[i][0] = tooLowValueCoulour[0];
            pixelsColor[i][1] = tooLowValueCoulour[1];
            pixelsColor[i][2] = tooLowValueCoulour[2];
            continue;
        }
        if (color > 1)
        {
            pixelsColor[i][0] = tooHighValueCoulour[0];
            pixelsColor[i][1] = tooHighValueCoulour[1];
            pixelsColor[i][2] = tooHighValueCoulour[2];
            continue;
        }
        int index = 0;
        while (ss[index] < color && index < 4)
            index++;
        index--;
        if (index < 0) index = 0;
        float weight0 = (color-ss[index]) / (ss[index+1]-ss[index]);
        if (weight0 > 1.0f) weight0 = 1.0f;
        if (weight0 < 0.0f) weight0 = 0.0f;
        float weight1 = 1.0f-weight0;
        pixelsColor[i][0] = weight1*rr[index] + weight0*rr[index+1];
        pixelsColor[i][1] = weight1*gg[index] + weight0*gg[index+1];
        pixelsColor[i][2] = weight1*bb[index] + weight0*bb[index+1];
    }

    for (int i=0;i<ACTUAL_NUM_PIXELS;i++)
    {
//        if (i == 690 ||
//            i == 70)
//            continue;
        glColor3fv(pixelsColor[i]);
        glLoadName(i);
if (drawBlur)
    drawBlurryHexagon(i);
else
    drawHexagon(i,true);

    }
    if (!alsoWire)
        return;
    glColor3f(0.0f,0.0f,0.0f);
    for (int i=0;i<ACTUAL_NUM_PIXELS;i++)
    {
//        if (i == 690 ||
//            i == 70)
//            continue;
        drawHexagon(i, false);
    }

}

/************************************************************
 * TRIM. FIXME this should not be here but taken from an existing class (somewhere)
 ***********************************************************
string Trim(const string &str)
{
    // Trim Both leading and trailing spaces
    const size_t start = str.find_first_not_of(' '); // Find the first character position after excluding leading blank spaces
    const size_t end   = str.find_last_not_of(' ');  // Find the first character position from reverse af

    // if all spaces or empty return an empty string
    if (string::npos==start || string::npos==end)
        return string();

    return str.substr(start, end-start+1);
}*/
/************************************************************
 * DRAW PIXEL CURVE. draws the raw impulse curve of the currently selected pixel
 ************************************************************/
void RawDataViewer::drawPixelCurve()
{
    if (!nRoi)
        return;

    float xZoom, yZoom;
    xZoom = yZoom = 1.0f;

    glBegin(GL_LINES);
    glLineWidth(1.0f);
    glColor3f(0.5,0.5,0.5);
    glVertex2f(bboxMin[0], bboxMin[1]);
    glVertex2f(bboxMax[0], bboxMin[1]);
    glVertex2f(bboxMin[0], bboxMin[1]);
    glVertex2f(bboxMin[0], bboxMax[1]);
    glVertex2f(bboxMin[0], (bboxMin[1]+bboxMax[1])/2.0f);
    glVertex2f(bboxMax[0], (bboxMin[1]+bboxMax[1])/2.0f);
    float xRange = bboxMax[0] - bboxMin[0];
    float yRange = bboxMax[1] - bboxMin[1];
    glColor3f(1.0,1.0,1.0);
    float divideMe = (float)(VALUES_SPAN-1);
    float plusMe = VALUES_SPAN/2;
    if (drawCalibrationLoaded)
        plusMe += 0;//VALUES_SPAN/2;
    if (drawCalibrationLoaded && calibrationLoaded)
    {
        divideMe /=2;
        plusMe /=2;
    }
    for (int i=0;i<nRoi-1;i++)
    {
#ifdef LOAD_RAW
        glVertex2f(bboxMin[0] + xRange*i/(float)nRoi,
                   bboxMin[1] + yRange*(eventsData[eventNum][selectedPixel][i]+plusMe) /divideMe);
        glVertex2f(bboxMin[0] + xRange*(i+1)/(float)nRoi,
                   bboxMin[1] + yRange*(eventsData[eventNum][selectedPixel][i+1]+plusMe) /divideMe);
#else

        glVertex2f(bboxMin[0] + xRange*i/(float)nRoi,
                   bboxMin[1] + yRange*(eventData[nRoi*selectedPixel + i]+plusMe) /divideMe);
        glVertex2f(bboxMin[0] + xRange*(i+1)/(float)nRoi,
                   bboxMin[1] + yRange*(eventData[nRoi*selectedPixel + i+1]+plusMe) /divideMe);
#endif
    }
    glColor3f(1.0,0.0,0.0);
    glVertex2f(bboxMin[0] + xRange*whichSlice/(float)nRoi,
               bboxMin[1]);
    glVertex2f(bboxMin[0] + xRange*whichSlice/(float)nRoi,
               bboxMax[1]);

/*    glColor3f(0.f,0.5f,0.f);
    for (int i=0;i<nRoi-1;i++)
    {
        glVertex2f(bboxMin[0] + xRange*i/(float)nRoi,
                   bboxMin[1] + yRange*(n1mean[ i]+plusMe) /divideMe);
        glVertex2f(bboxMin[0] + xRange*(i+1)/(float)nRoi,
                   bboxMin[1] + yRange*(n1mean[i+1]+plusMe) /divideMe);
    }
*/
    glEnd();
    glEnable(GL_MULTISAMPLE);
    setFont(QFont("Times", 12));
    qglColor(QColor(255,223,127));
    float xShift = 0.10f;
    float yShift = 0.01f;
    renderText(bboxMin[0]-xShift/2.0f, bboxMax[1]+3*yShift, 0, QString("Volts"));
    if (drawCalibrationLoaded)
    {
        renderText(bboxMin[0]-xShift, bboxMax[1]-yShift,0,QString("+2.10"));
        renderText(bboxMin[0]-xShift,  ((bboxMin[1]+bboxMax[1])/2.0f) - yShift, 0, QString("+1.05"));//((bboxMin[1]+bboxMax[1])/2.0f)
        renderText(bboxMin[0]-xShift, bboxMin[1]-yShift, 0, QString("0.00"));
    }
    else
    {
        renderText(bboxMin[0]-xShift, bboxMax[1]-yShift,0,QString("+1.05"));
        renderText(bboxMin[0]-xShift,  ((bboxMin[1]+bboxMax[1])/2.0f) - yShift, 0, QString("+0.00"));//((bboxMin[1]+bboxMax[1])/2.0f)
        renderText(bboxMin[0]-xShift, bboxMin[1]-yShift, 0, QString("-1.05"));
    }
    renderText(bboxMax[0]+xShift/2.0f, bboxMin[1]-4*yShift, 0, QString("Slices"));
    renderText(bboxMin[0]-yShift/2.0f, bboxMin[1]-4*yShift, 0, QString("0"));
    ostringstream str;
    str << nRoi/2;
    renderText(((bboxMin[0]+bboxMax[0])/2.0f)-xShift/2.0f, bboxMin[1]-4*yShift, 0, QString(str.str().c_str()));
    str.str("");
    str << nRoi;
    renderText(bboxMax[0]-xShift/2.0f, bboxMin[1]-4*yShift, 0, QString(str.str().c_str()));

}
/************************************************************
 * CONSTRUCTOR.
 ************************************************************/
RawDataViewer::RawDataViewer(QWidget *cParent) : BasicGlCamera(cParent)
{
 //   setFormat(QGLFormat(QGL::DoubleBuffer));// | QGL::DepthBuffer));
    whichSlice = 0;
#ifdef LOAD_RAW
    nRoi = 1024;
#else
    nRoi = 0;
#endif
    eventNum = 0;
    rowNum = -1;
    eventStep = 1;
    selectedPixel = 393;
    inputFile = NULL;
    eventData = NULL;
    drawPatch = true;
    drawImpulse = false;
    drawBlur = false;
    loopCurrentEvent = false;
    SetAutoRefresh(true);
#ifdef LOAD_RAW
    loadEvents("/scratch/00000043.001_T.bin");
#endif
    PixelMap mypMap;
    if (!mypMap.Read("FACTmapV5.txt"))
    {
        cerr << "ERROR - Problems reading FACTmapV5.txt" << endl;
        exit(-1);
    }
    ifstream fin1("Trigger-Patches.txt");
    if (!fin1.is_open())
    {
        cout << "Error: file \"Trigger-Patches\" missing. aborting." << endl;
        exit(-1);
    }
    string buf;
    vector<int> patchHW(1440);
    int l = 0;
    while (getline(fin1, buf, '\n'))
    {
        buf = Tools::Trim(buf);
        if (buf[0]=='#')
            continue;

        stringstream str(buf);
        for (int i=0; i<9; i++)
        {
            unsigned int n;
            str >> n;

            if (n>=patchHW.size())
                continue;

            patchHW[n] = l;
        }
        l++;
    }
    if (l!=160)
        cerr << "WARNING - Problems reading Trigger-Patches.txt" << endl;

    assignPixelMap(mypMap);
    assignTriggerPatchesMap(patchHW);

    GLfloat tempPixelsCoords[MAX_NUM_PIXELS][3];
    for (int i=0;i<1440;i++)
        for (int j=0;j<3;j++)
            tempPixelsCoords[hardwareMapping[i]][j] = pixelsCoords[i][j];
    for (int i=0;i<1440;i++)
        for (int j=0;j<3;j++)
            pixelsCoords[i][j] = tempPixelsCoords[i][j];

    for (int i=0;i<1440;i++)
    updateNeighbors(i);
    buildVerticesList();

/*    ifstream fin1("Trigger-Patches.txt");
   if (!fin1.is_open())
   {
       cout << "Error: file \"Trigger-Patches.txt\" missing. Aborting." << endl;
       exit(-1);
   }
   l=0;
    while (getline(fin1, buf, '\n'))
    {
        buf = Trim(buf);
        if (buf[0]=='#')
            continue;

        stringstream str(buf);
        for (int i=0; i<9; i++)
        {
            unsigned int n;
            str >> n;

            if (n>=1440)
                continue;

            patches[l][i] = hardwareMapping[n];
        }
        l++;
    }*/

    buildPatchesIndices();
    float color[3];
    for (int i=0;i<160;i++)
    {
        color[0] = 0.5; color[1] = 0.5; color[2] = 0.3;
        for (int j=0;j<3;j++)
            patchesColor[i][j] = color[j];
    }

    for (int i=0;i<1440;i++)
        updateNeighbors(i);

    calibrationLoaded = false;
    drawCalibrationLoaded = false;

}
/************************************************************
 *  DESTRUCTOR
 ************************************************************/
RawDataViewer::~RawDataViewer()
{
    if (inputFile != NULL)
    {
        inputFile->close();
        delete inputFile;
    }
    if (eventData != NULL) {
        delete[] eventData;
        delete[] rawEventData;
        delete[] waveLetArray;
    }
}

void RawDataViewer::buildPatchesIndices()
{
    vector<edge>::iterator it;
    bool erased = false;
//        patchesIndices.resize(NTMARK);
    for (int i=0;i<NTMARK;i++)//for all patches
    {
        patchesIndices[i].clear();
        for (int j=0;j<9;j++)//for all cells of the current patch
        {
//            if (patches[i][j] == 690 ||
//                patches[i][j] == 70)
//                continue;
            for (int k=0;k<6;k++)//for all sides of the current cell
            {
                int first = k-1;
                int second = k;
                if (first < 0)
                    first = 5;
                erased = false;
                for (it=(patchesIndices[i]).begin(); it != (patchesIndices[i]).end(); it++)//check if this side is here already or not
                {
                    if (((*it).first == verticesIndices[patches[i][j]][first] &&
                         (*it).second == verticesIndices[patches[i][j]][second]) ||
                        ((*it).first == verticesIndices[patches[i][j]][second] &&
                         (*it).second == verticesIndices[patches[i][j]][first]))
                    {
                        patchesIndices[i].erase(it);
                        erased = true;
                        break;
                    }
                }
                if (!erased)
                {
                    edge temp;
                    temp.first = verticesIndices[patches[i][j]][first];
                    temp.second = verticesIndices[patches[i][j]][second];
                    patchesIndices[i].push_back(temp);
                }
            }
        }
    }
}
/************************************************************
 * PAINT GL. main drawing function.
 ************************************************************/
void RawDataViewer::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT);
    glLoadIdentity();


    if (drawBlur)
    {
        glShadeModel(GL_SMOOTH);
        drawCamera(false);
    }
    else
    {
        glShadeModel(GL_FLAT);
        drawCamera(true);
    }
    if (drawPatch)
        drawPatches();

   if (!drawBlur)
   {
        glLineWidth(1.0f);
        glColor3f(1.0,1.0,1.0);
        drawHexagon(selectedPixel, false);
   }
   if (drawImpulse)
   {
    //   glRotatef(cameraRotation, 0,0,1);
       glLoadIdentity();
       glLineWidth(2.0);
       drawPixelCurve();
   }

   DrawScale();
}

/************************************************************
 * MOUSE PRESS EVENT. mouse click handler.
 ************************************************************/
void RawDataViewer::mousePressEvent(QMouseEvent *cEvent)
{
    if (cEvent->pos().x() > width()-(width()/50.f))
    {
        toggleInterfaceDisplay();
        return;
    }
    lastPos = cEvent->pos();
    setCorrectSlice(cEvent);
    updateGL();
}

/************************************************************
 * SET CORRECT SLICE. if displayed, figures out if the graph was
 * clicked, and if so, which slice should be displayed
 ************************************************************/
void RawDataViewer::setCorrectSlice(QMouseEvent* cEvent)
{
    if (!drawImpulse)
        return;
    float cx = (float)cEvent->x() * pixelSize - shownSizex/2;
    float cy = ((float)height()-(float)cEvent->y())*pixelSize - shownSizey/2;
    if (cx < bboxMin[0] ||
        cx > bboxMax[0] ||
        cy < bboxMin[1] ||
        cy > bboxMax[1])
        return;
    whichSlice = (cx - bboxMin[0])*1024/(bboxMax[0] - bboxMin[0]);
    emit signalCurrentSlice(whichSlice);
}

/************************************************************
 * MOUSE MOVE EVENT. used to track the dragging of slices display
 ************************************************************/
void RawDataViewer::mouseMoveEvent(QMouseEvent *cEvent)
{
    if (cEvent->buttons() & Qt::LeftButton) {
        setCorrectSlice(cEvent);
        updateGL();
    } else if (cEvent->buttons() & Qt::RightButton) {
        updateGL();
    }
    lastPos = cEvent->pos();
}

/************************************************************
 * MOUSE DOUBLE CLICK EVENT. used to select pixels
 ************************************************************/
void RawDataViewer::mouseDoubleClickEvent(QMouseEvent *cEvent)
{
    int face = PixelAtPosition(cEvent->pos());
    if (face != -1) {
        selectedPixel = face;
        emit signalCurrentPixel(face);
        updateGL();
        }
}

/************************************************************
 * OPEN FILE. opens a new fits file
 ************************************************************/
void RawDataViewer::openFile(string& file)
{
    if (inputFile)
    {
        inputFile->close();
        delete inputFile;
    }
    try {
    inputFile = new fits(file);
    }
    catch (std::runtime_error e)
    {
        cout << "Something went wrong while loading fits. aborting: " << e.what() << endl;
        return;
    }
    if (!*inputFile)
    {
        delete inputFile;
        inputFile = NULL;
        return;
    }
    vector<string> entriesToCheck;
    entriesToCheck.push_back("NAXIS2");
    entriesToCheck.push_back("NROI");
    entriesToCheck.push_back("NTMARK");
    entriesToCheck.push_back("RUNTYPE");
    entriesToCheck.push_back("REVISION");
    entriesToCheck.push_back("BLDVER");
    entriesToCheck.push_back("RUNID");
    entriesToCheck.push_back("NBOARD");
    entriesToCheck.push_back("NPIX");
    entriesToCheck.push_back("NROITM");
    entriesToCheck.push_back("TIMESYS");
    entriesToCheck.push_back("DATE");
    entriesToCheck.push_back("NIGHT");
    entriesToCheck.push_back("CAMERA");
    entriesToCheck.push_back("DAQ");
    entriesToCheck.push_back("TSTART");
    entriesToCheck.push_back("TSTOP");
    //entriesToCheck.push_back("ADCRANGE");
    //entriesToCheck.push_back("NBEVTOK");
    //entriesToCheck.push_back("NBEVTREJ");
    //entriesToCheck.push_back("NBEVTBAD");

    for (vector<string>::const_iterator it=entriesToCheck.begin(); it != entriesToCheck.end(); it++)
    {
        try {
        if (!inputFile->HasKey(*it)){
            cout << *it << " missing. Aborting load..." << endl;
            return;}
        }
        catch (std::runtime_error e)
        {
            cout << e.what() << endl;
            return;
        }
    }
    nRows = inputFile->GetInt("NAXIS2");
    nRoi = inputFile->GetInt("NROI");
    runNumber = inputFile->GetInt("RUNID");
    nTM = inputFile->GetInt("NTMARK");
    runType = inputFile->GetInt("RUNTYPE");
    firstDataTime = inputFile->GetInt("TSTART");
    lastDataTime = inputFile->GetInt("TSTOP");
    nRoiTM = inputFile->GetInt("NROITM");
    revision = inputFile->GetInt("REVISION");
    builderVersion = inputFile->GetInt("BLDVER");
    nBoards = inputFile->GetInt("NBOARD");
    nPixels = inputFile->GetInt("NPIX");
    timeSystem = inputFile->GetStr("TIMESYS");
    creationDate = inputFile->GetStr("DATE");
    nightInt = inputFile->GetInt("NIGHT");
    camera = inputFile->GetStr("CAMERA");
    daq = inputFile->GetStr("DAQ");
    adcCount = inputFile->HasKey("ADCRANGE") ? inputFile->GetFloat("ADCRANGE") : 2000;
    nbOk = 0;//inputFile->GetInt("NBEVTOK");
    nbRej = 0;//inputFile->GetInt("NBEVTREJ");
    nbBad = 0;//inputFile->GetInt("NBEVTBAD");

    eventNum = 0;

#ifdef LOAD_RAW
    nRows = NUM_STORED_EVENTS;
#endif

    if (eventData != NULL) {
        delete[] eventData;
        delete[] rawEventData;
        delete[] waveLetArray;
    }
    eventData = new float[(1440+160)*nRoi];
    rawEventData = new int16_t[(1440+160)*nRoi];
    waveLetArray = new int16_t[1024*1440];
    if (!inputFile->SetPtrAddress("Data", rawEventData)){
        cout << "Missing column " << "Data" << " Aborting load..." << endl;
        nRoi = nRows = 0;return;}
    if (!inputFile->SetPtrAddress("EventNum", &eventNum)){
        cout << "Missing column " << "EventNum" << " Aborting load..." << endl;
        nRoi = nRows = 0;return;}
    if (!inputFile->SetPtrAddress("TriggerType", &triggerType)){
        cout << "Missing column " << "TriggerType" << " Aborting load..." << endl;
        nRoi = nRows = 0;return;}
    if (!inputFile->SetPtrAddress("SoftTrig", &softTrig)){
        cout << "Missing column " << "SoftTrig" << " Aborting load..." << endl;
        nRoi = nRows = 0;return;}
    if (!inputFile->SetPtrAddress("PCTime", &pcTime)){
        cout << "Missing column " << "PCTime" << " Aborting load..." << endl;
        nRoi = nRows = 0;return;}
    if (!inputFile->SetPtrAddress("BoardTime", boardTime)){
        cout << "Missing column " << "BoardTime" << " Aborting load..." << endl;
        nRoi = nRows = 0;return;}
    if (!inputFile->SetPtrAddress("StartCellData", startPix)){
        cout << "Missing column " << "StartCellData" << " Aborting load..." << endl;
        nRoi = nRows = 0;return;}
    if (!inputFile->SetPtrAddress("StartCellTimeMarker", startTM)){
        cout << "Missing column " << "StartCellTimeMarker" << " Aborting load..." << endl;
        nRoi = nRows = 0;return;}
    int backupStep = eventStep;
    rowNum = -1;
    eventStep = 1;

    doMyWaveletTestPlease();


    plusEvent();
    eventStep = backupStep;
    emit newFileLoaded();
    emit signalCurrentPixel(selectedPixel);
}
/*
bool RawDataViewer::doWaveLetsPlease(int givenSpan, int16_t* orig_in, int16_t* wavelets_in, bool verifyResult)
{
    float* interArray = new float[givenSpan];
    float* resultArray = new float[givenSpan];
    float* orig = new float[givenSpan];
    float* wavelets = new float[givenSpan];
    for (int i=0;i<givenSpan;i++)
    {
        if (fabs((float)(orig_in[i])) > 32767.f)
            cout << "Input overflow: " << orig_in[i] << endl;
        orig[i] = (float)orig_in[i];
    }
    for (int k=0;k<givenSpan;k++)
        interArray[k] = orig[k];
    int span = givenSpan/2;
    while (span > 0)
    {
        for (int k=0;k<span;k++)
        {
            wavelets[k]        = (interArray[2*k] + interArray[2*k + 1])/2.f;
            wavelets[k + span] = (interArray[2*k + 1] - interArray[2*k])/2.f;
        }
        for (int k=0;k<givenSpan;k++)
            interArray[k] = wavelets[k];
        span /= 2;
    }
    //move float results to int16_t array
    float intScaling = 15.9f;
    int max = 0;
    for (int i=0;i<givenSpan;i++)
    {
        float cValue = intScaling*wavelets[i];//
        if (cValue > 0)
            cValue += 0.5f;
        else
            cValue -= 0.5f;
        wavelets_in[i] = (int16_t)(cValue);
        if (fabs(cValue) >  32767.f)
        {
            cout << "Overflow ! " << cValue << endl;
        }
        if (fabs(cValue) > fabs(max))
            max = cValue;
    }
//    cout << "Max wave value: " << max << endl;
    //result reconstruction and checking
    if (!verifyResult)
        return true;

   for (int k=0;k<givenSpan;k++)
   {
       resultArray[k] = wavelets_in[k]/intScaling;
   }

   span = 1;
   while (span < givenSpan)
   {
       for (int k=0;k<givenSpan;k++)
           interArray[k] = resultArray[k];
      for (int k=0;k<span;k++)
       {
          resultArray[2*k]     = (float)(((interArray[k] - interArray[k + span])*(1.f/1.f)) + 0.0f);
          resultArray[2*k + 1] = (float)(((interArray[k] + interArray[k + span])*(1.f/1.f)) + 0.0f);
       }
       span *= 2;
   }

   for (int k=0;k<givenSpan;k++)
   {
       float plus = 0.5f;
       if (resultArray[k] < 0)
           plus *= -1.f;
       if ((int)(resultArray[k]+plus) != (int)(orig_in[k]))
       {
           cout << "Nop, sorry: k: "  << k << " " << resultArray[k] << " " << (int)(resultArray[k]+plus) << " " << plus << " " << orig[k] << endl;
           return false;
       }
   }
   return true;
}
*/
bool RawDataViewer::doWaveLetsPlease(int givenSpan, int16_t* orig_in, int16_t* wavelets_in, bool verifyResult)
{
    float* interArray = new float[givenSpan];
    float* resultArray = new float[givenSpan];
    float* orig = new float[givenSpan];
    float* wavelets = new float[givenSpan];
    for (int i=0;i<givenSpan;i++)
    {
        if (fabs((float)(orig_in[i])) > 32767.f)
            cout << "Input overflow: " << orig_in[i] << endl;
        orig[i] = (float)orig_in[i];
    }
    for (int k=0;k<givenSpan;k++)
        interArray[k] = orig[k];
    int span = givenSpan/2;
    while (span > 0)
    {
        for (int k=0;k<span;k++)
        {
            wavelets[k]        = interArray[2*k];// + interArray[2*k + 1])/2.f;
            wavelets[k + span] = interArray[2*k + 1] - interArray[2*k];//)/2.f;
        }
        for (int k=0;k<givenSpan;k++)
            interArray[k] = wavelets[k];
        span /= 2;
    }
    //move float results to int16_t array
    float intScaling = 1.f;
    int max = 0;
    for (int i=0;i<givenSpan;i++)
    {
        float cValue = intScaling*wavelets[i];//
        if (cValue > 0)
            cValue += 0.5f;
        else
            cValue -= 0.5f;
        wavelets_in[i] = (int16_t)(cValue);
        if (fabs(cValue) >  32767.f)
        {
            cout << "Overflow ! " << cValue << endl;
        }
        if (fabs(cValue) > fabs(max))
            max = cValue;
    }
//    cout << "Max wave value: " << max << endl;
    //result reconstruction and checking
    if (!verifyResult)
        return true;

   for (int k=0;k<givenSpan;k++)
   {
       resultArray[k] = wavelets_in[k]/intScaling;
   }

   span = 1;
   while (span < givenSpan)
   {
       for (int k=0;k<givenSpan;k++)
           interArray[k] = resultArray[k];
      for (int k=0;k<span;k++)
       {
          resultArray[2*k]     = (float)(((interArray[k])*(1.f/1.f)) + 0.0f);
          resultArray[2*k + 1] = (float)(((interArray[k] + interArray[k + span])*(1.f/1.f)) + 0.0f);
       }
       span *= 2;
   }

   for (int k=0;k<givenSpan;k++)
   {
       float plus = 0.5f;
       if (resultArray[k] < 0)
           plus *= -1.f;
       if ((int)(resultArray[k]+plus) != (int)(orig_in[k]))
       {
           cout << "Nop, sorry: k: "  << k << " " << resultArray[k] << " " << (int)(resultArray[k]+plus) << " " << plus << " " << orig[k] << endl;
           return false;
       }
   }
   delete[] interArray;
   delete[] resultArray;
   delete[] orig;
   delete[] wavelets;
   return true;
}

void RawDataViewer::doWaveLetOnCurrentEventPlease()
{
     int16_t* origTheWayIWant = new int16_t[1024*1440];

//     int numPixels = 1024;
//         int leftOver = 1440-numPixels;
         for (int k=0;k<1024;k++)
             for (int j=0;j<1440;j++)
             {
                 origTheWayIWant[k*1440 + j] = rawEventData[j + k*1440];
             }

         int waveSpan = 1024;
         int waveToPixelsRatio = 32;
         waveSpan = waveSpan*waveToPixelsRatio;
         int totalNumSamples = 1024*1440;
         int j=0;
         for (;j<totalNumSamples;j+= waveSpan)
         {
             if (j + waveSpan < totalNumSamples)
             if (!doWaveLetsPlease(waveSpan, &origTheWayIWant[j], &waveLetArray[j], true))
                 return;
         }

         while (j%1440 != 0)
         {
             int lastRun = 1;
             while (lastRun < 1440 - j%1440)
                 lastRun *= 2;
             lastRun /= 2;
             if (lastRun > 2)
             {
                 doWaveLetsPlease(lastRun, &origTheWayIWant[j], &waveLetArray[j], true);
             }
             else
             {
                 for (int l=0;l<lastRun;l++)
                     waveLetArray[j+l] = origTheWayIWant[j+l];
             }
             if (!lastRun)
                 break;
             j += lastRun;
         }

     delete[] origTheWayIWant;

}
void RawDataViewer::doMyWaveletTestPlease()
{
//    cout << "Size of float: " << sizeof(float) << endl;
    return;
    ofstream outBin("/scratch/bin/outputBin.bin", ios_base::out | ios_base::binary);
    ofstream outWave("/scratch/bin/outputWave.bin", ios_base::out | ios_base::binary);
    int16_t* waveLetArray_ = new int16_t[1024*1440];
    int16_t* origTheWayIWant = new int16_t[1024*1440];

    for (int i=0;i<nRows;i++)
    {
        cout << '\r' <<  "Doing row " << i << " of " << nRows;
        cout.flush();
        inputFile->GetRow(i);
        outBin.write((const char*)(rawEventData), 1440*1024*2);

//       int numPixels = 1024;
//        int leftOver = 1440-numPixels;
        for (int k=0;k<1024;k++)
            for (int j=0;j<1440;j++)
            {
                origTheWayIWant[k*1440 + j] = rawEventData[j + k*1440];
            }

        int waveSpan = 1024;
        int waveToPixelsRatio = 32;
        waveSpan = waveSpan*waveToPixelsRatio;
        int totalNumSamples = 1024*1440;
        int j=0;
        for (;j<totalNumSamples;j+= waveSpan)//1440/waveToPixelsRatio;j++)
        {
            if (j + waveSpan < totalNumSamples)
            if (!doWaveLetsPlease(waveSpan, &origTheWayIWant[j], &waveLetArray_[j], true))
                return;
        }

        while (j%1440 != 0)// < totalNumSamples)
        {
            cout << "Copying the remaining of the data" << endl;
            int lastRun = 1;
            while (lastRun < 1440 - j%1440)//totalNumSamples-j)
                lastRun *= 2;
            lastRun /= 2;
            if (lastRun > 2)
            {
//                   cout << "   Doint one last run of " << lastRun << " samples" << endl;
                doWaveLetsPlease(lastRun, &origTheWayIWant[j], &waveLetArray_[j], true);
            }
            else
            {
//                    cout << " Filling in " << lastRun << " samples" << endl;
                for (int l=0;l<lastRun;l++)
                    waveLetArray_[j+l] = origTheWayIWant[j+l];
            }
            if (!lastRun)
                break;
            j += lastRun;
        }
       outWave.write((const char*)(waveLetArray_), 1440*1024*2);
    }
    outWave.close();
    outBin.close();
    inputFile->GetRow(0);

    delete[] waveLetArray_;
    delete[] origTheWayIWant;
}
void RawDataViewer::openCalibFile(string& file)
{
    calibrationLoaded = false;
    calibInputFile = new fits(file);
    if (!*calibInputFile)
    {
        delete calibInputFile;
        calibInputFile = NULL;
        return;
    }

    if (calibInputFile->HasKey("NROI"))
    {
        cout << "Looks like you're trying to load a regular raw data file as DRS calib. aborting." << endl;
        delete calibInputFile;
        calibInputFile = NULL;
        return;
    }

    if (!calibInputFile->SetPtrAddress("BaselineMean", baseLineMean)){
        cout << "Missing column " << "BaseLineMean" << " Aborting load..." << endl;
        return;}
    if (!calibInputFile->SetPtrAddress("GainMean", gainMean)){
        cout << "Missing column " << "GainMean" << " Aborting load..." << endl;
        return;}
    if (!calibInputFile->SetPtrAddress("TriggerOffsetMean", triggerOffsetMean)){
        cout << "Missing column " << "TriggerOffsetMean" << " Aborting load..." << endl;
        return;}

    calibInputFile->GetNextRow();

 //   for (int i=0;i<1024;i++)
 //       cout << gainMean[i] << " ";
 //   cout << endl << endl;

    delete calibInputFile;

    calibrationLoaded = true;

    emit newFileLoaded();
    if (drawCalibrationLoaded)
        updateGL();
}
/************************************************************
 * PLUS EVENT
 ************************************************************/
void RawDataViewer::plusEvent()
{
    eventStepping(true);
}
/************************************************************
 * MINUS EVENT
 ************************************************************/
void RawDataViewer::minusEvent()
{
    eventStepping(false);
}
/************************************************************
 * SET EVENT STEP
 ************************************************************/
void RawDataViewer::setEventStep(int step)
{
    eventStep = step;
}
/************************************************************
 * EVENT STEPPING
 ************************************************************/
void RawDataViewer::eventStepping(bool plus)
{
    if (plus)
        rowNum += eventStep;
    else
        rowNum -= eventStep;
    if (rowNum >= nRows)
        rowNum -= nRows;
    if (rowNum < 0)
        rowNum += nRows;
#ifdef LOAD_RAW
    eventNum+=eventStep;
#else
    if (inputFile == NULL)
        return;
    inputFile->GetRow(rowNum);
//    cout << "Getting row " << rowNum << endl;
    for (int i=0;i<(1440+160)*nRoi;i++)
        eventData[i] = (float)rawEventData[i];
#endif

    if (drawCalibrationLoaded && calibrationLoaded)
    {
        for (int i=0;i<1440;i++)
            for (int j=0;j<nRoi;j++)
            {
                int realj = (j+startPix[j])%1024;
                eventData[i*1024+j] *= 2000.f/4096.f;
                eventData[i*1024+j] -= (baseLineMean[i*1024+realj]+triggerOffsetMean[i*1024+j]);
                eventData[i*1024+j] /= gainMean[i*1024+realj];
                eventData[i*1024+j] *= (50000.f/65536.f) * 2500.f;
            }
    }
    updateGL();
    emit signalCurrentEvent(eventNum);
    emit signalCurrentPixel(selectedPixel);
}
/************************************************************
 * NEXT SLICE. deprec ?
 ************************************************************/
void RawDataViewer::nextSlice()
{
    whichSlice++;
    if (whichSlice >= nRoi)
    {
        whichSlice = 0;
        if (!loopCurrentEvent)
        {
            int backupStep = eventStep;
            eventStep = 1;
            eventStepping(true);
            eventStep = backupStep;
        }
    }
    emit signalCurrentSlice(whichSlice);
    updateGL();
}
void RawDataViewer::previousSlice()
{
    whichSlice--;
    if (whichSlice < 0)
    {
        whichSlice = nRoi-1;
        if (!loopCurrentEvent)
        {
            int backupStep = eventStep;
            eventStep = 1;
            eventStepping(false);
            eventStep = backupStep;
        }
    }
    emit signalCurrentSlice(whichSlice);
    updateGL();
}

void RawDataViewer::computePulsesStatistics()
{
    if (!inputFile)
    {
        cout << "A FITS file must be open in order to complete this operation" << endl;
        return;
    }


//    for (int i=0;i<nRows;i++)//for all events
//    {
//        inputFile->GetRow(rowNum);
//        for (int i=0;i<(1440+160)*nRoi;i++)
//            eventData[i] = (float)rawEventData[i];

//        for (int j=0;j<ACTUAL_NUM_PIXELS;j++)
///        {
    int j = selectedPixel;
            for (int i=0;i<nRoi;i++)
            {
                aMeas[i] = eventData[j*1024+i];// * adcCount;

            }
            for (int i=0;i<nRoi;i++)
            {
                if (i==0)
                    n1mean[i] = aMeas[i+1];
                else
                {
                    if (i==1023)
                        n1mean[i] = aMeas[i-1];
                    else
                        n1mean[i] = (aMeas[i-1]+aMeas[i+1])/2.f;
                }
            }
            //find spike
            for (int i=0;i<nRoi-3;i++)
            {
                const float fract = 0.8f;
                float xx, xp, xpp;
                vCorr[i] = 0;//aMeas[i];
                xx = aMeas[i] - n1mean[i];
                if (xx < -8.f)
                {
                    xp = aMeas[i+1] - n1mean[i+1];
                    xpp = aMeas[i+2] - n1mean[i+2];
                    if ((aMeas[i+2] - (aMeas[i] + aMeas[i+3])/2.f) > 10.f)
                    {
                        vCorr[i+1] = (aMeas[i] + aMeas[i+3])/2.f;
                        vCorr[i+2] = (aMeas[i] + aMeas[i+3])/2.f;
                        i = i+2;
                    }
                    else
                    {
                        if ((xp > -2.*xx*fract) && (xpp < -10.f))
                        {
                            vCorr[i+1] = n1mean[i+1];
                            n1mean[i+2] = aMeas[i+1] - aMeas[i+3]/2.f;
                            i++;
                        }
                    }
                }
            }
            for (int i=0;i<nRoi;i++)
                n1mean[i] = aMeas[i]-n1mean[i];
 //       }
 //   }
}
/************************************************************
 * UICONNECTOR CONSTRUCTOR
 ************************************************************/
UIConnector::UIConnector(QWidget*)
{
    updateSpinnerDisplay = true;

    timer.setInterval(10.0);
    QObject::connect(&timer, SIGNAL(timeout()),
                      this, SLOT(nextSlicePlease()));
    hwID = 393;
    swID = 0;
    crateID = 9;
    boardID = 8;
    patchID = 1;
    rescaleWholeCamera = true;
    currentFile = "none";
    currentCalibFile = "none";

}
void UIConnector::slicesPlusPlus()
{
    viewer->nextSlice();
}
void UIConnector::slicesMinusMinus()
{
    viewer->previousSlice();
}
void UIConnector::drawCalibratedDataChanged(int state)
{
     if (state)
    {
        if (viewer->calibrationLoaded)
        {
            viewer->drawCalibrationLoaded = true;
            for (int i=0;i<1440;i++)
                for (int j=0;j<viewer->nRoi;j++)
                {
                    int realj = (j+viewer->startPix[j])%1024;
                    viewer->eventData[i*1024+j] *= 2000.f/4096.f;
                    viewer->eventData[i*1024+j] -= (viewer->baseLineMean[i*1024+realj]+viewer->triggerOffsetMean[i*1024+j]);
                    viewer->eventData[i*1024+j] /= viewer->gainMean[i*1024+realj];
                    viewer->eventData[i*1024+j] *= (50000.f/65536.f) * 2500.f;
                }
            viewer->updateGL();
        }
        else
        {
            drawCalibrationCheckBox->setChecked(false);
        }
    }
    else
    {
        viewer->drawCalibrationLoaded = false;
        if (viewer->calibrationLoaded)
        {
            for (int i=0;i<1440;i++)
                for (int j=0;j<viewer->nRoi;j++)
                {
                    int realj = (j+viewer->startPix[j])%1024;
                    viewer->eventData[i*1024+j] /= (50000.f/65536.f) * 2500.f;
                    viewer->eventData[i*1024+j] *= viewer->gainMean[i*1024+realj];
                    viewer->eventData[i*1024+j] += (viewer->baseLineMean[i*1024+realj]+viewer->triggerOffsetMean[i*1024+j]);
                    viewer->eventData[i*1024+j] /= 2000.f/4096.f;
               }
            viewer->updateGL();
        }

    }
     autoScalePressed();

}
/************************************************************
 * DRAW PATCHES CHECK CHANGE. checkbox handler
 ************************************************************/
void UIConnector::drawPatchesCheckChange(int state)
{
    if (state)
        viewer->drawPatch = true;
    else
        viewer->drawPatch = false;
    viewer->updateGL();
}
/************************************************************
 * DRAW IMPULSE CHECK CHANGE. checkbox handler
 ************************************************************/
void UIConnector::drawImpulseCheckChange(int state)
{
    if (state)
        viewer->drawImpulse = true;
    else
        viewer->drawImpulse = false;
    viewer->updateGL();
}
/************************************************************
 * DRAW BLUR CHECK CHANGE. checkbox handler
 ************************************************************/
void UIConnector::drawBlurCheckChange(int state)
{
    if (state)
        viewer->drawBlur = true;
    else
        viewer->drawBlur = false;
    viewer->updateGL();
}
void UIConnector::loopEventCheckChange(int state)
{
    if (state)
        viewer->loopCurrentEvent = true;
    else
        viewer->loopCurrentEvent = false;
}
/************************************************************
 * NEXT SLICE PLEASE
 ************************************************************/
void UIConnector::nextSlicePlease()
{
    if (playEventsRadio->isChecked ())
        viewer->eventStepping(true);
    else
        viewer->nextSlice();
}
/************************************************************
 * SET VIEWER.
 ************************************************************/
void UIConnector::setViewer(RawDataViewer* v)
{
    viewer = v;
}
/************************************************************
 * SLICES PER SECOND CHANGED. timing ui handler
 ************************************************************/
void UIConnector::slicesPerSecondChanged(double value)
{
    timer.setInterval(1000.0/value);
}
/************************************************************
 * RANGE CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::rangeChanged0(double value)
{
    viewer->ss[0] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * RANGE CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::rangeChanged1(double value)
{
    viewer->ss[1] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * RANGE CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::rangeChanged2(double value)
{
    viewer->ss[2] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * RANGE CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::rangeChanged3(double value)
{
    viewer->ss[3] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * RANGE CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::rangeChanged4(double value)
{
    viewer->ss[4] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * RANGE CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::redChanged0(double value)
{
    viewer->rr[0] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * RED CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::redChanged1(double value)
{
    viewer->rr[1] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * RED CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::redChanged2(double value)
{
    viewer->rr[2] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * RED CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::redChanged3(double value)
{
    viewer->rr[3] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * RED CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::redChanged4(double value)
{
    viewer->rr[4] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * GREEN CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::greenChanged0(double value)
{
    viewer->gg[0] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * GREEN CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::greenChanged1(double value)
{
    viewer->gg[1] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * GREEN CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::greenChanged2(double value)
{
    viewer->gg[2] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * GREEN CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::greenChanged3(double value)
{
    viewer->gg[3] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * GREEN CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::greenChanged4(double value)
{
    viewer->gg[4] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * BLUE CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::blueChanged0(double value)
{
    viewer->bb[0] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * BLUE CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::blueChanged1(double value)
{
    viewer->bb[1] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * BLUE CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::blueChanged2(double value)
{
    viewer->bb[2] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * BLUE CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::blueChanged3(double value)
{
    viewer->bb[3] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * BLUE CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::blueChanged4(double value)
{
    viewer->bb[4] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * LOAD NEW FILE CLICKED. button handler
 ************************************************************/
void UIConnector::loadNewFileClicked()
{
    QFileDialog dialog;
    dialog.setFileMode(QFileDialog::ExistingFile);
    dialog.open(this, SLOT(fileSelected(QString)));
    dialog.setVisible(true);
    dialog.exec();
}
void UIConnector::loadNewCalibFileClicked()
{
    QFileDialog dialog;
    dialog.setFileMode(QFileDialog::ExistingFile);
    dialog.open(this, SLOT(calibFileSelected(QString)));
    dialog.setVisible(true);
    dialog.exec();
}
/************************************************************
 * FILE SELECTED. return of the file open dialog handler
 ************************************************************/
void UIConnector::fileSelected(QString file)
{
    currentFile = file.toStdString();
    if (currentFile != "")
        viewer->openFile(currentFile);
}
void UIConnector::calibFileSelected(QString file)
{
    currentCalibFile = file.toStdString();
    if (currentCalibFile != "")
        viewer->openCalibFile(currentCalibFile);
}
/************************************************************
 * NEW FILE LOADED. update of the UI after a new file has been loaded
 ************************************************************/
void UIConnector::newFileLoaded()
{
    ostringstream str;

    //extract the file name only (no path) from the full name
    str << "File: " << currentFile.substr(currentFile.find_last_of("//")+1, currentFile.size()) << "\n";
    str << "Calibration: " << currentCalibFile.substr(currentCalibFile.find_last_of("//")+1, currentCalibFile.size()) << "\n";
//    fileLoadedLabel->setText(QString(str.str().c_str()));
//    str.str("");
    str << "Run number: " << viewer->runNumber << "\n";
//    runNumberLabel->setText(QString(str.str().c_str()));
//    str.str("");
    str << "Number of Events: " << viewer->nRows << "\n";

    eventNumberBox->setMaximum(viewer->nRows-1);

    str << "Number of Slices: " << viewer->nRoi << "\n";// << "/1024";
//    numberOfSlicesLabel->setText(QString(str.str().c_str()));
//    str.str("");
    str << "Number of Time Marks: " << viewer->nTM << "\n";
//    numberOfTimeMarksLabel->setText(QString(str.str().c_str()));

//    str.str("");
    str << "Run Type: " << viewer->runType << "\n";
//    runTypeLabel->setText(QString(str.str().c_str()));
//    str.str("");
    str << "Time of 1st data: " << viewer->firstDataTime << "\n";
//    firstTimeLabel->setText(QString(str.str().c_str()));
//    str.str("");
    str << "Time of last data: " << viewer->lastDataTime << "\n";
//    lastTimeLabel->setText(QString(str.str().c_str()));
//    str.str("");
    str << "SVN revision: " << viewer->revision << '\n';
    str << "Number of boards: " << viewer->nBoards << '\n';
    str << "Number of pixels: " << viewer->nPixels << '\n';
    str << "Number of Slices TM: " << viewer->nRoiTM << '\n';
    str << "Time system: " << viewer->timeSystem << '\n';
    str << "Date: " << viewer->creationDate << '\n';
    str << "Night: " << viewer->nightInt << '\n';
    str << "Camera: " << viewer->camera << '\n';
    str << "DAQ: " << viewer->daq << '\n';
    str << "ADC Count: " << viewer->adcCount << '\n';
    str << "NB Evts OK:" << viewer->nbOk << '\n';
    str << "NB Evts Rejected: " << viewer->nbRej << '\n';
    str << "NB Evts Bad: " << viewer->nbBad << '\n';
    extraInfoLabel->setText(QString(str.str().c_str()));

    if (viewer->calibrationLoaded)
    {
        drawCalibrationCheckBox->setEnabled(true);
    }


}
/************************************************************
 * PLAY PAUSE CLICKED. ui handler
 ************************************************************/
void UIConnector::playPauseClicked()
{
    if (timer.isActive())
        timer.stop();
    else
        timer.start();
}
/************************************************************
 * CURRENT SLICE HAS CHANGE. ui handler
 ************************************************************/
void UIConnector::currentSliceHasChanged(int slice)
{
    if (!viewer->nRoi)
        return;
    ostringstream str;
//    str << "Displaying Slice " << slice;
//    QString qstr(str.str().c_str());
    if (updateSpinnerDisplay)
        emit updateCurrentSliceDisplay(slice);

    str.str("");
    str << "Current Pixel val.: " << viewer->eventData[viewer->nRoi*viewer->selectedPixel + viewer->whichSlice];
    QString qstr = qstr.fromStdString(str.str());
    emit updateCurrentPixelSliceValue(qstr);

}
/************************************************************
 * CURRENT EVENT HAS CHANGED. ui handler
 ************************************************************/
double xval[50000];
double yval[50000];
void UIConnector::eventChangedFromSpinner(int cEvent)
{
//    cout << "Here " << updateSpinnerDisplay << endl;
    if (!updateSpinnerDisplay)
        return;
    updateSpinnerDisplay = false;
//    currentEventHasChanged(cEvent);
    viewer->rowNum = cEvent - viewer->eventStep;
    viewer->eventStepping(true);
    updateSpinnerDisplay = true;

//    viewer->updateGL();
}
void UIConnector::sliceChangedFromSpinner(int cSlice)
{
    updateSpinnerDisplay = false;
    currentSliceHasChanged(cSlice);
    updateSpinnerDisplay = true;
    viewer->whichSlice = cSlice;
    viewer->updateGL();
}
void UIConnector::currentEventHasChanged(int )
{
    ostringstream str;
//    str << "Displaying Event " << cEvent;
//    QString qstr(str.str().c_str());
//    emit updateCurrentEventDisplay(qstr);
    if (updateSpinnerDisplay)
    {
        updateSpinnerDisplay = false;
        emit updateCurrentEventDisplay(viewer->rowNum);
        updateSpinnerDisplay = true;
    }

 //   viewer->doWaveLetOnCurrentEventPlease();

        //retrieve the data that we want to display
    str.str("");
    str << "PC Time: " << viewer->pcTime;
    QString qstr = qstr.fromStdString(str.str());
    emit updateCurrentPCTime(qstr);

    str.str("");
    str << "Software Trigger: " << viewer->softTrig;
    qstr = qstr.fromStdString(str.str());
    emit updateCurrentSoftTrigger(qstr);

    str.str("");
    str << "Trigger Type: " << viewer->triggerType;
    qstr = qstr.fromStdString(str.str());
    emit updateCurrentTriggerType(qstr);

    str.str("");
    str << "Current Pixel val.: " << viewer->eventData[viewer->nRoi*viewer->selectedPixel + viewer->whichSlice];
    qstr = qstr.fromStdString(str.str());
    emit updateCurrentPixelSliceValue(qstr);

    if (autoScaleColor->isChecked())
        emit viewer->colorPaletteHasChanged();//autoScalePressed();

    boardsTimeList->clear();
    startPixelsList->clear();
    startTimeMarksList->clear();
    triggerDelayList->clear();
    std::map<int, int> boardsHistoMap;
    for (int i=0;i <NBOARDS; i++)
    {
        str.str("");
        str << i;
        if (i<10) str << " ";
        if (i<100) str << " ";
        if (i<1000) str << " ";
        str << ": " << viewer->boardTime[i];
        boardsTimeList->addItem(QString(str.str().c_str()));
        if (boardsHistoMap.find(viewer->boardTime[i]) != boardsHistoMap.end())
            boardsHistoMap[viewer->boardTime[i]]++;
        else
            boardsHistoMap[viewer->boardTime[i]] = 1;
    }
    std::map<int, int> pixelHistoMap;
    for (int i=0;i <NPIX; i++)
    {
        str.str("");
        str << i;
        if (i<10) str << " ";
        if (i<100) str << " ";
        if (i<1000) str << " ";
        str << ": " << viewer->startPix[i];
        startPixelsList->addItem(QString(str.str().c_str()));
        if (pixelHistoMap.find(viewer->startPix[i]) != pixelHistoMap.end())
            pixelHistoMap[viewer->startPix[i]]++;
        else
            pixelHistoMap[viewer->startPix[i]] = 1;
    }

    std::map<int, int> timeMarksMap;
    for (int i=0;i <NTMARK; i++)
    {
        str.str("");
        str << i;
        if (i<10) str << " ";
        if (i<100) str << " ";
        if (i<1000) str << " ";
        str << ": " << viewer->startTM[i];
        startTimeMarksList->addItem(QString(str.str().c_str()));
        if (timeMarksMap.find(viewer->startTM[i]) != timeMarksMap.end())
            timeMarksMap[viewer->startTM[i]]++;
        else
            timeMarksMap[viewer->startTM[i]] = 1;
    }
    std::map<int,int> delayMap;
    triggerDelayList->addItem(QString("Patch | Slice:Delay Slice:Delay..."));
    for (int i=0;i<NTMARK; i++)
    {
        str.str("");
        str << i << " | ";
        for (int j=0;j<viewer->nRoi;j++)
        {
            int value = viewer->eventData[1440*viewer->nRoi + i*viewer->nRoi + j];
            if (delayMap.find(value) != delayMap.end())
                 delayMap[value]++;
             else
                 delayMap[value] = 1;
            str << j << ":" << value << " ";
         }
        triggerDelayList->addItem(QString(str.str().c_str()));
    }

    std::map<int,int>::iterator it = boardsHistoMap.begin();
    int nsamples = 0;
    int previousValue = it->first-10;
    for (unsigned int i=0;i<boardsHistoMap.size();i++)
    {
        if (previousValue != it->first-1)
        {
            xval[nsamples] = previousValue+1;
            yval[nsamples] = 0;
            nsamples++;
            xval[nsamples] = it->first-1;
            yval[nsamples] = 0;
            nsamples++;
        }
        xval[nsamples] = it->first;
        yval[nsamples] = it->second;
        previousValue = it->first;
        it++;
        nsamples++;
        xval[nsamples] = previousValue;
        yval[nsamples] = 0;
        nsamples++;
        if (nsamples > 4090)
        {
            cout << "Error: Maximum number of samples reached for histograms. skipping what's remaining" << endl;
            break;
        }
    }
    xval[nsamples] = it==boardsHistoMap.begin() ? 0 : (--it)->first+1;
    yval[nsamples] = 0;
    nsamples++;
 //   if (nsamples > 5)
#if QWT_VERSION < 0x060000
       boardsTimeHistoItem.setData(xval, yval, nsamples);
#else
       boardsTimeHistoItem.setSamples(xval, yval, nsamples);
#endif

    it = pixelHistoMap.begin();
    nsamples = 0;
    previousValue = it->first-10;
    for (unsigned int i=0;i<pixelHistoMap.size();i++)
    {
        if (previousValue != it->first-1)
        {
            xval[nsamples] = previousValue+1;
            yval[nsamples] = 0;
            nsamples++;
            xval[nsamples] = it->first-1;
            yval[nsamples] = 0;
            nsamples++;
        }
        xval[nsamples] = it->first;
        yval[nsamples] = it->second;
        previousValue = it->first;
        it++;
        nsamples++;
        xval[nsamples] = previousValue;
        yval[nsamples] = 0;
        nsamples++;
        if (nsamples > 4090)
        {
            cout << "Error: Maximum number of samples reached for histograms. skipping what's remaining" << endl;
            break;
        }
   }
    xval[nsamples] = it==pixelHistoMap.begin() ? 0 : (--it)->first+1;
    yval[nsamples] = 0;
    nsamples++;
//    if (nsamples > 5)
#if QWT_VERSION < 0x060000
       startCellHistoItem.setData(xval, yval, nsamples);
#else
       startCellHistoItem.setSamples(xval, yval, nsamples);
#endif

    it = timeMarksMap.begin();
    nsamples = 0;
    previousValue = it->first-10;
    for (unsigned int i=0;i<timeMarksMap.size();i++)
    {
        if (previousValue != it->first-1)
        {
            xval[nsamples] = previousValue+1;
            yval[nsamples] = 0;
            nsamples++;
            xval[nsamples] = it->first-1;
            yval[nsamples] = 0;
            nsamples++;
        }
        xval[nsamples] = it->first;
        yval[nsamples] = it->second;
        previousValue = it->first;
        it++;
        nsamples++;
        xval[nsamples] = previousValue;
        yval[nsamples] = 0;
        nsamples++;
        if (nsamples > 4090)
        {
            cout << "Error: Maximum number of samples reached for histograms. skipping what's remaining" << endl;
            break;
        }
    }
    xval[nsamples] = it==timeMarksMap.begin() ? 0 : (--it)->first+1;
    yval[nsamples] = 0;
    nsamples++;
 //   if (nsamples > 5)
#if QWT_VERSION < 0x060000
       startTimeMarkHistoItem.setData(xval, yval, nsamples);
#else
       startTimeMarkHistoItem.setSamples(xval, yval, nsamples);
#endif

    it = delayMap.begin();
    nsamples = 0;
    previousValue = it->first-10;
    for (unsigned int i=0;i<delayMap.size();i++)
    {
        if (previousValue != it->first-1)
        {
            xval[nsamples] = previousValue+1;
            yval[nsamples] = 0;
            nsamples++;
            xval[nsamples] = it->first-1;
            yval[nsamples] = 0;
            nsamples++;
        }
        xval[nsamples] = it->first;
        yval[nsamples] = it->second;
        previousValue = it->first;
        it++;
        nsamples++;
        xval[nsamples] = previousValue;
        yval[nsamples] = 0;
        nsamples++;
        if (nsamples > 4090)
        {
            cout << "Error: Maximum number of samples reached for histograms. skipping what's remaining" << endl;
            break;
        }
    }
    xval[nsamples] = it==delayMap.begin() ? 0 : (--it)->first+1;
    yval[nsamples] = 0;
    nsamples++;
  //  if (nsamples > 5)
#if QWT_VERSION < 0x060000
       triggerDelayHistoItem.setData(xval, yval, nsamples);
#else
       triggerDelayHistoItem.setSamples(xval, yval, nsamples);
#endif
       //WAVELETS HACK
/*       std::map<int, int> valuesHistoMap;
       std::map<int, int> waveletHistoMap;
       for (int i=0;i<1024*1440;i++)
       {
           if (valuesHistoMap.find(viewer->rawEventData[i]) != valuesHistoMap.end())
               valuesHistoMap[viewer->rawEventData[i]]++;
           else
               valuesHistoMap[viewer->rawEventData[i]] = 1;
           if (waveletHistoMap.find(viewer->waveLetArray[i]) != waveletHistoMap.end())
               waveletHistoMap[viewer->waveLetArray[i]]++;
           else
               waveletHistoMap[viewer->waveLetArray[i]] = 1;
       }

       it = valuesHistoMap.begin();
       nsamples = 0;
       previousValue = it->first-10;
       cout << "Num values Original: " << valuesHistoMap.size() << endl;
       for (unsigned int i=0;i<valuesHistoMap.size();i++)
       {
           if (previousValue != it->first-1)
           {
               xval[nsamples] = previousValue+1;
               yval[nsamples] = 0;
               nsamples++;
               xval[nsamples] = it->first-1;
               yval[nsamples] = 0;
               nsamples++;
           }
           xval[nsamples] = it->first;
           yval[nsamples] = it->second;
           previousValue = it->first;
           it++;
           nsamples++;
           xval[nsamples] = previousValue;
           yval[nsamples] = 0;
           nsamples++;
           if (nsamples > 50000)
           {
               cout << "Error: Maximum number of samples reached for histograms. skipping what's remaining" << endl;
               break;
           }
       }
       xval[nsamples] = it==valuesHistoMap.begin() ? 0 : (--it)->first+1;
       yval[nsamples] = 0;
       nsamples++;
     //  if (nsamples > 5)
   #if QWT_VERSION < 0x060000
          triggerDelayHistoItem.setData(xval, yval, nsamples);
   #else
          triggerDelayHistoItem.setSamples(xval, yval, nsamples);
   #endif

          it = waveletHistoMap.begin();
          nsamples = 0;
          previousValue = it->first-10;
          cout << "Num values WaveLets: " << waveletHistoMap.size() << endl;
          for (unsigned int i=0;i<waveletHistoMap.size();i++)
          {
              if (previousValue != it->first-1)
              {
                  xval[nsamples] = previousValue+1;
                  yval[nsamples] = 0;
                  nsamples++;
                  xval[nsamples] = it->first-1;
                  yval[nsamples] = 0;
                  nsamples++;
              }
              xval[nsamples] = it->first;
              yval[nsamples] = it->second;
              previousValue = it->first;
              it++;
              nsamples++;
              xval[nsamples] = previousValue;
              yval[nsamples] = 0;
              nsamples++;
              if (nsamples > 50000)
              {
                  cout << "Error: Maximum number of samples reached for histograms. skipping what's remaining" << endl;
                  break;
              }
          }
          xval[nsamples] = it==waveletHistoMap.begin() ? 0 : (--it)->first+1;
          yval[nsamples] = 0;
          nsamples++;
        //  if (nsamples > 5)
      #if QWT_VERSION < 0x060000
          startTimeMarkHistoItem.setData(xval, yval, nsamples);
      #else
          startTimeMarkHistoItem.setSamples(xval, yval, nsamples);
      #endif
*/
//END OF WAVELETS HACK
       //    startCellHistoZoom->setZoomBase(startCellHistoItem.boundingRect());
    QStack< QRectF > stack;
//    QRectF cRectangle = boardsTimeHistoItem.boundingRect();
    stack.push(scaleBoundingRectangle(boardsTimeHistoItem.boundingRect(), 1.05f));//cRectangle);//boardsTimeHistoItem.boundingRect());
    boardsTimeHistoZoom->setZoomStack(stack);
    stack.pop();
    stack.push(scaleBoundingRectangle(startCellHistoItem.boundingRect(), 1.05f));
    startCellHistoZoom->setZoomStack(stack);
    stack.pop();
    stack.push(scaleBoundingRectangle(startTimeMarkHistoItem.boundingRect(), 1.05f));
    startTimeMarkHistoZoom->setZoomStack(stack);
    stack.pop();
    stack.push(scaleBoundingRectangle(triggerDelayHistoItem.boundingRect(), 1.05f));
    triggerDelayHistoZoom->setZoomStack(stack);
    stack.pop();
    pixelChanged(viewer->selectedPixel);
}
//can't use a ref to rectangle, as the type must be converted first
QRectF UIConnector::scaleBoundingRectangle(QRectF rectangle, float scale)
{
    QPointF bottomRight = rectangle.bottomRight();
    QPointF topLeft = rectangle.topLeft();
    QPointF center = rectangle.center();
    return QRectF(topLeft + (topLeft-center)*(scale-1.0f), //top left
                  bottomRight + (bottomRight-center)*(scale-1.0f)); //bottom right
}
void UIConnector::initHistograms()
{
//    QwtPlot*     boardsTimeHisto;
//    QwtPlotHistogram boardsTimeHistoItem;
    QwtPlotGrid* grid = new QwtPlotGrid;
    grid->enableX(false);
    grid->enableY(true);
    grid->enableXMin(false);
    grid->enableYMin(false);
    grid->setMajPen(QPen(Qt::black, 0, Qt::DotLine));
    grid->attach(boardsTimeHisto);

    grid = new QwtPlotGrid;
    grid->enableX(false);
    grid->enableY(true);
    grid->enableXMin(false);
    grid->enableYMin(false);
    grid->setMajPen(QPen(Qt::black, 0, Qt::DotLine));
    grid->attach(startCellHisto);

    grid = new QwtPlotGrid;
    grid->enableX(false);
    grid->enableY(true);
    grid->enableXMin(false);
    grid->enableYMin(false);
    grid->setMajPen(QPen(Qt::black, 0, Qt::DotLine));
    grid->attach(startTimeMarkHisto);

    grid = new QwtPlotGrid;
    grid->enableX(false);
    grid->enableY(true);
    grid->enableXMin(false);
    grid->enableYMin(false);
    grid->setMajPen(QPen(Qt::black, 0, Qt::DotLine));
    grid->attach(pixelValueCurve);

    grid = new QwtPlotGrid;
    grid->enableX(false);
    grid->enableY(true);
    grid->enableXMin(false);
    grid->enableYMin(false);
    grid->setMajPen(QPen(Qt::black, 0, Qt::DotLine));
    grid->attach(triggerDelayHisto);


    boardsTimeHisto->setAutoReplot(true);
    startCellHisto->setAutoReplot(true);
    startTimeMarkHisto->setAutoReplot(true);
    pixelValueCurve->setAutoReplot(true);
    triggerDelayHisto->setAutoReplot(true);
    boardsTimeHisto->setTitle("Boards time values");
    startCellHisto->setTitle("Start Cell values");
    startTimeMarkHisto->setTitle("Start Time Marks values");
    pixelValueCurve->setTitle("Current pixel values");
    triggerDelayHisto->setTitle("Trigger Delays");

 //   boardsTimeHistoItem.setBrush(QBrush(Qt::red));
//    startCellHistoItem.setBrush(QBrush(Qt::red));
//    startTimeMarkHistoItem.setBrush(QBrush(Qt::red));
//    triggerDelayHistoItem.setBrush(QBrush(Qt::red));
//    pixelValueCurveItem.setBrush(QBrush(Qt::red));

    boardsTimeHistoItem.setPen(QColor(Qt::darkGreen));
    boardsTimeHistoItem.setStyle(QwtPlotCurve::Steps);
    startCellHistoItem.setPen(QColor(Qt::darkGreen));
    startCellHistoItem.setStyle(QwtPlotCurve::Steps);
    startTimeMarkHistoItem.setPen(QColor(Qt::darkGreen));
    startTimeMarkHistoItem.setStyle(QwtPlotCurve::Steps);
    triggerDelayHistoItem.setPen(QColor(Qt::darkGreen));
    triggerDelayHistoItem.setStyle(QwtPlotCurve::Steps);

    boardsTimeHistoItem.attach(boardsTimeHisto);
    startCellHistoItem.attach(startCellHisto);
    startTimeMarkHistoItem.attach(startTimeMarkHisto);
    triggerDelayHistoItem.attach(triggerDelayHisto);

    //curve
//    pixelValueCurveItem.setSymbol(new QwtSymbol(QwtSymbol::Cross, Qt::NoBrush, QPen(Qt::black), QSize(5,5)));
    pixelValueCurveItem.setPen(QColor(Qt::black));
    aMeanCurveItem.setPen(QColor(Qt::darkGreen));
    vCorrCurveItem.setPen(QColor(Qt::red));
    meanCurveItem.setPen(QColor(Qt::blue));
    pixelValueCurveItem.setStyle(QwtPlotCurve::Lines);
    aMeanCurveItem.setStyle(QwtPlotCurve::Lines);
    vCorrCurveItem.setStyle(QwtPlotCurve::Lines);
    meanCurveItem.setStyle(QwtPlotCurve::Lines);

//    pixelValueCurveItem.setCurveAttribute(QwtPlotCurve::Fitted);
    pixelValueCurveItem.attach(pixelValueCurve);
//    aMeanCurveItem.attach(pixelValueCurve);
 //   vCorrCurveItem.attach(pixelValueCurve);
//    meanCurveItem.attach(pixelValueCurve);

    //FIXME delete these pointers with the destructor
    curveZoom = new QwtPlotZoomer(pixelValueCurve->canvas());
    curveZoom->setRubberBandPen(QPen(Qt::gray, 2, Qt::DotLine));
    curveZoom->setTrackerPen(QPen(Qt::gray));
    boardsTimeHistoZoom = new QwtPlotZoomer(boardsTimeHisto->canvas());
    boardsTimeHistoZoom->setRubberBandPen(QPen(Qt::gray, 2, Qt::DotLine));
    boardsTimeHistoZoom->setTrackerPen(QPen(Qt::gray));
    startCellHistoZoom = new QwtPlotZoomer(startCellHisto->canvas());
    startCellHistoZoom->setRubberBandPen(QPen(Qt::gray, 2, Qt::DotLine));
    startCellHistoZoom->setTrackerPen(QPen(Qt::gray));
    startTimeMarkHistoZoom = new QwtPlotZoomer(startTimeMarkHisto->canvas());
    startTimeMarkHistoZoom->setRubberBandPen(QPen(Qt::gray, 2, Qt::DotLine));
    startTimeMarkHistoZoom->setTrackerPen(QPen(Qt::gray));
    triggerDelayHistoZoom = new QwtPlotZoomer(triggerDelayHisto->canvas());
    triggerDelayHistoZoom->setRubberBandPen(QPen(Qt::gray, 2, Qt::DotLine));
    triggerDelayHistoZoom->setTrackerPen(QPen(Qt::gray));


}
void UIConnector::pixelChanged(int pixel)
{
    if (!viewer->nRoi)
        return;

    if (hwID == pixel)
        return;
    for (int i=0;i<viewer->nRoi;i++)
    {
        xval[i] = i;
#ifdef LOAD_RAW
        yval[i] = eventsData[0][pixel][i];
#else
        yval[i] = viewer->eventData[viewer->nRoi*pixel + i];
#endif
    }

  //  viewer->computePulsesStatistics();
#if QWT_VERSION < 0x060000
    pixelValueCurveItem.setData(xval, yval, viewer->nRoi);
////    aMeanCurveItem.setData(xval, viewer->aMeas, viewer->nRoi);
 //   meanCurveItem.setData(xval, viewer->n1mean, viewer->nRoi);
 //   vCorrCurveItem.setData(xval, viewer->vCorr, viewer->nRoi-3);
#else
       pixelValueCurveItem.setSamples(xval, yval, viewer->nRoi);
//       aMeanCurveItem.setSamples(xval, viewer->aMeas, viewer->nRoi);
 //      meanCurveItem.setSamples(xval, viewer->n1mean, viewer->nRoi);
 //      vCorrCurveItem.setSamples(xval, viewer->vCorr, viewer->nRoi-3);
#endif


    QStack< QRectF > stack;
    stack.push(scaleBoundingRectangle(pixelValueCurveItem.boundingRect(), 1.5f));
    curveZoom->setZoomStack(stack);
    stack.pop();

    hwID = pixel;
    swID = viewer->softwareMapping[pixel];
    crateID = pixel/360;
    boardID = (pixel - crateID*360)/36;
    patchID = (pixel - crateID*360 - boardID*36)/9;

    if (HwIDBox->value() != hwID)
        HwIDBox->setValue(hwID);
    if (SwIDBox->value() != swID)
        SwIDBox->setValue(swID);
    if (crateIDBox->value() != crateID)
        crateIDBox->setValue(crateID);
    if (boardIDBox->value() != boardID)
        boardIDBox->setValue(boardID);
    if (patchIDBox->value() != patchID)
        patchIDBox->setValue(patchID);

    ostringstream str;
    QString qstr;
    str.str("");
    str << "Current Pixel val.: " << viewer->eventData[viewer->nRoi*viewer->selectedPixel + viewer->whichSlice];
    qstr = qstr.fromStdString(str.str());
    emit updateCurrentPixelSliceValue(qstr);
    autoScalePressed();

}

void UIConnector::hwIDChanged(int hwid)
{
    hwID = hwid;
    swID = viewer->softwareMapping[hwid];
    crateID = hwID/360;
    boardID = (hwID - crateID*360)/36;
    patchID = (hwID - crateID*360 - boardID*36)/9;

//    crateID = (hwid/4)/10;
//    boardID = (hwid/4)%10;
//    patchID = hwid%4;
    HwIDBox->setValue(hwID);
    SwIDBox->setValue(swID);
    crateIDBox->setValue(crateID);
    boardIDBox->setValue(boardID);
    patchIDBox->setValue(patchID);

    viewer->selectedPixel = hwid;
    pixelChanged(hwid);
    viewer->updateGL();

}
void UIConnector::swIDChanged(int swid)
{
    swID = swid;
    hwID = viewer->hardwareMapping[swid];
    crateID = hwID/360;
    boardID = (hwID - crateID*360)/36;
    patchID = (hwID - crateID*360 - boardID*36)/9;

//    crateID = (hwID/4)/10;
//    boardID = (hwID/4)%10;
//    patchID = hwID%4;
    HwIDBox->setValue(hwID);
    SwIDBox->setValue(swID);
    crateIDBox->setValue(crateID);
    boardIDBox->setValue(boardID);
    patchIDBox->setValue(patchID);

    viewer->selectedPixel = hwID;
    pixelChanged(hwID);
    viewer->updateGL();
}
void UIConnector::crateIDChanged(int cid)
{
    hwID -= 360*crateID;
    crateID = cid;
    hwID += 360*crateID;
    swID = viewer->softwareMapping[hwID];
    HwIDBox->setValue(hwID);
    SwIDBox->setValue(swID);
    viewer->selectedPixel = hwID;
    pixelChanged(hwID);
    viewer->updateGL();
}
void UIConnector::boardIDChanged(int bid)
{
    hwID -= 36*boardID;
    boardID = bid;
    hwID += 36*boardID;
    swID = viewer->softwareMapping[hwID];
    HwIDBox->setValue(hwID);
    SwIDBox->setValue(swID);
    viewer->selectedPixel = hwID;
    pixelChanged(hwID);
   viewer->updateGL();
}
void UIConnector::patchIDChanged(int pid)
{
    hwID -= 9*patchID;
    patchID = pid;
    hwID += 9*patchID;
    swID = viewer->softwareMapping[hwID];
    HwIDBox->setValue(hwID);
    SwIDBox->setValue(swID);
    viewer->selectedPixel = hwID;
    pixelChanged(hwID);
    viewer->updateGL();
}
void UIConnector::autoScalePressed()
{
    if (!autoScaleColor->isChecked())
    {
        viewer->ss[0] = 0;
        viewer->ss[1] = 0.25;
        viewer->ss[2] = 0.5;
        viewer->ss[3] = 0.75;
        viewer->ss[4] = 1;
        range0->setValue(viewer->ss[0]);
        range1->setValue(viewer->ss[1]);
        range2->setValue(viewer->ss[2]);
        range3->setValue(viewer->ss[3]);
        range4->setValue(viewer->ss[4]);
        return;
    }
    if (!viewer->nRoi)
        return;
    int start, end;
    if (rescaleWholeCamera)
    {
        start = 0;
        end = 1440;
    }
    else
    {
        start = viewer->selectedPixel;
        end = viewer->selectedPixel+1;
    }

    int min = 100000; //real min = -2048, int_16 = -32768 to 32767
    int max = -100000; //real max = 2047
    long average = 0;
    long numSamples = 0;
    int errorDetected = -1;
    for (int i=start;i<end;i++)
    {
        for (int j=0;j<viewer->nRoi;j++)
        {
            int cValue = viewer->eventData[i*viewer->nRoi+j];
            if (cValue > max && cValue < 32767)
                max = cValue;
            if (cValue < min && cValue > -32768)
               min = cValue;
            if (cValue < 32767 && cValue > -32768)
            {
                average+=cValue;
                numSamples++;
            }
            else
            {
                errorDetected = i;
            }
//            numSamples++;
        }
    }
    average /= numSamples;
    if (errorDetected != -1)
    {
        cout << "Overflow detected at pixel " << errorDetected << " (at least)" << endl;
    }
//    cout << "min: " << min << " max: " << max << " average: " << average << endl;
    double minRange = (double)(min+(VALUES_SPAN/2))/(double)VALUES_SPAN;
    double maxRange = (double)(max+(VALUES_SPAN/2))/(double)VALUES_SPAN;
    double midRange = (double)(average+(VALUES_SPAN/2))/(double)VALUES_SPAN;
    if (viewer->logScale)
    {
        minRange *= 9;
        maxRange *= 9;
//        midRange *= 9;
        minRange += 1;
        maxRange += 1;
//        midRange += 1;
        minRange = log10(minRange);
        maxRange = log10(maxRange);
//        midRange = (minRange + maxRange)/2.f;
        midRange = log10(midRange);
    }
    viewer->ss[0] = minRange;
    range0->setValue(viewer->ss[0]);
    viewer->ss[4] = maxRange;
    range4->setValue(viewer->ss[4]);
    viewer->ss[2] = midRange;
    range2->setValue(viewer->ss[2]);
    viewer->ss[1] = (minRange+midRange)/2;
    range1->setValue(viewer->ss[1]);
    viewer->ss[3] = (maxRange+midRange)/2;
    range3->setValue(viewer->ss[3]);


}
void UIConnector::entireCameraChanged(bool state)
{
    if (state)
    {
        rescaleWholeCamera = true;
        currentPixelScale->setChecked(false);
    }
    else
    {
        rescaleWholeCamera = false;
        currentPixelScale->setChecked(true);
    }
    autoScalePressed();
}
void UIConnector::currentPixelChanged(bool state)
{

    if (state)
    {
        rescaleWholeCamera = false;
        entireCameraScale->setChecked(false);
    }
    else
    {
        rescaleWholeCamera = true;
        entireCameraScale->setChecked(true);
    }
    autoScalePressed();
}



void PrintHelp()
{
    cout <<
            "\n"
         << endl;
}
void SetupConfiguration(Configuration& conf)
{
    po::options_description configs("Raw Events Viewer Options");
    configs.add_options()
        ("color.range", vars<double>(), "Range of the display colours")
        ("color.red", vars<double>(), "Range of red values")
        ("color.green", vars<double>(), "Range of green values")
        ("color.blue", vars<double>(), "Range of blue values")
        ("file,f", var<string>(), "File to be loaded at startup")
        ;
    conf.AddOptions(configs);

    po::positional_options_description p;
    p.add("file", 1); // The first positional options
    conf.SetArgumentPositions(p);

}
/************************************************************
 * MAIN PROGRAM FUNCTION.
 ************************************************************/
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    if (!QGLFormat::hasOpenGL()) {
        std::cerr << "This system has no OpenGL support" << std::endl;
        return 1;
    }

   QMainWindow mainWindow;

    Ui_MainWindow myUi;
    myUi.setupUi(&mainWindow);

    UIConnector connector;

    RawDataViewer *canvas = myUi.GLWindow;

    Configuration conf(argv[0]);
    conf.SetPrintUsage(PrintHelp);
    SetupConfiguration(conf);
    if (!conf.DoParse(argc, const_cast<const char**>(argv), PrintHelp))
        return -1;

    if (conf.Has("color.range"))
    {
        vector<double> value = conf.Vec<double>("color.range");
        if (value.size() != 5)
        {
            cout << "Error, colorRange option should have exactly 5 double values" << endl;
            return -1;
        }
        for (int i=0;i<5;i++)
            canvas->ss[i] = value[i];
    }

    if (conf.Has("color.red"))
    {
        vector<double> value = conf.Vec<double>("color.red");
        if (value.size() != 5)
        {
            cout << "Error, colorRed option should have exactly 5 double values" << endl;
            return -1;
        }
        for (int i=0;i<5;i++)
            canvas->rr[i] = value[i];
    }

    if (conf.Has("color.green"))
    {
        vector<double> value = conf.Vec<double>("color.green");
        if (value.size() != 5)
        {
            cout << "Error, colorGreen option should have exactly 5 double values" << endl;
            return -1;
        }
        for (int i=0;i<5;i++)
            canvas->gg[i] = value[i];
    }

    if (conf.Has("color.blue"))
    {
        vector<double> value = conf.Vec<double>("color.blue");
        if (value.size() != 5)
        {
            cout << "Error, colorBlue option should have exactly 5 double values" << endl;
            return -1;
        }
        for (int i=0;i<5;i++)
            canvas->bb[i] = value[i];
    }



//    QObject::connect(myUi.eventsMinusButton, SIGNAL(clicked()),
//                     canvas, SLOT(minusEvent()));
//    QObject::connect(myUi.eventsPlusButton, SIGNAL(clicked()),
//                     canvas, SLOT(plusEvent()));
//    QObject::connect(myUi.eventsStepBox, SIGNAL(valueChanged(int)),
//                     canvas, SLOT(setEventStep(int)));

    myUi.colorRange0->setValue(canvas->ss[0]);
    myUi.colorRange1->setValue(canvas->ss[1]);
    myUi.colorRange2->setValue(canvas->ss[2]);
    myUi.colorRange3->setValue(canvas->ss[3]);
    myUi.colorRange4->setValue(canvas->ss[4]);
    myUi.redValue0->setValue(canvas->rr[0]);
    myUi.redValue1->setValue(canvas->rr[1]);
    myUi.redValue2->setValue(canvas->rr[2]);
    myUi.redValue3->setValue(canvas->rr[3]);
    myUi.redValue4->setValue(canvas->rr[4]);
    myUi.greenValue0->setValue(canvas->gg[0]);
    myUi.greenValue1->setValue(canvas->gg[1]);
    myUi.greenValue2->setValue(canvas->gg[2]);
    myUi.greenValue3->setValue(canvas->gg[3]);
    myUi.greenValue4->setValue(canvas->gg[4]);
    myUi.blueValue0->setValue(canvas->bb[0]);
    myUi.blueValue1->setValue(canvas->bb[1]);
    myUi.blueValue2->setValue(canvas->bb[2]);
    myUi.blueValue3->setValue(canvas->bb[3]);
    myUi.blueValue4->setValue(canvas->bb[4]);

    connector.setViewer(canvas);
    connector.boardsTimeList = myUi.boardsTimeList;
    connector.boardsTimeHisto = myUi.boardsTimeHisto;
    connector.startPixelsList = myUi.startPixelsList;
    connector.startCellHisto = myUi.startCellsHisto;
    connector.startTimeMarkHisto = myUi.startTimeMarkHisto;
    connector.pixelValueCurve = myUi.pixelValueCurve;
    connector.triggerDelayHisto = myUi.triggerDelayHisto;
    connector.triggerDelayList = myUi.triggerDelayList;
    connector.autoScaleColor = myUi.autoScaleColor;

    connector.startTimeMarksList = myUi.startTimeMarksList;
//    connector.fileLoadedLabel = myUi.fileLoadedLabel;
//    connector.runNumberLabel = myUi.runNumberLabel;
//    connector.numberOfSlicesLabel = myUi.numberOfSlicesLabel;
//    connector.numberOfTimeMarksLabel = myUi.numberOfTimeMarksLabel;
//    connector.runTypeLabel = myUi.runTypeLabel;
//    connector.firstTimeLabel = myUi.timeOfFirstDataLabel;
//    connector.lastTimeLabel = myUi.timeOfLastDataLabel;
    connector.currentPixelValue = myUi.currentPixelValue;

    connector.currentPixelScale = myUi.currentPixelScale;
    connector.entireCameraScale = myUi.entireCameraScale;
    connector.playEventsRadio = myUi.playEventsRadio;

    connector.extraInfoLabel = myUi.extraInfoLabel;

    connector.HwIDBox = myUi.HwIDBox;
    connector.SwIDBox = myUi.SwIDBox;
    connector.crateIDBox = myUi.crateIDBox;
    connector.boardIDBox = myUi.boardIDBox;
    connector.patchIDBox = myUi.patchIDBox;

    connector.eventNumberBox = myUi.displayingEventBox;

    connector.range0 = myUi.colorRange0;
    connector.range1 = myUi.colorRange1;
    connector.range2 = myUi.colorRange2;
    connector.range3 = myUi.colorRange3;
    connector.range4 = myUi.colorRange4;
    connector.drawCalibrationCheckBox = myUi.calibratedCheckBox;
    connector.drawCalibrationCheckBox->setEnabled(false);

    connector.initHistograms();

    QButtonGroup scaleGroup(canvas);// = new QButtonGroup(canvas);
    QButtonGroup animateGroup(canvas);// = new QButtonGroup(canvas);
    scaleGroup.addButton(myUi.currentPixelScale);
    scaleGroup.addButton(myUi.entireCameraScale);
    animateGroup.addButton(myUi.playEventsRadio);
    animateGroup.addButton(myUi.playSlicesRadio);
    myUi.entireCameraScale->setChecked(true);
//    QObject::connect(myUi.slicesPlusPlusButton, SIGNAL(clicked()),
//                    &connector, SLOT(slicesPlusPlus()));
//    QObject::connect(myUi.slicesMinusMinusButton, SIGNAL(clicked()),
//                     &connector, SLOT(slicesMinusMinus()));

    QObject::connect(myUi.autoScaleColor, SIGNAL(clicked()),
                     &connector, SLOT(autoScalePressed()));
    QObject::connect(canvas, SIGNAL(colorPaletteHasChanged()),
                     &connector, SLOT(autoScalePressed()));

    QObject::connect(myUi.currentPixelScale, SIGNAL(toggled(bool)),
                     &connector, SLOT(currentPixelChanged(bool)));
    QObject::connect(myUi.entireCameraScale, SIGNAL(toggled(bool)),
                     &connector, SLOT(entireCameraChanged(bool)));

    QObject::connect(myUi.HwIDBox, SIGNAL(valueChanged(int)),
                         &connector, SLOT(hwIDChanged(int)));
    QObject::connect(myUi.SwIDBox, SIGNAL(valueChanged(int)),
                         &connector, SLOT(swIDChanged(int)));
    QObject::connect(myUi.crateIDBox, SIGNAL(valueChanged(int)),
                         &connector, SLOT(crateIDChanged(int)));
    QObject::connect(myUi.boardIDBox, SIGNAL(valueChanged(int)),
                         &connector, SLOT(boardIDChanged(int)));
    QObject::connect(myUi.patchIDBox, SIGNAL(valueChanged(int)),
                         &connector, SLOT(patchIDChanged(int)));

 //   connector.pixelChanged(0);
    QObject::connect(canvas, SIGNAL(signalCurrentPixel(int)),
                     &connector, SLOT(pixelChanged(int)));
    QObject::connect(myUi.drawPatchCheckBox, SIGNAL(stateChanged(int)),
                     &connector, SLOT(drawPatchesCheckChange(int)));
    QObject::connect(myUi.drawImpulseCheckBox, SIGNAL(stateChanged(int)),
                     &connector, SLOT(drawImpulseCheckChange(int)));
    QObject::connect(myUi.drawBlurCheckBox, SIGNAL(stateChanged(int)),
                     &connector, SLOT(drawBlurCheckChange(int)));
    QObject::connect(myUi.loopOverCurrentEventBox, SIGNAL(stateChanged(int)),
                     &connector, SLOT(loopEventCheckChange(int)));
    QObject::connect(canvas, SIGNAL(newFileLoaded()),
                     &connector, SLOT(newFileLoaded()));

    QObject::connect(myUi.calibratedCheckBox, SIGNAL(stateChanged(int)),
                     &connector, SLOT(drawCalibratedDataChanged(int)));
    QObject::connect(myUi.loadNewFileButton, SIGNAL(clicked()),
                     &connector, SLOT(loadNewFileClicked()));
    QObject::connect(myUi.loadDRSCalibButton, SIGNAL(clicked()),
                     &connector, SLOT(loadNewCalibFileClicked()));

    QObject::connect(myUi.colorRange0, SIGNAL(valueChanged(double)),
                      &connector, SLOT(rangeChanged0(double)));

    QObject::connect(myUi.colorRange1, SIGNAL(valueChanged(double)),
                      &connector, SLOT(rangeChanged1(double)));

    QObject::connect(myUi.colorRange2, SIGNAL(valueChanged(double)),
                      &connector, SLOT(rangeChanged2(double)));

    QObject::connect(myUi.colorRange3, SIGNAL(valueChanged(double)),
                      &connector, SLOT(rangeChanged3(double)));

    QObject::connect(myUi.colorRange4, SIGNAL(valueChanged(double)),
                      &connector, SLOT(rangeChanged4(double)));

    QObject::connect(myUi.redValue0, SIGNAL(valueChanged(double)),
                      &connector, SLOT(redChanged0(double)));

    QObject::connect(myUi.redValue1, SIGNAL(valueChanged(double)),
                      &connector, SLOT(redChanged1(double)));

    QObject::connect(myUi.redValue2, SIGNAL(valueChanged(double)),
                      &connector, SLOT(redChanged2(double)));

    QObject::connect(myUi.redValue3, SIGNAL(valueChanged(double)),
                      &connector, SLOT(redChanged3(double)));

    QObject::connect(myUi.redValue4, SIGNAL(valueChanged(double)),
                      &connector, SLOT(redChanged4(double)));

    QObject::connect(myUi.greenValue0, SIGNAL(valueChanged(double)),
                      &connector, SLOT(greenChanged0(double)));

    QObject::connect(myUi.greenValue1, SIGNAL(valueChanged(double)),
                      &connector, SLOT(greenChanged1(double)));

    QObject::connect(myUi.greenValue2, SIGNAL(valueChanged(double)),
                      &connector, SLOT(greenChanged2(double)));

    QObject::connect(myUi.greenValue3, SIGNAL(valueChanged(double)),
                      &connector, SLOT(greenChanged3(double)));

    QObject::connect(myUi.greenValue4, SIGNAL(valueChanged(double)),
                      &connector, SLOT(greenChanged4(double)));

    QObject::connect(myUi.blueValue0, SIGNAL(valueChanged(double)),
                      &connector, SLOT(blueChanged0(double)));

    QObject::connect(myUi.blueValue1, SIGNAL(valueChanged(double)),
                      &connector, SLOT(blueChanged1(double)));

    QObject::connect(myUi.blueValue2, SIGNAL(valueChanged(double)),
                      &connector, SLOT(blueChanged2(double)));

    QObject::connect(myUi.blueValue3, SIGNAL(valueChanged(double)),
                      &connector, SLOT(blueChanged3(double)));

    QObject::connect(myUi.blueValue4, SIGNAL(valueChanged(double)),
                      &connector, SLOT(blueChanged4(double)));

    QObject::connect(myUi.slicesPerSecValue, SIGNAL(valueChanged(double)),
                      &connector, SLOT(slicesPerSecondChanged(double)));
    QObject::connect(myUi.playPauseButton, SIGNAL(clicked()),
                     &connector, SLOT(playPauseClicked()));

    QObject::connect(canvas, SIGNAL(signalCurrentSlice(int)),
                     &connector, SLOT(currentSliceHasChanged(int)));
    QObject::connect(canvas, SIGNAL(signalCurrentEvent(int)),
                     &connector, SLOT(currentEventHasChanged(int)));

    QObject::connect(&connector, SIGNAL(updateCurrentSliceDisplay(int)),
                     myUi.displayingSliceBox, SLOT(setValue(int)));

    QObject::connect(myUi.displayingSliceBox, SIGNAL(valueChanged(int)),
                    &connector, SLOT(sliceChangedFromSpinner(int)));
    QObject::connect(myUi.displayingEventBox, SIGNAL(valueChanged(int)),
                    &connector, SLOT(eventChangedFromSpinner(int)));

//    QObject::connect(&connector, SIGNAL(updateCurrentEventDisplay(QString)),
//                     myUi.displayingEventLabel, SLOT(setText(const QString)));
    QObject::connect(&connector, SIGNAL(updateCurrentEventDisplay(int)),
                     myUi.displayingEventBox, SLOT(setValue(int)));

    QObject::connect(&connector, SIGNAL(updateCurrentPCTime(QString)),
                     myUi.PCTimeLabel, SLOT(setText(const QString)));
    QObject::connect(&connector, SIGNAL(updateCurrentSoftTrigger(QString)),
                     myUi.softwareTriggerLabel, SLOT(setText(const QString)));
    QObject::connect(&connector, SIGNAL(updateCurrentTriggerType(QString)),
                     myUi.triggerTypeLabel, SLOT(setText(const QString)));
    QObject::connect(&connector, SIGNAL(updateCurrentPixelSliceValue(const QString)),
                     myUi.currentPixelValue, SLOT(setText(const QString)));

    if (conf.Has("file"))
    {
        string str = conf.Get<string>("file");
        QString qstr(str.c_str());
        connector.fileSelected(qstr);
    }

    mainWindow.show();

    return app.exec();
}

