// $Id: slots.cpp,v 1.5 2008/03/08 22:53:14 hvengel Exp $
// 
//  Lttle cms Profiler
//  Copyright (C) 1998-2001 Marti Maria
// Copyright (C) 2007 Hal Engel
//
// THIS SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
// EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
// WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
//
// IN NO EVENT SHALL THE DEVELOPERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL,
// INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
// OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
// LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
// OF THIS SOFTWARE.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// Version 1.11

#if !defined(__WIN32__) && (defined(_WIN32) || defined(WIN32))
#define __WIN32__
#endif

#include "lprofmain-priv.h"

#include <profileid.h>
#include <profileparms.h>
#include <profileparmsmon.h>
#include <monitorvalues.h>
#include <profilechecker.h>
#include <qtlcmswidgets.h>
#include "lprofmain.h"
#include <lcmsprf.h>
#include "installreffile.h"
#include "moncalcontrol.h"

#include "ui_lprofmainbase.h"

#include <QTranslator>
#include <q3buttongroup.h>
#include <qradiobutton.h>
#include <qpushbutton.h>
#include <qmessagebox.h>
#include <Q3FileDialog>
#include <QFile>

#include "vigra/imageiterator.hxx"
#include "vigra/rgbvalue.hxx"
#include "vigra/accessor.hxx"
#include "vigra/impex.hxx"
#include "vigra/stdimage.hxx"
#include "vigra/inspectimage.hxx"

struct parms_ID_data
{
    char Description[256];
    char Manufacturer[256];
    char Model[256];
    char Copyright[256];
    char Comments[256];
    cmsCIExyYTRIPLE Primaries;
    int CLUTPoints;                 // Final CLUT resolution 
    int ProfileVerbosityLevel;	    // 0=minimum, 1=additional, 2=Verbose, 3=Any suitable
    bool lUseCIECAM02;              // Use CIECAM02 for chromatic adaptation?

    cmsViewingConditions device;     // Viewing condition of source
    cmsViewingConditions PCS;        // Viewing condition of PCS

    LCMSHANDLE hDevice;              // CIECAM02 models used for adaptation
    LCMSHANDLE hPCS;                 // and viewing conditions
    int        RsplSmoothness;       // smoothing factor
    bool       lOptRGCV;
};

static parms_ID_data pdata[3];
static passPickedRGB picked;

void setData(uint i)
{
    pdata[i].CLUTPoints = sys.hdr.CLUTPoints;
    pdata[i].ProfileVerbosityLevel = sys.hdr.ProfileVerbosityLevel;
    pdata[i].RsplSmoothness = sys.RsplSmoothness;
    pdata[i].lOptRGCV =  sys.lOptRGCV;
    pdata[i].device.surround = sys.hdr.device.surround;
    pdata[i].device.La = sys.hdr.device.La;
    pdata[i].device.Yb = sys.hdr.device.Yb;
    // profile ID information
    strcpy(pdata[i].Manufacturer, sys.hdr.Manufacturer);
    strcpy(pdata[i].Model, sys.hdr.Model);
    strcpy(pdata[i].Copyright, sys.hdr.Copyright);
    strcpy(pdata[i].Description, sys.hdr.Description);
}

void lprofMain::slotLoad()
{
    // qDebug("lprofMain::slotLoad");
    zeroProgressBars();
    QString dir = lprofSettings -> readEntry(QString::fromLocal8Bit("/LPROF/Files/last_load_dir"), QDir::homeDirPath());

    fn = Q3FileDialog::getOpenFileName( dir,
                                       tr("Image files (*.gif *.png *.jpg *.bmp *.pbm *.pgm *.pnm *.sun *.tif *.tiff *.viff *.GIF *.PNG *.JPG *.BMP *.PBM *.PGM *.PNM *.SUN *.TIF *.TIFF *.VIFF)\nAll files (*.*)"),
                                          this,
                                          "",
                                          tr("Select target image"));

    if (!fn.isNull()) // return;
    {
        lprofSettings -> writeEntry(QString::fromLocal8Bit("/LPROF/Files/last_load_dir"), fn.left(fn.findRev(QString::fromLocal8Bit("/"))));

        FigEditor->clear();
        TheGrid = NULL;
        CurrentTemplate = QString::fromLocal8Bit("");
        // if ui->ProofToggle isOn turn it off
        if (ui->ProofToggle -> isOn()) ui->ProofToggle -> toggle();

        TheImage = new ImageItem(fn, ui->MonitorProfileSelector ->getFilename(),
                                 ui->InputProfileSelector->getFilename(),
                                         Canvas);
        init_marks();
    }
}

void lprofMain::slotProof()
{
    // qDebug(QString::fromLocal8Bit("lprofMain::slotProof()"));
    if (TheImage)
    {
        intent = ui->ComboBoxIntent -> currentItem();
        TheImage -> lProof = ui->ProofToggle -> isOn();

        TheImage -> Reload(fn, ui->MonitorProfileSelector ->getFilename(),
                           ui->InputProfileSelector->getFilename(),
                                   Canvas);

        Canvas->setChanged(rect());
        Canvas->update();
        ControlsToValues();
    }
    zeroProgressBars();
    // qDebug(QString::fromLocal8Bit("lprofMain::slotProof() done"));
}


// ------------------------------------------------------------------------------ Slots

void lprofMain::slotPick()
{
    if (TheImage && TheGrid)
    {
        //convert corner marks to unscaled image size
        grid_corners.putPoints (0, 4,
                                (int) (Marks.ul_x * TheImage -> sx), (int) (Marks.ul_y * TheImage -> sy),
                                 (int) (Marks.ur_x * TheImage -> sx), (int) (Marks.ur_y * TheImage -> sy),
                                  (int) (Marks.lr_x * TheImage -> sx), (int) (Marks.lr_y * TheImage -> sy),
                                   (int) (Marks.ll_x * TheImage -> sx), (int) (Marks.ll_y * TheImage -> sy));
        
        TheGrid -> Pick(ui->InputProfileSelector->getFilename(),
                        TheImage -> image,
                        TheImage -> sx, TheImage -> sy);
        
        if (clippedPatches/3.0 > patchCount / 12.5  ) // more than 8% of the patches are clipped 
            QMessageBox::warning(this, QTranslator::tr("Some Patches Clipped"),
                                 QTranslator::tr("There appear to be some clipped "
                                         "patches in your target image.  "
                                         "The number of clipped patches exceeds 8%.  "
                                         "This may result in an invalid profile.  "
                                         "Clipping is likely a severe problem for this image." ));
        else if (clippedPatches/3.0 > patchCount / 25  ) // more than 4% of the patches are clipped 
            QMessageBox::warning(this, QTranslator::tr("Some Patches Clipped"),
                                 QTranslator::tr("There appear to be some clipped "
                                         "patches in your target image.  "
                                         "The number of clipped patches exceeds 4%.  "
                                         "This may result in an invalid profile.  "
                                         "Clipping is a major problem for this image."  ));
        else if (clippedPatches/3.0 > patchCount / 50  ) // more than 2% of the patches are clipped 
            QMessageBox::warning(this, QTranslator::tr("Some Patches Clipped"),
                                 QTranslator::tr("There appear to be some clipped "
                                         "patches in your target image.  "
                                         "The number of clipped patches exceeds 2%.  "
                                         "This may result in an invalid profile.  "
                                         "Clipping is likely a problem for this image." ));
        else if (clippedPatches/3.0 > patchCount / 100  ) // more than 1% of the patches are clipped 
            QMessageBox::warning(this, QTranslator::tr("Some Patches Clipped"),
                                 QTranslator::tr("There appear to be some clipped "
                                         "patches in your target image.  "
                                         "The number of clipped patches exceeds 1%.  "
                                         "This may result in an invalid profile.  "
                                         "Clipping is likely an issue for this image." ));
        
        DumpResultsToIT8(TheGrid -> Layout);
        
        // convert back
        grid_corners.putPoints(0, 4, Marks.ul_x,  Marks.ul_y,
                               Marks.ur_x, Marks.ur_y,
                               Marks.lr_x, Marks.lr_y,
                               Marks.ll_x, Marks.ll_y);
        
        slotIsAllReady();
        
    }
    // qDebug(QString::fromLocal8Bit("lprofMain::slotPick() done"));
}

void lprofMain::tabChanged()
{
    // qDebug(QString::fromLocal8Bit("tabChanged"));
    sys.hdr.ProfilerTab = ui->TabProfiler -> currentPageIndex();
    setData(last_tab);

    last_tab = ui->TabProfiler -> currentPageIndex();
    if (last_tab == 0)
        Console = ui->ProgressConsole;
    else if (last_tab == 1)
        Console = ui->ProgressConsole_mon; 
     // profile parms
    sys.hdr.CLUTPoints = pdata[last_tab].CLUTPoints;
    sys.hdr.ProfileVerbosityLevel = pdata[last_tab].ProfileVerbosityLevel;
    sys.RsplSmoothness = pdata[last_tab].RsplSmoothness;
    sys.lOptRGCV = pdata[last_tab].lOptRGCV;
    sys.hdr.device.surround = pdata[last_tab].device.surround;
    sys.hdr.device.La = pdata[last_tab].device.La;
    sys.hdr.device.Yb = pdata[last_tab].device.Yb;

    // profile ID information
    strcpy(sys.hdr.Manufacturer, pdata[last_tab].Manufacturer);
    strcpy(sys.hdr.Model, pdata[last_tab].Model);
    strcpy(sys.hdr.Copyright, pdata[last_tab].Copyright);
    strcpy(sys.hdr.Description, pdata[last_tab].Description);

    ControlsToValues();
    setProfileIDText();
    setProfileParmsText();
    slotIsAllReady();
}

void lprofMain::OutputFileNameChangedMon()
{
    QString temp, profile;
    bool ok;

    // qDebug(QString::fromLocal8Bit("OutputFileNameChangedMon"));
    profile =  ui->OutputFileEdit_Mon -> text().mid(ui->OutputFileEdit_Mon -> text().findRev(QString::fromLocal8Bit("/")) + 1,
                                              ui->OutputFileEdit_Mon -> text().length() - ui->OutputFileEdit_Mon -> text().findRev(QString::fromLocal8Bit("/")) - 1);
    temp = lprofSettings->readEntry(QString::fromLocal8Bit("/LPROF/profile-") + profile + QString::fromLocal8Bit("/Files/MON_OUTPUT_PROFILE"), QString::null, &ok);
    if (ok)  // found entry in lprof lprofSettings
    {

        getConfigParmsandID(profile);

        ok = lprofSettings->readBoolEntry(QString::fromLocal8Bit("/LPROF/profile-") +  
                                          profile + 
                                          QString::fromLocal8Bit("/boolians/Course"));
        ui->RadioCoarse->setChecked(ok);
        ui->RadioAccurate->setChecked(!ok);

        if (!ok)
        {
            ui->MonMeasurementSheet -> setFilename( lprofSettings->readEntry(QString::fromLocal8Bit("/LPROF/profile-") + profile + QString::fromLocal8Bit("/Files/MEASUREMENT_SHEET") ));
            ui->MonCalibrationSheet -> setFilename( lprofSettings->readEntry(QString::fromLocal8Bit("/LPROF/profile-") + profile + QString::fromLocal8Bit("/Files/MON_CAL_SHEET") ));
        }
        else
        { 
            monitorValues.items.wppos = lprofSettings->readNumEntry(QString::fromLocal8Bit("/LPROF/profile-") + profile + QString::fromLocal8Bit("/numbers/whitePpos") );
            monitorValues.items.ppos = lprofSettings->readNumEntry(QString::fromLocal8Bit("/LPROF/profile-") + profile + QString::fromLocal8Bit("/numbers/primePos") );

            monitorValues.items.rgamma = lprofSettings->readDoubleEntry(QString::fromLocal8Bit("/LPROF/profile-") + profile + QString::fromLocal8Bit("/numbers/rgamma") );
            monitorValues.items.ggamma = lprofSettings->readDoubleEntry(QString::fromLocal8Bit("/LPROF/profile-") + profile + QString::fromLocal8Bit("/numbers/ggamma") );
            monitorValues.items.bgamma = lprofSettings->readDoubleEntry(QString::fromLocal8Bit("/LPROF/profile-") + profile + QString::fromLocal8Bit("/numbers/bgamma") );

            sys.hdr.Primaries.Red.x = lprofSettings->readDoubleEntry(QString::fromLocal8Bit("/LPROF/profile-") + profile + QString::fromLocal8Bit("/numbers/red_x"));
            sys.hdr.Primaries.Red.y = lprofSettings->readDoubleEntry(QString::fromLocal8Bit("/LPROF/profile-") + profile + QString::fromLocal8Bit("/numbers/red_y") );
            sys.hdr.Primaries.Green.x = lprofSettings->readDoubleEntry(QString::fromLocal8Bit("/LPROF/profile-") +profile + QString::fromLocal8Bit("/numbers/green_x") );
            sys.hdr.Primaries.Green.y = lprofSettings->readDoubleEntry(QString::fromLocal8Bit("/LPROF/profile-") + profile + QString::fromLocal8Bit("/numbers/green_y") );
            sys.hdr.Primaries.Blue.x = lprofSettings->readDoubleEntry(QString::fromLocal8Bit("/LPROF/profile-") + profile + QString::fromLocal8Bit("/numbers/blue_x") );
            sys.hdr.Primaries.Blue.y = lprofSettings->readDoubleEntry(QString::fromLocal8Bit("/LPROF/profile-") + profile + QString::fromLocal8Bit("/numbers/blue_y") );

            monitorValues.items.temp = lprofSettings->readNumEntry(QString::fromLocal8Bit("/LPROF/profile-") + profile + QString::fromLocal8Bit("/numbers/whitePoint") );
            monitorValues.items.valid_mon = FALSE;
            monitorValues.items.linked = lprofSettings->readBoolEntry(QString::fromLocal8Bit("/LPROF/profile-") +  profile + QString::fromLocal8Bit("/boolians/linked") );

            if (sys.Prelinearization[0]) cmsFreeGamma(sys.Prelinearization[0]);
            if (sys.Prelinearization[1]) cmsFreeGamma(sys.Prelinearization[1]);
            if (sys.Prelinearization[2]) cmsFreeGamma(sys.Prelinearization[2]);

            sys.Prelinearization[0] = cmsBuildGamma(256,       
                    lprofSettings->readDoubleEntry(QString::fromLocal8Bit("/LPROF/profile-") + 
                                                   profile + 
                                                   QString::fromLocal8Bit("/numbers/rgamma")));
            sys.Prelinearization[1] = cmsBuildGamma(256, 
                    lprofSettings->readDoubleEntry(QString::fromLocal8Bit("/LPROF/profile-") + 
                                                   profile + 
                                                   QString::fromLocal8Bit("/numbers/ggamma")));
            sys.Prelinearization[2] = cmsBuildGamma(256, 
                    lprofSettings->readDoubleEntry(QString::fromLocal8Bit("/LPROF/profile-") + 
                                                   profile + 
                                                   QString::fromLocal8Bit("/numbers/bgamma")));
        }
        setData(1);

        ControlsToValues();
        setProfileIDText();
        setProfileParmsText();
    }

    slotIsAllReady();
}

void lprofMain::OutputFileNameChanged()
{
    // qDebug("lprofMain::OutputFileNameChanged()");
    QString temp, profile, template_file, target;
    bool ok;

    // qDebug("lprofMain::OutputFileNameChanged");
    profile =  ui->OutputFileEdit -> text().mid(ui->OutputFileEdit -> text().findRev(QString::fromLocal8Bit("/")) + 1,
                                          ui->OutputFileEdit -> text().length() - ui->OutputFileEdit -> text().findRev(QString::fromLocal8Bit("/")) - 1);
    
    temp = lprofSettings->readEntry(QString::fromLocal8Bit("/LPROF/profile-")  + 
                                    profile + 
                                    QString::fromLocal8Bit("/Files/OUTPUT_PROFILE"), 
                                    QString::null, &ok);
    
    if (ok)  // found entry in lprofSettings
    {
        fn = lprofSettings->readEntry(QString::fromLocal8Bit("/LPROF/profile-") + 
                                      profile + 
                                      QString::fromLocal8Bit("/Files/IT8Image") );
        
        target = lprofSettings->readEntry(QString::fromLocal8Bit("/LPROF/profile-") + 
                                          profile + 
                                          QString::fromLocal8Bit("/numbers/TARGET_Filename") );

        if (targetList->count() > 0)
            for (uint i=0; i<=targetList->count()-1; i++)
        {
            if (targetList->at(i)->targetFile == target)
            {
                ui->SelectTemplate->setCurrItem(targetList->at(i)->tempPos);
                ui->TargetSelector->setCurrItem(targetList->at(i)->targPos);
            }
        }
        getConfigParmsandID(profile);

        ControlsToValues();
        setProfileIDText();
        setProfileParmsText();
        setData(0);

        FigEditor->clear();
        if (QFile::exists(fn))  // only if image exists
        {
            Marks.ur_x = lprofSettings->readNumEntry(QString::fromLocal8Bit("/LPROF/profile-")  +  
                    profile + 
                    QString::fromLocal8Bit("/numbers/ur_x"));
            Marks.ur_y = lprofSettings->readNumEntry(QString::fromLocal8Bit("/LPROF/profile-")  +  
                    profile + 
                    QString::fromLocal8Bit("/numbers/ur_y"));
            Marks.lr_x = lprofSettings->readNumEntry(QString::fromLocal8Bit("/LPROF/profile-") + 
                    profile + 
                    QString::fromLocal8Bit("/numbers/lr_x"));
            Marks.lr_y = lprofSettings->readNumEntry(QString::fromLocal8Bit("/LPROF/profile-") + 
                    profile + 
                    QString::fromLocal8Bit("/numbers/lr_y"));
            Marks.ul_x = lprofSettings->readNumEntry(QString::fromLocal8Bit("/LPROF/profile-") + 
                    profile + 
                    QString::fromLocal8Bit("/numbers/ul_x"));
            Marks.ul_y = lprofSettings->readNumEntry(QString::fromLocal8Bit("/LPROF/profile-") + 
                    profile + 
                    QString::fromLocal8Bit("/numbers/ul_y"));
            Marks.ll_x = lprofSettings->readNumEntry(QString::fromLocal8Bit("/LPROF/profile-") + 
                    profile + 
                    QString::fromLocal8Bit("/numbers/ll_x"));
            Marks.ll_y = lprofSettings->readNumEntry(QString::fromLocal8Bit("/LPROF/profile-") + 
                    profile + 
                    QString::fromLocal8Bit("/numbers/ll_y"));

            TheGrid = NULL;
            CurrentTemplate = QString::fromLocal8Bit("");
            // if ProofTogle isON turn it off.
            if (ui->ProofToggle -> isOn()) ui->ProofToggle -> toggle();
            TheImage = new ImageItem(fn, ui->MonitorProfileSelector ->getFilename(),
                                     ui->InputProfileSelector->getFilename(),
                                             Canvas);
            // open the image file
            // Reload();
            // place corner markers and pick
            grid_corners.putPoints(0, 4, Marks.ul_x,  Marks.ul_y,
                                   Marks.ur_x, Marks.ur_y,
                                   Marks.lr_x, Marks.lr_y,
                                   Marks.ll_x, Marks.ll_y);
            AddTemplate();
           // check to see if all corners are marked and it is time to place full template and pick

            corners_ready=TRUE;
            slotPick();
        }
    }
    slotIsAllReady();
    // qDebug("lprofMain::OutputFileNameChanged() done");
}

void lprofMain::slotSelectOutputFile()
{
    // qDebug("lprofMain::slotSelectOutputFile");

    QString fn = Q3FileDialog::getSaveFileName( outprofile,
                                               tr("icc profiles (*.icc *.icm)\nAll files (*.*)"),
                                               this,
                                               "",
                                               tr("Select output profile filename"));
    if (fn != QString::null)
    {
        SetOutputFile(fn);
    }
    /* TRANSLATOR Text displayed in the messages widget */
    ConsolePrintf("select file name", 0, 'c');
    slotIsAllReady();
}

void lprofMain::slotIsAllReady()
{
    // qDebug("lprofMain::slotIsAllReady");
    // check what type of profile is currently being worked on
    // and decide if the GoButton should be enabled
    zeroProgressBars();
    switch (ui->TabProfiler -> currentPageIndex()) {

        case 0:
            if (ui->TargetSelector -> getFilename() == QString::null)
                SetGoButton(tr("You still have to select the target reference file"), FALSE);
            else if (ui->OutputFileEdit -> text() == QString::fromLocal8Bit(""))
                SetGoButton(tr("You need to specify output profile!"), FALSE);
            else
            {
                    // OutputFileNameChanged();
                if (!(Marks.ul_x>0 && Marks.ur_x>0 && Marks.ll_x>0 && Marks.lr_x>0))
                    SetGoButton(tr("You need to load a target image and select it's corners!"), FALSE);
                else
                    SetGoButton(tr("Ready to GO!"), TRUE);
            }
            break;
        case 1:
            if (ui->OutputFileEdit_Mon -> text().length() == 0)
                SetGoButton_2(tr("You need to specify output profile!"), FALSE);
            else
            {
                    // OutputFileNameChanged();
                if (ui->RadioCoarse->isChecked())
                {
                    if (monitorValues.items.valid_mon)
                        SetGoButton_2(tr("Ready to GO!"), TRUE);
                    else
                        SetGoButton_2(tr("You need to enter monitor values."), FALSE);
                }
                else if (ui->RadioAccurate -> isOn())
                    if (ui->radioButtonCandMFile -> isOn())
                {
                    if (ui->MonMeasurementSheet->getFilename() == QString::fromLocal8Bit(""))
                        SetGoButton_2(tr("You need to specify a measurement sheet!"), FALSE);
                    else
                        SetGoButton_2(tr("Ready to GO!"), TRUE);
                }
                        // FIXME more work needed to make sure
                        // the create profile button is enabled only
                        // when a valid measurement and calibration
                        // have been created by the user
                else if (monMeasOK && !monCalOK && ui->MonCalibrationSheet->getFilename() == QString::fromLocal8Bit(""))
                    SetGoButton_2(tr("Ready to GO!"), TRUE);
                else if (monMeasOK && monCalOK)
                    SetGoButton_2(tr("Ready to GO!"), TRUE);
                else if (ui->MonMeasurementSheet->getFilename() == QString::fromLocal8Bit(""))
                    SetGoButton_2(tr("You need to specify a measurement sheet!"), FALSE);
                else
                    SetGoButton_2(tr("Ready to GO!"), TRUE);
            }
            break;

            default:; // if not on a profileing tab then do nothing

    }
}


void lprofMain::Go_button_clicked()
{ 
    QString fn;
    // qDebug("lprofMain::Go_button_clicked");
    switch (ui->TabProfiler -> currentPageIndex()) 
    {
    
        case 0:
            fn = ui->OutputFileEdit -> text();
            if (validateFileName(fn))
            {
                if (fn != ui->OutputFileEdit -> text()) ui->OutputFileEdit -> setText(fn); 
                ProgBar = ui->ProgressBar;
                Gauger("Init...", 0, 100, 0);
                ControlsToValues();
                saveProfileDetails();
                DoScannerProfile(); 
            }
            break;
        case 1:
            fn = ui->OutputFileEdit_Mon -> text();
            if (validateFileName(fn))
            {
                if (fn != ui->OutputFileEdit_Mon -> text()) ui->OutputFileEdit_Mon -> setText(fn); 
                ProgBar = ui->ProgressBar_2;
                Gauger("Init...", 0, 100, 0);
                ControlsToValues();
                saveProfileDetails();
                DoMonitorProfile(); 
            }
            break;
    
            default:;  // if not on a profiling tab do nothing
    }
}


void lprofMain::slotTargetChanged()
{
    // qDebug("lprofMain::slotTargetChanged");

    QString TargetFile = ui->TargetSelector -> getFilename();

    if (TargetFile == QString::null) return;

    LCMSHANDLE hIT8 = cmsxIT8LoadFromFile(TargetFile.local8Bit());
    if (hIT8 == NULL) return;

    cmsxIT8Free(hIT8);
    slotIsAllReady();

}

void lprofMain::slotUpdateProfileParmsText()
{
    // qDebug("lprofMain::slotUpdateProfileParmsText()");
    setProfileParmsText();
    zeroProgressBars();
}

void lprofMain::setProfileParmsText()
{
    QString Buff, temp;
    // qDebug("setProfileParmsText");
    QString
       res = lprofMain::tr("Resolution (CLUT points)"),
       matrix = lprofMain::tr("Matrix/TRC profile - no CLUT"),
       verb1 = lprofMain::tr("Profile verbosity: Only required tags"),
       verb2 = lprofMain::tr("Profile verbosity: Store additional tags"),
       verb3 = lprofMain::tr("Profile verbosity: Store anything"),
       reg = lprofMain::tr("Regression:"),
       sm = lprofMain::tr("Smoothness:"),
       autoSm = lprofMain::tr("Auto smoothness with offset:"),
       manSm = lprofMain::tr("Manual smoothness factor:"),
       dev = lprofMain::tr("Deviation:"),
       capav4 = lprofMain::tr("     Captured Average surround (>4)"),
       capav = lprofMain::tr("     Captured Average surround"),
       capdim = lprofMain::tr("     Captured Dim surround"),
       capdark = lprofMain::tr("     Captured Dark surround"),
       capcut = lprofMain::tr("     Captured Cutsheet surround"),
       monav4 = lprofMain::tr("     Display Average surround (>4)"),
       monav = lprofMain::tr("     Display Average surround"),
       mondim = lprofMain::tr("     Display Dim surround"),
       mondark = lprofMain::tr("     Display Dark surround"),
       moncut = lprofMain::tr("     Display Cutsheet surround"),
       // lb = lprofMain::tr("Linear Bradford "),
       pcsav4 = lprofMain::tr("     PCS Average surround (>4)"),
       pcsav = lprofMain::tr("     PCS Average surround"),
       pcsdim = lprofMain::tr("     PCS Dim surround"),
       pcsdark = lprofMain::tr("     PCS Dark surround"),
       pcscut = lprofMain::tr("     PCS Cutsheet surround"),
       capLa = lprofMain::tr("     Captured a:"),
       capYb = lprofMain::tr("     Captured Yb:"),
       monLa = lprofMain::tr("     Display La:"),
       monYb = lprofMain::tr("     Display Yb:"),
       pcsLa = lprofMain::tr("     PCS La:"),
       pcsYb = lprofMain::tr("     PCS Yb:"),
       VC = lprofMain::tr("Viewing Conditions:"),
       WPH = lprofMain::tr("White Point Handling"),
       diffuse = lprofMain::tr("Diffuse reflector/illuminant color"),
       dmin = lprofMain::tr("Dmin taget patch"),
       adopt = lprofMain::tr("Adopt device white point"),
       rgb = lprofMain::tr("RGB"),
       lab = lprofMain::tr("L*a*b*"),
       xyz = lprofMain::tr("XYZ"),
       lumScaling = lprofMain::tr("Luminance Scaling"),
       loc = lprofMain::tr("Location"),
       dontScale = lprofMain::tr("Do not scale"),
       scaleClip = lprofMain::tr("Scale to max RGB clip"),
       scaleDontClip = lprofMain::tr("Scale to max RGB don't clip");
             
   if (sys.hdr.ProfilerTab == 0)  // camera/scanner profiler
    {
        if (sys.hdr.CLUTPoints>0)
        {
            Buff.sprintf(":  %i", sys.hdr.CLUTPoints );
            ui->textEditProfileParms->setText(res + Buff);
        }
        else
        {
            ui->textEditProfileParms->setText(matrix);
        }

        switch (sys.hdr.ProfileVerbosityLevel)
        {
            case 0:
                ui->textEditProfileParms->insertParagraph(verb1, 3);
                break;
            case 1:
                ui->textEditProfileParms->insertParagraph(verb2, 3);
                break;
            case 2:
                ui->textEditProfileParms->insertParagraph(verb3, 3);
                break;
        }
        ui->textEditProfileParms->insertParagraph(reg, 4);

        if (sys.lOptRGCV)
            Buff = QString::fromLocal8Bit("     ") + autoSm + Buff.sprintf(" %i" ,sys.RsplSmoothness);
        else
            Buff = QString::fromLocal8Bit("     ") + manSm + Buff.sprintf(" %i" ,sys.RsplSmoothness);

        ui->textEditProfileParms->insertParagraph(Buff, 5);


        ui->textEditProfileParms->insertParagraph(VC, 6);

        switch (sys.hdr.device.surround)
        {
            case 0:
                ui->textEditProfileParms->insertParagraph(capav4,7);
                break;
            case 1:
                ui->textEditProfileParms->insertParagraph(capav, 7);
                break;
            case 2:
                ui->textEditProfileParms->insertParagraph(capdim, 7);
                break;
            case 3:
                ui->textEditProfileParms->insertParagraph(capdark, 7);
                break;
            case 4:
                ui->textEditProfileParms->insertParagraph(capcut, 7);
                break;
            default:
                ui->textEditProfileParms->insertParagraph(capav, 7);
        }
        Buff = capLa +  Buff.sprintf(" %g", sys.hdr.device.La); ui->textEditProfileParms->insertParagraph(Buff, 8);
        Buff = capYb +  Buff.sprintf(" %g", sys.hdr.device.Yb);
        ui->textEditProfileParms->insertParagraph(Buff, 8);

        switch (sys.hdr.PCS.surround)
        {
            case 0:
                ui->textEditProfileParms->insertParagraph(pcsav4,9);
                break;
            case 1:
                ui->textEditProfileParms->insertParagraph(pcsav, 9);
                break;
            case 2:
                ui->textEditProfileParms->insertParagraph(pcsdim, 9);
                break;
            case 3:
                ui->textEditProfileParms->insertParagraph(pcsdark, 9);
                break;
            case 4:
                ui->textEditProfileParms->insertParagraph(pcscut, 9);
                break;
            default:
                ui->textEditProfileParms->insertParagraph(pcsav, 9);
        }

        Buff = pcsLa +  Buff.sprintf(" %g", sys.hdr.PCS.La); ui->textEditProfileParms->insertParagraph(Buff, 10);
        Buff = pcsYb +  Buff.sprintf(" %g", sys.hdr.PCS.Yb);
        ui->textEditProfileParms->insertParagraph(Buff, 11);

        Buff = WPH + QString::fromLocal8Bit(":");
        ui->textEditProfileParms->insertParagraph(Buff, 11);
        Buff = QString::fromLocal8Bit("    ") + loc + QString::fromLocal8Bit(": ");
        switch (sys.hdr.WhitePointParams.location)
        {
            case WP_LOC_ILLUMINANT:
                Buff = Buff + diffuse;
                break;
            case WP_LOC_DMIN:
                Buff = Buff + dmin;
                break;
            case WP_LOC_RGB_255:
                Buff = Buff + adopt;
                break;
            case WP_LOC_RGB:
                Buff = Buff + tr(" R:") +
                        Buff.sprintf(" %5.2f", sys.hdr.WhitePointParams.RGB[0]);
                Buff = Buff + tr(" G:") +
                        Buff.sprintf(" %5.2f", sys.hdr.WhitePointParams.RGB[1]);
                Buff = Buff + tr(" B:") +
                        Buff.sprintf(" %5.2f", sys.hdr.WhitePointParams.RGB[2]);
                break;
            case WP_LOC_LAB:
                Buff = Buff + tr("L*:") +
                        Buff.sprintf(" %5.2f", sys.hdr.WhitePointParams.Lab.L);
                Buff = Buff + tr(" a*:") +
                        Buff.sprintf(" %5.2f", sys.hdr.WhitePointParams.Lab.a);
                Buff = Buff + tr(" b*:") +
                        Buff.sprintf(" %5.2f", sys.hdr.WhitePointParams.Lab.b);
                break;
            case WP_LOC_XYZ:
                Buff = Buff + tr("X:") +
                        Buff.sprintf(" %5.2f", sys.hdr.WhitePointParams.XYZ.X);
                Buff = Buff + tr(" Y:") +
                        Buff.sprintf(" %5.2f", sys.hdr.WhitePointParams.XYZ.Y);
                Buff = Buff + tr(" Z:") +
                        Buff.sprintf(" %5.2f", sys.hdr.WhitePointParams.XYZ.Z);
                break;
        }
        ui->textEditProfileParms->insertParagraph(Buff, 12);

        Buff = QString::fromLocal8Bit("    ") + lumScaling + QString::fromLocal8Bit(": ");
        switch (sys.hdr.WhitePointParams.scale)
        {
            case WP_SCALE_NONE:
                Buff = Buff + dontScale;
                break;
            case WP_SCALE_RGB_255_CLIP:
                Buff = Buff + scaleClip;
                break;
            case WP_SCALE_RGB_255_DONTCLIP:
                Buff = Buff + scaleDontClip;
                break;
        }
        ui->textEditProfileParms->insertParagraph(Buff, 13);
    }

    else if (sys.hdr.ProfilerTab == 1)  // monitor profiler
    {
    // qDebug("monitor profile arms update");
        if (sys.hdr.CLUTPoints>0)
        {
            Buff.sprintf(":  %i", sys.hdr.CLUTPoints );
            ui->textEditProfileParms_mon->setText(res + Buff);
        }
        else
        {
            ui->textEditProfileParms_mon->setText(matrix);
        }

        switch (sys.hdr.ProfileVerbosityLevel)
        {
            case 0:
                ui->textEditProfileParms_mon->insertParagraph(verb1, 3);
                break;
            case 1:
                ui->textEditProfileParms_mon->insertParagraph(verb2, 3);
                break;
            case 2:
                ui->textEditProfileParms_mon->insertParagraph(verb3, 3);
                break;
        }
        ui->textEditProfileParms_mon->insertParagraph(VC, 4);
        switch (sys.hdr.device.surround)
        {
            case 0:
                ui->textEditProfileParms_mon->insertParagraph(monav4,5);
                break;
            case 1:
                ui->textEditProfileParms_mon->insertParagraph(monav, 5);
                break;
            case 2:
                ui->textEditProfileParms_mon->insertParagraph(mondim, 5);
                break;
            case 3:
                ui->textEditProfileParms_mon->insertParagraph(mondark, 5);
                break;
            case 4:
                ui->textEditProfileParms_mon->insertParagraph(moncut, 5);
                break;
            default:
                ui->textEditProfileParms_mon->insertParagraph(monav, 5);
        }
        Buff = monLa +  Buff.sprintf(" %g", sys.hdr.device.La); ui->textEditProfileParms_mon->insertParagraph(Buff, 6);
        Buff = monYb +  Buff.sprintf(" %g", sys.hdr.device.Yb);
        ui->textEditProfileParms_mon->insertParagraph(Buff, 6);

        switch (sys.hdr.PCS.surround)
        {
            case 0:
                ui->textEditProfileParms_mon->insertParagraph(pcsav4,7);
                break;
            case 1:
                ui->textEditProfileParms_mon->insertParagraph(pcsav, 7);
                break;
            case 2:
                ui->textEditProfileParms_mon->insertParagraph(pcsdim, 7);
                break;
            case 3:
                ui->textEditProfileParms_mon->insertParagraph(pcsdark, 7);
                break;
            case 4:
                ui->textEditProfileParms_mon->insertParagraph(pcscut, 7);
                break;
            default:
                ui->textEditProfileParms_mon->insertParagraph(pcsav, 7);
        }

        Buff = pcsLa +  Buff.sprintf(" %g", sys.hdr.PCS.La); ui->textEditProfileParms_mon->insertParagraph(Buff, 8);
        Buff = pcsYb +  Buff.sprintf(" %g", sys.hdr.PCS.Yb);
        ui->textEditProfileParms_mon->insertParagraph(Buff, 8);
    }
}

void lprofMain::setProfileIDText()
{
    // qDebug("lprofMain::setProfileIDText");
    zeroProgressBars();
    if (sys.hdr.ProfilerTab == 0)  // camera/scanner profiler
    {
        ui->textEditProfileID->setText( tr("File_Name: "));
        ui->textEditProfileID->moveCursor(Q3TextEdit::MoveDown, 0);
        ui->textEditProfileID->moveCursor(Q3TextEdit::MoveLineEnd, 0);
        ui->textEditProfileID->insert(QString::fromLocal8Bit(sys.hdr.OutputProfileFile));
        ui->textEditProfileID->insertParagraph(tr("Description: "), 3);
        ui->textEditProfileID->moveCursor(Q3TextEdit::MoveDown, 0);
        ui->textEditProfileID->moveCursor(Q3TextEdit::MoveLineEnd, 0);
        ui->textEditProfileID->insert(QString::fromLocal8Bit(sys.hdr.Description));
        ui->textEditProfileID->insertParagraph( tr("Model: "), 5);
        ui->textEditProfileID->moveCursor(Q3TextEdit::MoveDown, 0);
        ui->textEditProfileID->moveCursor(Q3TextEdit::MoveLineEnd, 0);
        ui->textEditProfileID->insert(QString::fromLocal8Bit(sys.hdr.Model));
        ui->textEditProfileID->insertParagraph(tr("Manufacturer: "), 7);
        ui->textEditProfileID->moveCursor(Q3TextEdit::MoveDown, 0);
        ui->textEditProfileID->moveCursor(Q3TextEdit::MoveLineEnd, 0);
        ui->textEditProfileID->insert(QString::fromLocal8Bit(sys.hdr.Manufacturer));
        ui->textEditProfileID->insertParagraph(tr("Copyright: "), 9);
        ui->textEditProfileID->moveCursor(Q3TextEdit::MoveDown, 0);
        ui->textEditProfileID->moveCursor(Q3TextEdit::MoveLineEnd, 0);
        ui->textEditProfileID->insert(QString::fromLocal8Bit(sys.hdr.Copyright));
    }
    if (sys.hdr.ProfilerTab == 1)  // monitor profiler
    {
        ui->textEditProfileID_mon->setText( tr("File_Name: "));
        ui->textEditProfileID_mon->moveCursor(Q3TextEdit::MoveDown, 0);
        ui->textEditProfileID_mon->moveCursor(Q3TextEdit::MoveLineEnd, 0);
        ui->textEditProfileID_mon->insert(QString::fromLocal8Bit(sys.hdr.mon_profile_file_name));
        ui->textEditProfileID_mon->insertParagraph(tr("Description: "), 3);
        ui->textEditProfileID_mon->moveCursor(Q3TextEdit::MoveDown, 0);
        ui->textEditProfileID_mon->moveCursor(Q3TextEdit::MoveLineEnd, 0);
        ui->textEditProfileID_mon->insert(QString::fromLocal8Bit(sys.hdr.Description));
        ui->textEditProfileID_mon->insertParagraph( tr("Model: "), 5);
        ui->textEditProfileID_mon->moveCursor(Q3TextEdit::MoveDown, 0);
        ui->textEditProfileID_mon->moveCursor(Q3TextEdit::MoveLineEnd, 0);
        ui->textEditProfileID_mon->insert(QString::fromLocal8Bit(sys.hdr.Model));
        ui->textEditProfileID_mon->insertParagraph(tr("Manufacturer: "), 7);
        ui->textEditProfileID_mon->moveCursor(Q3TextEdit::MoveDown, 0);
        ui->textEditProfileID_mon->moveCursor(Q3TextEdit::MoveLineEnd, 0);
        ui->textEditProfileID_mon->insert(QString::fromLocal8Bit(sys.hdr.Manufacturer));
        ui->textEditProfileID_mon->insertParagraph(tr("Copyright: "), 9);
        ui->textEditProfileID_mon->moveCursor(Q3TextEdit::MoveDown, 0);
        ui->textEditProfileID_mon->moveCursor(Q3TextEdit::MoveLineEnd, 0);
        ui->textEditProfileID_mon->insert(QString::fromLocal8Bit(sys.hdr.Copyright));
    }
}


void lprofMain::slotChangeStrategy()
{
    // qDebug("lprofMain::setProfileIDText");
    ui->frameSetMonitorValues->setEnabled(ui->RadioCoarse->isChecked());
    ui->buttonGroupMeasurements->setEnabled(ui->RadioAccurate->isChecked());
    slotMeasureTypeChanged();
    ControlsToValues();
    slotIsAllReady();
}

void lprofMain::slotTargetRefChanged()
{
    // qDebug("lprofMain::slotTargetRefChanged");
    zeroProgressBars();
    if (targetList -> count() > 0)  // taragetList has items and we are now at the begining
    {
        for (int i=0; i<targetList->count(); i++)
        {
            if (targetList->at(i)->targPos == ui->TargetSelector->getCurrItem())
            {
                ui->SelectTemplate->setCurrItem(targetList->at(i)->tempPos);
                break;
            }
        }
    }
    // qDebug("lprofMain::slotTargetRefChanged done");
}

// interfaces to other dialogs

void lprofMain::ProfChecker_clicked()
{
    // qDebug("lprofMain::profChecker_clicked");
    zeroProgressBars();
    QString temp_measurement, temp_Output, Mon_temp_measure, Mon_temp_cal;

    ControlsToValues();
    temp_measurement= QString::fromLocal8Bit(sys.hdr.MeasurementSheet);
    temp_Output = QString::fromLocal8Bit(sys.hdr.OutputProfileFile);
    Mon_temp_measure = QString::fromLocal8Bit(sys.hdr.MonMeasurementSheet);
    Mon_temp_cal = QString::fromLocal8Bit(sys.hdr.MonCalibrationSheet);

    switch (lprofMain::ui->TabProfiler -> currentPageIndex())
    {
        case 0:  break;
        case 1:  if (ui->RadioCoarse->isChecked())
                 {
                    strcpy( sys.hdr.MonMeasurementSheet, "");
                 }
                 strcpy(sys.hdr.OutputProfileFile, sys.hdr.MonOutputProfileFile);
                 strcpy(sys.hdr.MeasurementSheet, sys.hdr.MonMeasurementSheet);
                 break;

        default:;  // if not on a profiling tab do nothing
    }

    ProfileChecker check(this);
    if (dsizes.profchH > 0 && dsizes.profchW > 0)
        check.resize(dsizes.profchW, dsizes.profchH);
    check.show();
    check.exec();
    strcpy(sys.hdr.MonMeasurementSheet, Mon_temp_measure.toLocal8Bit());
    strcpy(sys.hdr.MeasurementSheet, temp_measurement.toLocal8Bit());
    strcpy(sys.hdr.OutputProfileFile, temp_Output.toLocal8Bit());
    strcpy(sys.hdr.MonCalibrationSheet, Mon_temp_cal.toLocal8Bit());
}

void lprofMain::ProfIDpushButton_clicked()
{
    // qDebug("lprofMain::ProfIDButton_clicked");
    ProfileID profID(this);
    profID.setModal(true);
    if (dsizes.profidH > 0 && dsizes.profidW > 0)
        profID.resize(dsizes.profidW, dsizes.profidH);
    profID.exec();
    
    switch (lprofMain::ui->TabProfiler -> currentPageIndex())
    {
        case 0:  
            ui->OutputFileEdit -> setText(QString::fromLocal8Bit(sys.hdr.OutputProfileFile));
            break;
        case 1:  
            ui->OutputFileEdit_Mon -> setText(QString::fromLocal8Bit(sys.hdr.mon_profile_file_name));
            break;

            default:;  // if not on a profiling tab do nothing
    }

    setProfileIDText();
    slotIsAllReady();
}

void lprofMain::ProfileParmsbutton()
{
     // qDebug("lprofMain::ProfileParmsbutton");
    if (ui->TabProfiler -> currentPageIndex() == 0)
    {   // camera/scanner profile parms
        emit showProfileParms();
    }
    else if (ui->TabProfiler -> currentPageIndex() == 1)
    {   // display profile parms
        ProfileParmsMon ParmsMon(this);
        if (dsizes.profparmsmonH > 0 && dsizes.profparmsmonW > 0)
            ParmsMon.resize(dsizes.profparmsmonW, dsizes.profparmsmonH);
        ParmsMon.exec();
        setProfileParmsText();
    }
    slotIsAllReady();
}


void lprofMain::monitorvalues_clicked()
{
    // qDebug("lprofMain::monitorvalues_clicked");

    MonitorValues monVal(this);
    if (dsizes.monvalH > 0 && dsizes.monvalW > 0)
        monVal.resize(dsizes.monvalW, dsizes.monvalH);
    // monVal.show();
    monVal.exec();
    slotIsAllReady();
}

void lprofMain::slotInstallReference()
{
    // qDebug("lprofMain::ProfIDButton_clicked");
    
    zeroProgressBars();

    refinstOK = false;
    InstallRefFile reffile(this);
    reffile.setModal(true);
    if (dsizes.reffileH > 0 && dsizes.reffileW > 0)
        reffile.resize(dsizes.reffileW, dsizes.reffileH);
    reffile.show();
    reffile.exec();

    if (refinstOK)
    {

        init_targetlist();
        slotTargetRefChanged();
        slotIsAllReady();
    }
}

void lprofMain::setRGBpatchValues()
{
    SelectWPpatch = false;

    double mult;
    
    zeroProgressBars();

    vigra::DRGBImage in(image_data->width(), image_data->height());
    vigra::importImage(*image_data, destImage(in));
    vigra::DRGBImage::Iterator point=in.upperLeft();

    if (uint8lprof) mult=1.0;
    else if (int16lprof) mult= 255.0/65535.0;
    else if (int32lprof) mult = 255.0/4294967295.0;
    else mult = 255.0;  // floating point type images

    // Ok, take

    Statistic r, g, b;  // These are doubles


    double sx = (double) in.width() / measure_view_H;
    double sy = (double) in.height() / measure_view_V;
    int xstart = int(double(WPHotZone.x()) * sx);
    int ystart = int(double(WPHotZone.y()) * sy);
    int xsize  = int(double(WPHotZone.width()) * sx);
    int ysize  = int(double(WPHotZone.height()) * sy);

    if ((xstart < 0) || (ystart < 0) ||
         ((xstart + xsize) > in.width()) ||
         ((ystart + ysize > in.height())))
    {
        qDebug("coordinates are not in range");
        // continue;
    }

    double rv;
    double gv;
    double bv;
    int npixels;

    for (int i = npixels = 0; i < ysize; i++)
    {
        for (int j=0; j < xsize; j++)
        {
            rv = point(xstart+j, ystart+i).red();
            gv = point(xstart+j, ystart+i).green();
            bv = point(xstart+j, ystart+i).blue();
           // Fix for VIGRA bug
            if (int16lprof)
            {
               // This code is a work around for a bug in VIGRA
                if (rv < 0.0)rv = rv + 65536.0;
                if (gv < 0.0) gv = gv + 65536.0;
                if (bv < 0.0) bv = bv + 65536.0;
            }
            else if (int32lprof)
            {
               // This code is a work around for a bug in VIGRA
                if (rv < 0.0) rv = rv + 4294967296.0;
                if (gv < 0.0) gv = gv + 4294967296.0;
                if (bv < 0.0) bv = bv + 4294967296.0;
            }
           // if (rv*mult > 255.0 || rv*mult<0.0)
           //  qDebug("red is out of range");
            r.Add(rv*mult); g.Add(gv*mult); b.Add(bv*mult);
            npixels++;
        }
    }

    picked.RGB[0] = r.Mean();
    picked.RGB[1] = g.Mean();
    picked.RGB[2] = b.Mean();
    emit showProfileParms();
}

void lprofMain::slotPickRGBPatch()
{

    zeroProgressBars();
    QMessageBox mb( QTranslator::tr("Select white point area from target."),
                    QTranslator::tr("Bring the main LProf window into focus and use the mouse to select the image area to be used to calulate the white point.  Click on the upper left and then the lower right corners of the area to be used for calulating the white point."),
                                    QMessageBox::Information,
                                    QMessageBox::Ok | QMessageBox::Default,
                                    Qt::NoButton,  Qt::NoButton);

    mb.exec();

    SelectWPpatch = true;
    firstClick = true;

}

void passPickedRGB::getPickedRGB(passPickedRGB* rgb)
{
    if (picked.RGB[0] > -0.0000001 && picked.RGB[0] < 255.0000001)
    {
        rgb -> RGB[0] = picked.RGB[0];
        rgb -> RGB[1] = picked.RGB[1];
        rgb -> RGB[2] = picked.RGB[2];
    }
    else
        qDebug("picked RGB values are out of range");
}

void lprofMain::slotHelpButton()
{
    zeroProgressBars();
    QString temp = QString::fromLocal8Bit("/lprof-help.html");
    QString path = global_help_path.append(temp); 
    // qDebug(path.toLocal8Bit());
    help->openAssistant ();
    help->showPage(path);
}

void lprofMain::slotMeasure()
{
    monCalOK = FALSE;
    monMeasOK = FALSE;
    MonitorCalControl monCal(this);
    monCal.setModal(true);
    if (dsizes.moncalconH > 0 && dsizes.moncalconW > 0)
        monCal.resize(dsizes.moncalconW, dsizes.moncalconH);
    monCal.show();
    monCal.exec();
    if (monMeasOK)
        ui->MonMeasurementSheet -> setFilename(QString::fromLocal8Bit(monmeasFile));
    else
        ui->MonMeasurementSheet -> setFilename(QString::fromLocal8Bit(""));
    if (monCalOK)
        ui->MonCalibrationSheet -> setFilename(QString::fromLocal8Bit(moncalFile));
    else
        ui->MonCalibrationSheet -> setFilename(QString::fromLocal8Bit(""));
    slotIsAllReady();
}

void lprofMain::slotMeasureTypeChanged()
{
    if (ui->RadioAccurate -> isOn())
        if (ui->radioButtonCandM -> isOn())
    {
        ui->frameIT8Selectors -> setEnabled(FALSE);
        ui->pushButtonMeasure -> setEnabled(TRUE);
    }
    else
    {
        ui->frameIT8Selectors -> setEnabled(TRUE);
        ui->pushButtonMeasure -> setEnabled(FALSE);
    }
    else
    {
        ui->frameIT8Selectors -> setEnabled(FALSE);
        ui->pushButtonMeasure -> setEnabled(FALSE);
    }
    slotIsAllReady();
}

void lprofMain::slotProofProfilesChanged()
{
    // qDebug("lprofMain::slotProofProfilesChanged()");
    ui->ProofToggle -> setEnabled(ui->MonitorProfileSelector -> getFilename() != QString::null &&
            ui->InputProfileSelector->getFilename() != QString::null); 
    zeroProgressBars();
}

void lprofMain::safeFarmeChanged()
{
    AddTemplate();
    slotPick(); 
}
