#include <qaction.h>
#include <qapplication.h>
#include <qfile.h>
#include <qfiledialog.h>
#include <qlabel.h>
#include <qmenubar.h>
#include <qmessagebox.h>
#include <qpopupmenu.h>
#include <qspinbox.h>
#include <qstatusbar.h>
#include <qpainter.h>
#include <qpushbutton.h>
#include <qradiobutton.h>
#include <qhbuttongroup.h>
#include <qspinbox.h>
#include <qtoolbar.h>
#include <qcheckbox.h>
#include <qdatetime.h>
#include <qcombobox.h>
#include <qhgroupbox.h>
#include <qlineedit.h>
#include <qvalidator.h>
#include <qsettings.h>
#include <qstringlist.h>
#include <qtooltip.h>
#include <qsemaphore.h>

#include "Display3D.h"
#include "imagewindow.h"
#include "resizedialog.h"
#include "ColorConfigure.h"
#include "ColormapPlotConfigure.h"
#include "VectorFieldPlotConfigure.h"
#include "ScreenshotFrequencyConfigure.h"
#include "Types3DInvisibleConfigure.h"
#include "CellTypeColorConfigure.h"
#include "ColorItem.h"
#include "Configure3DDialog.h"
#include "Configure3DData.h"

#include "GraphicsDataFields.h"

#include "Graphics2D.h"
#include "FileUtils.h"
#include <string>
#include <algorithm>
#include <sstream>

using namespace std;

ImageWindow::ImageWindow(QWidget *parent, const char *name, bool _silent)
    : QMainWindow(parent, name),silent(_silent),maxScreenshotListLength(20),screenshotCoreName("screen")
{


    bufferFillUsedSemPtr=0;
    bufferFillFreeSemPtr=0;

    bufferFillUsedSemPtr=new QSemaphore(1);
    bufferFillFreeSemPtr=new QSemaphore(1);

    thread.setTargetWidget(this);

    //important default settings to be intialized even if readSettings() fails to read some settings
    univGraphSet.zoomFactor=1;
    
    readSettings();///read settings  
    
    
    createActions();
    createMenus();
    createStatusBar();
    
    createSteeringBar();
    
    curFileStripped=strippedName(curFile);
    setCurrentFile(curFileStripped);

    modified = false;

    painter=0;
    
    screenshotCounter=0;
    scrollView = new QScrollView(this,"scrollview");

    graphFieldsPtr=new GraphicsDataFields();

    graphics2DPtr = new Graphics2D(this);
    ((Graphics2D*)graphics2DPtr)->resize(0,0);
    ((Graphics2D*)graphics2DPtr)->setSizePolicy(QSizePolicy::Ignored,
                              QSizePolicy::Ignored);

    ((Graphics2D*)graphics2DPtr)->setBackgroundMode(PaletteDark);
    ((Graphics2D*)graphics2DPtr)->setAlignment(AlignLeft | AlignTop);
    
    projDataPtr= &((Graphics2D*)graphics2DPtr)->projData;

    graphics2DPtr->setGraphicsDataFieldPtr(graphFieldsPtr);
    graphics2DPtr->setUnivGraphSetPtr(&univGraphSet);
    
    display3D=new Display3D(this);
    
    ((Display3D*)display3D)->resize(0,0);
    
    ((Display3D*)display3D)->setSizePolicy(QSizePolicy::Ignored,
                              QSizePolicy::Ignored);
    ((Display3D*)display3D)->setBackgroundMode(PaletteDark);
    
    display3D->setGraphicsDataFieldPtr(graphFieldsPtr);
    display3D->setUnivGraphSetPtr(&univGraphSet);

    currentGraphicsPtr=graphics2DPtr;
    currentGraphicsPtr->setCurrentPainitgFcnPtr(currentGraphicsPtr->getPaintLattice());

    graphicsPtrVec.push_back(graphics2DPtr);
    graphicsPtrVec.push_back(display3D);

    
    for(unsigned int i  = 0 ; i < graphicsPtrVec.size() ; ++i){
         graphicsPtrVec[i]->setMinMagnitudeFixed(minMagnitudeFixed);
         graphicsPtrVec[i]->setMaxMagnitudeFixed(maxMagnitudeFixed);
         graphicsPtrVec[i]->setMinMagnitude(minMagnitude);
         graphicsPtrVec[i]->setMaxMagnitude(maxMagnitude);
         graphicsPtrVec[i]->setMaxMagnitude(maxMagnitude);
         graphicsPtrVec[i]->setNumberOfLegendBoxes(numberOfLegendBoxes);
         graphicsPtrVec[i]->setNumberAccuracy(numberAccuracy);
         
         graphicsPtrVec[i]->setArrowLength(arrowLength);
         graphicsPtrVec[i]->setNumberOfLegendBoxesVector(numberOfLegendBoxesVector);
         graphicsPtrVec[i]->setNumberAccuracyVector(numberAccuracyVector);
         graphicsPtrVec[i]->setLegendEnableVector(legendEnableVector);                  
      }

            
    inventoryFileName="graphicsList.grl";

   drawingAllowed=false;
       
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ImageWindow::~ImageWindow(){

   if(painter) delete painter; painter=0;

   if(graphFieldsPtr) delete graphFieldsPtr; graphFieldsPtr=0;

   for(list<ScreenshotData*>::iterator litr = screenshotDataList.begin() ; litr != screenshotDataList.end() ; ++litr){
      if(*litr){
         delete *litr;
         *litr=0;
      }      
   }
   if(bufferFillUsedSemPtr) delete bufferFillUsedSemPtr; bufferFillUsedSemPtr=0;
   if(bufferFillFreeSemPtr) delete bufferFillFreeSemPtr; bufferFillFreeSemPtr=0;

   
   mutex.lock();
   mutex.unlock();
   mutexStartPause.lock();
   mutexStartPause.unlock();
   mutexFieldDraw.lock();
   mutexFieldDraw.unlock();
   mutexTransaction.lock();
   mutexTransaction.unlock();

}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void ImageWindow::startSimulation(){
   simulation();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ImageWindow::setXMLFile(const QString &fileName){
   setCurrentFile(fileName);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ImageWindow::setScreenshotDescriptionFileName(const QString & scrDesFileName){
   screenshotDescriptionFileName=scrDesFileName;
   
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void ImageWindow::writeSettings(){
   
    QSettings settings;

    settings.setPath("physics.indiana.edu", "CompuCellPlayer.info");
    settings.beginGroup("/DefaultColors");
    settings.writeEntry("/brush", univGraphSet.defaultBrush.color().name());
    settings.writeEntry("/pen", univGraphSet.defaultPen.color().name());
    settings.writeEntry("/border", univGraphSet.borderPen.color().name());
    settings.writeEntry("/bordersOn",univGraphSet.bordersOn/*QString().setNum(bordersOn) */);
    settings.writeEntry("/concentrationLimitsOn",univGraphSet.concentrationLimitsOn/*QString().setNum(bordersOn) */);
    
    settings.writeEntry("/contour", univGraphSet.contourPen.color().name());
    settings.writeEntry("/contoursOn",univGraphSet.contoursOn/*QString().setNum(contoursOn)*/ );
    settings.writeEntry("/recentFile",curFile);
    
    QStringList penColorList;
    std::map<unsigned short,QPen>::iterator penMitr;

    for( penMitr = univGraphSet.typePenMap.begin() ; penMitr != univGraphSet.typePenMap.end() ; ++penMitr ){
        penColorList+=QString().setNum(penMitr->first);
        penColorList+=penMitr->second.color().name();
    }
    settings.writeEntry("/typeColorMap", penColorList);
    settings.writeEntry("/zoomFactor",univGraphSet.zoomFactor);
    settings.writeEntry("/screenshotFrequency",(int)screenshotFrequency);

    settings.writeEntry("/minConcentration",graphics2DPtr->getMinConcentration());
    settings.writeEntry("/minConcentrationFixed",graphics2DPtr->getMinConcentrationFixed());
    settings.writeEntry("/maxConcentration",graphics2DPtr->getMaxConcentration());
    settings.writeEntry("/maxConcentrationFixed",graphics2DPtr->getMaxConcentrationFixed());

    settings.writeEntry("/minMagnitude",graphics2DPtr->getMinMagnitude());
    settings.writeEntry("/minMagnitudeFixed",graphics2DPtr->getMinMagnitudeFixed());
    settings.writeEntry("/maxMagnitude",graphics2DPtr->getMaxMagnitude());
    settings.writeEntry("/maxMagnitudeFixed",graphics2DPtr->getMaxMagnitudeFixed());
    settings.writeEntry("/numberOfLegendBoxes",(int)graphics2DPtr->getNumberOfLegendBoxes());
    settings.writeEntry("/numberAccuracy",(int)graphics2DPtr->getNumberAccuracy());
    settings.writeEntry("/legendEnable",graphics2DPtr->getLegendEnable());
    
    settings.writeEntry("/arrowLength",graphics2DPtr->getArrowLength());
    settings.writeEntry("/numberOfLegendBoxesVector",(int)graphics2DPtr->getNumberOfLegendBoxesVector());
    settings.writeEntry("/numberAccuracyVector",(int)graphics2DPtr->getNumberAccuracyVector());
    settings.writeEntry("/legendEnableVector",graphics2DPtr->getLegendEnableVector());
    
    QStringList types3DinvisibleList;
    for(unsigned int i = 0 ; i < univGraphSet.types3DInvisibleVec.size() ; ++i){
      types3DinvisibleList+=QString().setNum(univGraphSet.types3DInvisibleVec[i]);
    }
    settings.writeEntry("/types3DInvisible", types3DinvisibleList);
    settings.endGroup();

}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ImageWindow::saveSettings(){
   writeSettings();
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void ImageWindow::readSettings(){
   
    QSettings settings;
   
    QString defaultBrushColor;
    QString defaultPenColor;
    QString borderPenColor;
    QString contourPenColor;

    
    settings.setPath("physics.indiana.edu", "CompuCellPlayer.info");
       
    settings.beginGroup("/DefaultColors");
    defaultBrushColor=settings.readEntry("/brush","white");
    defaultPenColor=settings.readEntry("/pen"," white");
    borderPenColor=settings.readEntry("/border","blue");
    univGraphSet.bordersOn=settings.readBoolEntry("/bordersOn",false);
    univGraphSet.concentrationLimitsOn=settings.readBoolEntry("/concentrationLimitsOn",false);
    contourPenColor=settings.readEntry("/contour","magenta");
    univGraphSet.contoursOn=settings.readBoolEntry("/contoursOn",false);
    curFile=settings.readEntry("/recentFile","xml");
    

    univGraphSet.defaultBrush.setColor(QColor(defaultBrushColor));
    univGraphSet.defaultPen.setColor(QColor(defaultPenColor));
    univGraphSet.borderPen.setColor(QColor(borderPenColor));
    univGraphSet.contourPen.setColor(QColor(contourPenColor));

    univGraphSet.defaultColor=QColor(defaultPenColor);
    univGraphSet.borderColor=QColor(borderPenColor);
    univGraphSet.contourColor=QColor(contourPenColor);
    
        

    QString key,value;
    QStringList defaultPenColorList;
    defaultPenColorList+="0";
    defaultPenColorList+="black";
    defaultPenColorList+="1";
    defaultPenColorList+="red";
    
    
    QStringList penColorList=settings.readListEntry("/typeColorMap");
    if(penColorList.empty()){
      penColorList=defaultPenColorList;
    }
    
    for ( QStringList::Iterator it = penColorList.begin(); it != penColorList.end();  ) {
         key=*it;
         ++it;
         value=*it;
         ++it;
         univGraphSet.typePenMap.insert(std::make_pair(key.toUShort(),QPen(QColor(value))));
         univGraphSet.typeBrushMap.insert(std::make_pair(key.toUShort(),QBrush(QColor(value))));
         univGraphSet.typeColorMap.insert(std::make_pair(key.toUShort(),QColor(value)));
      
    }

    univGraphSet.zoomFactor=settings.readNumEntry("/zoomFactor",1);
    screenshotFrequency=settings.readNumEntry("/screenshotFrequency",1);

    minConcentration = settings.readDoubleEntry("/minConcentration",0.0);
    minConcentrationFixed = settings.readBoolEntry("/minConcentrationFixed",false);
    maxConcentration = settings.readDoubleEntry("/maxConcentration",1.0);
    maxConcentrationFixed = settings.readBoolEntry("/maxConcentrationFixed",false);

    minMagnitude = settings.readDoubleEntry("/minMagnitude",0.0);
    minMagnitudeFixed = settings.readBoolEntry("/minMagnitudeFixed",false);
    maxMagnitude = settings.readDoubleEntry("/maxMagnitude",1.0);
    maxMagnitudeFixed = settings.readBoolEntry("/maxMagnitudeFixed",false);
    numberOfLegendBoxes=settings.readNumEntry("/numberOfLegendBoxes",5);
    numberAccuracy=settings.readNumEntry("/numberAccuracy",3);
    legendEnable=settings.readBoolEntry("/legendEnable",true);
    arrowLength = settings.readNumEntry("/arrowLength",3);
    numberOfLegendBoxesVector=settings.readNumEntry("/numberOfLegendBoxesVector",5);
    numberAccuracyVector=settings.readNumEntry("/numberAccuracyVector",3);
    legendEnableVector=settings.readBoolEntry("/legendEnableVector",true);
        
    QStringList types3DinvisibleList=settings.readListEntry("/types3DInvisible");
    
    univGraphSet.types3DInvisibleVec.clear();
    univGraphSet.types3DInvisibleVec.push_back(0);//by default avoid displaying medium in 3D
    for ( QStringList::Iterator it = types3DinvisibleList.begin(); it != types3DinvisibleList.end(); ++it ) {
      if((*it).toUShort() != 0)
        univGraphSet.types3DInvisibleVec.push_back((*it).toUShort());
    }

    
    settings.endGroup();

   
    
    
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///this function draws Field in 3D
void ImageWindow::drawField3D(){
   mutexFieldDraw.lock();

   scrollView->removeChild((Graphics2D*)graphics2DPtr);
   scrollView->addChild((Display3D*)display3D);
   setCentralWidget(scrollView);


      //setCentralWidget((Display3D*)display3D);
      ((Graphics2D*)graphics2DPtr)->setShown(false);
      ((Display3D*)display3D)->setShown(true);
   mutexFieldDraw.unlock();
      
   
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ImageWindow::drawField(){
   (this->*draw)();

   
   mutexFieldDraw.lock();
      if(!plotTypeComboBox->count()){ ///no items in combo box - return
      mutexFieldDraw.unlock();
      return;

    }
    
   QString selectedPlotType=plotTypeComboBox->currentText();

            
   if( selectedPlotType == QString("Cell Field") ){
   

     currentGraphicsPtr->setCurrentPainitgFcnPtr(currentGraphicsPtr->getPaintLattice());
     currentGraphicsPtr->drawCurrentScene();

     
     
   }
   else if(selectedPlotType == QString("CellVelocity")){
   
     GraphicsDataFields::vectorCellFloatField3DNameMapItr_t mitr=
     currentGraphicsPtr->getGraphFieldsPtr()->getVectorCellFloatField3DNameMap().find(string(selectedPlotType.ascii()));
     
     currentGraphicsPtr->setCurrentPainitgFcnPtr(currentGraphicsPtr->getPaintCellVectorFieldLattice());
     currentGraphicsPtr->setCurrentVectorCellFieldPtr(mitr->second);
     currentGraphicsPtr->drawCurrentScene();
   }
   else{
      GraphicsDataFields::floatField3DNameMapItr_t mitr=
         currentGraphicsPtr->getGraphFieldsPtr()->getFloatField3DNameMap().find(string(selectedPlotType.ascii()));

//       cerr<<"LOOKING FOR A STRING:"<<string(selectedPlotType.ascii())<<endl;
      
      if(mitr != currentGraphicsPtr->getGraphFieldsPtr()->getFloatField3DNameMap().end() ){
      
//          cerr<<"FOUND:"<<string(selectedPlotType.ascii())<<endl;   
         currentGraphicsPtr->setCurrentConcentrationFieldPtr(mitr->second);

         currentGraphicsPtr->setCurrentPainitgFcnPtr(currentGraphicsPtr->getPaintConcentrationLattice());
         currentGraphicsPtr->drawCurrentScene();
                  
                  
         if(univGraphSet.concentrationLimitsOn){
            minMaxConcentrationLabel->setText(tr(
                                                   "Min: "+QString::number(currentGraphicsPtr->getMinConcentrationTrue())+
                                                   " Max: "+QString::number(currentGraphicsPtr->getMaxConcentrationTrue())
            ));
         }
         
      }else{
      
         currentGraphicsPtr->setCurrentConcentrationFieldPtr(& currentGraphicsPtr->getGraphFieldsPtr()->field3DConcentration);
         
         currentGraphicsPtr->setCurrentPainitgFcnPtr(currentGraphicsPtr->getPaintConcentrationLattice());
         currentGraphicsPtr->drawCurrentScene();
         
         if(univGraphSet.concentrationLimitsOn){
            minMaxConcentrationLabel->setText(tr(
                                                   "Min"+QString::number(currentGraphicsPtr->getMinConcentrationTrue())+
                                                   " Max"+QString::number(currentGraphicsPtr->getMaxConcentrationTrue())
            ));
         }         

      }
   }


   mutexFieldDraw.unlock();

}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///this function draws Field in 2D

void ImageWindow::drawField2D(){
   mutexFieldDraw.lock();
   ///setting central widget
   scrollView->removeChild((Display3D*)display3D);
   scrollView->addChild((Graphics2D*)graphics2DPtr);
   setCentralWidget(scrollView);
   ((Display3D*)display3D)->setShown(false);
   ((Graphics2D*)graphics2DPtr)->setShown(true);

   mutexFieldDraw.unlock();

}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void ImageWindow::customEvent(QCustomEvent *event)
{
   
   if ((int)event->type() == TransactionStart) {
   
      GraphicsBase &graphics2D = *graphics2DPtr;
      for(unsigned int i  = 0 ; i < graphicsPtrVec.size() ; ++i){
         graphicsPtrVec[i]->setMinConcentrationFixed(minConcentrationFixed);
         graphicsPtrVec[i]->setMaxConcentrationFixed(maxConcentrationFixed);
         graphicsPtrVec[i]->setMinConcentration(minConcentration);
         graphicsPtrVec[i]->setMaxConcentration(maxConcentration);
         graphicsPtrVec[i]->setNumberOfLegendBoxes(numberOfLegendBoxes);
         graphicsPtrVec[i]->setNumberAccuracy(numberAccuracy);
         graphicsPtrVec[i]->setLegendEnable(legendEnable);
         graphicsPtrVec[i]->setArrowLength(arrowLength);
         graphicsPtrVec[i]->setNumberOfLegendBoxesVector(numberOfLegendBoxesVector);
         graphicsPtrVec[i]->setNumberAccuracyVector(numberAccuracyVector);
         graphicsPtrVec[i]->setLegendEnableVector(legendEnableVector);                  
                  
      }


      TransactionStartEvent *transactionStartEvent = (TransactionStartEvent*)(event);
      
      xSpinBox->setMinValue(0);
      xSpinBox->setMaxValue(graphFieldsPtr->getSizeL()-1);
      xSpinBox->setValue(graphFieldsPtr->getSizeL()/2);
      xSpinBox->setWrapping(true);
      
      
      ySpinBox->setMinValue(0);
      ySpinBox->setMaxValue(graphFieldsPtr->getSizeM()-1);
      ySpinBox->setValue(graphFieldsPtr->getSizeM()/2);
      ySpinBox->setWrapping(true);
      
      zSpinBox->setMinValue(0);
      zSpinBox->setMaxValue(graphFieldsPtr->getSizeN()-1);
      zSpinBox->setValue(graphFieldsPtr->getSizeN()/2);
      zSpinBox->setWrapping(true);
      
      ///using custom settings provided by users in xml config file
      if(transactionStartEvent->playerSettings.xyProjFlag){
         zSpinBox->setValue(transactionStartEvent->playerSettings.xyProj);
      }

      if(transactionStartEvent->playerSettings.xzProjFlag){
         ySpinBox->setValue(transactionStartEvent->playerSettings.xzProj);
      }

      if(transactionStartEvent->playerSettings.yzProjFlag){
         xSpinBox->setValue(transactionStartEvent->playerSettings.yzProj);
      }
        

      ///initialize graphics obj
      
      Configure3DData data3D;
      if(transactionStartEvent->playerSettings.rotationXFlag){
         data3D.rotationX=transactionStartEvent->playerSettings.rotationX;
      }
      
      if(transactionStartEvent->playerSettings.rotationYFlag){
         data3D.rotationY=transactionStartEvent->playerSettings.rotationY;
      }
      if(transactionStartEvent->playerSettings.rotationZFlag){
         data3D.rotationZ=transactionStartEvent->playerSettings.rotationZ;
      }

      if(transactionStartEvent->playerSettings.sizeX3DFlag){
         data3D.sizeX=transactionStartEvent->playerSettings.sizeX3D;
      }else{
         data3D.sizeX=graphFieldsPtr->getSizeL();
      }

      if(transactionStartEvent->playerSettings.sizeY3DFlag){
         data3D.sizeY=transactionStartEvent->playerSettings.sizeY3D;
      }else{
         data3D.sizeY=graphFieldsPtr->getSizeM();
      }

      if(transactionStartEvent->playerSettings.sizeZ3DFlag){
         data3D.sizeZ=transactionStartEvent->playerSettings.sizeZ3D;
      }else{
         data3D.sizeZ=graphFieldsPtr->getSizeN();
      }

      data3D.sizeL=graphFieldsPtr->getSizeL();
      data3D.sizeM=graphFieldsPtr->getSizeM();
      data3D.sizeN=graphFieldsPtr->getSizeN();
      
      ((Display3D*)display3D)->setInitialConfigure3DData(data3D);
      
      //((Display3D*)display3D)->setSizeLMN(graphFieldsPtr->getSizeL(),graphFieldsPtr->getSizeM(),graphFieldsPtr->getSizeN());
      //cerr<<"graphFieldsPtr->getSizeL()="<<graphFieldsPtr->getSizeL()<<" graphFieldsPtr->getSizeM()="<<graphFieldsPtr->getSizeM()<<
      //" graphFieldsPtr->getSizeN()="<<graphFieldsPtr->getSizeN()<<endl;


            
///      projDataPtr->imageLabelPtr=imageLabel;
      projDataPtr->sizeL = graphFieldsPtr->getSizeL(); //change it!
      projDataPtr->sizeM = graphFieldsPtr->getSizeM(); //change it!

      //default configuration
      projDataPtr->xMin = 0;
      projDataPtr->xMax = graphFieldsPtr->getSizeL();
      projDataPtr->yMin = 0;
      projDataPtr->yMax = graphFieldsPtr->getSizeM();
      projDataPtr->zMin = graphFieldsPtr->getSizeN()/2;
      projDataPtr->zMax = graphFieldsPtr->getSizeN()/2+1;
      projDataPtr->projection="xy";

      if(transactionStartEvent->playerSettings.initialProjection=="xy"){
         initProjectionXYData();
      }

      if(transactionStartEvent->playerSettings.initialProjection=="xz"){
         initProjectionXZData();
      }

      if(transactionStartEvent->playerSettings.initialProjection=="yz"){
         initProjectionYZData();
      }
      

      ///initialize painter and pixmap
    
       ((Graphics2D*)graphics2DPtr)->pixmap()->fill();
       ///painter=new QPainter(imageLabel->pixmap(),this);
       
       ///projDataPtr->painterPtr=painter;

       /// Required activate  projection  pixmap and painter must be initialized 
       if(transactionStartEvent->playerSettings.initialProjection=="xy"){
         xyButton->toggle();
       }
       
       if(transactionStartEvent->playerSettings.initialProjection=="xz"){
         xzButton->toggle();
       }

       if(transactionStartEvent->playerSettings.initialProjection=="yz"){
         yzButton->toggle();
       }
              
      ///initialize Combo box with field types
      GraphicsDataFields::floatField3DNameMapItr_t mitr;

      
      plotTypeComboBox->insertItem("Cell Field");
      ///initialize Combo box with scalar field names
      for ( mitr = graphics2D.getGraphFieldsPtr()->getFloatField3DNameMap().begin();
            mitr != graphics2D.getGraphFieldsPtr()->getFloatField3DNameMap().end() ;
            ++mitr)
      {
         plotTypeComboBox->insertItem(QString(mitr->first));   
      }
      
      //vectorCellFloatField3DNameMapItr_t
      GraphicsDataFields::vectorCellFloatField3DNameMapItr_t mitrV;
      ///initialize Combo box with  vector field names      
      for ( mitrV = graphics2D.getGraphFieldsPtr()->getVectorCellFloatField3DNameMap().begin();
            mitrV != graphics2D.getGraphFieldsPtr()->getVectorCellFloatField3DNameMap().end() ;
            ++mitrV)
      {
         plotTypeComboBox->insertItem(QString(mitrV->first));   
      }
            
      ///make tmp directory for storing pictures
      tmpDirName=curFileStripped;
      QDate date=QDate::currentDate();
      QTime time=QTime::currentTime();
      QString dirSuffix;
      
      dirSuffix+=QString("_");
      dirSuffix+=date.toString();
      dirSuffix+=QString("_");
      dirSuffix+=time.toString();
      tmpDirName+=dirSuffix;
      
      

      cerr<<"NAME OF THE TEMPORARY DIR: "<<tmpDirName<<endl;
      QDir dir;
      
      bool dirOK=dir.mkdir(tmpDirName);
      if(!dirOK){
         cerr<<"could not create directory: "<<tmpDirName<<endl;
         cerr<<"Make sure that directory with this name is removed"<<endl;
         exit(0);
      }
      
      ///opening graphics list file
      QString path=dir.absPath();
      simulationRootDir=QString(path+QDir::separator()+tmpDirName);
      QString fullInventoryFileName(simulationRootDir+QDir::separator()+inventoryFileName);
      cerr<<fullInventoryFileName<<endl;


            
      inventoryFile.open(fullInventoryFileName.ascii());

      ///copying xml file to folder with graphics
      QString xmlFileFullName=simulationRootDir+QDir::separator()+curFileStripped;
      copyFile( curFile.ascii() , xmlFileFullName.ascii());

            
      ///enabling zooms
      if(univGraphSet.zoomFactor>1){
         zoomOutAct->setEnabled(true);
      }
      zoomInAct->setEnabled(true);
      ///enabling show menu


      if(univGraphSet.bordersOn){
         showBordersAct->setOn(true);
      }
      showBordersAct->setEnabled(true);
      
      if(univGraphSet.contoursOn){
         showContoursAct->setOn(true);
      }

      if(univGraphSet.concentrationLimitsOn){
         showConcentrationLimitsAct->setOn(true);
      }
      showConcentrationLimitsAct->setEnabled(true);
      
      showContoursAct->setEnabled(true);
      


      drawingAllowed=true;
      ((Display3D*)display3D)->setDrawingAllowedFlag(true);


      ///init screenshot data
      if(silent && ! screenshotDescriptionFileName.isEmpty()){
         readScreenshotDescriptionList(screenshotDescriptionList,screenshotDescriptionFileName);
         produceScreenshotDataList(screenshotDescriptionList);
      }

                        
      return;
      
   }

   if ((int)event->type() == TransactionRefresh) {
      TransactionRefreshEvent *refreshEvent = (TransactionRefreshEvent *)event;
      ((Graphics2D*)graphics2DPtr)->pixmap()->fill();
   
      ///unlock mutextransaction
      //mutexTransaction.unlock();
      (*bufferFillUsedSemPtr)++;//acquire semaphore
      mcStepLabel->setText("MC Step: "+QString::number(refreshEvent->mcStep));

      drawField();

      ///screenshot
      outputScreenshot();
      (*bufferFillFreeSemPtr)--; //release semaphore

      return;
   }

   if ((int)event->type() == TransactionFinish) {
   
      TransactionFinishEvent *finishEvent = (TransactionFinishEvent *)event;
      cerr<<finishEvent->message<<endl;
      
   }
   
}

void ImageWindow::outputScreenshot(){

   if(screenshotCounter % screenshotFrequency){
       ++screenshotCounter;
      return;
   }

   QImage image;
   
   if(display3DButton->isOn()){
      display3D->produceImage(image);
   }else{
      graphics2DPtr->produceImage(image);
   }
   
   ostringstream imageFileFullNameStream("");
   ostringstream imageFileNameStream("");
   imageCoreFileName=curFileStripped.ascii();
   imageFileExtension="png";
   imageFileFullNameStream<<tmpDirName<<QDir::separator()<<imageCoreFileName<<"."<<screenshotCounter<<"."<<imageFileExtension;
   imageFileNameStream<<imageCoreFileName<<"."<<screenshotCounter<<"."<<imageFileExtension;
   
   
   

      image.save(QString(imageFileFullNameStream.str()),"PNG");
      inventoryFile<<imageFileNameStream.str()<<endl;
      cerr<<"SAVING: "<<imageFileFullNameStream.str()<<endl;

   for(list<ScreenshotData*>::iterator litr = screenshotDataList.begin() ; litr != screenshotDataList.end() ; ++litr){
      (*litr)->outputScreenshot(screenshotCounter);
      
   }

   
   ++screenshotCounter;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ImageWindow::closeEvent(QCloseEvent *event)
{
   writeSettings();
   event->accept();
   

}



void ImageWindow::open()
{

   QString fileName = QFileDialog::getOpenFileName(".", "*.xml", this);

   if (!fileName.isEmpty()){
      curFile=fileName;
      curFileStripped=strippedName(fileName);
      setCurrentFile(fileName);
      
   }

}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool ImageWindow::saveScrDes()
{
    QString fileName = QFileDialog::getSaveFileName(".", "", this);
    if (QFile::exists(fileName)) {
        int ret = QMessageBox::warning(this, tr("CompuCellPlayer"),
                     tr("File %1 already exists.\n"
                        "Do you want to overwrite it?")
                     .arg(QDir::convertSeparators(fileName)),
                     QMessageBox::Yes | QMessageBox::Default,
                     QMessageBox::No | QMessageBox::Escape);
        if (ret == QMessageBox::No)
            return true;
    }
    if (!fileName.isEmpty())
        saveScrDesFile(fileName);
    return true;
}


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ImageWindow::simulation()
{
    
    if(!mutexStartPause.locked()){///this happens only once you start program
      CC3DTransaction *transactionCC3D= new CC3DTransaction(string(curFile.ascii()));
      transactionCC3D->setPauseMutexPtr(&mutex);
      transactionCC3D->setFieldDrawMutexPtr(&mutexFieldDraw);
      transactionCC3D->setTransactionMutexPtr(&mutexTransaction);
      transactionCC3D->setBufferFreeSem(bufferFillFreeSemPtr);
      transactionCC3D->setBufferUsedSem(bufferFillUsedSemPtr);
      
      
      
      transactionCC3D->setGraphicsDataFieldPtr(graphFieldsPtr);
      
      addTransaction(transactionCC3D );
      simulationAct->setEnabled(false);
      simulationPauseAct->setEnabled(true);
      
    }else{
      mutex.unlock();
      mutexStartPause.unlock();
      simulationAct->setEnabled(false);
      simulationPauseAct->setEnabled(true);   
      
    }
    
    
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ImageWindow::simulationPause(){
   ///need to have second mutex (StartPause) because if  mutex is unlocked, then locked by cc3d thread then if between these two instructions
   ///one hits "play" button then another thread would be created if instead of if(!mutexStartPause.locked()){ there was
   ///if(!mutex.locked()){ instruction

   
   simulationPauseAct->setEnabled(false);
   mutex.lock();
   mutexStartPause.lock();
   simulationAct->setEnabled(true);
   
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ImageWindow::zoomIn(){
   
   univGraphSet.zoomFactor++;
   if((univGraphSet.zoomFactor-1)==1){
      zoomOutAct->setEnabled(true);
   }

   QSize size = ((Graphics2D*)graphics2DPtr)->size();
   size/=(univGraphSet.zoomFactor-1);
   size*=univGraphSet.zoomFactor;   
   drawField();
   cerr<<"Zoom factor="<<univGraphSet.zoomFactor<<endl;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ImageWindow::zoomOut(){
   
   univGraphSet.zoomFactor--;
   if(univGraphSet.zoomFactor==1){
      zoomOutAct->setEnabled(false);
   }
   QSize size = ((Graphics2D*)graphics2DPtr)->size();
   size/=(univGraphSet.zoomFactor+1);
   size*=univGraphSet.zoomFactor;
   drawField();
   cerr<<"Zoom factor="<<univGraphSet.zoomFactor<<endl;
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ImageWindow::initProjectionXYData(){

   projDataPtr->sizeL = graphFieldsPtr->getSizeL(); //change it!
   projDataPtr->sizeM = graphFieldsPtr->getSizeM(); //change it!

   
   projDataPtr->xMin = 0;
   projDataPtr->xMax = graphFieldsPtr->getSizeL();
   projDataPtr->yMin = 0;
   projDataPtr->yMax = graphFieldsPtr->getSizeM();
   projDataPtr->zMin = zSpinBox->value();
   projDataPtr->zMax = zSpinBox->value()+1;
   projDataPtr->projection="xy";

}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ImageWindow::changeProjectionXY(bool _state){

   draw=&ImageWindow::drawField2D;
   
   if(_state){

      initProjectionXYData()   ;
      drawField();
   }

}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ImageWindow::alterZCoordinate(int _value){

     xyProjData=*projDataPtr;
     
     xyProjData.resetBoundaries(graphFieldsPtr->getSizeL(),graphFieldsPtr->getSizeM(),graphFieldsPtr->getSizeN());

     xyProjData.zMin = _value;
     xyProjData.zMax = _value+1;
     xyProjData.projection="xy";

     if(xyButton->isChecked()){
         *projDataPtr=xyProjData;
         
         drawField();
     }


}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ImageWindow::initProjectionXZData(){
   projDataPtr->sizeL = graphFieldsPtr->getSizeL(); //change it!
   projDataPtr->sizeM = graphFieldsPtr->getSizeN(); //change it!

   
   projDataPtr->xMin = 0;
   projDataPtr->xMax = graphFieldsPtr->getSizeL();
   projDataPtr->yMin = ySpinBox->value();
   projDataPtr->yMax = ySpinBox->value()+1;
   projDataPtr->zMin = 0;
   projDataPtr->zMax = graphFieldsPtr->getSizeN();
   projDataPtr->projection="xz";

}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ImageWindow::changeProjectionXZ(bool _state){
   draw=&ImageWindow::drawField2D;
   

   if(_state){

      initProjectionXZData();
      drawField();
   }

}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ImageWindow::alterYCoordinate(int _value){


     xzProjData=*projDataPtr;
     
     xzProjData.resetBoundaries(graphFieldsPtr->getSizeL(),graphFieldsPtr->getSizeM(),graphFieldsPtr->getSizeN());

     xzProjData.yMin = _value;
     xzProjData.yMax = _value+1;
     xzProjData.projection="xz";

     if(xzButton->isChecked()){
         *projDataPtr=xzProjData;
         
         drawField();
     }



}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ImageWindow::initProjectionYZData(){

   projDataPtr->sizeL = graphFieldsPtr->getSizeM(); //change it!
   projDataPtr->sizeM = graphFieldsPtr->getSizeN(); //change it!

   
   projDataPtr->xMin = xSpinBox->value();
   projDataPtr->xMax = xSpinBox->value()+1;
   projDataPtr->yMin = 0;
   projDataPtr->yMax = graphFieldsPtr->getSizeM();
   projDataPtr->zMin = 0;
   projDataPtr->zMax = graphFieldsPtr->getSizeN();
   projDataPtr->projection="yz";


}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ImageWindow::changeProjectionYZ(bool _state){

   draw=&ImageWindow::drawField2D;

   if(_state){

      initProjectionYZData();
      drawField();
   }

}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ImageWindow::alterXCoordinate(int _value){


     yzProjData=*projDataPtr;
     
     yzProjData.resetBoundaries(graphFieldsPtr->getSizeL(),graphFieldsPtr->getSizeM(),graphFieldsPtr->getSizeN());

     yzProjData.xMin = _value;
     yzProjData.xMax = _value+1;
     yzProjData.projection="yz";

     if(yzButton->isChecked()){
         *projDataPtr=yzProjData;
         
         drawField();
     }



}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void ImageWindow::switch3D(bool state){

   
   if(state){
      draw = &ImageWindow::drawField3D;
      currentGraphicsPtr=display3D;
   }else{
      draw = &ImageWindow::drawField2D;
      currentGraphicsPtr=graphics2DPtr;
      
   }
   
   drawField();
}



//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void ImageWindow::contoursDisplay(bool _on){

   if(showContoursAct->isOn()){

      univGraphSet.contoursOn=true;
      drawField();
   }else{

      univGraphSet.contoursOn=false;
      drawField();
   }


}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void ImageWindow::bordersDisplay(bool _on){
   
   if(showBordersAct->isOn()){

      univGraphSet.bordersOn=true;
      drawField();
   }else{

      univGraphSet.bordersOn=false;
      drawField();
   }

   
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void ImageWindow::concentrationLimitsDisplay(bool _on){

   if(showConcentrationLimitsAct->isOn()){
      
      univGraphSet.concentrationLimitsOn=true;
      
      
      
   }else{

      univGraphSet.concentrationLimitsOn=false;
      minMaxConcentrationLabel->setText("");
      minMaxConcentrationLabel->setMinimumSize(QSize());
      
   }
      
   
}


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ImageWindow::frequencyUpdate(int _value){
   screenshotFrequency=_value;
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ImageWindow::addTransaction(Transaction *transact)
{
    thread.addTransaction(transact);
    openAct->setEnabled(false);
}

void ImageWindow::about()
{
    QMessageBox::about(this, tr("About CompuCell3D Player"),
            tr("<h2>CompuCell3D Player 1.0</h2>"
               "<p>Copyright &copy; 2003 Software Inc."
               "<p>CompuCell3D Player is a small application that "
               "renders cell field in real time ."));
               
}


void ImageWindow::configureColors(){

   ///validator should be declared in the configureColorDialog file in function init() not here
    ConfigureColorsDialog dialog;
      
    
    
    short cellType;
    map<unsigned short,QPen>::iterator pmItr;
    map<unsigned short,QBrush>::iterator bmItr;
    UniversalGraphicsSettings::colorMapItr cItr;

    dialog.borderColorLabel->setPaletteBackgroundColor(univGraphSet.borderPen.color());
    dialog.contourColorLabel->setPaletteBackgroundColor(univGraphSet.contourPen.color());
    
    ///shows dialog
    if (dialog.exec()) {
          ///dialog vanished from the screen, read values from dialog

          QColor borderColor = dialog.borderColorLabel->paletteBackgroundColor();
          QColor contourColor = dialog.contourColorLabel->paletteBackgroundColor();
          univGraphSet.borderPen.setColor(borderColor);
          univGraphSet.contourPen.setColor(contourColor);

          univGraphSet.borderColor=borderColor;
          univGraphSet.contourColor=contourColor;
          
          QString text=dialog.cellTypeEdit->text();

          if( ! text.isEmpty() ){
            cellType=text.toShort();
//             cerr<<"CellType="<<dialog.cellTypeEdit->text()<<endl;
//             cerr<<"CellType="<<cellType<<endl;
   
            
               
            QColor color=dialog.colorLabel->paletteBackgroundColor();
   
            
            
            pmItr=univGraphSet.typePenMap.find(cellType);
            if(pmItr != univGraphSet.typePenMap.end() ){
               univGraphSet.typePenMap.erase(pmItr);
               univGraphSet.typePenMap.insert(make_pair(cellType,QPen(color)));
            }else{
               univGraphSet.typePenMap.insert(make_pair(cellType,QPen(color)));
            }
   
            
            bmItr=univGraphSet.typeBrushMap.find(cellType);
            if(bmItr != univGraphSet.typeBrushMap.end() ){
               univGraphSet.typeBrushMap.erase(bmItr);
               univGraphSet.typeBrushMap.insert(make_pair(cellType,QBrush(color)));
            }else{
               univGraphSet.typeBrushMap.insert(make_pair(cellType,QBrush(color)));
            }
            
            cItr=univGraphSet.typeColorMap.find(cellType);
            if(cItr != univGraphSet.typeColorMap.end() ){
               univGraphSet.typeColorMap.erase(cItr);
               univGraphSet.typeColorMap.insert(make_pair(cellType,color));
            }else{
               univGraphSet.typeColorMap.insert(make_pair(cellType,color));
            }
            
         }          
    }

   drawField();

}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ImageWindow::configureColorMapPlot(){
   ColorMapPlotDialog dialog;

//       cerr<<"legendEnable="<<legendEnable<<endl;
      dialog.loadCurrentValues(
                                 minConcentration , minConcentrationFixed,
                                 maxConcentration , maxConcentrationFixed,
                                 numberOfLegendBoxes,numberAccuracy,legendEnable
                                 
                              );   
    ///shows dialog
    if (dialog.exec()) {
      ///dialog vanished from the screen, read values from dialog
      minConcentration = dialog.minLineEdit->text().toFloat();
      minConcentrationFixed = dialog.minCheckBox->isOn();
      maxConcentration = dialog.maxLineEdit->text().toFloat();
      maxConcentrationFixed = dialog.maxCheckBox->isOn();
      numberOfLegendBoxes = dialog.boxSpinBox->value();
      numberAccuracy = dialog.accuracySpinBox->value();
      legendEnable = dialog.showLegendBox->isChecked();
      
      for(unsigned int i  = 0 ; i < graphicsPtrVec.size() ; ++i){
         graphicsPtrVec[i]->setMinConcentrationFixed(minConcentrationFixed);
         graphicsPtrVec[i]->setMaxConcentrationFixed(maxConcentrationFixed);
         graphicsPtrVec[i]->setMinConcentration(minConcentration);
         graphicsPtrVec[i]->setMaxConcentration(maxConcentration);
         graphicsPtrVec[i]->setNumberOfLegendBoxes(numberOfLegendBoxes);
         graphicsPtrVec[i]->setNumberAccuracy(numberAccuracy);
         graphicsPtrVec[i]->setLegendEnable(legendEnable);
      }

            
      drawField();      
    }
    
    
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void ImageWindow::configureVectorFieldPlot(){
   VectorFieldPlotDialog dialog;

      dialog.loadCurrentValues(
                                 minMagnitude , minMagnitudeFixed,
                                 maxMagnitude , maxMagnitudeFixed,
                                 arrowLength,
                                 numberOfLegendBoxesVector,numberAccuracyVector,legendEnableVector
                                 
                                 
                              );   
    ///shows dialog
    if (dialog.exec()) {
      ///dialog vanished from the screen, read values from dialog
      minMagnitude = dialog.minLineEdit->text().toFloat();
      minMagnitudeFixed = dialog.minCheckBox->isOn();
      maxMagnitude = dialog.maxLineEdit->text().toFloat();
      maxMagnitudeFixed = dialog.maxCheckBox->isOn();
      arrowLength = dialog.arrowLengthSpinBox->value();
      numberOfLegendBoxesVector = dialog.boxSpinBox->value();
      numberAccuracyVector = dialog.accuracySpinBox->value();
      legendEnableVector = dialog.showLegendBox->isChecked();
      
      for(unsigned int i  = 0 ; i < graphicsPtrVec.size() ; ++i){
         graphicsPtrVec[i]->setMinMagnitudeFixed(minMagnitudeFixed);
         graphicsPtrVec[i]->setMaxMagnitudeFixed(maxMagnitudeFixed);
         graphicsPtrVec[i]->setMinMagnitude(minMagnitude);
         graphicsPtrVec[i]->setMaxMagnitude(maxMagnitude);
         graphicsPtrVec[i]->setMaxMagnitude(maxMagnitude);
         graphicsPtrVec[i]->setArrowLength(arrowLength);
         graphicsPtrVec[i]->setNumberOfLegendBoxesVector(numberOfLegendBoxesVector);
         graphicsPtrVec[i]->setNumberAccuracyVector(numberAccuracyVector);
         graphicsPtrVec[i]->setLegendEnableVector(legendEnableVector);         
      }
            
      drawField();      
    }
    
    
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ImageWindow::configureScreenshotFrequency(){

   ScreenshotFrequencyDialog dialog;
   dialog.loadCurrentValues(screenshotFrequency);
   ///shows dialog
   if (dialog.exec()) {
      ///dialog vanished from the screen, read values from dialog
      screenshotFrequency=dialog.freqSpinBox->value();
   
   }      
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void ImageWindow::configureTypes3DInvisible(){
   
   Types3DInvisibleDialog dialog;

   dialog.loadCurrentValues(univGraphSet.types3DInvisibleVec);
      
   if (dialog.exec()) {
   
      dialog.fillTypes3DInvisibleVec(univGraphSet.types3DInvisibleVec);
      
      if(drawingAllowed)
         drawField();      
      
      
   }

 
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void ImageWindow::configure3DDisplay(){
   
   Configure3DDialog dialog;
   Display3D * disp=(Display3D*)display3D;
   Configure3DData data = disp->getConfigure3DData();
   dialog.loadCurrentValues(data);

//    cerr<<"data.sizeX="<<data.sizeX<<" data.sizeY="<<data.sizeY<<" data.sizeZ="<<data.sizeZ<<endl;
   
   if (dialog.exec()) {

      data.sizeX=dialog.xSpinBox->value();
      data.sizeY=dialog.ySpinBox->value();
      data.sizeZ=dialog.zSpinBox->value();
      data.rotationX=dialog.xRotSpinBox->value();
      data.rotationY=dialog.yRotSpinBox->value();
      data.rotationZ=dialog.zRotSpinBox->value();
      
      disp->setConfigure3DData(data);
      
      
      if(drawingAllowed)
         drawField();      
      
      
   }

 
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ImageWindow::configureCellTypeColors(){

   CellTypeColorDialog dialog;
   
    short cellType;
    map<unsigned short,QPen>::iterator pmItr;
    map<unsigned short,QBrush>::iterator bmItr;
    UniversalGraphicsSettings::colorMapItr cItr;

   //loading current color assignments
   dialog.loadCurrentValues(univGraphSet.typeColorMap);
   dialog.borderColorLabel->setPaletteBackgroundColor(univGraphSet.borderPen.color());
   dialog.contourColorLabel->setPaletteBackgroundColor(univGraphSet.contourPen.color());

   
   if (dialog.exec()) {

          QColor borderColor = dialog.borderColorLabel->paletteBackgroundColor();
          QColor contourColor = dialog.contourColorLabel->paletteBackgroundColor();
          univGraphSet.borderPen.setColor(borderColor);
          univGraphSet.contourPen.setColor(contourColor);

          univGraphSet.borderColor=borderColor;
          univGraphSet.contourColor=contourColor;

          for (int row=0;row < dialog.typeColorTable->numRows() ; ++row){
            QColor color = ((ColorItem*) dialog.typeColorTable->item (row, 1 ))->color();
            QString text = dialog.typeColorTable->text(row,0);
            bool conversionOK;
            cellType=text.toShort(&conversionOK);
            if(!conversionOK)
               continue; //in case user enters non-number value
            
            
            pmItr=univGraphSet.typePenMap.find(cellType);
            if(pmItr != univGraphSet.typePenMap.end() ){
               univGraphSet.typePenMap.erase(pmItr);
               univGraphSet.typePenMap.insert(make_pair(cellType,QPen(color)));
            }else{
               univGraphSet.typePenMap.insert(make_pair(cellType,QPen(color)));
            }
   
            
            bmItr=univGraphSet.typeBrushMap.find(cellType);
            if(bmItr != univGraphSet.typeBrushMap.end() ){
               univGraphSet.typeBrushMap.erase(bmItr);
               univGraphSet.typeBrushMap.insert(make_pair(cellType,QBrush(color)));
            }else{
               univGraphSet.typeBrushMap.insert(make_pair(cellType,QBrush(color)));
            }
            
            cItr=univGraphSet.typeColorMap.find(cellType);
            if(cItr != univGraphSet.typeColorMap.end() ){
               univGraphSet.typeColorMap.erase(cItr);
               univGraphSet.typeColorMap.insert(make_pair(cellType,color));
            }else{
               univGraphSet.typeColorMap.insert(make_pair(cellType,color));
            }

          }
      
   }

      if(drawingAllowed)
         drawField();      


}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void ImageWindow::createActions()
{

    openAct = new QAction("Open",tr("&Open..."), tr("Ctrl+O"), this);
    openAct->setStatusTip(tr("Open an existing image file"));
    connect(openAct, SIGNAL(activated()),
            this, SLOT(open()));

    saveScrDesAct = new QAction("Save Screenshot Description...",tr("Save Screenshot Description..."), 0, this);
    saveScrDesAct->setStatusTip(tr("Save Screenshot Description text file"));
    connect(saveScrDesAct, SIGNAL(activated()),
            this, SLOT(saveScrDes()));
    saveScrDesAct->setEnabled(false);

            

    exitAct = new QAction("Exit",tr("E&xit"), tr("Ctrl+Q"), this);
    exitAct->setStatusTip(tr("Exit the application"));
    connect(exitAct, SIGNAL(activated()),
            this, SLOT(close()));


    ///simulation
    simulationAct = new QAction("Start Simulation",tr("Start Si&mulation"),
                                    tr("Ctrl+M"), this);
                                    
    simulationAct->setStatusTip(tr("Start simulation"));
    simulationAct->setIconSet(QPixmap::fromMimeSource("Tape_play.gif"));

    connect(simulationAct, SIGNAL(activated()),
            this, SLOT(simulation()));


    simulationPauseAct = new QAction("Pause",tr("Pause Simulation"),
                                    tr("Ctrl+Z"), this);

    simulationPauseAct->setStatusTip(tr("Pause simulation"));
    simulationPauseAct->setIconSet(QPixmap::fromMimeSource("Tape_pause.gif"));

    simulationPauseAct->setEnabled(false);
    
    connect(simulationPauseAct, SIGNAL(activated()),
            this, SLOT(simulationPause()));


            
   ///zooming
    zoomInAct = new QAction("Zoom In",tr("ZoomIn"),
                                    tr("Ctrl+="), this);
                                    
    zoomInAct->setStatusTip(tr("ZoomIn view"));
    zoomInAct->setIconSet(QPixmap::fromMimeSource("zoomin.png"));
    
    connect(zoomInAct, SIGNAL(activated()),
            this, SLOT(zoomIn()));

    zoomInAct->setEnabled(false);
   
    zoomOutAct = new QAction("Zoom Out",tr("ZoomOut"),
                                    tr("Ctrl+-"), this);

    zoomOutAct->setStatusTip(tr("ZoomOut view"));
    zoomOutAct->setIconSet(QPixmap::fromMimeSource("zoomout.png"));
    
    connect(zoomOutAct, SIGNAL(activated()),
            this, SLOT(zoomOut()));

    zoomOutAct->setEnabled(false);
            
   ///Show actions
    showBordersAct = new QAction("Cell Borders",tr("Cell borders"),
                                    tr(""), this);

    showBordersAct->setStatusTip(tr("Show cell borders"));
    
    showBordersAct->setToggleAction(true);  
    
    connect(showBordersAct, SIGNAL(toggled(bool)),
            this, SLOT(bordersDisplay(bool)));


    showContoursAct = new QAction("Concentration contours",tr("Concentration contours"),
                                    tr(""), this);
                                    
    showContoursAct->setStatusTip(tr("Show concentration isocontour lines"));
    
    showContoursAct->setToggleAction(true);
    
    connect(showContoursAct, SIGNAL(toggled(bool)),
            this, SLOT(contoursDisplay(bool)));
            
    showConcentrationLimitsAct = new QAction("Concentration limits",tr("Concentration limits"),
                                    tr(""), this);

    showConcentrationLimitsAct->setStatusTip(tr("Show min and max concentration"));
    
    showConcentrationLimitsAct->setToggleAction(true);
    
    connect(showConcentrationLimitsAct, SIGNAL(toggled(bool)),
            this, SLOT(concentrationLimitsDisplay(bool)));

        
    ///Configure colors action

    typeColorAct = new QAction("Cell type colors",tr("Cell type colors..."),
                                    tr(""), this);
                                    
    typeColorAct->setStatusTip(tr("Display and configure cell type colors"));
   
    connect(typeColorAct, SIGNAL(activated()),
            this, SLOT(configureCellTypeColors()));

    colorMapPlotAct = new QAction("Colormap plot...",tr("Colormap plot..."),
                                    tr(""), this);

    colorMapPlotAct->setStatusTip(tr("Configure color map plot"));
   
    connect(colorMapPlotAct, SIGNAL(activated()),
            this, SLOT(configureColorMapPlot()));
    
    vectorFieldPlotAct = new QAction("Vector field plot...",tr("Vector Field plot..."),
                                    tr(""), this);

    vectorFieldPlotAct->setStatusTip(tr("Configure vector field plot"));

    connect(vectorFieldPlotAct, SIGNAL(activated()),
            this, SLOT(configureVectorFieldPlot()));
                        

    screenshotFrequencyAct = new QAction("Screenshot Frequency...",tr("Screenshot frequency..."),
                                    tr(""), this);

    screenshotFrequencyAct->setStatusTip(tr("Configure screenshot frequency"));
   
    connect(screenshotFrequencyAct, SIGNAL(activated()),
            this, SLOT(configureScreenshotFrequency()));
            
    types3DInvisibleAct = new QAction("Cell Types invisible in 3D",tr("Cell Types invisible in 3D..."),
                                    tr(""), this);

    types3DInvisibleAct->setStatusTip(tr("You may list cell types that will be invisible in 3D"));
   
    connect(types3DInvisibleAct, SIGNAL(activated()),
            this, SLOT(configureTypes3DInvisible()));
            

    configure3DDisplayAct = new QAction("Configure 3D Display",tr("3D Display configuration"),
                                    tr(""), this);

    configure3DDisplayAct->setStatusTip(tr("3D Display configuration"));
   
    connect(configure3DDisplayAct, SIGNAL(activated()),
            this, SLOT(configure3DDisplay()));

    //save settings Action

    saveSettingsAct = new QAction("Save Default Settings",tr("Save Default Settings"),tr(""),this);
    saveSettingsAct->setStatusTip(tr("Saves current settings as default settings"));
    connect(saveSettingsAct, SIGNAL(activated()),
            this, SLOT(saveSettings()));
    
                        
    aboutAct = new QAction("About",tr("&About"), 0, this);
    aboutAct->setStatusTip(tr("Show the application's About box"));
    connect(aboutAct, SIGNAL(activated()),
            this, SLOT(about()));


    aboutQtAct = new QAction("About Qt",tr("About &Qt"), 0, this);    
    aboutQtAct->setStatusTip(tr("Show the Qt library's About box"));
    connect(aboutQtAct, SIGNAL(activated()),
            qApp, SLOT(aboutQt()));
    
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ImageWindow::plotTypeUpdate( const QString &){

   drawField();
   
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ImageWindow::readScreenshotDescriptionList(std::list<ScreenshotDescription> & _screenshotDescriptionList, const std::string &fileName){

   ifstream in(fileName.c_str());
   if(!in.good()){
      cerr<<"Could not open file "<<fileName<<endl;
      exit(1);
   }

   _screenshotDescriptionList.clear();
   
   while(!in.eof()){
      ScreenshotDescription scshDes;
      in>>scshDes;
      cerr<<" new scrDes:"<<endl;
      cerr<<scshDes<<endl;
      if(!in.fail()){
         _screenshotDescriptionList.push_back(scshDes);
      }
   }
   
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void ImageWindow::produceScreenshotDataList(const std::list<ScreenshotDescription> & _screenshotDescriptionList){
   //This function produces list of screenshot descriptions and stores them in a list. Then every screenshotFrequency MCS
   //this list is being read and screenshots are taken.
   
   //will clear screenshotDataList just in case...
   for (list<ScreenshotData*>::iterator litr = screenshotDataList.begin() ; litr != screenshotDataList.end() ; ++litr){

      delete *litr;
      *litr=0;
   }
   screenshotDataList.clear();

   int scrCounter=0;
   
   for ( list<ScreenshotDescription>::const_iterator litr = _screenshotDescriptionList.begin() ;
         litr != _screenshotDescriptionList.end() ;
         ++litr )
   {
      ScreenshotData * scshPtr=new ScreenshotData();
      if(litr->viewDimension=="3D"){
         scshPtr->graphicsPtr=new Display3D(0);
         scshPtr->graphicsPtr->setGraphicsDataFieldPtr(graphFieldsPtr);
        ((Display3D * )scshPtr->graphicsPtr)->setSizeLMN(graphFieldsPtr->getSizeL(),graphFieldsPtr->getSizeM(),graphFieldsPtr->getSizeN());
        ((Display3D * )scshPtr->graphicsPtr)->setDrawingAllowedFlag(true);
        ((Display3D * )scshPtr->graphicsPtr)->setConfigure3DData(litr->data3D);
      }else{
      
         //check if projData are within field boundaries
         if(! litr->projData.checkIfCompatibleWithField(graphFieldsPtr->getSizeL(),graphFieldsPtr->getSizeM(),graphFieldsPtr->getSizeN()) ){
            delete scshPtr ;
            continue;
         }
         
         scshPtr->graphicsPtr=new Graphics2D(0);
         ((Graphics2D * )scshPtr->graphicsPtr)->projData=litr->projData;
         scshPtr->graphicsPtr->setGraphicsDataFieldPtr(graphFieldsPtr);
      }
      
      QString selectedPlotType=litr->plotName;
      
      if( selectedPlotType == QString("Cell_Field") ){
         scshPtr->graphicsPtr->setCurrentPainitgFcnPtr(scshPtr->graphicsPtr->getPaintLattice());
      }else{
         

         
         GraphicsDataFields::floatField3DNameMapItr_t mitr=
         scshPtr->graphicsPtr->getGraphFieldsPtr()->getFloatField3DNameMap().find(string(selectedPlotType.ascii()));
   
         cerr<<"LOOKING FOR A STRING:"<<string(selectedPlotType.ascii())<<endl;
         
         if(mitr != scshPtr->graphicsPtr->getGraphFieldsPtr()->getFloatField3DNameMap().end() ){
         
            cerr<<"FOUND:"<<string(selectedPlotType.ascii())<<endl;
            scshPtr->graphicsPtr->setCurrentConcentrationFieldPtr(mitr->second);
   
            scshPtr->graphicsPtr->setCurrentPainitgFcnPtr(currentGraphicsPtr->getPaintConcentrationLattice());
                        
         }else{
            delete scshPtr ;
            continue;   
         }
      
      }
      
      if(screenshotDataList.size()<=maxScreenshotListLength){
      
         QString currentScreenshotName=screenshotCoreName+QString().setNum(scrCounter);
         scrCounter++;
         
         scshPtr->univGraphSet=univGraphSet;//copying current graphics settings - IMPORTANT
         
         scshPtr->setCoreName(currentScreenshotName.ascii());
         scshPtr->setScreenshotIdName(currentScreenshotName);
         
         screenshotDataList.push_back(scshPtr);
         
         scshPtr->activate(simulationRootDir);
      }
   }

}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ImageWindow::addScreenshot(){

      if(!drawingAllowed)
         return;
         
     mutexFieldDraw.lock();

      ScreenshotDescription scshDes;
       
      ScreenshotData * scshPtr=new ScreenshotData();
      QString scrName;
      
      
      scrName=screenshotName();
      if(display3DButton->isOn()){
         scshDes.viewDimension="3D" ;
         
         scshPtr->graphicsPtr=new Display3D(0);
         

         scshPtr->graphicsPtr->setGraphicsDataFieldPtr(graphFieldsPtr);
        ((Display3D * )scshPtr->graphicsPtr)->setSizeLMN(graphFieldsPtr->getSizeL(),graphFieldsPtr->getSizeM(),graphFieldsPtr->getSizeN());
        
        ((Display3D * )scshPtr->graphicsPtr)->setDrawingAllowedFlag(true);
        Configure3DData   data3D = ((Display3D * )display3D)->getConfigure3DData();
        ((Display3D * )scshPtr->graphicsPtr)->setConfigure3DData(data3D);


      }else{
         //scshDes
         scshDes.viewDimension="2D";
         scshDes.projData=((Graphics2D * )graphics2DPtr)->projData;
         //scshData
         scshPtr->graphicsPtr=new Graphics2D(0);
         ((Graphics2D * )scshPtr->graphicsPtr)->projData=((Graphics2D * )graphics2DPtr)->projData;
         scshPtr->graphicsPtr->setGraphicsDataFieldPtr(graphFieldsPtr);



      }

      scshPtr->univGraphSet=univGraphSet;//copying current graphics settings - IMPORTANT

      
      scshPtr->setCoreName(scrName.ascii());
      scshPtr->setScreenshotIdName(scrName);


      
      QString selectedPlotType=plotTypeComboBox->currentText();
      
      if( selectedPlotType == QString("Cell Field") ){
         scshDes.plotName="Cell_Field";
         scshPtr->graphicsPtr->setCurrentPainitgFcnPtr(scshPtr->graphicsPtr->getPaintLattice());
         
      }else{
            scshDes.plotName=selectedPlotType;
            
            GraphicsDataFields::floatField3DNameMapItr_t mitr=
            scshPtr->graphicsPtr->getGraphFieldsPtr()->getFloatField3DNameMap().find(string(selectedPlotType.ascii()));
      
            cerr<<"LOOKING FOR A STRING:"<<string(selectedPlotType.ascii())<<endl;
            
            if(mitr != scshPtr->graphicsPtr->getGraphFieldsPtr()->getFloatField3DNameMap().end() ){
            
               cerr<<"FOUND:"<<string(selectedPlotType.ascii())<<endl;
               scshPtr->graphicsPtr->setCurrentConcentrationFieldPtr(mitr->second);
      
               scshPtr->graphicsPtr->setCurrentPainitgFcnPtr(currentGraphicsPtr->getPaintConcentrationLattice());
               
                        
               
               
               
            }else{
            
               scshPtr->graphicsPtr->setCurrentConcentrationFieldPtr(& scshPtr->graphicsPtr->getGraphFieldsPtr()->field3DConcentration);
               scshPtr->graphicsPtr->setCurrentPainitgFcnPtr(scshPtr->graphicsPtr->getPaintConcentrationLattice());
               
               
      
            }
         //scshDes
         scshDes.minConcentration=minConcentration;
         scshDes.maxConcentration=maxConcentration;
         scshDes.minConcentrationFixed=minConcentrationFixed;
         scshDes.maxConcentrationFixed=maxConcentrationFixed;
         
         //scshData   
         scshPtr->graphicsPtr->setMinConcentrationFixed(minConcentrationFixed);
         scshPtr->graphicsPtr->setMaxConcentrationFixed(maxConcentrationFixed);
         scshPtr->graphicsPtr->setMinConcentration(minConcentration);
         scshPtr->graphicsPtr->setMaxConcentration(maxConcentration);
         scshPtr->graphicsPtr->setNumberOfLegendBoxes(numberOfLegendBoxes);
         scshPtr->graphicsPtr->setNumberAccuracy(numberAccuracy);
         scshPtr->graphicsPtr->setLegendEnable(legendEnable);
         scshPtr->graphicsPtr->setArrowLength(arrowLength);
         scshPtr->graphicsPtr->setNumberOfLegendBoxesVector(numberOfLegendBoxesVector);
         scshPtr->graphicsPtr->setNumberAccuracyVector(numberAccuracyVector);
         scshPtr->graphicsPtr->setLegendEnableVector(legendEnableVector);
         scshPtr->graphicsPtr->setArrowLength(arrowLength);
         scshPtr->graphicsPtr->setCurrentPainitgFcnPtr(scshPtr->graphicsPtr->getPaintConcentrationLattice());
      }

         scshPtr->activate(simulationRootDir);
         //saving scshDes
         screenshotDescriptionList.push_back(scshDes);
         //saving scshData
         screenshotDataList.push_back(scshPtr);

         if(!saveScrDesAct->isEnabled())   
            saveScrDesAct->setEnabled(true);
         
         
         if(screenshotDataList.size()>maxScreenshotListLength){
            recordButton->setEnabled(false);
         }
         


   mutexFieldDraw.unlock();
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

QString ImageWindow::screenshotName(){
   QString name;

   if(display3DButton->isOn()){
      Display3D & d3D = *((Display3D*)display3D);
      name+=QString("3D_");
      name+=QString().setNum(d3D.getRotationX());
      name+=QString("_");
      name+=QString().setNum(d3D.getRotationY());
      name+=QString("_");
      name+=QString().setNum(d3D.getRotationZ());
      
   }else{
      name+=QString("2D_");
      if(xyButton->isOn()){
         name+=QString("xy_");
         name+=zSpinBox->text();
      }
      else if(xzButton->isOn()){
         name+=QString("xz_");
         name+=ySpinBox->text();
      }
      else if(yzButton->isOn()){
         name+=QString("yz_");
         name+=xSpinBox->text();
      }
            
   }

   name+=QString("_");
   name+=plotTypeComboBox->currentText();
   return name;

}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void ImageWindow::createSteeringBar(){
   steeringBar=new QToolBar(tr("Steering"),this);

   simulationAct->addTo(steeringBar);
   simulationPauseAct->addTo(steeringBar);
   simulationPauseAct->setEnabled(false);
      
   zoomInAct->addTo(steeringBar);
   zoomOutAct->addTo(steeringBar);

      
   steeringBar->addSeparator();
   
   
   crossSectionButtonsG = new QHButtonGroup(QString("Cross Section"),steeringBar,"Cross Section");
   display3DButton = new QRadioButton(QString("3D"),crossSectionButtonsG,"3D");
   QToolTip::add(display3DButton,tr("Switch to 3D mode. To speed up rendering \n set some cell types to be invisible in the 3D mode\nClick: Configure->Cell types invisible in 3D..."));
   
   ///xy cross section
   xyButton=new QRadioButton(tr("xy"),crossSectionButtonsG);
   QToolTip::add(xyButton,tr("View lattice along xy plane"));
   zSpinBox=new QSpinBox(crossSectionButtonsG,tr("Z"));
   QToolTip::add(zSpinBox,tr("Change \'z\' coordinate of xy plane"));

   ///xz cross section
   xzButton=new QRadioButton(tr("xz"),crossSectionButtonsG);
   QToolTip::add(xzButton,tr("View lattice along xz plane"));
   ySpinBox=new QSpinBox(crossSectionButtonsG,tr("Y"));
   QToolTip::add(ySpinBox,tr("Change \'y\' coordinate of xz plane"));
   
   yzButton=new QRadioButton(tr("yz"),crossSectionButtonsG);
   QToolTip::add(yzButton,tr("View lattice along yz plane"));
   xSpinBox=new QSpinBox(crossSectionButtonsG,tr("X"));
   QToolTip::add(xSpinBox,tr("Change \'x\' coordinate of yz plane"));
   
   steeringBar->addSeparator();

   
   steeringBar->addSeparator();
   plotTypeComboBoxName=new QLabel(steeringBar,"Plot Type");
   plotTypeComboBox=new QComboBox(steeringBar,tr("Plot Type"));
   QToolTip::add(plotTypeComboBox,tr("Select plot type"));
   
   steeringBar->addSeparator();

   recordButton= new QPushButton(QString(""), steeringBar,tr("add ScrShot button"));
   recordButton->setIconSet(QPixmap::fromMimeSource("Camera.gif"));

   QToolTip::add(recordButton,tr("Add screenshot of current view to be recorded from now on"));
   //recordButton->setWhatsThis(tr("Add screenshot of current view to be recorded from now on"));
   
       connect(xyButton, SIGNAL(toggled(bool)),
            this, SLOT(changeProjectionXY(bool)) );

       connect(zSpinBox, SIGNAL(valueChanged(int)),
            this, SLOT(alterZCoordinate(int)) );
            
            
       connect(xzButton, SIGNAL(toggled(bool)),
            this, SLOT(changeProjectionXZ(bool)) );

       connect(ySpinBox, SIGNAL(valueChanged(int)),
            this, SLOT(alterYCoordinate(int)) );
            
            
       connect(yzButton, SIGNAL(toggled(bool)),
            this, SLOT(changeProjectionYZ(bool)) );

       connect(xSpinBox, SIGNAL(valueChanged(int)),
            this, SLOT(alterXCoordinate(int)) );

       connect(display3DButton, SIGNAL(toggled(bool)),
            this, SLOT(switch3D(bool)) );
            
            
       connect(plotTypeComboBox, SIGNAL(activated ( const QString &)),
            this, SLOT(plotTypeUpdate(const QString &)) );

       connect(recordButton, SIGNAL(clicked()),
            this, SLOT(addScreenshot()) );
            
                                                   
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void ImageWindow::createMenus()
{
    fileMenu = new QPopupMenu(this);
    openAct->addTo(fileMenu);
    saveScrDesAct->addTo(fileMenu);
    fileMenu->insertSeparator();
    exitAct->addTo(fileMenu);

   QPopupMenu *simulationMenu=new QPopupMenu(this);
   simulationAct->addTo(simulationMenu);
   simulationPauseAct->addTo(simulationMenu);

   QPopupMenu *zoomMenu=new QPopupMenu(this);
   zoomInAct->addTo(zoomMenu);
   zoomOutAct->addTo(zoomMenu);
   
   QPopupMenu *showMenu=new QPopupMenu(this);
   showBordersAct->addTo(showMenu);
   showContoursAct->addTo(showMenu);
   showConcentrationLimitsAct->addTo(showMenu);
   
   showBordersAct->setEnabled(false);
   showContoursAct->setEnabled(false);
   
   QPopupMenu *configureMenu=new QPopupMenu(this);
   typeColorAct->addTo(configureMenu);
   colorMapPlotAct->addTo(configureMenu);
   vectorFieldPlotAct->addTo(configureMenu);
   screenshotFrequencyAct->addTo(configureMenu);
   types3DInvisibleAct->addTo(configureMenu);
   configure3DDisplayAct->addTo(configureMenu);

   configureMenu->insertSeparator();
   saveSettingsAct->addTo(configureMenu);
   
    helpMenu = new QPopupMenu(this);
    aboutAct->addTo(helpMenu);
    aboutQtAct->addTo(helpMenu);

    menuBar()->insertItem(tr("&File"), fileMenu);
    menuBar()->insertItem(tr("Si&mulation"), simulationMenu);
    menuBar()->insertItem(tr("Zoom"), zoomMenu);
    menuBar()->insertItem(tr("Show"), showMenu);
    menuBar()->insertItem(tr("Configure"), configureMenu);
    menuBar()->insertSeparator();
    menuBar()->insertItem(tr("&Help"), helpMenu);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void ImageWindow::createStatusBar()
{
    
    mcStepLabel = new QLabel(this);
    mcStepLabel->setPaletteBackgroundColor("white");
    mcStepLabel->setPaletteForegroundColor("red");
    mcStepLabel->setAlignment(AlignHCenter);
    mcStepLabel->setMinimumSize(mcStepLabel->sizeHint());
    
    minMaxConcentrationLabel=new QLabel(this);
    minMaxConcentrationLabel->setAlignment(AlignHCenter);
    minMaxConcentrationLabel->setMinimumSize(minMaxConcentrationLabel->sizeHint());

    statusBar()->addWidget(mcStepLabel);
    statusBar()->addWidget(minMaxConcentrationLabel);


}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ImageWindow::saveScrDesFile(const QString &fileName){

   ofstream out(fileName.ascii());
   for (list<ScreenshotDescription>::iterator litr = screenshotDescriptionList.begin() ; litr != screenshotDescriptionList.end() ; ++litr){
      out<<*litr<<endl;
   }
   
   

}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ImageWindow::setCurrentFile(const QString &fileName)
{
    curFile = fileName;
    modified = false;

     bool hasNewConfigFile = !curFile.isEmpty();

    if (hasNewConfigFile) {
        setCaption(tr("%1 - %2").arg(strippedName(curFile))
                                .arg(tr("CompuCellPlayer")));
    } else {
        setCaption(tr("CompuCellPlayer"));
    }

}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
QString ImageWindow::strippedName(const QString &fullFileName)
{
    return QFileInfo(fullFileName).fileName();
}
