#include "mainwindow.h"
#include "./ui_mainwindow.h"

HANDLE MainWindow::semget()
{
    return semForRF;
}

SemaphoreWorkerThread::SemaphoreWorkerThread(QObject* parent, MainWindow* wnd = nullptr) : QThread(parent)
{
    this->wnd = wnd;
}

void SemaphoreWorkerThread::run()
{
#ifdef _WIN32
    HANDLE sem = wnd->semget();
    DWORD dwWaitResult = WaitForSingleObject(sem, 20000);
#endif
    delay(50);
    qDebug() << "Semaphore released!";
}

Counter::Counter(int counts)
{
    this->ncounts = 0;
    this->counts = counts;
}

void Counter::count()
{
    ncounts++;
    qDebug() << "ncounts: " << ncounts;
    qDebug() << "counts: " << counts;

    if(ncounts >= counts)
    {
        qDebug() << "ncounts: " << ncounts;
        emit Counter::countsEnd();
    }
}

void Counter::reset()
{
    ncounts = 0;
    qDebug() << "counts: " << this->counts;
}

void Counter::rebind(int counts)
{
    this->counts = counts;
    qDebug() << "counts: " << this->counts;
}

void delay(int ms)
{
    QTime dieTime= QTime::currentTime().addMSecs(ms);
    while (QTime::currentTime() < dieTime)
        QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->SampleRateBox->addItem("2 MHz");
    ui->SampleRateBox->addItem("8 MHz");
    ui->SampleRateBox->addItem("10 MHz");
    ui->SampleRateBox->addItem("12.5 MHz");
    ui->SampleRateBox->addItem("16 MHz");
    ui->SampleRateBox->addItem("20 MHz");

    ui->GainEdit->setEnabled(true);
    ui->AnaliseButton->setEnabled(true);

    syncport = new QSerialPort(this);

    portInfos = QSerialPortInfo::availablePorts();

    for(const QSerialPortInfo& info : portInfos)
    {
        ui->SerialPortBox->addItem(info.portName() + " (" + info.description() + ")");
    }

    int w = ui->label->pixmap().width();
    int h = ui->label->pixmap().height();
    ui->label->setPixmap(ui->label->pixmap().scaled(w, h, Qt::KeepAspectRatio));

    ui->centralwidget->setLayout(ui->verticalLayout);

    tmrForRF = new QTimer();
    tmrForRF->setInterval(15000);

#ifdef _WIN32
    semForRF = CreateSemaphoreA(NULL, 0, 1, "wait-semaphore-5d95950d-a278-4733-a041-ee9fb05ad4e4");
    if(semForRF == NULL)
    {
        qDebug() << "Cannot create semaphore!";
        exit(-1);
    }
#endif

    semThread = new SemaphoreWorkerThread(this, this);

    ui->GRA1Check->setCheckState(Qt::Checked);
    graCounter = new Counter(1);

    // GUI events:

    connect(ui->SDRFileButton, &QToolButton::pressed, this, &MainWindow::sdrFDialog);
    connect(ui->AnaliseButton, &QPushButton::pressed, this, &MainWindow::analizeButtonPress);
    connect(ui->SyncFileButton, &QToolButton::pressed, this, &MainWindow::syncFDialog);
    connect(ui->GRAFileButton, &QToolButton::pressed, this, &MainWindow::graFDialog);
    connect(ui->GRAFileButton2, &QToolButton::pressed, this, &MainWindow::gra2FDialog);
    connect(ui->GRAFileButton3, &QToolButton::pressed, this, &MainWindow::gra3FDialog);
    connect(ui->OutPropFileButton, &QToolButton::pressed, this, &MainWindow::outFDialog);
    connect(ui->RunButton, &QPushButton::pressed, this, &MainWindow::runButtonPress);
    connect(&(this->plotproc), &QProcess::finished, this, &MainWindow::plotprocFinishedSlot);
    connect(ui->CancelButton, &QPushButton::pressed, this, &MainWindow::cancelProgram);

    connect(ui->SaveProfileButton, &QPushButton::pressed, this, &MainWindow::saveProfilePress);
    connect(ui->LoadProfileButton, &QPushButton::pressed, this, &MainWindow::loadProfilePress);

    connect(ui->OUTCheck, &QCheckBox::checkStateChanged, this, &MainWindow::OUTcheckBoxEvent);
    connect(ui->GRA1Check, &QCheckBox::checkStateChanged, this, &MainWindow::GRA1checkBoxEvent);
    connect(ui->GRA2Check, &QCheckBox::checkStateChanged, this, &MainWindow::GRA2checkBoxEvent);
    connect(ui->GRA3Check, &QCheckBox::checkStateChanged, this, &MainWindow::GRA3checkBoxEvent);

    // Make program logic:

    connect(&(this->syncproc), &QProcess::finished, this, &MainWindow::syncFinished); // Kills Sync, sends command to serial port and starts UDP_test

    connect(&(this->graproc), &QProcess::finished, graCounter, &Counter::count);
    connect(&(this->graproc2), &QProcess::finished, graCounter, &Counter::count);
    connect(&(this->graproc3), &QProcess::finished, graCounter, &Counter::count);

    connect(graCounter, &Counter::countsEnd, this, &MainWindow::graFinished); // Kills UDP_test.exe, starts pico_test_00_second_copy, starts timer for SDR
    connect(semThread, &QThread::finished, this, &MainWindow::startHackRF); // Waits for semaphore/timeout and starts hacrftrans00
    connect(&(this->hackrfproc), &QProcess::finished, this, &MainWindow::hackrfFinished); // Kills hackrftrans00
    connect(&(this->picoproc), &QProcess::finished, this, &MainWindow::picoFinished); // Kills pico_test_00_second_copy and close the serial port
}

int MainWindow::saveProfilePress()
{
    if(!QDir("profiles").exists())
    {
        QDir().mkdir("profiles");
    }

    QString filename = QFileDialog::getSaveFileName(this, tr("Save File"), QDir::currentPath() + "\\profiles", tr("JSON profiles (*.json)"));
    QFile file(filename);

    if(!file.open(QIODevice::ReadWrite)) {
        qDebug() << "File open error";
    } else {
        qDebug() <<"JSONTest2 File open!";
    }

    file.resize(0);

    QJsonObject jsonProfile, GRA, GRA1, GRA2, GRA3, SDR, OUTPROP, SYNC;

    SYNC.insert("FileName", ui->SyncFileEdit->text());
    SYNC.insert("Port", ui->SerialPortBox->currentText());
    if(ui->SyncDebugModeCheck->isChecked())
        SYNC.insert("Debug Mode", 1);
    else
        SYNC.insert("Debug Mode", 0);


    GRA1.insert("FileName", ui->GRAFileEdit->text());
    GRA1.insert("IP", ui->IP1edit->text());
    if(ui->GRA1Check->isChecked())
        GRA1.insert("enabled", 1);
    else
        GRA1.insert("enabled", 0);

    GRA2.insert("FileName", ui->GRAFileEdit2->text());
    GRA2.insert("IP", ui->IP2edit->text());
    if(ui->GRA2Check->isChecked())
        GRA2.insert("enabled", 1);
    else
        GRA2.insert("enabled", 0);


    GRA3.insert("FileName", ui->GRAFileEdit3->text());
    GRA3.insert("IP", ui->IP3edit->text());
    if(ui->GRA3Check->isChecked())
        GRA3.insert("enabled", 1);
    else
        GRA3.insert("enabled", 0);


    GRA.insert("GRA1", GRA1);
    GRA.insert("GRA2", GRA2);
    GRA.insert("GRA3", GRA3);
    if(ui->GRADebugModeCheck->isChecked())
        GRA.insert("Debug Mode", 1);
    else
        GRA.insert("Debug Mode", 0);

    OUTPROP.insert("FileName", ui->OutPropFileEdit->text());
    if(ui->OutPropDebugModeCheck->isChecked())
        OUTPROP.insert("Debug Mode", 1);
    else
        OUTPROP.insert("Debug Mode", 0);
    if(ui->OUTCheck->isChecked())
        OUTPROP.insert("Enabled", 1);
    else
        OUTPROP.insert("Enabled", 0);
    if(ui->BelowCheck->isChecked())
        OUTPROP.insert("Below", 1);
    else
        OUTPROP.insert("Below", 0);

    SDR.insert("FileName", ui->SDRFileEdit->text());
    SDR.insert("Frequency", ui->FreqBox->text());
    SDR.insert("Sample Rate", ui->SampleRateBox->currentText());
    SDR.insert("Gain", ui->GainEdit->text());
    if(ui->AmplCheck->isChecked())
        SDR.insert("Amplified", 1);
    else
        SDR.insert("Amplified", 0);

    jsonProfile.insert("SYNC", SYNC);
    jsonProfile.insert("GRA", GRA);
    jsonProfile.insert("OUT", OUTPROP);
    jsonProfile.insert("SDR", SDR);

    QJsonDocument doc;
    doc.setObject(jsonProfile);
    file.write(doc.toJson());
    file.close();

    qDebug() << "Writed to JSON: " + filename;

    return 0;
}

int MainWindow::loadProfilePress()
{
    if(!QDir("profiles").exists())
    {
        QDir().mkdir("profiles");
    }

    QString val;
    QJsonDocument doc;
    QJsonObject obj, SYNC, GRA, GRA1, GRA2, GRA3, OUTPROP, SDR;

    QString filename = QFileDialog::getOpenFileName(this, tr("Open File"), QDir::currentPath() + "\\profiles", tr("JSON profiles (*.json)"));
    QFile file(filename);
    file.open(QIODevice::ReadOnly | QIODevice::Text);

    val = file.readAll();

    file.close();

    doc = QJsonDocument::fromJson(val.toUtf8());
    obj = doc.object();

    SYNC = obj.value(QString("SYNC")).toObject();
    GRA = obj.value(QString("GRA")).toObject();
    OUTPROP = obj.value(QString("OUT")).toObject();
    SDR = obj.value(QString("SDR")).toObject();

    GRA1 = GRA.value(QString("GRA1")).toObject();
    GRA2 = GRA.value(QString("GRA2")).toObject();
    GRA3 = GRA.value(QString("GRA3")).toObject();

    ui->SyncFileEdit->setText(SYNC.value(QString("FileName")).toString());
    ui->SerialPortBox->setCurrentText(SYNC.value(QString("Port")).toString());
    if(SYNC.value(QString("Debug Mode")).toInt() == 1)
        ui->SyncDebugModeCheck->setCheckState(Qt::Checked);
    else
        ui->SyncDebugModeCheck->setCheckState(Qt::Unchecked);

    ui->GRAFileEdit->setText(GRA1.value("FileName").toString());
    ui->IP1edit->setText(GRA1.value("IP").toString());
    if(GRA1.value(QString("enabled")).toInt() == 1)
        ui->GRA1Check->setCheckState(Qt::Checked);
    else
        ui->GRA1Check->setCheckState(Qt::Unchecked);

    ui->GRAFileEdit2->setText(GRA2.value("FileName").toString());
    ui->IP2edit->setText(GRA2.value("IP").toString());
    if(GRA2.value(QString("enabled")).toInt() == 1)
        ui->GRA2Check->setCheckState(Qt::Checked);
    else
        ui->GRA2Check->setCheckState(Qt::Unchecked);

    ui->GRAFileEdit3->setText(GRA3.value("FileName").toString());
    ui->IP3edit->setText(GRA3.value("IP").toString());
    if(GRA3.value(QString("enabled")).toInt() == 1)
        ui->GRA3Check->setCheckState(Qt::Checked);
    else
        ui->GRA3Check->setCheckState(Qt::Unchecked);

    if(GRA.value(QString("Debug Mode")).toInt() == 1)
        ui->GRADebugModeCheck->setCheckState(Qt::Checked);
    else
        ui->GRADebugModeCheck->setCheckState(Qt::Unchecked);

    ui->OutPropFileEdit->setText(OUTPROP.value("FileName").toString());
    if(OUTPROP.value(QString("Debug Mode")).toInt() == 1)
        ui->OutPropDebugModeCheck->setCheckState(Qt::Checked);
    else
        ui->OutPropDebugModeCheck->setCheckState(Qt::Unchecked);
    if(OUTPROP.value(QString("Enabled")).toInt() == 1)
        ui->OUTCheck->setCheckState(Qt::Checked);
    else
        ui->OUTCheck->setCheckState(Qt::Unchecked);
    if(OUTPROP.value(QString("Below")).toInt() == 1)
        ui->BelowCheck->setCheckState(Qt::Checked);
    else
        ui->BelowCheck->setCheckState(Qt::Unchecked);

    ui->SDRFileEdit->setText(SDR.value("FileName").toString());
    ui->FreqBox->setValue(SDR.value("Frequency").toString().toInt());
    ui->SampleRateBox->setCurrentText(SDR.value("Sample Rate").toString());
    ui->GainEdit->setValue(SDR.value("Gain").toString().toInt());
    if(SDR.value(QString("Amplified")).toInt() == 1)
        ui->AmplCheck->setCheckState(Qt::Checked);
    else
        ui->AmplCheck->setCheckState(Qt::Unchecked);

    return 0;
}

void MainWindow::GRA1checkBoxEvent()
{
    graCounter->reset();

    qDebug() << "GRA1CheckBox event!";

    if(ui->GRA1Check->isChecked())
    {
        ui->GRAFileEdit->setEnabled(true);
        ui->GRAFileButton->setEnabled(true);
        ui->IP1edit->setEnabled(true);
    }
    else
    {
        ui->GRAFileEdit->setEnabled(false);
        ui->GRAFileButton->setEnabled(false);
        ui->IP1edit->setEnabled(false);
    }

    if((ui->GRA2Check->isChecked() || ui->GRA3Check->isChecked()) && ui->GRA1Check->isChecked())
    {
        if(ui->GRA2Check->isChecked() && ui->GRA3Check->isChecked())
        {
            graCounter->rebind(3);
        }
        else
        {
            graCounter->rebind(2);
        }
    }
    else if((ui->GRA2Check->isChecked() && ui->GRA3Check->isChecked()) && !ui->GRA1Check->isChecked())
    {
        graCounter->rebind(2);
    }
    else
    {
        graCounter->rebind(1);
    }
}

void MainWindow::GRA2checkBoxEvent()
{
    graCounter->reset();

    qDebug() << "GRA2CheckBox event!";

    if(ui->GRA2Check->isChecked())
    {    
        ui->GRAFileEdit2->setEnabled(true);
        ui->GRAFileButton2->setEnabled(true);
        ui->IP2edit->setEnabled(true);
    }
    else
    {
        ui->GRAFileEdit2->setEnabled(false);
        ui->GRAFileButton2->setEnabled(false);
        ui->IP2edit->setEnabled(false);
    }

    if((ui->GRA2Check->isChecked() || ui->GRA3Check->isChecked()) && ui->GRA1Check->isChecked())
    {
        if(ui->GRA2Check->isChecked() && ui->GRA3Check->isChecked())
        {
            graCounter->rebind(3);
        }
        else
        {
            graCounter->rebind(2);
        }
    }
    else if((ui->GRA2Check->isChecked() && ui->GRA3Check->isChecked()) && !ui->GRA1Check->isChecked())
    {
        graCounter->rebind(2);
    }
    else
    {
        graCounter->rebind(1);
    }
}

void MainWindow::GRA3checkBoxEvent()
{
    graCounter->reset();

    qDebug() << "GRA3CheckBox event!";

    if(ui->GRA3Check->isChecked())
    {
        ui->GRAFileEdit3->setEnabled(true);
        ui->GRAFileButton3->setEnabled(true);
        ui->IP3edit->setEnabled(true);
    }
    else
    {
        ui->GRAFileEdit3->setEnabled(false);
        ui->GRAFileButton3->setEnabled(false);
        ui->IP3edit->setEnabled(false);
    }

    if((ui->GRA2Check->isChecked() || ui->GRA3Check->isChecked()) && ui->GRA1Check->isChecked())
    {
        if(ui->GRA2Check->isChecked() && ui->GRA3Check->isChecked())
        {
            graCounter->rebind(3);
        }
        else
        {
            graCounter->rebind(2);
        }
    }
    else if((ui->GRA2Check->isChecked() && ui->GRA3Check->isChecked()) && !ui->GRA1Check->isChecked())
    {
        graCounter->rebind(2);
    }
    else
    {
        graCounter->rebind(1);
    }
}

void MainWindow::OUTcheckBoxEvent()
{
    if(ui->OUTCheck->isChecked())
    {
        ui->OutPropFileEdit->setEnabled(true);
        ui->OutPropFileButton->setEnabled(true);
    }
    else
    {
        ui->OutPropFileEdit->setEnabled(false);
        ui->OutPropFileButton->setEnabled(false);
    }
}

void MainWindow::sdrFDialog()
{
    QString filename = QFileDialog::getOpenFileName(this, tr("Open File"), "C:\\", tr("SDR Sequence (*.bin)"));
    ui->SDRFileEdit->setText(filename);
}

void MainWindow::syncFDialog()
{
    QString filename = QFileDialog::getOpenFileName(this, tr("Open File"), "C:\\", tr("Synchronization sequence (*.xml)"));
    ui->SyncFileEdit->setText(filename);
}

void MainWindow::graFDialog()
{
    QString filename = QFileDialog::getOpenFileName(this, tr("Open File"), "C:\\", tr("GRA Sequence (*.txt)"));
    ui->GRAFileEdit->setText(filename);
}

void MainWindow::gra2FDialog()
{
    QString filename = QFileDialog::getOpenFileName(this, tr("Open File"), "C:\\", tr("GRA Sequence (*.txt)"));
    ui->GRAFileEdit2->setText(filename);
}

void MainWindow::gra3FDialog()
{
    QString filename = QFileDialog::getOpenFileName(this, tr("Open File"), "C:\\", tr("GRA Sequence (*.txt)"));
    ui->GRAFileEdit3->setText(filename);
}

void MainWindow::outFDialog()
{
    QString filename = QFileDialog::getOpenFileName(this, tr("Open File"), "C:\\", tr("Out Properties file (*.xml)"));
    ui->OutPropFileEdit->setText(filename);
}

int MainWindow::cancelProgram()
{
    syncproc.blockSignals(true);
    graproc.blockSignals(true);
    graproc2.blockSignals(true);
    graproc3.blockSignals(true);
    graCounter->blockSignals(true);
    picoproc.blockSignals(true);
    hackrfproc.blockSignals(true);
    tmrForRF->blockSignals(true);
    semThread->blockSignals(true);

    syncport->close();

    syncproc.close();
    graCounter->reset();
    graproc.close();
    graproc2.close();
    graproc3.close();
    picoproc.close();
    hackrfproc.close();
    tmrForRF->stop();
    ReleaseSemaphore(semForRF, 1, NULL);
    semThread->terminate();

    picoargs.clear();
    hackrfargs.clear();
    graargs.clear();
    graargs2.clear();
    graargs3.clear();
    syncargs.clear();

    ui->progress->setEnabled(false);
    ui->RunButton->setEnabled(true);
    ui->CancelButton->setEnabled(false);
    ui->GRA2Check->setEnabled(true);
    ui->GRA3Check->setEnabled(true);

    syncproc.blockSignals(false);
    graproc.blockSignals(false);
    graCounter->blockSignals(false);
    picoproc.blockSignals(false);
    hackrfproc.blockSignals(false);
    tmrForRF->blockSignals(false);
    semThread->blockSignals(false);
    return 0;
}

int MainWindow::syncFinished()
{
    syncproc.close();
    qDebug() << "Hwa";

    switch(syncproc.exitCode())
    {
    case -1:
        QMessageBox::critical(this, tr("LMRIgui App"), tr("Wrong arguments for sync!"));
        cancelProgram();
        return -1;
        break;
    case -2:
        QMessageBox::critical(this, tr("LMRIgui App"), tr("Wrong serial port number!"));
        cancelProgram();
        return -2;
        break;
    case -5:
        QMessageBox::critical(this, tr("LMRIgui App"), tr("Wrong sync-file structure!"));
        cancelProgram();
        return -5;
        break;
    case -6:
        QMessageBox::critical(this, tr("LMRIgui App"), tr("No connection to serial port in Sync.exe!"));
        cancelProgram();
        return -6;
        break;
    }

    pvalue = pvalue + 12;
    ui->progress->setValue(pvalue);

    syncport->setPortName(portInfos[ui->SerialPortBox->currentIndex()].portName());
    syncport->setBaudRate(QSerialPort::Baud9600);
    syncport->setDataBits(QSerialPort::Data8);
    syncport->setParity(QSerialPort::NoParity);
    syncport->setStopBits(QSerialPort::OneStop);
    syncport->setFlowControl(QSerialPort::NoFlowControl);

    if(!syncport->open(QIODevice::ReadWrite))
    {
        QMessageBox::critical(this, tr("LMRIgui App"), tr((syncport->portName() + QString(" cannot be connected!")).toStdString().c_str()));
        cancelProgram();
        return -3;
    }

    //while(syncport->isOpen())
    //{
    if(!syncport->write("e"))
    {
        QMessageBox::critical(this, tr("LMRIgui App"), tr("Cannot send data to serial port!"));
        cancelProgram();
        emit progress->canceled();
        return -4;
    };
    //syncport->close();
    //}

    pvalue = pvalue + 13;
    ui->progress->setValue(pvalue);

    for(QString arg : graargs)
    {
        qDebug() << arg;
    }

    if(ui->GRA1Check->isChecked())
    {
        graproc.start(QDir::currentPath() + QString("\\UDP_test.exe"), graargs);

        //qDebug() << QDir::currentPath();

        if(!graproc.waitForStarted())
        {
            QMessageBox::critical(this, tr("LMRIgui App"), tr("GRA1 programm not started"));
            cancelProgram();
            return -7;
        }
    }

    if(ui->GRA2Check->isChecked())
    {
        graproc2.start(QDir::currentPath() + QString("\\UDP_test.exe"), graargs2);

        if(!graproc2.waitForStarted())
        {
            QMessageBox::critical(this, tr("LMRIgui App"), tr("GRA2 programm not started"));
            cancelProgram();
            return -7;
        }
    }

    if(ui->GRA3Check->isChecked())
    {
        graproc3.start(QDir::currentPath() + QString("\\UDP_test.exe"), graargs3);

        if(!graproc3.waitForStarted())
        {
            QMessageBox::critical(this, tr("LMRIgui App"), tr("GRA2 programm not started"));
            cancelProgram();
            return -7;
        }
    }

    if(!(ui->GRA1Check->isChecked() || ui->GRA2Check->isChecked() || ui->GRA3Check->isChecked()))
    {
        graCounter->count();
    }

    return 0;
}

int MainWindow::readOutput()
{
    for(int i = 0; i < test; i++)
    {
        qDebug() << picoproc.readAll();
    }

    return 0;
}

int MainWindow::graFinished()
{
    graCounter->reset();
    graproc.close();
    graproc2.close();
    graproc3.close();

    pvalue = pvalue + 25;
    ui->progress->setValue(pvalue);


    for(QString arg : graargs)
    {
        qDebug() << arg;
    }

    semThread->start();
    tmrForRF->start();

    qDebug() << ui->OUTCheck->isChecked();

    if(ui->OUTCheck->isChecked())
        picoproc.start(QDir::currentPath() + QString("\\pico_test_00_second_copy.exe"), picoargs);
    else
        ReleaseSemaphore(semForRF, 1, NULL);

    //test = 3;
    //connect(&(this->picoproc), &QProcess::readyReadStandardOutput, this, &MainWindow::readOutput);

    return 0;
}

int MainWindow::startHackRF()
{
    tmrForRF->stop();

    hackrfproc.start(QDir::currentPath() + QString("\\hackrftrans00.exe"), hackrfargs);
    qDebug() << "startHackRF 1";

    if(!hackrfproc.waitForStarted())
    {
        QMessageBox::critical(this, tr("LMRIgui App"), tr("SDR programm not started"));
        cancelProgram();
        return -9;
    }

    qDebug() << "startHackRF 2";

    return 0;
}

int MainWindow::hackrfFinished()
{
    hackrfproc.close();

    pvalue = pvalue + 25;
    ui->progress->setValue(pvalue);

    qDebug() << "hackrfFinished 1";

    if(!ui->OUTCheck->isChecked())
    {
        pvalue = pvalue + 25;
        programFinished();
    }

    return 0;
}

int MainWindow::picoFinished()
{
    picoproc.close();
    syncport->close();

    pvalue = pvalue + 25;
    ui->progress->setValue(pvalue);

    qDebug() << "picoFinished 1";

    programFinished();

    return 0;
}

int MainWindow::programFinished()
{
    QMessageBox::information(this, tr("LMRIgui App"), tr("Program successufuly finished!"));

    tmrForRF->stop();
    graCounter->reset();

    semThread->blockSignals(true);
    semThread->terminate();
    semThread->blockSignals(false);

    picoargs.clear();
    hackrfargs.clear();
    graargs.clear();
    graargs2.clear();
    graargs3.clear();
    syncargs.clear();
    syncport->close();

    ui->progress->setEnabled(false);
    ui->RunButton->setEnabled(true);
    ui->CancelButton->setEnabled(false);
    ui->GRA2Check->setEnabled(true);
    ui->GRA3Check->setEnabled(true);

    return 0;
}

int MainWindow::runButtonPress()
{
    if(ui->GRA2Check->isChecked() && (ui->GRAFileEdit2->text()=="" || ui->IP2edit->text()==""))
    {
        QMessageBox::warning(this, tr("LMRIgui App"), tr("Please, enter all file destinations!"));
        return -1;
    }

    if(ui->GRA3Check->isChecked() && (ui->GRAFileEdit3->text()=="" || ui->IP3edit->text()==""))
    {
        QMessageBox::warning(this, tr("LMRIgui App"), tr("Please, enter all file destinations!"));
        return -1;
    }

    if(ui->OUTCheck->isChecked() && ui->OutPropFileEdit->text() != "")
    {
        QMessageBox::warning(this, tr("LMRIgui App"), tr("Please, enter all file destinations!"));
        return -1;
    }

    if(ui->SyncFileEdit->text() != "" && ((ui->GRAFileEdit->text() != "" && ui->IP1edit->text() != "") || !ui->GRA2Check->isChecked()) && ui->SDRFileEdit->text() != "")
    {   
        syncargs << ui->SyncFileEdit->text();
        graargs << ui->GRAFileEdit->text() << ui->IP1edit->text();

        if(ui->GRA2Check->isChecked())
            graargs2 << ui->GRAFileEdit2->text() << ui->IP2edit->text();
        if(ui->GRA3Check->isChecked())
            graargs3 << ui->GRAFileEdit3->text() << ui->IP3edit->text();

        hackrfargs << "-t" << ui->SDRFileEdit->text();
        hackrfargs << "-f" << ui->FreqBox->text();
        hackrfargs << "-a" << (ui->AmplCheck->isChecked() ? QString("1") : QString("0"));
        hackrfargs << "-x" << ui->GainEdit->text();

        if(ui->SampleRateBox->currentText() == "20 MHz")
        {
            hackrfargs << "-s" << "20000000";
        }
        else if(ui->SampleRateBox->currentText() == "16 MHz")
        {
            hackrfargs << "-s" << "16000000";
        }
        else if(ui->SampleRateBox->currentText() == "12.5 MHz")
        {
            hackrfargs << "-s" << "12500000";
        }
        else if(ui->SampleRateBox->currentText() == "10 MHz")
        {
            hackrfargs << "-s" << "10000000";
        }
        else if(ui->SampleRateBox->currentText() == "8 MHz")
        {
            hackrfargs << "-s" << "8000000";
        }
        else if(ui->SampleRateBox->currentText() == "2 MHz")
        {
            hackrfargs << "-s" << "2000000";
        }

        qDebug() << hackrfargs;

        picoargs << ui->OutPropFileEdit->text();

    }
    else
    {
        QMessageBox::warning(this, tr("LMRIgui App"), tr("Please, enter all file destinations!"));
        return -1;
    }

    if(true)
    {
        pvalue = 0;
        ui->progress->setEnabled(true);
        ui->progress->setValue(pvalue);
        ui->GRA2Check->setEnabled(false);
        ui->GRA3Check->setEnabled(false);
        ui->RunButton->setEnabled(false);
        ui->CancelButton->setEnabled(true);

        if(ui->SyncDebugModeCheck->isChecked())
        {
            syncargs << "--debug";
        }


        QString pnum = portInfos[ui->SerialPortBox->currentIndex()].portName().mid(3);
        syncargs << "-p" << pnum;

        if(ui->GRADebugModeCheck->isChecked())
        {
            graargs << "--debug";
        }

        if(ui->OutPropDebugModeCheck->isChecked())
        {
            picoargs << "--debug";
        }
        if(ui->BelowCheck->isChecked())
        {
            picoargs << "--below";
        }


        syncproc.start(QDir::currentPath() + QString("\\Sync.exe"), syncargs);
        syncargs.clear();

        if(!syncproc.waitForStarted())
        {
            QMessageBox::critical(this, tr("LMRIgui App"), tr("Sync not started!"));
            cancelProgram();
            return -11;
        }

        qDebug() << hackrfargs;

    }

    return 0;
}

int MainWindow::analizeButtonPress()
{
    QStringList plotargs;

    plotargs << QString("plot.py");

    plotproc.start("python.exe", plotargs);

    if(!plotproc.waitForStarted())
    {
        QMessageBox::critical(this, tr("LMRIgui App"), tr("Analize App not started!"));
        cancelProgram();
        return -11;
    }

    return 0;
}

void MainWindow::plotprocFinishedSlot()
{
    std::string output = plotproc.readAllStandardOutput().toStdString();
    qDebug() << QString("C:\\test.py") << ": " << output;
    plotproc.close();
}

MainWindow::~MainWindow()
{
    delete ui;
}
