Exemplo n.º 1
0
long CDownload::retrieveLocalFile(const MYCHAR* _url,int _order,MyString& _path, MyString& _short)
{

	MyString url = _url;
	
	MyString ext(getext(url));	
	
	if (!ext.CompareNoCase("zip"))
	{
	
		if (!retrieveZippedFile(url,_order,_path,_short))
		{
			if (!unzipFile(url,url))
			{
				// unzip failed...
				outputInfo("unzip failed (%s)\n",_url);
				return 0;
			}
			if (!retrieveZippedFile(url,_order,_path,_short))
			{
				outputInfo("could not find zip (%s)\n",_url);
				return 0;
			}
		}
		
	}
	else
	{
		_path = url;
		
		_short = getfile(url);
	}



	FILE* f = fopen(_path.c_str(),"rb");
	if (f)
	{
		/*int err =*/ fseek(f,0,SEEK_END);
		long size = ftell(f);
		fclose(f);	
		return size;
	}
	else
	{
		outputInfo("could not find file (%s)\n",_url);
		::showStatus("Failed to load %s",getfile(_url));
		return 0;
	}

}
Exemplo n.º 2
0
void NNClassifier::train(const TYPE_TRAIN_DATA_SET &trainDataSet)
{
    for(auto &trainData : trainDataSet)
    {
        Mat patch = getPatch(trainData.first);
        
        if(trainData.second == CLASS_POS || trainData.second == CLASS_NEG)
        {
            if(update(patch, trainData.second))
            {
                addToNewSamples(patch, trainData.second);
            }
        }
    }
    
    for(auto &trainData : trainDataSet)
    {
        if(trainData.second == CLASS_TEST_NEG)
        {
            int dummy;
            float Sr = calcSr(trainData.first, dummy);
            if(Sr > thPos)
            {
                thPos = Sr;

                stringstream info;
                info << "Increase threshold of positive class to " << thPos;
                outputInfo("NN", info.str());
            }
        }
    }
}
Exemplo n.º 3
0
int _tmain(int argc, char* argv[])
{
	char *inFile = NULL;
	outFormat format = NOTSET;
	int rowStart = -1;
	int rowEnd = -1;
	packets parsedList;

#ifdef _DEBUG
	testparseQueryString();
	testParseFile();
#endif

	printf("Content-Type: text/xml\n\n");

	if (!checkArgs(argc, argv, &inFile, format, rowStart, rowEnd))
	{
		printUsage();
		return -1;
	}

	parseFile(inFile, rowStart, rowEnd, parsedList);

	outputInfo(parsedList, format);

	return 0;
}
Exemplo n.º 4
0
void XRandROutput::init()
{
    XCB::OutputInfo outputInfo(m_id, XCB_TIME_CURRENT_TIME);
    Q_ASSERT(outputInfo);
    if (!outputInfo) {
        return;
    }

    XCB::PrimaryOutput primary(XRandR::rootWindow());

    m_name = QString::fromUtf8((const char *) xcb_randr_get_output_info_name(outputInfo.data()), outputInfo->name_len);
    m_type = fetchOutputType(m_id, m_name);
    m_icon = QString();
    m_connected = (xcb_randr_connection_t) outputInfo->connection;
    m_primary = (primary->output == m_id);
    xcb_randr_output_t *clones = xcb_randr_get_output_info_clones(outputInfo.data());
    for (int i = 0; i < outputInfo->num_clones; ++i) {
        m_clones.append(clones[i]);
    }
    m_widthMm = outputInfo->mm_width;
    m_heightMm = outputInfo->mm_height;
    m_crtc = m_config->crtc(outputInfo->crtc);
    if (m_crtc) {
        m_crtc->connectOutput(m_id);
    }

    updateModes(outputInfo);
}
Exemplo n.º 5
0
void XRandROutput::update(xcb_randr_crtc_t crtc, xcb_randr_mode_t mode, xcb_randr_connection_t conn, bool primary)
{
    qCDebug(KSCREEN_XRANDR) << "XRandROutput" << m_id << "update";
    qCDebug(KSCREEN_XRANDR) << "\tm_connected:" << m_connected;
    qCDebug(KSCREEN_XRANDR) << "\tm_crtc" << m_crtc;
    qCDebug(KSCREEN_XRANDR) << "\tCRTC:" << crtc;
    qCDebug(KSCREEN_XRANDR) << "\tMODE:" << mode;
    qCDebug(KSCREEN_XRANDR) << "\tConnection:" << conn;
    qCDebug(KSCREEN_XRANDR) << "\tPrimary:" << primary;

    // Connected or disconnected
    if (isConnected() != (conn == XCB_RANDR_CONNECTION_CONNECTED)) {
        if (conn == XCB_RANDR_CONNECTION_CONNECTED) {
            // New monitor has been connected, refresh everything
            init();
        } else {
            // Disconnected
            m_connected = conn;
            m_clones.clear();
            m_heightMm = 0;
            m_widthMm = 0;
            m_type = KScreen::Output::Unknown;
            qDeleteAll(m_modes);
            m_modes.clear();
            m_preferredModes.clear();
        }
    } else if (conn == XCB_RANDR_CONNECTION_CONNECTED) {
        // the output changed in some way, let's update the internal
        // list of modes, as it may have changed
        XCB::OutputInfo outputInfo(m_id, XCB_TIME_CURRENT_TIME);
        if (outputInfo) {
            updateModes(outputInfo);
        }

    }

    // A monitor has been enabled or disabled
    // We don't use isEnabled(), because it checks for crtc && crtc->mode(), however
    // crtc->mode may already be unset due to xcb_randr_crtc_tChangeNotify coming before
    // xcb_randr_output_tChangeNotify and reseting the CRTC mode

    if ((m_crtc == Q_NULLPTR) != (crtc == XCB_NONE)) {
        if (crtc == XCB_NONE && mode == XCB_NONE) {
            // Monitor has been disabled
            m_crtc->disconectOutput(m_id);
            m_crtc = 0;
        } else {
            m_crtc = m_config->crtc(crtc);
            m_crtc->connectOutput(m_id);
        }
    }

    // Primary has changed
    m_primary = primary;
}
Exemplo n.º 6
0
void NNClassifier::showModel()
{
    if(!SHOW_NEW_NN_SAMPLES) return;
    
    stringstream info;
    info << "Positive samples : " << pPatches.size() << " Negative samples : " << nPatches.size();
    
    outputInfo("NN", info.str());
    
    if(newSamplesP.cols) imshow("new positive samples", newSamplesP);
    if(newSamplesN.cols) imshow("new negative samples", newSamplesN);

    waitKey(1);
}
Exemplo n.º 7
0
void Invocation::runTesting() {
	cout << endl;
	Tester * curTest = new Tester(params, info);
	int testsCount = params->getTestsCount();
	if (!params->getInputFileMask()->getDigitsCount() || !params->getOutputFileMask()->getDigitsCount()) testsCount = 1;
	ERROR_CODE errorCode = EC_OK;
	OUTCOME_TYPE outcome = OT_UD;
	bool autoDetectTestsNumber = !testsCount;
	for (int test = 1; !testsCount || test <= testsCount; ++test) { 
		errorCode = curTest->runTest(test, autoDetectTestsNumber);
		if (errorCode) {
			delete curTest;
			if (!testsCount && (errorCode == EC_INPUT_DATA_FILE_NOT_FOUND || errorCode == EC_ANSWER_DATA_FILE_NOT_FOUND)) {
				info->setOutcome(OT_AC);
				return;
			}
			printColoredText("Internal Error", CC_LIGHTMAGENTA);
			cout << endl;
			info->setOutcome(OT_IE);
			info->setComment("Test " + toa(test) + ": " + ERROR_MESSAGES[errorCode]);
			outputInfo();
			if (errorCode != EC_CANNOT_TERMINATE_TESTING_PROGRAM && errorCode != EC_CANNOT_TERMINATE_CHECKER) terminate(true, true); else terminate(true, false);
		}
		cout << "Time: ";
		printColoredText(toa(info->getLastTestTime()), CC_LIGHTCYAN);
		cout << " ms  Memory: ";
		int usedMemory = info->getLastTestMemory();
		if (usedMemory < 1000) {
			printColoredText(toa(usedMemory), CC_LIGHTCYAN); 
			cout << " B  ";
		} else
		if (usedMemory < 1000000) {
			printColoredText(toa(usedMemory / 1000), CC_LIGHTCYAN); 
			cout << " KB  ";
		} else {
			printColoredText(toa(usedMemory / 1000000.), CC_LIGHTCYAN); 
			cout << " MB  ";
		}
		outcome = info->getOutcome();
		printColoredText(SHORT_OUTCOME_NAME[outcome], OUTCOME_COLOR[outcome]);
		cout << endl;
		if (outcome != OT_UD) {
			delete curTest;
			return;
		}
	}
	info->setOutcome(OT_AC);
	delete curTest;
}
Exemplo n.º 8
0
bool Gcc::compile(QString filename)
{
	QFileInfo sourceInfo(filename);
	QStringList args;

	refreshSettings();

#ifdef Q_OS_WIN32
	m_outputFileName = sourceInfo.dir().absoluteFilePath(sourceInfo.baseName() + ".exe");
#else
	m_outputFileName = sourceInfo.dir().absoluteFilePath(sourceInfo.baseName());
#endif
	QString objectName = sourceInfo.dir().absoluteFilePath(sourceInfo.baseName() + ".o");

	QFileInfo outputInfo(m_outputFileName);
	if(sourceInfo.lastModified() < outputInfo.lastModified())
		return true;

	args = m_cflags;
	m_defaultPort.replace("\\", "\\\\");
	args << "-DDEFAULT_SERIAL_PORT=\"" + m_defaultPort + "\"";
	args << "-c" << filename << "-o" << objectName;
	m_gcc.start(m_gccPath, args);
	m_gcc.waitForFinished();
	processCompilerOutput();
	m_linkerMessages.clear();

	if(m_gcc.exitCode() != 0)
		return false;

	args.clear();
	args << "-o" << m_outputFileName << objectName;
	args << m_lflags;
	m_gcc.start(m_gccPath, args);
	m_gcc.waitForFinished();
	processLinkerOutput();

	QFile objectFile(objectName);
	objectFile.remove();

	if(m_gcc.exitCode() == 0)
		return true;
	return false;
}
Exemplo n.º 9
0
/*!
  \internal

  Returns true if file names for \a input and \a output are the same.
 */
bool SpdrImportPrivate::areFilesTheSame(const QString &input, const QString &output) const
{
    Q_Q(const SpdrImport);

    QFileInfo outputInfo(output);
    if (!outputInfo.exists()) {

        if (q->isSuffixCaseSensitive()) {
            return false;
        } else {
            SpdrFileData inputData(input, q->inputPath(), SpdrFileData::ShallowSearch, q);

            QDir outputDir(output);
            outputDir.cdUp();
            QFileInfoList outputFiles(outputDir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot));

            foreach (const QFileInfo &file, outputFiles) {
                if (file.baseName() != outputInfo.baseName()) {
                    continue;
                }

                SpdrFileData outputData(file.absoluteFilePath(), "", SpdrFileData::ShallowSearch, q);

                if (inputData.isEqual(outputData, q->isSuffixCaseSensitive())) {
                    return true;
                } else {
                    continue;
                }
            }
        }

        return false;
    }

    SpdrFileData inputData(input, q->inputPath(), SpdrFileData::ShallowSearch, q);
    SpdrFileData outputData(output, q->inputPath(), SpdrFileData::ShallowSearch, q);

    if (inputData.isEqual(outputData, q->isSuffixCaseSensitive())) {
        return true;
    }

    return false;
}
Exemplo n.º 10
0
void AddTulpaWidget::save()
{
    /*Checks*/
    if(lineEdits.at(LINE_EDIT_NAME)->text().isEmpty())
    {
        QMessageBox::critical(this,"Error","Please specify a name");
    }
    else
    {
        if(lineEdits.at(LINE_EDIT_FIRST_WORD)->text().isEmpty())
        {
            lineEdits.at(LINE_EDIT_FIRST_WORD)->setText("Not yet answered");
        }
        if(personalityTraits.isEmpty())
        {
            QMessageBox::information(this,"Peronality","Remember to set a personality for your Tulpa later");
        }


        /*Saving*/
        tulpa.setName(lineEdits.at(LINE_EDIT_NAME)->text().toStdString());
        tulpa.setBirthTime(dateEdit->date().toString(DATE_TYPE).toStdString());
        tulpa.setFirstWordTime(lineEdits.at(LINE_EDIT_FIRST_WORD)->text().toStdString());

        std::vector<std::string> personality;

        for(int i=0;i<personalityTraits.size();i++)
        {
            personality.push_back(personalityTraits.at(i).toStdString());
        }

        tulpa.setPersonalityTraits(personality);

        tulpa.generateFilePath();
        tulpa.save();

        outputInfo(L_DEBUG,std::string("Saved tulpa ") + tulpa.getName());

        emit finished();
        this->close();
    }
}
Exemplo n.º 11
0
int QStartupWorker::main_routine()
{
    //Contacts the remote server to update the database regarding the number of users.
    //It sends the version of the software. The PHP page uses the IP and the current time

    //I might use a similar way in the future to remotely save your tulpas so you'll just have to sync an account.

    QNetworkAccessManager *manager = new QNetworkAccessManager;
    QNetworkRequest request;

    QUrl url("http://florentuguet.net16.net/tulpadiary/software.php"); //Main URL
    //QUrl url("http://florentuguet.net16.net/tulpadiary/software-test\.php"); //Test URL
    QUrlQuery params;

    request.setUrl(url.toString());
    request.setRawHeader("User-Agent", "TulpaDiary");
    request.setRawHeader("Content-Type","application/x-www-form-urlencoded");

    params.addQueryItem("version", QString(VERSION));
    params.addQueryItem("build", QString::number(BUILD));

    if(DEBUG){params.addQueryItem("type", "debug");}
    else{params.addQueryItem("type", "release");}

    QByteArray data;
    data.append(params.toString()); //POST params

    QNetworkReply* m_pReply = manager->post(request,data);

    QTimer timer(0);
    timer.setInterval(5000); //5s timeout

    QObject::connect(&timer, SIGNAL(timeout()),m_pReply, SLOT(abort()));

    QEventLoop loop;
    QObject::connect(m_pReply, SIGNAL(finished()),&loop, SLOT(quit()));
    loop.exec();


    if(m_pReply->error() != QNetworkReply::NoError)
    {
        outputInfo(L_ERROR,std::string("Error when sending version : ") + m_pReply->errorString().toStdString());
        return m_pReply->error();
    }

    bool ok;

    qDebug() << "Version :"<<m_pReply->rawHeader("X-Version") <<m_pReply->rawHeader("X-Build");
    qDebug()<< m_pReply->rawHeaderList();

    QString lastBuild_s = QString(m_pReply->rawHeader("X-Build"));
    QString version = QString(m_pReply->rawHeader("X-Version"));

    int lastBuild = lastBuild_s.toInt(&ok);

    if(!ok)
    {
        //Logs the HTTP response
        outputInfo(L_ERROR,std::string("Retrieved build isn't a String : ") + lastBuild_s.toStdString());
        outputInfo(L_ERROR,std::string("Full string : ") + QString(m_pReply->readAll()).toStdString());
    }
    else
    {
        //Checks the update status
        if(lastBuild > BUILD)
        {
            //Update needed
            outputInfo(L_DEBUG,std::string("Update required : ") + std::string(VERSION) + std::string(" -> ") + version.toStdString());

            int rep = QMessageBox::question(0,"Update","Version " + version  + " is available, do you wish to update ?\nYou will need to restart the software after the update is complete.\nChangelog: https://community.tulpa.info/thread-software-tulpadiary", QMessageBox ::Yes | QMessageBox::No);
            if (rep == QMessageBox::Yes)
            {
                QDownloadWidget *down = new QDownloadWidget(0,true);
                down->show();
                down->download(URL_EXECUTABLE,EXECUTABLE_DL,true);
            }
        }
        else
        {
            //Update not needed
            outputInfo(L_DEBUG,std::string("You have the latest version"));
        }
    }

    return 0;
}
Exemplo n.º 12
0
CEmulatorMac::~CEmulatorMac()
{
	outputInfo("~CEmulatorMac (%X)\n",this);
}
Exemplo n.º 13
0
QString QgsRasterFileWriter::partFileName( int fileIndex )
{
  // .tif for now
  QFileInfo outputInfo( mOutputUrl );
  return QString( "%1.%2.tif" ).arg( outputInfo.fileName() ).arg( fileIndex );
}
Exemplo n.º 14
0
bool CDownload::retrieveDistantFile(const char* _url,int _order,MyString& _path, MyString& _short)
{
	
	MyString url;
	normalize(_url,url);


	MyString ext(getext(url.c_str()));
	bool bZip = !ext.CompareNoCase("zip");
	bool bRet;

	if (bZip)
	{
		// essaie de rÈcupÈrer la version existante ?
		
		bRet =  retrieveZippedFile(url.c_str(),_order,_path,_short);

		if (!bRet)
		{
			if (bTestOnly)
				return false;

			// essaie de downloader
			bRet = downloadHTTPFile(url.c_str(),_path);

			if (bRet)
			{
				if (!unzipFile(url.c_str(),_path.c_str()))
				{
					// unzip failed...
					outputInfo("unzip failed (%s)\n",getfile(url.c_str()));
					bRet=false;
					deleteFile(_path.c_str());
					outputInfo("deleting file (%s) for recovery next time \n",getfile(_path.c_str()));
					
				}

				if (bRet)
					bRet =  retrieveZippedFile(url.c_str(),_order,_path,_short);
			}
		}
	}
	else
	{
	
	//	if (bUsePersistentPath)
		{
			// fichier distant non zip
			MyString dir;
			MyString local;
			
			dir = getPersistentDir(url.c_str());
			createDirectory(dir.c_str());
			local = dir.c_str();
			local += ACTIVEGS_DIRECTORY_SEPARATOR;
			local += getfile(url.c_str()) ;
		
			// regarde si le fichier existe ?
			// QUID SI LE FICHIER EST CORROMPU ?
            
			FILE* f = fopen(local.c_str(),"rb");
			if (f)
			{
				fclose(f);
				bRet=true;
			}
			else
			{
				// retŽlŽcharge le fichier
				if (bTestOnly)
						return false;
				bRet = GetFile(url.c_str(),local.c_str());
				
			}
			if (bRet)
				_path = local;
		}
		/*
		else
			bRet = downloadHTTPFile(url.c_str(),_path);
		*/

		if (bRet)
			_short = getfile(_path.c_str());

	}
	
	if (!bRet)
	{
	//	showProgress(url.c_str(),-1);
		::showStatus("Failed to download %s\n",getfile(url.c_str()));
	}
	return bRet;
		
}
Exemplo n.º 15
0
void Learner::learn(const Mat &img, const Mat &imgB, const Mat &img32F, const TYPE_BBOX &ret)
{
    TYPE_TRAIN_DATA_SET &nnTrainDataset = detector->trainDataSetNN;
    nnTrainDataset.clear();
    TYPE_TRAIN_DATA_SET &rfTrainDataset = detector->trainDataSetRF;
    rfTrainDataset.clear();
    auto &scanBBs = detector->scanBBs;
    
    detector->sortByOverlap(ret, true);
    
    int count = 0;
    
    // P-expert - NN
    nnTrainDataset.push_back(make_pair(img32F(scanBBs[0]), CLASS_POS));
    
    // P-expert - RF
    int tlx = img.cols, tly = img.rows, brx = 0, bry = 0;
    
    for(int i = 0; i < LEARNER_N_GOOD_BB && scanBBs[i].overlap >= GOODBB_OL; i++)
    {
        tlx = min(tlx, scanBBs[i].tl().x);
        tly = min(tly, scanBBs[i].tl().y);
        brx = max(brx, scanBBs[i].br().x);
        bry = max(bry, scanBBs[i].br().y);
    }
    
    Point tl(tlx, tly), br(brx, bry);
    Rect bbHull(tl, br);
    
    int cx, cy;
    cx = round((double)(tlx + brx) / 2);
    cy = round((double)(tly + bry) / 2);
    
    for(int j = 0; j < LEARNER_N_WARPED; j++)
    {
        Mat warped;
        
        if(j != 0)
        {
            patchGenerator(imgB, Point(cx, cy), warped, bbHull.size(), theRNG());
            // for optimum in RF::getcode()
            Mat tmp(imgB.size() ,CV_8U, Scalar::all(0));
            warped.copyTo(tmp(Rect(0, 0, bbHull.size().width, bbHull.size().height)));
            warped = tmp;
        }
        else
        {
            warped = imgB(bbHull);
        }
        
        for(int i = 0; i < LEARNER_N_GOOD_BB && scanBBs[i].overlap >= GOODBB_OL; i++)
        {
            Rect rect(scanBBs[i].tl() - tl, scanBBs[i].br() - tl);
            
            TYPE_TRAIN_DATA trainData(make_pair(warped(rect), CLASS_POS));
            rfTrainDataset.push_back(trainData);
            
            count++;
        }
    }

    // N-expert - NN
    int nCountNN = 0;
    for(int i = 0; i < detector->scanBBs.size(); i++)
    {
        TYPE_DETECTOR_SCANBB &sbb = detector->scanBBs[i];
        
        if(sbb.status != DETECTOR_REJECT_VAR)
        {
            if(sbb.overlap < BADBB_OL)
            {
                nCountNN++;
                
                TYPE_TRAIN_DATA trainData(make_pair(img32F(sbb), CLASS_NEG));
                nnTrainDataset.push_back(trainData);
            }
        }
        
        if(nCountNN == LEARNER_N_NN_NEG) break;
    }
    
    // N-expert - RF
    int nCountRF = 0;
    for(int i = 0; i < detector->scanBBs.size(); i++)
    {
        TYPE_DETECTOR_SCANBB &sbb = detector->scanBBs[i];
        
        if(sbb.status != DETECTOR_REJECT_VAR)
        {
            if(sbb.overlap < BADBB_OL && sbb.posterior >= 0.1)
            {
                nCountRF++;
                
                TYPE_TRAIN_DATA trainData(make_pair(imgB(sbb), CLASS_NEG));
                rfTrainDataset.push_back(trainData);
            }
        }
    }
    
    stringstream info;
    info << "Generated 1 positive example for NN, and " << count << " positive example for RF.";
    outputInfo("Learner", info.str());
    
    stringstream info2;
    info2 << "Generated " << nCountNN << " NN negative sample(s), and " << nCountRF << " RF negative example(s).";
    outputInfo("Learner", info2.str());
    
    detector->update();
    stringstream info3;
    info3 << "Updated detector.";
    outputInfo("Learner", info3.str());
    
    detector->nNClassifier.showModel();
}
Exemplo n.º 16
0
QString QgsRasterFileWriter::vrtFileName()
{
  QFileInfo outputInfo( mOutputUrl );
  return QString( "%1.vrt" ).arg( outputInfo.fileName() );
}
Exemplo n.º 17
0
int DNGWriter::convert()
{
    d->cancel = false;

    try
    {
        if (inputFile().isEmpty())
        {
            kDebug( 51000 ) << "DNGWriter: No input file to convert. Aborted..." << endl;
            return -1;
        }

        QFileInfo inputInfo(inputFile());
        QString   dngFilePath = outputFile();

        if (dngFilePath.isEmpty())
        {
            dngFilePath = QString(inputInfo.baseName() + QString(".dng"));
        }

        QFileInfo          outputInfo(dngFilePath);
        QByteArray         rawData;
        DcrawInfoContainer identify;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: Loading RAW data from " << inputInfo.fileName() << endl;

        KDcraw rawProcessor;
        if (!rawProcessor.extractRAWData(inputFile(), rawData, identify))
        {
            kDebug( 51000 ) << "DNGWriter: Loading RAW data failed. Aborted..." << endl;
            return -1;
        }

        if (d->cancel) return -2;

        int width      = identify.imageSize.width();
        int height     = identify.imageSize.height();
        int pixelRange = 16;

        kDebug( 51000 ) << "DNGWriter: Raw data loaded:" << endl;
        kDebug( 51000 ) << "--- Data Size:     " << rawData.size() << " bytes" << endl;
        kDebug( 51000 ) << "--- Date:          " << identify.dateTime.toString(Qt::ISODate) << endl;
        kDebug( 51000 ) << "--- Make:          " << identify.make << endl;
        kDebug( 51000 ) << "--- Model:         " << identify.model << endl;
        kDebug( 51000 ) << "--- Size:          " << width << "x" << height << endl;
        kDebug( 51000 ) << "--- Orientation:   " << identify.orientation << endl;
        kDebug( 51000 ) << "--- Top margin:    " << identify.topMargin << endl;
        kDebug( 51000 ) << "--- Left margin:   " << identify.leftMargin << endl;
        kDebug( 51000 ) << "--- Filter:        " << identify.filterPattern << endl;
        kDebug( 51000 ) << "--- Colors:        " << identify.rawColors << endl;
        kDebug( 51000 ) << "--- Black:         " << identify.blackPoint << endl;
        kDebug( 51000 ) << "--- White:         " << identify.whitePoint << endl;
        kDebug( 51000 ) << "--- CAM->XYZ:" << endl;

        QString matrixVal;
        for(int i=0; i<12; i+=3)
        {
            kDebug( 51000 ) << "                   "
                     << QString().sprintf("%03.4f  %03.4f  %03.4f", identify.cameraXYZMatrix[0][ i ],
                                                                    identify.cameraXYZMatrix[0][i+1],
                                                                    identify.cameraXYZMatrix[0][i+2])
                     << endl;
        }

        // Check if CFA layout is supported by DNG SDK.
        int bayerMosaic;

        if (identify.filterPattern == QString("GRBGGRBGGRBGGRBG"))
        {
            bayerMosaic = 0;
        }
        else if (identify.filterPattern == QString("RGGBRGGBRGGBRGGB"))
        {
            bayerMosaic = 1;
        }
        else if (identify.filterPattern == QString("BGGRBGGRBGGRBGGR"))
        {
            bayerMosaic = 2;
        }
        else if (identify.filterPattern == QString("GBRGGBRGGBRGGBRG"))
        {
            bayerMosaic = 3;
        }
        else
        {
            kDebug( 51000 ) << "DNGWriter: Bayer mosaic not supported. Aborted..." << endl;
            return -1;
        }

        // Check if number of Raw Color components is supported.
        if (identify.rawColors != 3)
        {
            kDebug( 51000 ) << "DNGWriter: Number of Raw color components not supported. Aborted..." << endl;
            return -1;
        }

/*      // NOTE: code to hack RAW data extraction

        QString   rawdataFilePath(inputInfo.baseName() + QString(".dat"));
        QFileInfo rawdataInfo(rawdataFilePath);

        QFile rawdataFile(rawdataFilePath);
        if (!rawdataFile.open(QIODevice::WriteOnly))
        {
            kDebug( 51000 ) << "DNGWriter: Cannot open file to write RAW data. Aborted..." << endl;
            return -1;
        }
        QDataStream rawdataStream(&rawdataFile);
        rawdataStream.writeRawData(rawData.data(), rawData.size());
        rawdataFile.close();
*/
        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: Formating RAW data to memory" << endl;

        std::vector<unsigned short> raw_data;
        raw_data.resize(rawData.size());
        const unsigned short* dp = (const unsigned short*)rawData.data();
        for (uint i = 0; i < raw_data.size()/2; i++)
        {
            raw_data[i] = *dp;
            *dp++;
        }

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: DNG memory allocation and initialization" << endl;

        dng_memory_allocator memalloc(gDefaultDNGMemoryAllocator);
        dng_memory_stream stream(memalloc);
        stream.Put(&raw_data.front(), raw_data.size()*sizeof(unsigned short));

        dng_rect rect(height, width);
        DNGWriterHost host(d, &memalloc);

        // Unprocessed raw data.
        host.SetKeepStage1(true);

        // Linearized, tone curve processed data.
        host.SetKeepStage2(true);

        AutoPtr<dng_image> image(new dng_simple_image(rect, 1, ttShort, 1<<pixelRange, memalloc));

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: DNG IFD structure creation" << endl;

        dng_ifd ifd;

        ifd.fUsesNewSubFileType        = true;
        ifd.fNewSubFileType            = 0;
        ifd.fImageWidth                = width;
        ifd.fImageLength               = height;
        ifd.fBitsPerSample[0]          = pixelRange;
        ifd.fBitsPerSample[1]          = 0;
        ifd.fBitsPerSample[2]          = 0;
        ifd.fBitsPerSample[3]          = 0;
        ifd.fCompression               = ccUncompressed;
        ifd.fPredictor                 = 1;
        ifd.fCFALayout                 = 1;                 // Rectangular (or square) layout.
        ifd.fPhotometricInterpretation = piCFA;
        ifd.fFillOrder                 = 1;
        ifd.fOrientation               = identify.orientation;
        ifd.fSamplesPerPixel           = 1;
        ifd.fPlanarConfiguration       = 1;
        ifd.fXResolution               = 0.0;
        ifd.fYResolution               = 0.0;
        ifd.fResolutionUnit            = 0;

        ifd.fUsesStrips                = true;
        ifd.fUsesTiles                 = false;

        ifd.fTileWidth                 = width;
        ifd.fTileLength                = height;
        ifd.fTileOffsetsType           = 4;
        ifd.fTileOffsetsCount          = 0;

        ifd.fSubIFDsCount              = 0;
        ifd.fSubIFDsOffset             = 0;
        ifd.fExtraSamplesCount         = 0;
        ifd.fSampleFormat[0]           = 1;
        ifd.fSampleFormat[1]           = 1;
        ifd.fSampleFormat[2]           = 1;
        ifd.fSampleFormat[3]           = 1;

        ifd.fLinearizationTableType    = 0;
        ifd.fLinearizationTableCount   = 0;
        ifd.fLinearizationTableOffset  = 0;

        ifd.fBlackLevelRepeatRows      = 1;
        ifd.fBlackLevelRepeatCols      = 1;
        ifd.fBlackLevel[0][0][0]       = identify.blackPoint;
        ifd.fBlackLevelDeltaHType      = 0;
        ifd.fBlackLevelDeltaHCount     = 0;
        ifd.fBlackLevelDeltaHOffset    = 0;
        ifd.fBlackLevelDeltaVType      = 0;
        ifd.fBlackLevelDeltaVCount     = 0;
        ifd.fBlackLevelDeltaVOffset    = 0;
        ifd.fWhiteLevel[0]             = identify.whitePoint;
        ifd.fWhiteLevel[1]             = identify.whitePoint;
        ifd.fWhiteLevel[2]             = identify.whitePoint;
        ifd.fWhiteLevel[3]             = identify.whitePoint;

        ifd.fDefaultScaleH             = dng_urational(1, 1);
        ifd.fDefaultScaleV             = dng_urational(1, 1);
        ifd.fBestQualityScale          = dng_urational(1, 1);

        ifd.fCFARepeatPatternRows      = 0;
        ifd.fCFARepeatPatternCols      = 0;

        ifd.fBayerGreenSplit           = 0;
        ifd.fChromaBlurRadius          = dng_urational(0, 0);
        ifd.fAntiAliasStrength         = dng_urational(100, 100);

        ifd.fActiveArea                = rect;
        ifd.fDefaultCropOriginH        = dng_urational(0, 1);
        ifd.fDefaultCropOriginV        = dng_urational(0, 1);
        ifd.fDefaultCropSizeH          = dng_urational(width, 1);
        ifd.fDefaultCropSizeV          = dng_urational(height, 1);

        ifd.fMaskedAreaCount           = 0;
        ifd.fLosslessJPEGBug16         = false;
        ifd.fSampleBitShift            = 0;

        ifd.ReadImage(host, stream, *image.Get());

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: DNG Negative structure creation" << endl;

        AutoPtr<dng_negative> negative(host.Make_dng_negative());

        negative->SetDefaultScale(ifd.fDefaultScaleH, ifd.fDefaultScaleV);
        negative->SetDefaultCropOrigin(ifd.fDefaultCropOriginH, ifd.fDefaultCropOriginV);
        negative->SetDefaultCropSize(ifd.fDefaultCropSizeH, ifd.fDefaultCropSizeV);
        negative->SetActiveArea(ifd.fActiveArea);

        negative->SetModelName(identify.model.toAscii());
        negative->SetLocalName(QString("%1 %2").arg(identify.make).arg(identify.model).toAscii());
        negative->SetOriginalRawFileName(inputInfo.fileName().toAscii());

        negative->SetColorChannels(3);
        negative->SetColorKeys(colorKeyRed, colorKeyGreen, colorKeyBlue);
        negative->SetBayerMosaic(bayerMosaic);

        negative->SetWhiteLevel(identify.whitePoint, 0);
        negative->SetWhiteLevel(identify.whitePoint, 1);
        negative->SetWhiteLevel(identify.whitePoint, 2);
        negative->SetBlackLevel(identify.blackPoint, 0);
        negative->SetBlackLevel(identify.blackPoint, 1);
        negative->SetBlackLevel(identify.blackPoint, 2);

        negative->SetBaselineExposure(0.0);
        negative->SetBaselineNoise(1.0);
        negative->SetBaselineSharpness(1.0);

        dng_orientation orientation;
        switch (identify.orientation)
        {
            case DcrawInfoContainer::ORIENTATION_180:
                orientation = dng_orientation::Rotate180();
                break;

            case DcrawInfoContainer::ORIENTATION_90CCW:
                orientation = dng_orientation::Rotate90CCW();
                break;

            case DcrawInfoContainer::ORIENTATION_90CW:
                orientation = dng_orientation::Rotate90CW();
                break;

            default:   // ORIENTATION_NONE
                orientation = dng_orientation::Normal();
                break;
        }
        negative->SetBaseOrientation(orientation);

        negative->SetAntiAliasStrength(dng_urational(100, 100));
        negative->SetLinearResponseLimit(1.0);
        negative->SetShadowScale( dng_urational(1, 1) );

        negative->SetAnalogBalance(dng_vector_3(1.0, 1.0, 1.0));

        // -------------------------------------------------------------------------------

        // Set Camera->XYZ Color matrix as profile.
        dng_matrix_3by3 matrix(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0);
        dng_matrix_3by3 camXYZ;

        AutoPtr<dng_camera_profile> prof(new dng_camera_profile);
        prof->SetName(QString("%1 %2").arg(identify.make).arg(identify.model).toAscii());

        camXYZ[0][0] = identify.cameraXYZMatrix[0][0];
        camXYZ[0][1] = identify.cameraXYZMatrix[0][1];
        camXYZ[0][2] = identify.cameraXYZMatrix[0][2];
        camXYZ[1][0] = identify.cameraXYZMatrix[0][3];
        camXYZ[1][1] = identify.cameraXYZMatrix[1][0];
        camXYZ[1][2] = identify.cameraXYZMatrix[1][1];
        camXYZ[2][0] = identify.cameraXYZMatrix[1][2];
        camXYZ[2][1] = identify.cameraXYZMatrix[1][3];
        camXYZ[2][2] = identify.cameraXYZMatrix[2][0];

        if (camXYZ.MaxEntry() == 0.0)
            kDebug( 51000 ) << "DNGWriter: Warning, camera XYZ Matrix is null" << endl;
        else 
            matrix = camXYZ;

        prof->SetColorMatrix1((dng_matrix) matrix);
        prof->SetCalibrationIlluminant1(lsD65);
        negative->AddProfile(prof);

        // -------------------------------------------------------------------------------

        // Clear "Camera WhiteXY"
        negative->SetCameraWhiteXY(dng_xy_coord());

        // This settings break color on preview and thumbnail
        //negative->SetCameraNeutral(dng_vector_3(1.0, 1.0, 1.0));

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: Updating metadata to DNG Negative" << endl;

        dng_exif *exif = negative->GetExif();
        exif->fModel.Set_ASCII(identify.model.toAscii());
        exif->fMake.Set_ASCII(identify.make.toAscii());

        // Time from original shot
        dng_date_time dt;
        dt.fYear   = identify.dateTime.date().year();
        dt.fMonth  = identify.dateTime.date().month();
        dt.fDay    = identify.dateTime.date().day();
        dt.fHour   = identify.dateTime.time().hour();
        dt.fMinute = identify.dateTime.time().minute();
        dt.fSecond = identify.dateTime.time().second();

        dng_date_time_info dti;
        dti.SetDateTime(dt);
        exif->fDateTimeOriginal  = dti;
        exif->fDateTimeDigitized = dti;
        negative->UpdateDateTime(dti);

        long int num, den;
        long     val;
        QString  str;
        KExiv2   meta;
        if (meta.load(inputFile()))
        {
            // String Tags

            str = meta.getExifTagString("Exif.Image.Software");
            if (!str.isEmpty()) exif->fSoftware.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.Image.ImageDescription");
            if (!str.isEmpty()) exif->fImageDescription.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.Image.Artist");
            if (!str.isEmpty()) exif->fArtist.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.Image.Copyright");
            if (!str.isEmpty()) exif->fCopyright.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.Photo.UserComment");
            if (!str.isEmpty()) exif->fUserComment.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.Image.CameraSerialNumber");
            if (!str.isEmpty()) exif->fCameraSerialNumber.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSLatitudeRef");
            if (!str.isEmpty()) exif->fGPSLatitudeRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSLongitudeRef");
            if (!str.isEmpty()) exif->fGPSLongitudeRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSSatellites");
            if (!str.isEmpty()) exif->fGPSSatellites.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSStatus");
            if (!str.isEmpty()) exif->fGPSStatus.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSMeasureMode");
            if (!str.isEmpty()) exif->fGPSMeasureMode.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSSpeedRef");
            if (!str.isEmpty()) exif->fGPSSpeedRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSTrackRef");
            if (!str.isEmpty()) exif->fGPSTrackRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSSpeedRef");
            if (!str.isEmpty()) exif->fGPSSpeedRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSImgDirectionRef");
            if (!str.isEmpty()) exif->fGPSSpeedRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSMapDatum");
            if (!str.isEmpty()) exif->fGPSMapDatum.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSDestLatitudeRef");
            if (!str.isEmpty()) exif->fGPSDestLatitudeRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSDestLongitudeRef");
            if (!str.isEmpty()) exif->fGPSDestLongitudeRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSDestBearingRef");
            if (!str.isEmpty()) exif->fGPSDestBearingRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSDestDistanceRef");
            if (!str.isEmpty()) exif->fGPSDestDistanceRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSProcessingMethod");
            if (!str.isEmpty()) exif->fGPSProcessingMethod.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSAreaInformation");
            if (!str.isEmpty()) exif->fGPSAreaInformation.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSDateStamp");
            if (!str.isEmpty()) exif->fGPSDateStamp.Set_ASCII(str.toAscii());

            // Rational Tags

            if (meta.getExifTagRational("Exif.Photo.ExposureTime", num, den))          exif->fExposureTime          = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.FNumber", num, den))               exif->fFNumber               = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.ShutterSpeedValue", num, den))     exif->fShutterSpeedValue     = dng_srational(num, den);
            if (meta.getExifTagRational("Exif.Photo.ApertureValue", num, den))         exif->fApertureValue         = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.BrightnessValue", num, den))       exif->fBrightnessValue       = dng_srational(num, den);
            if (meta.getExifTagRational("Exif.Photo.ExposureBiasValue", num, den))     exif->fExposureBiasValue     = dng_srational(num, den);
            if (meta.getExifTagRational("Exif.Photo.MaxApertureValue", num, den))      exif->fMaxApertureValue      = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.FocalLength", num, den))           exif->fFocalLength           = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.DigitalZoomRatio", num, den))      exif->fDigitalZoomRatio      = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.SubjectDistance", num, den))       exif->fSubjectDistance       = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Image.BatteryLevel", num, den))          exif->fBatteryLevelR         = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.FocalPlaneXResolution", num, den)) exif->fFocalPlaneXResolution = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.FocalPlaneYResolution", num, den)) exif->fFocalPlaneYResolution = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSAltitude", num, den))         exif->fGPSAltitude           = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSDOP", num, den))              exif->fGPSDOP                = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSSpeed", num, den))            exif->fGPSSpeed              = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSTrack", num, den))            exif->fGPSTrack              = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSImgDirection", num, den))     exif->fGPSImgDirection       = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSDestBearing", num, den))      exif->fGPSDestBearing        = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSDestDistance", num, den))     exif->fGPSDestDistance       = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSLatitude", num, den))         exif->fGPSLatitude[0]        = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSLongitude", num, den))        exif->fGPSLongitude[0]       = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSTimeStamp", num, den))        exif->fGPSTimeStamp[0]       = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSDestLatitude", num, den))     exif->fGPSDestLatitude[0]    = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSDestLongitude", num, den))    exif->fGPSDestLongitude[0]   = dng_urational(num, den);

            // Integer Tags

            if (meta.getExifTagLong("Exif.Photo.ExposureProgram", val))          exif->fExposureProgram          = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.MeteringMode", val))             exif->fMeteringMode             = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.LightSource", val))              exif->fLightSource              = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.Flash", val))                    exif->fFlash                    = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.SensingMethod", val))            exif->fSensingMethod            = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.FileSource", val))               exif->fFileSource               = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.SceneType", val))                exif->fSceneType                = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.CustomRendered", val))           exif->fCustomRendered           = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.ExposureMode", val))             exif->fExposureMode             = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.WhiteBalance", val))             exif->fWhiteBalance             = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.SceneCaptureType", val))         exif->fSceneCaptureType         = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.GainControl", val))              exif->fGainControl              = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.Contrast", val))                 exif->fContrast                 = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.Saturation", val))               exif->fSaturation               = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.Sharpness", val))                exif->fSharpness                = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.SubjectDistanceRange", val))     exif->fSubjectDistanceRange     = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.FocalLengthIn35mmFilm", val))    exif->fFocalLengthIn35mmFilm    = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.ComponentsConfiguration", val))  exif->fComponentsConfiguration  = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.PixelXDimension", val))          exif->fPixelXDimension          = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.PixelYDimension", val))          exif->fPixelYDimension          = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.FocalPlaneResolutionUnit", val)) exif->fFocalPlaneResolutionUnit = (uint32)val;
            if (meta.getExifTagLong("Exif.GPSInfo.GPSVersionID", val))           exif->fGPSVersionID             = (uint32)val;
            if (meta.getExifTagLong("Exif.GPSInfo.GPSAltitudeRef", val))         exif->fGPSAltitudeRef           = (uint32)val;
            if (meta.getExifTagLong("Exif.GPSInfo.GPSDifferential", val))        exif->fGPSDifferential          = (uint32)val;
        }

        // Markernote backup.

        QByteArray mkrnts = meta.getExifTagData("Exif.Photo.MakerNote");
        if (!mkrnts.isEmpty())
        {
            kDebug( 51000 ) << "DNGWriter: Backup Makernote (" << mkrnts.size() << " bytes)" << endl;

            dng_memory_allocator memalloc(gDefaultDNGMemoryAllocator);
            dng_memory_stream stream(memalloc);
            stream.Put(mkrnts.data(), mkrnts.size());
            AutoPtr<dng_memory_block> block(host.Allocate(mkrnts.size()));
            stream.SetReadPosition(0);
            stream.Get(block->Buffer(), mkrnts.size());
            negative->SetMakerNote(block);
            negative->SetMakerNoteSafety(true);
        }

        if (d->backupOriginalRawFile)
        {
            kDebug( 51000 ) << "DNGWriter: Backup Original RAW file (" << inputInfo.size() << " bytes)" << endl;

            // Compress Raw file data to Zip archive.

            QTemporaryFile zipFile;
            if (!zipFile.open())
            {
                kDebug( 51000 ) << "DNGWriter: Cannot open temporary file to write Zip Raw file. Aborted..." << endl;
                return -1;
            }
            KZip zipArchive(zipFile.fileName());
            zipArchive.open(QIODevice::WriteOnly);
            zipArchive.setCompression(KZip::DeflateCompression);
            zipArchive.addLocalFile(inputFile(), inputFile());
            zipArchive.close();

            // Load Zip Archive in a byte array

            QFileInfo zipFileInfo(zipFile.fileName());
            QByteArray zipRawFileData;
            zipRawFileData.resize(zipFileInfo.size());
            QDataStream dataStream(&zipFile);
            dataStream.readRawData(zipRawFileData.data(), zipRawFileData.size());
            kDebug( 51000 ) << "DNGWriter: Zipped RAW file size " << zipRawFileData.size() << " bytes" << endl;

            // Pass byte array to DNG sdk and compute MD5 fingerprint.

            dng_memory_allocator memalloc(gDefaultDNGMemoryAllocator);
            dng_memory_stream stream(memalloc);
            stream.Put(zipRawFileData.data(), zipRawFileData.size());
            AutoPtr<dng_memory_block> block(host.Allocate(zipRawFileData.size()));
            stream.SetReadPosition(0);
            stream.Get(block->Buffer(), zipRawFileData.size());

            dng_md5_printer md5;
            md5.Process(block->Buffer(), block->LogicalSize());
            negative->SetOriginalRawFileData(block);
            negative->SetOriginalRawFileDigest(md5.Result());
            negative->ValidateOriginalRawFileDigest();

            zipFile.remove();
        }

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: Build DNG Negative" << endl;

        // Assign Raw image data.
        negative->SetStage1Image(image);

        // Compute linearized and range mapped image
        negative->BuildStage2Image(host);

        // Compute demosaiced image (used by preview and thumbnail)
        negative->BuildStage3Image(host);

        negative->SynchronizeMetadata();
        negative->RebuildIPTC();

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        dng_preview_list previewList;

// NOTE: something is wrong with Qt < 4.4.0 to import TIFF data as stream in QImage.
#if QT_VERSION >= 0x40400

        if (d->previewMode != DNGWriter::NONE)
        {
            kDebug( 51000 ) << "DNGWriter: DNG preview image creation" << endl;

            // Construct a preview image as TIFF format.
            AutoPtr<dng_image> tiffImage;
            dng_render tiff_render(host, *negative);
            tiff_render.SetFinalSpace(dng_space_sRGB::Get());
            tiff_render.SetFinalPixelType(ttByte);
            tiff_render.SetMaximumSize(d->previewMode == MEDIUM ? 1280 : width);
            tiffImage.Reset(tiff_render.Render());

            dng_image_writer tiff_writer;
            AutoPtr<dng_memory_stream> dms(new dng_memory_stream(gDefaultDNGMemoryAllocator));

            tiff_writer.WriteTIFF(host, *dms, *tiffImage.Get(), piRGB,
                                  ccUncompressed, negative.Get(), &tiff_render.FinalSpace());

            // Write TIFF preview image data to a temp JPEG file
            std::vector<char> tiff_mem_buffer(dms->Length());
            dms->SetReadPosition(0);
            dms->Get(&tiff_mem_buffer.front(), tiff_mem_buffer.size());
            dms.Reset();

            QImage pre_image;
            if (!pre_image.loadFromData((uchar*)&tiff_mem_buffer.front(), tiff_mem_buffer.size(), "TIFF"))
            {
                kDebug( 51000 ) << "DNGWriter: Cannot load TIFF preview data in memory. Aborted..." << endl;
                return -1;
            }

            QTemporaryFile previewFile;
            if (!previewFile.open())
            {
                kDebug( 51000 ) << "DNGWriter: Cannot open temporary file to write JPEG preview. Aborted..." << endl;
                return -1;
            }

            if (!pre_image.save(previewFile.fileName(), "JPEG", 90))
            {
                kDebug( 51000 ) << "DNGWriter: Cannot save file to write JPEG preview. Aborted..." << endl;
                return -1;
            }

            // Load JPEG preview file data in DNG preview container.
            AutoPtr<dng_jpeg_preview> jpeg_preview;
            jpeg_preview.Reset(new dng_jpeg_preview);
            jpeg_preview->fPhotometricInterpretation = piYCbCr;
            jpeg_preview->fPreviewSize.v             = pre_image.height();
            jpeg_preview->fPreviewSize.h             = pre_image.width();
            jpeg_preview->fCompressedData.Reset(host.Allocate(previewFile.size()));

            QDataStream previewStream( &previewFile );
            previewStream.readRawData(jpeg_preview->fCompressedData->Buffer_char(), previewFile.size());

            AutoPtr<dng_preview> pp( dynamic_cast<dng_preview*>(jpeg_preview.Release()) );
            previewList.Append(pp);

            previewFile.remove();
        }

#endif /* QT_VERSION >= 0x40400 */

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: DNG thumbnail creation" << endl;

        dng_image_preview thumbnail;
        dng_render thumbnail_render(host, *negative);
        thumbnail_render.SetFinalSpace(dng_space_sRGB::Get());
        thumbnail_render.SetFinalPixelType(ttByte);
        thumbnail_render.SetMaximumSize(256);
        thumbnail.fImage.Reset(thumbnail_render.Render());

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: Creating DNG file " << outputInfo.fileName() << endl;

        dng_image_writer writer;
        dng_file_stream filestream(QFile::encodeName(dngFilePath), true);

        writer.WriteDNG(host, filestream, *negative.Get(), thumbnail, 
                        d->jpegLossLessCompression ? ccJPEG : ccUncompressed,
                        &previewList);
    }

    catch (const dng_exception &exception)
    {
        int ret = exception.ErrorCode();
        kDebug( 51000 ) << "DNGWriter: DNG SDK exception code (" << ret << ")" << endl;
        return ret;
    }

    catch (...)
    {
        kDebug( 51000 ) << "DNGWriter: DNG SDK exception code unknow" << endl;
        return dng_error_unknown;
    }

    kDebug( 51000 ) << "DNGWriter: DNG conversion complete..." << endl;

    return dng_error_none;
}