/*
 * 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

#include <QtGui/QFileDialog>

//Coordinates of an hexagon of radius 1 and center 0
GLfloat hexcoords[6][2] = {{-0.577367206,  1},
                           { 0.577367206,  1},
                           { 1.154734411,  0},
                           { 0.577367206, -1},
                           {-0.577367206, -1},
                           {-1.154734411,  0}};

//bounding box for diplaying the impulse curve
float bboxMin[2] = {-1,-0.9};
float bboxMax[2] = {1,-0.3};
/************************************************************
 * UPDATE NEIGHBORS recalculate the neighbors of the current pixels.
 * Only takes the previous pixels into account (and updates them, too)
 ************************************************************/
void RawDataViewer::updateNeighbors(int currentPixel)
{
    float squaredDistance = 0;
    for (int i=0;i<currentPixel;i++)
    {
        squaredDistance = (pixelsCoords[i][0] - pixelsCoords[currentPixel][0])*
                          (pixelsCoords[i][0] - pixelsCoords[currentPixel][0]) +
                          (pixelsCoords[i][1] - pixelsCoords[currentPixel][1])*
                          (pixelsCoords[i][1] - pixelsCoords[currentPixel][1]);
        if (squaredDistance < 4*hexRadius*hexRadius*(1.0f+hexTolerance))//neighbor !
        {//ok, but which one ?
            if (fabs(pixelsCoords[i][0] - pixelsCoords[currentPixel][0]) < hexTolerance &&
                pixelsCoords[i][1] < pixelsCoords[currentPixel][1]){//top
                neighbors[i][0] = currentPixel;
                neighbors[currentPixel][3] = i;
                continue;}
            if (fabs(pixelsCoords[i][0] - pixelsCoords[currentPixel][0]) < hexTolerance &&
                pixelsCoords[i][1] > pixelsCoords[currentPixel][1]){//bottom
                neighbors[i][3] = currentPixel;
                neighbors[currentPixel][0] = i;
                continue;}
            if (pixelsCoords[i][0] > pixelsCoords[currentPixel][0] &&
                pixelsCoords[i][1] > pixelsCoords[currentPixel][1]){//top right
                neighbors[i][4] = currentPixel;
                neighbors[currentPixel][1] = i;
                continue;}
            if (pixelsCoords[i][0] > pixelsCoords[currentPixel][0] &&
                pixelsCoords[i][1] < pixelsCoords[currentPixel][1]){//bottom right
                neighbors[i][5] = currentPixel;
                neighbors[currentPixel][2] = i;
                continue;}
            if (pixelsCoords[i][0] < pixelsCoords[currentPixel][0] &&
                pixelsCoords[i][1] > pixelsCoords[currentPixel][1]){//top left
                neighbors[i][2] = currentPixel;
                neighbors[currentPixel][5] = i;
                continue;}
            if (pixelsCoords[i][0] < pixelsCoords[currentPixel][0] &&
                pixelsCoords[i][1] < pixelsCoords[currentPixel][1]){//bottom left
                neighbors[i][1] = currentPixel;
                neighbors[currentPixel][4] = i;
                continue;}
        }
    }
}
/************************************************************
 * SKIP PIXELS skips a given number of pixels.
 * Only update the pixel coordinates. i.e. update neighbors must
 * called again afterwards.
 ************************************************************/
void RawDataViewer::skipPixels(int start, int howMany)
{
    for (int i=start;i<MAX_NUM_PIXELS-howMany;i++)
    {
        pixelsCoords[i][0] = pixelsCoords[i+howMany][0];
        pixelsCoords[i][1] = pixelsCoords[i+howMany][1];
    }
}
/************************************************************
 * CALCULATE PIXELS COORDS as the name suggests
 ************************************************************/
void RawDataViewer::calculatePixelsCoords()
{
    pixelsCoords[0][0] = 0;
    pixelsCoords[0][1] = 0.3;
    pixelsCoords[0][2] = 0;
    pixelsCoords[1][0] = 0;
    pixelsCoords[1][1] = 0.3+2*hexRadius;
    pixelsCoords[1][2] = 0;
    neighbors[0][0] = 1;
    neighbors[1][3] = 0;
    //from which side of the previous hexagon are we coming from ?
    int fromSide = 3;
    //to which side are we heading to ?
    int toSide = 0;
    for (int i=2;i<MAX_NUM_PIXELS;i++)
    {
        toSide = fromSide-1;
        if (toSide < 0)
            toSide =5;
        while (neighbors[i-1][toSide] >= 0)
        {
            toSide--;
            if (toSide < 0)
                toSide = 5;
        }
        fromSide = toSide + 3;
        if (fromSide > 5)
            fromSide -= 6;
        //ok. now we now in which direction we're heading
        pixelsCoords[i][0] = pixelsCoords[i-1][0];
        pixelsCoords[i][1] = pixelsCoords[i-1][1];
        pixelsCoords[i][2] = pixelsCoords[i-1][2];
        switch (toSide)
        {
        case 0:
            pixelsCoords[i][1] += 2*hexRadius;
        break;
        case 1:
            pixelsCoords[i][0] += (2*hexRadius)*sin(M_PI/3.0);
            pixelsCoords[i][1] += (2*hexRadius)*cos(M_PI/3.0);
        break;
        case 2:
            pixelsCoords[i][0] += (2*hexRadius)*sin(M_PI/3.0);
            pixelsCoords[i][1] -= (2*hexRadius)*cos(M_PI/3.0);
        break;
        case 3:
            pixelsCoords[i][1] -= 2*hexRadius;
        break;
        case 4:
            pixelsCoords[i][0] -= (2*hexRadius)*sin(M_PI/3.0);
            pixelsCoords[i][1] -= (2*hexRadius)*cos(M_PI/3.0);
        break;
        case 5:
            pixelsCoords[i][0] -= (2*hexRadius)*sin(M_PI/3.0);
            pixelsCoords[i][1] += (2*hexRadius)*cos(M_PI/3.0);
        break;
        };

        updateNeighbors(i);
    }
    //Ok. So now we've circled around all the way to MAX_NUM_PIXELS
    //do the required shifts so that it matches the fact camera up to ACTUAL_NUM_PIXELS pixels
    skipPixels(1200, 1);
    skipPixels(1218, 3);
    skipPixels(1236, 1);
    skipPixels(1256, 1);
    skipPixels(1274, 3);
    skipPixels(1292, 3);
    skipPixels(1309, 6);
    skipPixels(1323, 7);
    skipPixels(1337, 6);
    skipPixels(1354, 6);
    skipPixels(1368, 7);
    skipPixels(1382, 9);
    skipPixels(1394, 12);
    skipPixels(1402, 15);
    skipPixels(1410, 12);
    skipPixels(1422, 12);
    skipPixels(1430, 15);
}
/************************************************************
 * BUILD VERTICES LIST. from the coordinates of the camera pixels,
 * calculate the list and coordinates of the vertices required to draw the
 * entire camera.
 ************************************************************/
void RawDataViewer::buildVerticesList()
{
    numVertices = 0;
    GLfloat cVertex[2];
    for (int i=0;i<ACTUAL_NUM_PIXELS;i++)
    {
        for (int j=0;j<6;j++)
        {
            for (int k=0;k<2;k++)
                cVertex[k] = hexcoords[j][k]*hexRadius + pixelsCoords[i][k];
            bool found = false;
            for (int k=0;k<numVertices;k++)
            {
                if ((cVertex[0] - verticesList[k][0])*
                    (cVertex[0] - verticesList[k][0]) +
                    (cVertex[1] - verticesList[k][1])*
                    (cVertex[1] - verticesList[k][1]) < hexTolerance*hexTolerance)
                    {
                        found = true;
                        break;
                    }
            }
            if (!found)
            {
                for (int k=0;k<2;k++)
                    verticesList[numVertices][k] = cVertex[k];
                numVertices++;
            }
        }
    }
    for (int i=0;i<ACTUAL_NUM_PIXELS;i++)
    {
        for (int j=0;j<6;j++)
        {
            for (int k=0;k<2;k++)
                cVertex[k] = hexcoords[j][k]*hexRadius + pixelsCoords[i][k];
            for (int k=0;k<numVertices;k++)
            {
                if ((cVertex[0] - verticesList[k][0])*
                     (cVertex[0] - verticesList[k][0]) +
                     (cVertex[1] - verticesList[k][1])*
                     (cVertex[1] - verticesList[k][1]) < hexTolerance*hexTolerance)
                     {
                        verticesIndices[i][j] = k;
                        break;
                     }
            }
        }
    }
}
/************************************************************
 * BUILD PATCHES INDICES. from the list of patches, crawls through
 * the list of camera pixels and build the list of edges that should be kept
 * in order to display the patches' contours.
 ************************************************************/
void RawDataViewer::buildPatchesIndices()
{
    vector<edge>::iterator it;
    bool erased = false;
    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);
                }
            }
        }
    }
}
/************************************************************
 * 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 HEXAGON. draws a single hexagon.
 ************************************************************/
void RawDataViewer::drawHexagon(int index, bool solid)
{
    if (solid)
        glBegin(GL_POLYGON);
    else
        glBegin(GL_LINE_LOOP);

    glVertex2fv(verticesList[verticesIndices[index][0]]);
    glVertex2fv(verticesList[verticesIndices[index][1]]);
    glVertex2fv(verticesList[verticesIndices[index][2]]);
    glVertex2fv(verticesList[verticesIndices[index][3]]);
    glVertex2fv(verticesList[verticesIndices[index][4]]);
    glVertex2fv(verticesList[verticesIndices[index][5]]);
    if (solid)
        glVertex2fv(verticesList[verticesIndices[index][0]]);

    glEnd();

    return;
}


float ss[5] = {0.00, 0.25, 0.5, 0.75, 1.00};
float rr[5] = {0.15, 0.00, 0.00, 1.00, 0.85};
float gg[5] = {0.15, 0.00, 1.00, 0.00, 0.85};
float bb[5] = {0.15, 1.00, 0.00, 0.00, 0.85};
/*
float ss[5] = {0., 0.47, 0.475, 0.48, 1.00};
float rr[5] = {0., 0.35, 0.85, 1.00, 1.00};
float gg[5] = {0., 0.10, 0.20, 0.73, 1.00};
float bb[5] = {0., 0.03, 0.06, 0.00, 1.00};
*/
/************************************************************
 * DRAW PATCHES. draws the clustering patches
 ************************************************************/
void RawDataViewer::drawPatches()
{
    glLineWidth(2.0f);
    float backupRadius = hexRadius;
    hexRadius *= 0.95;
    glBegin(GL_LINES);
    for (int i=0;i<NTMARK;i++)
    {
        glColor3fv(patchesColor[i]);
        for (unsigned int j=0;j<patchesIndices[i].size();j++)
        {
            glVertex2fv(verticesList[patchesIndices[i][j].first]);
            glVertex2fv(verticesList[patchesIndices[i][j].second]);
        }
    }
    glEnd();
    hexRadius = backupRadius;
}
/************************************************************
 * DRAW CAMERA draws all the camera pixels
 ************************************************************/
void RawDataViewer::drawCamera(bool alsoWire)
{
    glColor3f(0.5,0.5,0.5);
    glLineWidth(1.0);
    float color;

    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]+32767)/65535.0f;
#else
        color = float(eventData[nRoi*i + whichSlice]+32767)/65535.0f;
#endif
        int index = 0;
        while (ss[index] < color)
            index++;
        index--;
        float weight0 = (color-ss[index]) / (ss[index+1]-ss[index]);
        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;
    glBegin(GL_LINES);
    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]);

    float xRange = bboxMax[0] - bboxMin[0];
    float yRange = bboxMax[1] - bboxMin[1];
    glColor3f(1.0,1.0,1.0);
    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]+32767) /65535.0);
        glVertex2f(bboxMin[0] + xRange*(i+1)/(float)nRoi,
                   bboxMin[1] + yRange*(eventsData[eventNum][selectedPixel][i+1]+32767) /65535.0);
#else
        glVertex2f(bboxMin[0] + xRange*i/(float)nRoi,
                   bboxMin[1] + yRange*(eventData[nRoi*selectedPixel + i]+32767) /65535.0);
        glVertex2f(bboxMin[0] + xRange*(i+1)/(float)nRoi,
                   bboxMin[1] + yRange*(eventData[nRoi*selectedPixel + i+1]+32767) /65535.0);
#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]);

    glEnd();
}
/************************************************************
 * CONSTRUCTOR.
 ************************************************************/
RawDataViewer::RawDataViewer(QWidget *parent) : QGLWidget(parent)
{
    setFormat(QGLFormat(QGL::DoubleBuffer));// | QGL::DepthBuffer));
    hexRadius = 0.015f;
    hexTolerance = hexRadius/100.0f;
    viewSize = 1.0f;
    whichSlice = 0;
#ifdef LOAD_RAW
    nRoi = 1024;
#else
    nRoi = 0;
#endif
    eventNum = 0;
    rowNum = -1;
    eventStep = 1;
    selectedPixel = 0;
    inputFile = NULL;
    eventData = NULL;
    drawPatch = false;
    drawImpulse = false;
    drawBlur = false;
#ifdef LOAD_RAW
    loadEvents("/scratch/00000043.001_T.bin");
#endif
    calculatePixelsCoords();

    ifstream fin2("MasterList-v3.txt");
    if (!fin2.is_open())
    {
        cout << "Error: file \"MasterList-v3\" missing. aborting." << endl;
        exit(-1);
    }
    int l = 0;
    string buf;
    while (getline(fin2, buf, '\n'))
    {
        buf = Trim(buf);
        if (buf[0]=='#')
            continue;

        unsigned int softid, hardid, dummy;

        stringstream str(buf);

        str >> softid;
        str >> dummy;
        str >> hardid;

        if (softid>=1440)
            continue;

        hardwareMapping[softid] = hardid;

        l++;
    }
    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];
    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;
//        if (i==0 || i==2 || i==5 || i==126 || i==10 || i==23 || i==28 || i==38 || i==132 || i==42 || i==55 ||
//           i==18 || i==21 || i==34 || i==136 || i==122 || i==8 || i==14 || i==32 || i==45 || i==51 || i==138 ||
//            i==93 || i==75 || i==54 || i==158 || i==111 || i==105 || i==94 || i==82 || i==66 || i==61 || i==79 ||
//            i==156 || i==115 || i==102 || i==89 || i==71 || i==63 || i==152 || i==98 || i==84)
//        {
//            color[0] = 102.f/255.f;
//            color[1] = 0.f;
//            color[2] = 153.f/255.f;
//        }
        for (int j=0;j<3;j++)
            patchesColor[i][j] = color[j];
    }

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



}
/************************************************************
 *  DESTRUCTOR
 ************************************************************/
RawDataViewer::~RawDataViewer()
{
    if (inputFile != NULL)
    {
        inputFile->close();
        delete inputFile;
    }
    if (eventData != NULL)
        delete[] eventData;
}
/************************************************************
 * INITIALIZE GL. does not do much.
 ************************************************************/
void RawDataViewer::initializeGL()
{
    qglClearColor(QColor(25,25,38));
    glShadeModel(GL_FLAT);
    glDisable(GL_DEPTH_TEST);
    glDisable(GL_CULL_FACE);
//    glEnable(GL_LINE_SMOOTH);
//    glHint(GL_LINE_SMOOTH_HINT,GL_NICEST);
}

/************************************************************
 * RESIZE GL. reshapes the ortho projection to match the current window size
 ************************************************************/
void RawDataViewer::resizeGL(int width, int height)
{
    glViewport(0, 0, width, height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    GLfloat windowRatio = (float)width/(float)height;
    if (windowRatio < 1)
    {
        windowRatio = 1.0f/windowRatio;
        gluOrtho2D(-viewSize, viewSize, -viewSize*windowRatio, viewSize*windowRatio);
        pixelSize = 2*viewSize/(float)width;
        shownSizex = 2*viewSize;
        shownSizey = 2*viewSize*windowRatio;
    }
    else
    {
        gluOrtho2D(-viewSize*windowRatio, viewSize*windowRatio, -viewSize, viewSize);
        pixelSize = 2*viewSize/(float)height;
        shownSizex = 2*viewSize*windowRatio;
        shownSizey = 2*viewSize;
    }
    glMatrixMode(GL_MODELVIEW);

}

/************************************************************
 * PAINT GL. main drawing function.
 ************************************************************/
void RawDataViewer::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT);
    glLoadIdentity();

    if (!drawImpulse)
    {
        glTranslatef(0,-0.44,0);
        glScalef(1.5,1.5,1);
    }
    if (drawBlur)
    {
        glShadeModel(GL_SMOOTH);
        drawCamera(false);
    }
    else
    {
        glShadeModel(GL_FLAT);
        drawCamera(true);
    }
    if (drawImpulse)
    {
        glLineWidth(2.0);
        drawPixelCurve();
    }
    if (drawPatch)
        drawPatches();

    if (drawImpulse)
    {
        glLineWidth(1.0f);
        glColor3f(1.0,1.0,1.0);
        drawHexagon(selectedPixel, false);
    }
}

/************************************************************
 * MOUSE PRESS EVENT. mouse click handler.
 ************************************************************/
void RawDataViewer::mousePressEvent(QMouseEvent *event)
{
    lastPos = event->pos();
    setCorrectSlice(event);
    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* event)
{
    if (!drawImpulse)
        return;
    float x = (float)event->x() * pixelSize - shownSizex/2;
    float y = ((float)height()-(float)event->y())*pixelSize - shownSizey/2;
    if (x < bboxMin[0] ||
        x > bboxMax[0] ||
        y < bboxMin[1] ||
        y > bboxMax[1])
        return;
    whichSlice = (x - 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 *event)
{
    if (event->buttons() & Qt::LeftButton) {
        setCorrectSlice(event);
        updateGL();
    } else if (event->buttons() & Qt::RightButton) {
        updateGL();
    }
    lastPos = event->pos();
}

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

/************************************************************
 * PIXEL AT POSITION. figures out which camera pixel was clicked.
 ************************************************************/
int RawDataViewer::PixelAtPosition(const QPoint &pos)
{
    const int MaxSize = 512;
    GLuint buffer[MaxSize];
    GLint viewport[4];

    makeCurrent();

    glGetIntegerv(GL_VIEWPORT, viewport);
    glSelectBuffer(MaxSize, buffer);
    glRenderMode(GL_SELECT);

    glInitNames();
    glPushName(0);

    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();
    GLfloat windowRatio = GLfloat(width()) / GLfloat(height());
    gluPickMatrix(GLdouble(pos.x()), GLdouble(viewport[3] - pos.y()),
            1.0, 1.0, viewport);

    if (windowRatio < 1)
     {
         windowRatio = 1.0f/windowRatio;
         gluOrtho2D(-viewSize, viewSize, -viewSize*windowRatio, viewSize*windowRatio);
     }
     else
     {
         gluOrtho2D(-viewSize*windowRatio, viewSize*windowRatio, -viewSize, viewSize);
     }

    glMatrixMode(GL_MODELVIEW);
    drawCamera(false);
    glMatrixMode(GL_PROJECTION);
    glPopMatrix();

    //for some reason that I cannot understand, the push/pop matrix doesn't do the trick here... bizarre
    //ok, so re-do the resizeGL thing.
    resizeGL(width(), height());

    if (!glRenderMode(GL_RENDER))
        return -1;

    return buffer[3];
}
/************************************************************
 * OPEN FILE. opens a new fits file
 ************************************************************/
void RawDataViewer::openFile(string& file)
{
    if (inputFile)
    {
        inputFile->close();
        delete inputFile;
    }
    inputFile = new fits(file);
    if (!*inputFile)
    {
        cout << "Couldn't open file." << endl;
        delete inputFile;
        inputFile = NULL;
        return;
    }
    nRows = inputFile->GetInt("NAXIS2");
    nRoi = inputFile->GetInt("NROI");
    runNumber = -1;
    nTM = inputFile->GetInt("NTM");
    runType = inputFile->GetInt("RUNTYPE");
    firstDataTime = -1;
    lastDataTime = -1;

    eventNum = 0;

#ifdef LOAD_RAW
    nRows = NUM_STORED_EVENTS;
#endif

    if (eventData != NULL)
        delete[] eventData;
    eventData = new int16_t[1440*nRoi];
    inputFile->SetPtrAddress("Data", eventData);
    inputFile->SetPtrAddress("EventNum", &eventNum);
    inputFile->SetPtrAddress("TriggerType", &triggerType);
    inputFile->SetPtrAddress("SoftTrig", &softTrig);
    inputFile->SetPtrAddress("PCTime", &pcTime);
    inputFile->SetPtrAddress("BoardTime", boardTime);
    inputFile->SetPtrAddress("StartPix", startPix);
    inputFile->SetPtrAddress("StartTM", startTM);
    int backupStep = eventStep;
    rowNum = -1;
    eventStep = 1;
    plusEvent();
    eventStep = backupStep;
    emit newFileLoaded();
}

/************************************************************
 * 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);
#endif
    updateGL();
    emit signalCurrentEvent(eventNum);
}
/************************************************************
 * NEXT SLICE. deprec ?
 ************************************************************/
void RawDataViewer::nextSlice()
{
    whichSlice++;
    if (whichSlice >= nRoi)
        whichSlice=0;

    emit signalCurrentSlice(whichSlice);
    updateGL();
}
/************************************************************
 * UICONNECTOR CONSTRUCTOR
 ************************************************************/
UIConnector::UIConnector(QWidget* parent)
{
    timer.setInterval(1000.0);
    QObject::connect(&timer, SIGNAL(timeout()),
                      this, SLOT(nextSlicePlease()));
}
/************************************************************
 * 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();
}
/************************************************************
 * NEXT SLICE PLEASE
 ************************************************************/
void UIConnector::nextSlicePlease()
{
    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)
{
    ss[0] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * RANGE CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::rangeChanged1(double value)
{
    ss[1] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * RANGE CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::rangeChanged2(double value)
{
    ss[2] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * RANGE CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::rangeChanged3(double value)
{
    ss[3] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * RANGE CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::rangeChanged4(double value)
{
    ss[4] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * RANGE CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::redChanged0(double value)
{
    rr[0] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * RED CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::redChanged1(double value)
{
    rr[1] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * RED CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::redChanged2(double value)
{
    rr[2] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * RED CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::redChanged3(double value)
{
    rr[3] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * RED CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::redChanged4(double value)
{
    rr[4] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * GREEN CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::greenChanged0(double value)
{
    gg[0] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * GREEN CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::greenChanged1(double value)
{
    gg[1] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * GREEN CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::greenChanged2(double value)
{
    gg[2] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * GREEN CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::greenChanged3(double value)
{
    gg[3] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * GREEN CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::greenChanged4(double value)
{
    gg[4] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * BLUE CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::blueChanged0(double value)
{
    bb[0] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * BLUE CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::blueChanged1(double value)
{
    bb[1] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * BLUE CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::blueChanged2(double value)
{
    bb[2] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * BLUE CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::blueChanged3(double value)
{
    bb[3] = (float)value;
    viewer->updateGL();
}
/************************************************************
 * BLUE CHANGED . colors tweaking handler
 ************************************************************/
void UIConnector::blueChanged4(double value)
{
    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();
}
/************************************************************
 * FILE SELECTED. return of the file open dialog handler
 ************************************************************/
void UIConnector::fileSelected(QString file)
{
    currentFile = file.toStdString();
    if (currentFile != "")
        viewer->openFile(currentFile);
}
/************************************************************
 * NEW FILE LOADED. update of the UI after a new file has been loaded
 ************************************************************/
void UIConnector::newFileLoaded()
{
    ostringstream str;
    str << "File loaded: " << currentFile;
    fileLoadedLabel->setText(QString(str.str().c_str()));
    str.str("");
    str << "Run number: " << viewer->runNumber;
    runNumberLabel->setText(QString(str.str().c_str()));
    str.str("");
    str << "Number of Events/Slices: " << viewer->nRows << "/" << viewer->nRoi;
    numberOfSlicesLabel->setText(QString(str.str().c_str()));
    str.str("");
    str << "Number of Time Marks: " << viewer->nTM;
    numberOfTimeMarksLabel->setText(QString(str.str().c_str()));
    str.str("");
    str << "Run Type: " << viewer->runType;
    runTypeLabel->setText(QString(str.str().c_str()));
    str.str("");
    str << "Time of 1st data: " << viewer->firstDataTime;
    firstTimeLabel->setText(QString(str.str().c_str()));
    str.str("");
    str << "Time of last data: " << viewer->lastDataTime;
    lastTimeLabel->setText(QString(str.str().c_str()));
}
/************************************************************
 * 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)
{
    ostringstream str;
    str << "Displaying Slice " << slice;
    QString qstr(str.str().c_str());
    emit updateCurrentSliceDisplay(qstr);
}
/************************************************************
 * CURRENT EVENT HAS CHANGED. ui handler
 ************************************************************/
void UIConnector::currentEventHasChanged(int event)
{
    ostringstream str;
    str << "Displaying Event " << event;
    QString qstr(str.str().c_str());
    emit updateCurrentEventDisplay(qstr);
    //retrieve the data that we want to display
    str.str("");
    str << "PC Time: " << viewer->pcTime;
    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);

    boardsTimeList->clear();
    startPixelsList->clear();
    startTimeMarksList->clear();
    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()));
    }
    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()));
    }
    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()));
    }

}

/************************************************************
 * MAIN PROGRAM FUNCTION.
 ************************************************************/
int main(int argc, char *argv[])
{
    if (argc > 1)
    {
        cout << "Sorry, this program does not accept options (yet)." << endl;
        cout << "Usage: just launch it without arguments." << endl;
        cout << "Once launched, you can load a fits file (compressed: .fits.gz) using the \"Load New File\" button" << endl;
        cout << "Events stepping lets you crawl the events inside the loaded file, while the number between the \"-\" and \"+\" buttons determines how many events are skipped at every button click" << endl;
        cout << "Play/Pause start or stops the animation of the camera (looping over the current event's slices), while the \"slices per sec\" number determines how many slices are diplayed every second" << endl;
        cout << "The ranges, Red, Green and Blue series of inputs can be used to tweak the displayed colours. The range goes from 0 to 1, which would map to -32768 and 32767 respectively" << endl;
        cout << "Only 3 intermediate steps can be given, and the given colours are interpolated for the pixels accordingly" << endl;
        cout << "Eventually, the Draw Impulse, Draw Patches and Blur pixels checkboxes can be used to change what is displayed." << endl;
        cout << "when \"Draw Impulse\" is checked, it is possible to select a pixel by double clicking on it, and the current slice can be drag and dropped." << endl;
        return 0;
    }
    QApplication app(argc, argv);

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

    QMainWindow mainWindow;

    Ui_MainWindow myUi;
    myUi.setupUi(&mainWindow);

    RawDataViewer *canvas = myUi.GLWindow;

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

    UIConnector connector;
    connector.setViewer(canvas);
    connector.boardsTimeList = myUi.boardsTimeList;
    connector.startPixelsList = myUi.startPixelsList;
    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;

    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(canvas, SIGNAL(newFileLoaded()),
                     &connector, SLOT(newFileLoaded()));

    QObject::connect(myUi.loadNewFileButton, SIGNAL(clicked()),
                     &connector, SLOT(loadNewFileClicked()));

    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(QString)),
                     myUi.displayingSliceLabel, SLOT(setText(const QString)));
    QObject::connect(&connector, SIGNAL(updateCurrentEventDisplay(QString)),
                     myUi.displayingEventLabel, SLOT(setText(const QString)));
    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)));

    mainWindow.show();

    return app.exec();
}
