Foam::tmp<Foam::GeometricField<Type, Foam::fvsPatchField, Foam::surfaceMesh> >
Foam::extendedUpwindCellToFaceStencil::weightedSum
(
    const surfaceScalarField& phi,
    const GeometricField<Type, fvPatchField, volMesh>& fld,
    const List<List<scalar> >& ownWeights,
    const List<List<scalar> >& neiWeights
) const
{
    const fvMesh& mesh = fld.mesh();

    // Collect internal and boundary values
    List<List<Type> > ownFld;
    collectData(ownMap(), ownStencil(), fld, ownFld);
    List<List<Type> > neiFld;
    collectData(neiMap(), neiStencil(), fld, neiFld);

    tmp<GeometricField<Type, fvsPatchField, surfaceMesh> > tsfCorr
    (
        new GeometricField<Type, fvsPatchField, surfaceMesh>
        (
            IOobject
            (
                fld.name(),
                mesh.time().timeName(),
                mesh,
                IOobject::NO_READ,
                IOobject::NO_WRITE,
                false
            ),
            mesh,
            dimensioned<Type>
            (
                fld.name(),
                fld.dimensions(),
                pTraits<Type>::zero
            )
        )
    );
    GeometricField<Type, fvsPatchField, surfaceMesh>& sf = tsfCorr();

    // Internal faces
    for (label faceI = 0; faceI < mesh.nInternalFaces(); faceI++)
    {
        if (phi[faceI] > 0)
        {
            // Flux out of owner. Use upwind (= owner side) stencil.
            const List<Type>& stField = ownFld[faceI];
            const List<scalar>& stWeight = ownWeights[faceI];

            forAll(stField, i)
            {
                sf[faceI] += stField[i]*stWeight[i];
            }
        }
        else
        {
void ChartDataCollector::setupConnections()
{
	m_chartValues.clear();
	m_otherValue.value=0;
	if (m_chartDataSource!=FromStaticData && m_query.length() && findQuery(m_query))
	{
		findQuery(m_query)->disconnect();
		connect(findQuery(m_query),SIGNAL(afterFirst()),SLOT(collectData()));
		connect(findQuery(m_query),SIGNAL(afterNext()),SLOT(collectData()));
		connect(findQuery(m_query),SIGNAL(afterPrevious()),SLOT(collectData()));
		connect(findQuery(m_query),SIGNAL(afterLast()),SLOT(collectData()));
	}
}
示例#3
0
void CDiaryEdit::slotPrintPreview()
{
    CDiaryEditLock lock(this);
    collectData();

    QPrinter printer;
    QPrintDialog dialog(&printer, this);
    dialog.setWindowTitle(tr("Print Diary"));
    if (dialog.exec() != QDialog::Accepted)
        return;

    QTextDocument doc;
    QSizeF pageSize = printer.pageRect(QPrinter::DevicePixel).size();
    doc.setPageSize(pageSize);
    draw(doc);

    if(checkAddMap->isChecked())
    {
        QImage img;
        theMainWindow->getCanvas()->print(img, pageSize.toSize() - QSize(10,10));
        doc.rootFrame()->lastCursorPosition().insertImage(img);
    }
    doc.print(&printer);

    textEdit->clear();
    textEdit->document()->setTextWidth(textEdit->size().width() - 20);
    draw(*textEdit->document());
}
示例#4
0
int main(){
  int NPROBS = 1000;
  int NTHREADS = 5;
  int type =1;
  threadpool *tp = init_threadpool(NTHREADS,doCalc,NPROBS,type);

  int ntimes =5;
  int rc;


  workdata data_for_threads[NPROBS];
  while(ntimes){
    fprintf(fp,"ntimes=",ntimes);
    initData(data_for_threads,NPROBS);
    threadpool_iter(tp,data_for_threads,NPROBS);
    wait(tp);
    collectData(data_for_threads,NPROBS);
    ntimes--;

  }
  tp->STOPTHREADS=1;
  threadpool_iter(tp,data_for_threads,NPROBS);
  //  wait(tp);
  for (int i=0; i<NTHREADS; ++i) {
    if((rc = pthread_join(tp->threadid[i], NULL)))
      __printErr(tp->fp);
  }

  fprintf(stderr,"ncal is=%d\n",nCal);
}
示例#5
0
void Herby::update() {
	switch(_state) {
		case IDLE:
			if (_interrupted) {
				_state = INTERRUPTED;
			}
			else _state = AUTOMATIC;
			break;
		case INTERRUPTED:
			resetStateData();
			_parser->extractBuffer(_stateData);
			setGridTarget(_stateData.gridPosStepper, _stateData.gridPosDC);
			_interrupted = false;
			_state = MOVE;
			break;
		case AUTOMATIC:
			resetStateData();
			setGridTargetAuto();
			_state = MOVE;
			break;
		case MOVE:
			if (runAxisMotors()) _state = WORK;
			break;
		case WORK:
			if (_head->doWork()) _state = COLLECTING_DATA;
			break;
		case COLLECTING_DATA:
			collectData();
			_state = SENDING_DATA;
			break;
		case SENDING_DATA:
			if( !sendData()) _state = IDLE;
			break;
	}
}
示例#6
0
void EsItem::addDescriptor()
{
  m_es->m_descriptors.push_back(CDescriptor());
  DescriptorItem* item = new DescriptorItem(&m_es->m_descriptors.last(), this);
  ui->descriptors->layout()->addWidget(item);
  connect(item, SIGNAL(remove(DescriptorItem*)), this, SLOT(removeDescriptor(DescriptorItem*)));
  connect(this, SIGNAL(reqCollectData()), item, SLOT(collectData()));
}
示例#7
0
CDiaryEdit::~CDiaryEdit()
{
    collectData();

    SETTINGS;
    cfg.setValue("diary/showGeoCaches", checkGeoCache->isChecked());
    cfg.setValue("diary/showProfiles", checkProfile->isChecked());
    cfg.setValue("diary/addMapView", checkAddMap->isChecked());
}
示例#8
0
void Farmy::send( const char* device_id, int input_pins[], String api_key, WiFiClient client)
{
  if(!client.connect(host, 80)) {
    Serial.println("connection failed");
    return;
  }

  String data = collectData(input_pins);
  sendData(device_id, api_key, client, data);
}
示例#9
0
void OManager::collectAll(const string & nonstdcaseheader){

	// simple checks:
	if(oLinks.empty()) return;

	collectData();
	collectHeader();
	collectClosure();
	addHeader(nonstdcaseheader);

}
示例#10
0
void CDiaryEdit::resizeEvent(QResizeEvent * e)
{
    QWidget::resizeEvent(e);

    CDiaryEditLock lock(this);

    collectData();
    textEdit->clear();
    textEdit->document()->setTextWidth(textEdit->size().width() - 20);
    draw(*textEdit->document());
}
示例#11
0
void CDiaryEdit::slotSave()
{
    collectData();

    if(!CGeoDB::self().setProjectDiaryData(diary.keyProjectGeoDB, diary))
    {
        QMessageBox::warning(0, tr("Failed..."), tr("Failed to save diary to database. Probably because it was not created from a database project."), QMessageBox::Abort, QMessageBox::Abort);
        return;
    }

    diary.modified = false;

    setTabTitle();
}
示例#12
0
EsItem::EsItem(CSpliceElementaryStream* spliceStream, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::EsItem),
    m_es(spliceStream)
{
    ui->setupUi(this);
    ui->pid->setText(QString::number(m_es->m_pid));
    ui->streamType->setText(QString::number(m_es->m_streamType));
    ui->descriptors->setLayout(new QVBoxLayout(ui->descriptors));
    for (QList<CDescriptor>::iterator it = m_es->m_descriptors.begin(); it != m_es->m_descriptors.end(); ++it)
    {
      DescriptorItem* item = new DescriptorItem(&(*it), this);
      ui->descriptors->layout()->addWidget(item);
      connect(item, SIGNAL(remove(DescriptorItem*)), this, SLOT(removeDescriptor(DescriptorItem*)));
      connect(this, SIGNAL(reqCollectData()), item, SLOT(collectData()));
    }
}
// ------------ Switching and setting current rows
SUMOTime
MSAgentbasedTrafficLightLogic::trySwitch(bool) throw() {
    assert(getCurrentPhaseDef().minDuration >=0);
    assert(getCurrentPhaseDef().minDuration <= getCurrentPhaseDef().duration);
    if (myPhases[myStep]->isGreenPhase()) {
        // collects the data for the signal control
        collectData();
        // decides wheter greentime shall distributed between phases
        if (tDecide <= tSinceLastDecision) {
            calculateDuration();
        }
    }
    // increment the index to the current phase
    nextStep();
    // set the next event
    while (getCurrentPhaseDef().duration==0) {
        nextStep();
    }
    assert(myPhases.size()>myStep);
    return getCurrentPhaseDef().duration;
}
void ClassSpaceChecker::onCheckButtonClicked()
{
	QString jarPath = ui.comboBox_JarFile->currentText();
	QString mapPath = ui.lineEdit_MapFile->text();
	QString searchText = ui.lineEdit_Search->text();

	//jarPath = "C:\\work\\LINE_2013\\util\\TroublesomeRequester\\Download\\2013\\LINE.jar";
	//mapPath = "C:\\work\\LINE_2013\\util\\TroublesomeRequester\\Download\\2013\\pro_map.txt";

	removeAll();

	currentMapPath_ = mapPath;
	currentJarPath_ = jarPath;

	if(mapPath.isEmpty() == false)
	{
		ui.checkBox_ByUncryptName->setEnabled(true);
		ui.checkBox_ByUncryptName->setChecked(true);
		if(loadMapFile(mapPath) == false)
			return;
	}
	else
	{
		ui.checkBox_ByUncryptName->setEnabled(false);
		ui.checkBox_ByUncryptName->setChecked(false);
	}
	
	if(loadJarFile(jarPath))
	{
		collectData();

		search();
		analysisUniqueClassReport();
		analysisPackageReport();
	}

	ui.tabWidget->setCurrentIndex(0);

	saveCurrentPreset();
}
示例#15
0
文件: PC.c 项目: blaunay/preesm
    DWORD WINAPI computationThread_PC( LPVOID lpParam ){
        // Buffer declarations
        long i ;
        long j ;

        for(;;){
            GenerateTimeSample();
            {//ComputeFFT
                init_inLoopPort_0(outLoopPort_0_inLo_0, 16/*init_size*/);
                trigger();
                for(i = 0; i<8 ; i ++)
                {//cluster_0
                    char *outSub_i_out_clust_0 = &out_cluster_0_trig_0 [((i*(1))%8)];
                    sortData(dataOut_timeData, outLoopPort_0_inLo_0, outSub_i_out_clust_0, data1Out_data1In, data2Out_data2In, weights_W, 16/*size*/);
                    for(j = 0; j<8 ; j ++)
                    {//butterflyStep
                        char *inSub_j_data1Out_d_0 = &data1Out_data1In_0 [((j*(1))%8)];
                        char *inSub_j_data2Out_d_0 = &data2Out_data2In_0 [((j*(1))%8)];
                        char *outSub_j_data1Out__0 = &data1Out_data1In [((j*(1))%8)];
                        char *outSub_j_data2Out__0 = &data2Out_data2In [((j*(1))%8)];
                        char *outSub_j_weights_W = &weights_W [((j*(1))%8)];
                        char *out_op2 = &res_in [((0*1)%1)];
                        char *out_op2_0 = &res_in [((0*1)%1)];
                        mult(outSub_j_data2Out__0, outSub_j_weights_W, res_in);
                        add(outSub_j_data1Out__0, out_op2, inSub_j_data1Out_d_0);
                        sub(outSub_j_data1Out__0, out_op2_0, inSub_j_data2Out_d_0);
                    }
                    collectData(data1Out_data1In_0, data2Out_data2In_0, dataOut_in, 16/*size*/);
                    {//brSamples
                        fftData_dataIn = &dataOut_in[0];
                        outLoopPort_0_inLo_0 = &dataOut_in[0];
                    }
                }
            }
            DisplayResult();
        }

        return 0;
    }//computationThread
示例#16
0
void DBStore::removeData(const Location &location) {
    collectData(location);
}
示例#17
0
int main(int argc, char **argv) {
  collectData();
  return 0;
}
示例#18
0
文件: scan.c 项目: Rventric/opendias
char *internalDoScanningOperation(char *uuid, char *lang) {

  int request_resolution = 0;
  int docid;
  int current_page = 0;
  int total_requested_pages;
  double totbytes = 0;
  SANE_Status status;
  SANE_Handle *openDeviceHandle;
  SANE_Byte *raw_image;
  SANE_Parameters pars;
  char *docid_s;
  char *total_requested_pages_s;
  char *devName;
  char *outFilename;
  char *raw_image_format;
  char *header;

  o_log(DEBUGM, "doScanningOperation: sane initialized uuid(%s)",(char *)uuid);
  updateScanProgress(uuid, SCAN_WAITING_ON_SCANNER, 0);

  // Open the device
  devName = getScanParam(uuid, SCAN_PARAM_DEVNAME);
  o_log(DEBUGM, "sane_open of \"%s\"",devName);
  status = sane_open ((SANE_String_Const) devName, (SANE_Handle)&openDeviceHandle);
  if(status != SANE_STATUS_GOOD) {
    handleSaneErrors("Cannot open device ", devName, status, 0);
    updateScanProgress(uuid, SCAN_ERRO_FROM_SCANNER, status);
    free(devName);
    return 0;
  }
  free(devName);

  /* ========================================================== */
  if ( ! setOptions( (char *)uuid, openDeviceHandle, &request_resolution ) )
    return 0;
  o_log(DEBUGM, "sane_start: setOptions returned request_resolution %d\n",request_resolution);

  int timeout = 5;
  while( 0 < timeout ) {
    status = sane_start (openDeviceHandle);
    if(status == SANE_STATUS_GOOD) {  
      break;
    }
    else {
      if(status == SANE_STATUS_DEVICE_BUSY ) {  
        // BUSY signal could be the scanner just having a 
        // bit of lag - specially network connected devices
        timeout--;
        if ( timeout == 0 ) {
          handleSaneErrors("Cannot start scanning", "even after trying several time", status, 0);
          updateScanProgress(uuid, SCAN_ERRO_FROM_SCANNER, status);
          return 0;
        }
        else {
          o_log(WARNING, "Device reports not ready to 'start', waiting 500ms. Will try another %d times", timeout);
          usleep(500 * 1000); // 500ms or 0.5sec
        }
      }
      else {
        handleSaneErrors("Cannot start scanning", "", status, 0);
        updateScanProgress(uuid, SCAN_ERRO_FROM_SCANNER, status);
        return 0;
      }
    }
  }

  // Get scanning params (from the scanner)
  if( request_resolution == 0 ) {
    o_log(DEBUGM, "Resolution did not get set in scanner setup.");
    updateScanProgress(uuid, SCAN_INTERNAL_ERROR, 10004);
    return 0;
  }

  o_log(DEBUGM, "Get scanning params");
  status = sane_get_parameters (openDeviceHandle, &pars);
  o_log(INFORMATION, "Scanner Parm : stat=%s form=%d,lf=%d,bpl=%d,pixpl=%d,lin=%d,dep=%d",
    sane_strstatus (status),
    pars.format, pars.last_frame,
    pars.bytes_per_line, pars.pixels_per_line,
    pars.lines, pars.depth);

  switch (pars.format) {
    case SANE_FRAME_GRAY:
      o_log(DEBUGM, "Expecting Gray data (1 channel only).");
      raw_image_format = o_strdup( "P5" );
      break;
    case SANE_FRAME_RGB:
      o_log(DEBUGM, "Expecting RGB data (3 channels).");
      raw_image_format = o_strdup( "P6" );
      break;
    default:
      o_log(DEBUGM, "backend returns three frames speratly. We do not currently support this.");
      updateScanProgress(uuid, SCAN_INTERNAL_ERROR, 10003);
      return 0;
      break;
  }
  
  header = o_printf ("%s\n# SANE data follows\n%d %d\n%d\n", 
    raw_image_format, pars.pixels_per_line, pars.lines,
    (pars.depth <= 8) ? 255 : 65535);
  free( raw_image_format );


  // Save Record
  //
  docid_s = getScanParam(uuid, SCAN_PARAM_DOCID);
  total_requested_pages_s = getScanParam(uuid, SCAN_PARAM_REQUESTED_PAGES);
  total_requested_pages = atoi(total_requested_pages_s);
  free(total_requested_pages_s);
  if( docid_s == NULL ) {
    o_log(DEBUGM, "Saving record");
    updateScanProgress(uuid, SCAN_DB_WORKING, 0);

    docid_s = addNewScannedDoc(pars.lines, pars.pixels_per_line, request_resolution, total_requested_pages); 
    setScanParam(uuid, SCAN_PARAM_DOCID, docid_s);
    setScanParam(uuid, SCAN_PARAM_ON_PAGE, "1");
    current_page = 1;
  }
  else {
    char *current_page_s = getScanParam(uuid, SCAN_PARAM_ON_PAGE);
    current_page = atoi(current_page_s);
    free(current_page_s);

    current_page++;

    current_page_s = itoa(current_page, 10);
    setScanParam(uuid, SCAN_PARAM_ON_PAGE, current_page_s);
    free(current_page_s);
  }
  docid = atoi(docid_s);
  free(docid_s);

  totbytes = (double)((pars.bytes_per_line * pars.lines));

  /* ========================================================== */
  raw_image = collectData( (char *)uuid, openDeviceHandle, totbytes, pars.bytes_per_line, header );
  o_log(INFORMATION, "Scanning done.");

  o_log(DEBUGM, "sane_cancel");
  sane_cancel(openDeviceHandle);

  o_log(DEBUGM, "sane_close");
  sane_close(openDeviceHandle);


  // Convert Raw into JPEG
  //
  updateScanProgress(uuid, SCAN_CONVERTING_FORMAT, 0);
  PIX *pix;
  if ( ( pix = pixReadMem( raw_image, (pars.bytes_per_line*pars.lines)+strlen(header) ) ) == NULL) {
    o_log(ERROR, "Could not load the image data into a PIX");
  }
  updateScanProgress(uuid, SCAN_CONVERTING_FORMAT, 55);
  o_log(INFORMATION, "Convertion process: Loaded (depth: %d)", pixGetDepth(pix));
  free(raw_image);
  free(header);

  outFilename = o_printf("%s/scans/%d_%d.jpg", BASE_DIR, docid, current_page);
  pixWrite(outFilename, pix, IFF_JFIF_JPEG);
  free(outFilename);
  updateScanProgress(uuid, SCAN_CONVERTING_FORMAT, 100);
  o_log(INFORMATION, "Conversion process: Complete");




  // Do OCR - on this page
  // - OCR libs just wants the raw data and not the image header
  ocrImage( uuid, docid, current_page, request_resolution, pix, lang );


#ifdef CAN_PHASH
  // Calulate the pHash, so we can compare images later
  if( current_page == 1 ) {
    updateScanProgress(uuid, SCAN_CALULATING_PHASH, 0);
    unsigned long long hash = getImagePhash_px( pix );
    savePhash( docid, hash );
  }
#endif /* CAN_PHASH */
  pixDestroy( &pix );


  // cleaup && What should we do next
  //
  o_log(DEBUGM, "mostly done.");
  if(current_page >= total_requested_pages)
    updateScanProgress(uuid, SCAN_FINISHED, docid);
  else
    updateScanProgress(uuid, SCAN_WAITING_ON_NEW_PAGE, ++current_page);

  o_log(DEBUGM, "Page scan done.");

  return o_strdup("OK"); 
}
示例#19
0
文件: main.c 项目: nytopop/alter-evic
// Main
int main() {
	// initial settings, will change to user interactive / eeprom
	ctx.settings.mode = 3;
	ctx.settings.maxCtrlWatts = 75000;
	ctx.settings.maxWatts = 75000;
	ctx.settings.minTemp = 60;
	ctx.settings.maxTemp = 300;
	ctx.settings.tcrValue = 0.00092;

	ctx.settings.tT = 248;
	ctx.settings.tW = 56000;

	ctx.settings.lockRes = false;
	ctx.settings.flip = false;
	ctx.settings.stealth = false;
	ctx.settings.lock = false;
	ctx.settings.timeout = 10;

	// init timers
	uint8_t timeTimer;
	timeTimer = Timer_CreateTimer(1, 1, incrementTime, 1);
	uint8_t loopTimer;
	loopTimer = Timer_CreateTimer(FPS, 1, readyLoop, 1);

	// init atomizer
	Atomizer_SetErrorLock(true);

	// main loop, rest is event handling
	while(1) {
		loop = 0;
		// collect runtime data
		collectData();

		// do controls
		doControls();

		if(ctx.state.firing) {
			displayFiring();
		} else {
			if(ctx.state.idleTimer < 20) {
				switch(ctx.settings.mode) {
					case 0: // settings
						displaySettings();
						break;
					case 1: // vw
						displayVW();
						break;
					case 2: // bp
						displayBP();
						break;
					case 3: // tc
						displayTC();
						break;
				}
			} else {
				// switch to low power mode
				Display_Clear();
				Display_Update();
				sleep();
			}
		}

		// waste time until loop refresh timer is ready
		while(loop == 0) {}
	}

	return 0;
}
示例#20
0
int main()
{
	////////////////////////////////
	// Program settings 
	///////////////////////////////

	float		stageStepSize = 5.0/2; // in um
	int			stepTotalX = 1600;//2000/stageStepSize; 
	int			stepTotalY = 600;//2000/stageStepSize;
	int			stepX = 1;
	int			stepY = 1;
	int			stageLocation[2] = { 0, 0 };

	
	int16		*stageLocationSave[2]; // Ensure that this is made large enough for some spillover
	int			stageCount = 0;

	stageLocationSave[0] = new int16[NUMSTAGELOCATIONS];
	stageLocationSave[1] = new int16[NUMSTAGELOCATIONS];

	// Motors off
	XON(0);
	YON(0);


	
	////////////////////////////////
	// Initialize DAQ settings 
	///////////////////////////////

	TaskHandle	directionX = 0;
	TaskHandle	directionY = 0;

	DAQmxCreateTask("XDir", &directionX);
	DAQmxCreateTask("YDir", &directionY);

	DAQmxCreateAOVoltageChan(directionX, "Dev1/ao1", "XDir", 0.0, 5.0, DAQmx_Val_Volts, NULL); // X Direction
	DAQmxCreateAOVoltageChan(directionY, "Dev1/ao0", "YDir", 0.0, 5.0, DAQmx_Val_Volts, NULL); // Y Direction

	float64 fiveVoltOut[2] = { 5.0, 5.0 }; // 5.0 V
	float64 zeroVoltOut[2] = { 0.0, 0.0 }; // 0.0 V

	//Must be 2 bits
	uInt8 outClock[2] = { 0 , 1 };
	uInt8 onSig[2] = { 1, 1 };	
		

	////////////////////////////////
	// Initialize Gage card
	///////////////////////////////

	if (initializeGage(stageStepSize))
	{
		fprintf(stdout, ("Error initializing Gage card, please check settings\n\n"));
		getchar();
		return -1;
	}
	fprintf(stdout, ("Gage card sucessfully initialized.\n\n"));



	////////////////////////////////
	// Initial settings checks
	///////////////////////////////

	// Check program buffer sizes
	int currBufferSize = checkBufferSize();
	int totalNumStageMoves = (stepTotalX / stepX)*(stepTotalY / stepY);
	if (currBufferSize >= totalNumStageMoves && NUMSTAGELOCATIONS >= totalNumStageMoves)
	{
		fprintf(stdout, ("Buffer sizes appear correct.\n\n"));
	}
	else
	{
		fprintf(stdout, ("Buffer size is not set correctly. Stage locations (%d) and segment count (%d) must be greater than %d.\n\n"),
			(int)NUMSTAGELOCATIONS, currBufferSize, totalNumStageMoves);
		getchar();
		return -1;
	}
	

	////////////////////////////////
	// Print scan settings
	///////////////////////////////

	fprintf(stdout, ("\n\n Scan Settings\n---------------\n\n"));
	fprintf(stdout, ("X stage step size: %3.2f um\nY stage step size: %3.2f um\n"), (float)stepX*stageStepSize, (float)stepY*stageStepSize);
	fprintf(stdout, ("X range: %3.2f mm\nY range: %3.2f mm\n\n"), (float)stepTotalX * stageStepSize / 1000.0, (float)stepTotalY * stageStepSize / 1000.0);
	//fprintf(stdout, ("Total stage moves: %d\nStage clock speed: %d Hz\n\n---------------\n\n"), (stepTotalX / stepX)*(stepTotalY / stepY),getStageClockSpeed());
	fprintf(stdout, ("Total stage moves: %d\nStage clock speed: %d Hz\n"), (stepTotalX / stepX)*(stepTotalY / stepY), getStageClockSpeed());
	fprintf(stdout, ("Set trigger holdoff bettween %d us and %d us\n\n"), (int)(1.0 / (float)getStageClockSpeed()*1e6), (int)(2.0 / (float)getStageClockSpeed()*1e6));
	fprintf(stdout, ("---------------\n\n"));



	////////////////////////////////
	// Prep for scan
	///////////////////////////////

	// Ready to start scan
	fprintf(stdout, ("Ensure stage is centered.\nPress any key to start scan.\n\n"));
	getchar();

	fprintf(stdout, ("Moving stage to start location.\n\n"));

	// Motors on
	XON(1);
	YON(1);

	// Scan variables
	int steps;
	//int gageCollectStatus;
	int XDir = 1;
	int saveCount = 1;	
	
	// Move to start position
	steps = stepTotalX / 2;
	DAQmxWriteAnalogF64(directionX, 1, 1, 0.0, DAQmx_Val_GroupByChannel, zeroVoltOut, NULL, NULL); // dir
	moveXStage(steps, outClock);
	stageLocation[0] -= steps;

	steps = stepTotalY / 2;
	DAQmxWriteAnalogF64(directionY, 1, 1, 0.0, DAQmx_Val_GroupByChannel, zeroVoltOut, NULL, NULL); // dir 	
	moveYStage(steps, outClock); // Move
	stageLocation[1] -= steps;
	


	////////////////////////////////
	// Scan
	///////////////////////////////

	moveXStage(1, onSig); // hold on
	
	// Start data collection	
	if (collectData())
	{
		fprintf(stdout, ("Data Collection Failed"));
		getchar();
		return (-1);
	}


	// Scan along Y
	for (int countY = 0; countY < stepTotalY; countY += stepY)
	{
		if (countY != 0)
		{
			// Step Y
			DAQmxWriteAnalogF64(directionY, 1, 1, 0.0, DAQmx_Val_GroupByChannel, fiveVoltOut, NULL, NULL); // dir 			
			moveYStage(stepY, outClock); // Move--			
			stageLocation[1] += stepY;			
		}
		
		if (countY > 0)
		{
			_ftprintf(stdout, ("\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b"));
		}
		_ftprintf(stdout, _T("%04.0f um remaining in Y"), (float)(stepTotalY - countY) * stageStepSize);
		
		

		// Scan along X
		if (XDir == 1)
		{
			DAQmxWriteAnalogF64(directionX, 1, 1, 0.0, DAQmx_Val_GroupByChannel, fiveVoltOut, NULL, NULL); // dir 				
			stageLocation[0] += stepTotalX;
		}
		else {
			DAQmxWriteAnalogF64(directionX, 1, 1, 0.0, DAQmx_Val_GroupByChannel, zeroVoltOut, NULL, NULL); // dir 				
			stageLocation[0] -= stepTotalX;
		}
		moveXStage(stepTotalX, outClock); // Move			
		
		// Save stage data and change direction
		if (XDir == 1)
		{			
			XDir = 0;
		}
		else {
			XDir = 1;
		}		
	}

	_ftprintf(stdout, _T("\nScan complete. Returning to start position.\n\n"));

	// Move stage to center (0,0)
	if (stageLocation[0] > 0){
		steps = stageLocation[0];
		DAQmxWriteAnalogF64(directionX, 1, 1, 0.0, DAQmx_Val_GroupByChannel, zeroVoltOut, NULL, NULL); // dir 		
		moveXStage(steps, outClock); // Move
		stageLocation[0] -= steps;
	}
	else{
		steps = -stageLocation[0];
		DAQmxWriteAnalogF64(directionX, 1, 1, 0.0, DAQmx_Val_GroupByChannel, fiveVoltOut, NULL, NULL); // dir 
		moveXStage(steps, outClock); // Move
		stageLocation[0] += steps;
	}

	if (stageLocation[1] > 0){
		steps = stageLocation[1];
		DAQmxWriteAnalogF64(directionY, 1, 1, 0.0, DAQmx_Val_GroupByChannel, zeroVoltOut, NULL, NULL); // dir		
		moveYStage(steps, outClock); // Move
		stageLocation[1] -= steps;
	}
	else{
		steps = -stageLocation[1];
		DAQmxWriteAnalogF64(directionY, 1, 1, 0.0, DAQmx_Val_GroupByChannel, fiveVoltOut, NULL, NULL); // dir
		moveYStage(steps, outClock); // Move
		stageLocation[1] += steps;
	}


	moveXStage(2, onSig); // Move

	// Motors off
	XON(0);
	YON(0);

	//moveXStage(4, onSig); // hold on


	// Stage stage data
	int countX = 0;
	int countY = 0;
	XDir = 1;
	for (countY = 0; countY < stepTotalY; countY += stepY)
	{
		if (countY != 0)
		{
			stageLocationSave[0][stageCount] = countX;
			stageLocationSave[1][stageCount++] = countY;
		}
		if (XDir == 1)
		{
			for (countX = 0; countX < stepTotalX; countX += stepX)
			{
				stageLocationSave[0][stageCount] = countX;
				stageLocationSave[1][stageCount++] = countY;
			}
			XDir = 0;
		}
		else {
			for (countX = stepTotalX-1; countX > -1; countX -= stepX)
			{
				stageLocationSave[0][stageCount] = countX;
				stageLocationSave[1][stageCount++] = countY;
			}
			XDir = 1;
		}
	}

	// Check if aquisition is completed
	checkScanComplete();

	// Transfer and save data
	int nSaveError = saveGageData();
	if (nSaveError)
	{
		fprintf(stdout, ("Data Save Failed"));
		getchar();
		return (-1);
	}

	// Save stage data
	TCHAR StageFileName[MAX_PATH];
	FILE *fidStage;

	// Open Save files
	int nCount = 0;
	while (1)
	{
		nCount++;
		_stprintf(StageFileName, _T("E:\\GageData\\MechStageDataScan%d.txt"), nCount);
		fidStage = fopen(StageFileName, "r");
		if (fidStage)
		{
			fclose(fidStage);
		}
		else
		{
			fidStage = fopen(StageFileName, "w");
			break;
		}
	}

	//_stprintf(StageFileName, _T("E:\\GageData\\MechStageData.txt"));
	//fidStage = fopen(StageFileName, "w");

	
	for (int n = 0; n < stageCount; n++)
	{
		_ftprintf(fidStage, _T("%d %d\n"), stageLocationSave[0][n], stageLocationSave[1][n]); // print peakData
	}


	fclose(fidStage);
	fidStage = NULL;

	delete stageLocationSave[0];
	delete stageLocationSave[1];

	return 0;
}