Ejemplo n.º 1
0
int main(int argc, char** argv)
{
	try
	{
		// store required reports in vector
		std::vector<Report*> reports;

		// put build array out of command line args and process
		{
			std::vector<std::string> argVector(argv+1, argv + argc);
			if (argVector.empty())
			{
				throw std::runtime_error("invalide number of arguements (" + boost::lexical_cast<std::string>(argVector.size()) + ")\n");
			}
			CommandLine::ParseCommandLineInstructions(argVector, reports);
		}

		// read data file into store
		ReadInputFile(inputDataFile);

		// run reports
		std::string output;
		for (auto report : reports)
		{
			output += report->Generate() + "\n";
		}
		// output to standard out and file
		std::cout << output; 
		std::ofstream output_file(outputDataFile);
		std::ostream_iterator<char> output_iterator(output_file);
		std::copy(output.begin(), output.end(), output_iterator);
		output_file.close();	
    }
	catch (std::logic_error& ex)
	{
		std::cerr << "A systematic error has occured: " << ex.what() << "\nExiting...\n" << std::endl;
	}
	catch (std::runtime_error& ex)
	{
		std::cerr << "A runtime error has occured: " << ex.what() << "\nExiting...\n" << std::endl;
	}
	catch (std::exception& ex)
	{
		std::cerr << "A unexpected error has occured: " << ex.what() << "\nExiting...\n" << std::endl;
	}
	catch (...)
	{
		std::cerr << "An unexpected error occured: Exiting...\n" << std::endl;
	}

	return 0;
}
Ejemplo n.º 2
0
int DoSignature(TCHAR *homepath) {

  TCHAR fullsrcfile[MAX_PATH],fulldstfile[MAX_PATH];

  #if TESTBENCH
  StartupStore(_T(".... DoSignature start, homepath=<%s>\n"),homepath);
  #endif

  _stprintf(fullsrcfile,TEXT("%s/LOGGER_TMP.IGC"),homepath);
  _stprintf(fulldstfile,TEXT("%s/LOGGER_SIG.IGC"),homepath);

  // Force removal of anything existing.
  // We should have checked already that this file does not exist, and rename it eventually.
  // If it is here, we remove it, we are in the hurry and cannot loose time on previous files.
  FILE *ft;
  ft=NULL;
  lk::filesystem::deleteFile(fulldstfile);
  #if TESTBENCH
  StartupStore(_T("... DoSignature: delete ok%s"),NEWLINE);
  #endif
  if ( (ft=_tfopen(fulldstfile,TEXT("r")))!=NULL ) {
	StartupStore(_T("... DoSignature: ERROR existing destination file <%s>!%s"),fulldstfile,NEWLINE);
	fclose(ft);
	return 12;
  }
  #if TESTBENCH
  StartupStore(_T("... DoSignature: tfopen ok%s"),NEWLINE);
  #endif

  if (ReadInputFile(Linelist, fullsrcfile)) {
	StartupStore(_T("... DoSignature: ERROR source file <%s> disappeared%s"),fullsrcfile,NEWLINE);
	return 1;
  }
  #if TESTBENCH
  StartupStore(_T("... DoSignature: readinputfile ok%s"),NEWLINE);
  #endif
  GenerateMD5(Linelist, &md5gen);
  AddGRecordToBuffer(Linelist, &md5gen);
  #if TESTBENCH
  StartupStore(_T("... DoSignature: addgrecord ok%s"),NEWLINE);
  #endif
  WriteOutputFile(Linelist, fulldstfile);	

  #if TESTBENCH
  StartupStore(_T("... DoSignature: signature OK%s"),NEWLINE);
  #endif

  return 0;
} 
Ejemplo n.º 3
0
// #################################################################
//
void COMB::ReadInit(string input_file)
{

    // ------------------------------------
    FILE* fp = NULL;

    // TPインスタンス生成
    TextParser tpCntl;

    // 入力ファイルをセット
    int ierror = tpCntl.read(input_file);

    // 入力ファイルの読み込み--->パラメータのセット
    ReadInputFile(&tpCntl);

    // TextParserの破棄
    tpCntl.remove();

    return;
}
Ejemplo n.º 4
0
// #################################################################
//
void LAYOUT::ReadInit()
{
  
  // ------------------------------------
  FILE* fp = NULL;
  
  // TPインスタンス生成
  TextParser tpCntl;

  
  //入力ファイルをセット
  int ierror = tpCntl.read(fname);
  
  //入力ファイルの読み込み--->パラメータのセット
  ReadInputFile(&tpCntl);
  
  //TextParserの破棄
  tpCntl.remove();
  
  return;
}
Ejemplo n.º 5
0
   /* History:
   03/2007     NW        Implementation
 **************************************************************************/
int ExecuteDelaunay3DProcess(char* infilepath, char* outfilepath)
{
    int ireturnCode = 0;
    int node = 0;
    double* x = (double*)malloc(sizeof(double) * (NODE_MAX + 4));
    double* y = (double*)malloc(sizeof(double) * (NODE_MAX + 4));
    double* z = (double*)malloc(sizeof(double) * (NODE_MAX + 4));
    int nelm = 0;
    int* mtj = (int*)malloc(sizeof(int) * (ELEM_MAX * 4));
    int* jac = (int*)malloc(sizeof(int) * (ELEM_MAX * 4));
    int maxelm = ELEM_MAX;
    int maxnode = NODE_MAX;
    //printf("\n[AVAILABLE MEMORY]\n");
    //printf("X: %x\nY: %x\nZ: %x\n", x, y, z);
    //printf("MTJ: %x\nJAC: %x\n\n", mtj, jac);
    if (x == NULL || y == NULL || z == NULL || mtj == NULL || jac == NULL)
        //MyOutputDebugString("ERROR: Fail to malloc()");
        return 999;
    if(ReadInputFile(infilepath, &node, x, y, z))
    {
        generate_tetrahedra_mesh(&ireturnCode,&maxnode,&maxelm,&node,x,y,z,&nelm,mtj,jac);

        if (ireturnCode == 0)
            WriteOutputFile(outfilepath, &node,x,y,z,&nelm,mtj,jac,&maxelm);
    }
    else
        //MyOutputDebugString("ERROR: input()\n");
        return 999;
    free(x);
    free(y);
    free(z);
    free(mtj);
    free(jac);

    return ireturnCode;
}
Ejemplo n.º 6
0
// ==============================================================
// Extract License & Notes files
// These are stored as 4-bytes length, followed by length-bytes of compressed data
int	ExtractTextFile(BLOCK_DATA *Blk, ULONG FileType)
{
		ULONG n, m;
		BYTE *zSrcBuf = (BYTE *) Blk->SrcBuf;
		BYTE *zDstBuf = (BYTE *) Blk->DstBuf;

		const char *FileExt;
		if (FileType == FLAGS_License)
			FileExt = LicenseExt;
		else if (FileType == FLAGS_Notes)
			FileExt = NotesExt;
		else
			return 0;

		// NB:Can't use BioReadBuf... aligment problems? Yet it works for ProcessNextBlock() !!??
		// Ok, can use ReadInputFile here cause everythjing is whole no. of bytes...

		//BioReadBuf((BYTE *)&n, sizeof(n));					// Read length of block from file
	  ReadInputFile((BYTE *)&n, sizeof(n));					// Read length of block from file
	  FixEndian(&n, sizeof(n));										// Fix endian

		if (n <= 0  ||  n > ZBUF_SIZE)								// Check for valid block length
		{
			sprintf(MsgTxt, "ERROR - Invalid length for %s file (apparently %ld bytes) %s", FileExt, n, CorruptedMsg);
			msg(MsgTxt, MSG_PopUp);
			GlobalErrorFlag = SFARKLIB_ERR_CORRUPT;
			return 0;
		}

		//BioReadBuf(zSrcBuf, n);																					// Read the block
	  ReadInputFile((BYTE *)zSrcBuf, n);																// Read the block
		m = UnMemcomp(zSrcBuf, n, zDstBuf, ZBUF_SIZE);										// Uncompress
		Blk->FileCheck = adler32(Blk->FileCheck, zDstBuf, m);	   					// Accumulate checksum
		if (GlobalErrorFlag  ||  m > ZBUF_SIZE)														// Uncompressed ok & size is valid?
			return 0;

		// Write file - Use original file name plus specified extension for OutFileName...
		char OutFileName[MAX_FILENAME];
		strncpy(OutFileName, Blk->FileHeader.FileName, sizeof(OutFileName));	// copy output filename
		ChangeFileExt(OutFileName, FileExt, sizeof(OutFileName));
		OpenOutputFile(OutFileName);	// Create notes / license file
		WriteOutputFile(zDstBuf, m);																			// and write to output file
		CloseOutputFile();
		if (FileType == FLAGS_License)
		{
                    sprintf(MsgTxt, "Created license file: %s", OutFileName);
                    msg(MsgTxt, 0);
			if (GetLicenseAgreement((const char *)zDstBuf, OutFileName) == 0)
			{
				GlobalErrorFlag = SFARKLIB_ERR_LICENSE;
				return EndProcess(0);
			}
		}
		else if (FileType == FLAGS_Notes)
                {
                    sprintf(MsgTxt, "Created notes file: %s", OutFileName);
                    msg(MsgTxt, 0);
                    DisplayNotes((const char *)zDstBuf, OutFileName);
                }

		return 1;
}
Ejemplo n.º 7
0
// Read the File Header....
int ReadHeader(V2_FILEHEADER *FileHeader, BYTE *fbuf, int bufsize)
{
  int HeaderLen = 0, HdrOffset;
  char	CreatedByProg[HDR_NAME_LEN +1],  CreatedByVersion[HDR_VERS_LEN +1];
  ULONG	CalcHdrCheck = 0;
  BYTE *HdrBuf, *bpFileHeader = (BYTE *) FileHeader;

  // Find and process the Header:  This could be a plain sfArk file, a self-extracting file or some other (invalid) file.
  // Also, it could be a sfArk V1 file, which we can't decompress, but should at least recognise.
  // We locate the header by looking for the string "sfArk" within the first HEADER_MAX_OFFSET bytes of the file
  // but because self-extractor code is likely to contain that string, we look for its final occurence
  // by searching backwards.
  // To speed things up, we first check at offset 0 (the case for a standard sfArk file)
  // If we think we've found a (V2) header, we veryify it using the Header checksum.  If the checksum fails,
  // chances are it was a corrupt file, but could conceivably be a non-sfArk file.  either way we report it as corrupt.
  
  int fbufsize = HEADER_MAX_OFFSET + V2_FILEHEADER_SIZE;		// Amount data to read
  if (fbufsize > bufsize)  fbufsize = bufsize;				// Buffer too small (should never happen)

  SetInputFilePosition(0);						// set to logical start (maybe a predefined offset) 
  RETURN_ON_ERROR();
  ReadInputFile(fbuf, fbufsize);					// Read a chunk of data from the start of the file
  RETURN_ON_ERROR();

  int SigFound = 0, SeemsV1 = 0, HdrCheckDone = 0;		// Some flags to remember what we're doing

  for(int TryOffset = 0; TryOffset < HEADER_MAX_OFFSET; TryOffset++)
  {
    HdrOffset = (TryOffset == 0)? 0 : HEADER_MAX_OFFSET - TryOffset; // Check offset = 0 first, then backwards from end  
    
    BYTE *sigpos = fbuf + HdrOffset + HEADER_SIG_POS;
    if (*sigpos != 's'  ||  memcmp(sigpos, "sfArk", 5) != 0)  continue;
    
    SigFound = 1;					// Set a flag to remember that we at least got this far
    HdrBuf = fbuf + HdrOffset; 
       
    if (V2_FILEHEADER_SIZE != sizeof(V2_FILEHEADER))	// Compare structure size to real size
    {
      // The compiler has messed with structure (alignment), so copy the data to the structure byte by byte...
      BYTE *bptr = HdrBuf;		// Point to start
      // Copy all fields...
      #define CPF(f) memcpy(&(FileHeader->f), bptr, sizeof(FileHeader->f)); bptr += sizeof(FileHeader->f)
      CPF(Flags); CPF(OriginalSize); CPF(CompressedSize); CPF(FileCheck); CPF(HdrCheck);
      CPF(ProgVersionNeeded); CPF(ProgVersion); CPF(ProgName); CPF(CompMethod);
      CPF(FileType); CPF(AudioStart); CPF(PostAudioStart); CPF(FileName);
      #undef CPF
      if (bptr != HdrBuf+V2_FILEHEADER_SIZE)	return (GlobalErrorFlag = SFARKLIB_ERR_OTHER);	// Sanity check
    }
    else
      memcpy(bpFileHeader, HdrBuf, V2_FILEHEADER_SIZE);	// Copy entire data block to structure
      
    if (FileHeader->CompMethod < COMPRESSION_v2)	// Looks like a sfArk V1 file?
    {
      SeemsV1 = 1;					// set a flag
      continue;						// and keep searching
    }

    // Header->FileName is a null-terminated string, we need it's length to calculate actual length of header data...
    FileHeader->FileName[sizeof(FileHeader->FileName) -1] = '\0'; // Ensure strlen finds a terminator (string may be junk)
    HeaderLen = V2_FILEHEADER_SIZE - sizeof(FileHeader->FileName) + strlen(FileHeader->FileName) + 1;

    // If we get this far, there's a good chance we've got the header...
    /*#ifdef	__BIG_ENDIAN__
      // FixEndians of all multi-byte integers (currently only relevent to Mac)
      #define FIXENDIAN(field)	FixEndian(&(FileHeader->field), sizeof(FileHeader->field))
      FIXENDIAN(Flags); 	FIXENDIAN(OriginalSize); 	FIXENDIAN(CompressedSize);
      FIXENDIAN(FileCheck);	FIXENDIAN(HdrCheck); 		FIXENDIAN(FileType);
      FIXENDIAN(AudioStart);	FIXENDIAN(PostAudioStart);
      #undef FIXENDIAN
    #endif*/
      
    // Ok now, we know the HeaderLength and have the FileHeader structure properly populated...
    #if 0
    // debug, display header...
    printf("Flags %lx  OrignalSize %ld  CompressedSize %ld\n", FileHeader->Flags, FileHeader->OriginalSize, FileHeader->CompressedSize);
    printf("FileCheck %lx  HdrCheck %lx  ProgVersionNeeded %d\n", FileHeader->FileCheck, FileHeader->HdrCheck, FileHeader->ProgVersionNeeded);
    printf("AudioStart %ld  PostAudioStart %ld  Orginal filename %s\n", FileHeader->AudioStart, FileHeader->PostAudioStart, FileHeader->FileName);
    #endif
    *(uint32_t *)(HdrBuf+HEADER_HDRCHECK_POS) = 0;			// Zero-out the HeaderChecksum position in the buffer
    CalcHdrCheck = adler32(0, HdrBuf, HeaderLen);		// and recalculate the header checksum
    HdrCheckDone = 1;
    if (CalcHdrCheck == FileHeader->HdrCheck)  break;		// Check passed: Yes, we've found the header!
  }

  // When we get here, see what happened:
  if (SigFound && HdrCheckDone && CalcHdrCheck == FileHeader->HdrCheck)	// Everything Ok!  File is V2 and valid
    ; 							// Fall through to below (everything else is an error)
  else if (SeemsV1)					// Seems to be a sfArkV1 file
  {
    sprintf(MsgTxt, "This file was created with sfArk V1, and this program only handles sfArk V2+ files.  Unfortunately sfArk V1 uses a proprietary compression algorithm for the non-audio metadata, so we cannot really support that. You might try running the Windows sfArk program from http://melodymachine.com/sfark.htm under Wine."); 
    msg(MsgTxt, MSG_PopUp);
    return (GlobalErrorFlag = SFARKLIB_ERR_INCOMPATIBLE);
  }
  else if (SigFound)					// Apparently a corrupt sfArk file (well, it had "sfArk" in it!)
  {
    sprintf(MsgTxt, "File Header fails checksum!%s", CorruptedMsg);
    msg(MsgTxt, MSG_PopUp);
    return (GlobalErrorFlag = SFARKLIB_ERR_HEADERCHECK);
  }
  else							// Either very corrupted, or not a sfArk file
  {
    sprintf(MsgTxt, "This does not appear to be a sfArk file!");
    msg(MsgTxt, MSG_PopUp);
    return (GlobalErrorFlag = SFARKLIB_ERR_SIGNATURE);
  }

  // Get CreatedBy program name and version number (need null-terminated strings)...
  strncpy(CreatedByProg, FileHeader->ProgName, HDR_NAME_LEN);			// Copy program name
  CreatedByProg[HDR_NAME_LEN] = 0;																		// Terminate string
  strncpy(CreatedByVersion, FileHeader->ProgVersion, HDR_VERS_LEN);		// Copy version string
  CreatedByVersion[HDR_VERS_LEN] = 0;																	// Terminate string

  // Check for compatible version...
  if (FileHeader->ProgVersionNeeded > ProgVersionMaj)
  {
    sprintf(MsgTxt, "You need %s version %2.1f (or higher) to decompress this file (your version is %s) %s", 
		ProgName, (float)FileHeader->ProgVersionNeeded/10, ProgVersion, UpgradeMsg);
    msg(MsgTxt, MSG_PopUp);
    return (GlobalErrorFlag = SFARKLIB_ERR_INCOMPATIBLE);
  }

  // Warn if file was created by a newer version than this version...
  float fProgVersion = (float) atof(ProgVersion);
  float fCreatedByVersion = (float) atof(CreatedByVersion);
  if (fCreatedByVersion > fProgVersion)
  {
    sprintf(MsgTxt, "This file was created with %s %s.  Your version of %s (%s) can uncompress this file, "
			"but you might like to obtain the latest version.  %s",
			CreatedByProg, CreatedByVersion, ProgName, ProgVersion, UpgradeMsg);
    msg(MsgTxt, MSG_PopUp);
  }

  SetInputFilePosition(HdrOffset + HeaderLen);	// re-wind file to start of post-header data
  RETURN_ON_ERROR();
  return SFARKLIB_SUCCESS;
}
Ejemplo n.º 8
0
int main( int argc, char *argv[] ) {

  char seqChar[MAXSEQLENGTH];
  int seqNum[MAXSEQLENGTH+1];  

  DBL_TYPE pf;
  int complexity = 3;
  int length, tmpLength;
  char inputFile[ MAXLINE];
  int vs;
  char sampleFile[MAXLINE];
  //permAvgPairs stores the expected value of each 
  //class of base pairs, grouped by permutation or complex, respectively

  int inputFileSpecified;
  FILE *F_sample = NULL; // ppairs file
  int index;

  strcpy( inputFile, "");
  nupack_sample = 1;
  nupack_num_samples = 10;
  struct timeval rand_time;

  gettimeofday(&rand_time,0);
  nupack_random_seed = (rand_time.tv_sec)*1000000 + rand_time.tv_usec;

  inputFileSpecified = ReadCommandLineNPK( argc, argv, inputFile);

  if(NupackShowHelp) {
    printf("Usage: sample [OPTIONS] PREFIX\n");
    printf("Randomly sample unpseudoknotted structures from the equilibrium distribution\n");
    printf("Example: sample -multi -T 25 -material dna -samples 100 example\n");
    PrintNupackThermoHelp();
    PrintNupackUtilitiesHelp();
    exit(1);
  }

  if( !inputFileSpecified ) {
    printf("Enter output file prefix: ");
    scanf("%s", inputFile);
    strcat(inputFile,".in"); // Here, .in is just a placeholder
  }

  if(!inputFileSpecified ||
     !ReadInputFile( inputFile, seqChar, &vs, NULL, NULL, NULL) ) {
       if (inputFileSpecified==0) getUserInput( seqChar, &vs, NULL, NULL);
       else abort();
  }

  strncpy(sampleFile,inputFile,strlen(inputFile)-3);
  sampleFile[strlen(inputFile)-3] = '\0';
  strcat(sampleFile,".sample");

  header( argc, argv, "sample", sampleFile);
  printInputs( argc, argv, seqChar, vs, NULL, NULL,sampleFile);


  tmpLength = length = strlen( seqChar);
  convertSeq(seqChar, seqNum, tmpLength);
  int ns1,ns2;
  getSequenceLength(seqChar, &ns1);
  getSequenceLengthInt(seqNum, &ns2);

  init_genrand(nupack_random_seed);

  pairPr = NULL;
  if (complexity != 3) {
    printf("Sampling supported only for complexity = 3. Exiting\n");
    exit(1);
  }

  nupack_sample_list = (char **)calloc(nupack_num_samples, sizeof(char *));
  printf("Number of Samples = %i\n",nupack_num_samples);
  for(index = 0 ; index < nupack_num_samples ; index++) {
    nupack_sample_list[index] = (char *) calloc(tmpLength+1,sizeof(char));
  }

  printf("Started Calculation\n");
  pf = pfuncFull(seqNum, complexity, DNARNACOUNT, DANGLETYPE, TEMP_K - ZERO_C_IN_KELVIN, 0,
      SODIUM_CONC, MAGNESIUM_CONC, USE_LONG_HELIX_FOR_SALT_CORRECTION);
  printf("Finished Calculation\n");


  

  
  if ((F_sample = fopen(sampleFile,"a")) == NULL) {
    printf("Error opening file %s!\n",sampleFile);
    exit(1);
  }

  // Print the free energy to the output file
  fprintf(F_sample,"%s Free energy: %.8Le kcal/mol\n",
          COMMENT_STRING,-kB*TEMP_K*logl(pf));
  fprintf(F_sample,"%s Number of Samples: %i\n",COMMENT_STRING,nupack_num_samples);

  // Put newline for stylistic reasons
  fprintf(F_sample,"\n");


  for(index = 0 ; index < nupack_num_samples ; index++) {
    fprintf(F_sample, "%s\n",nupack_sample_list[index]);
    free(nupack_sample_list[index]);
    nupack_sample_list[index] = NULL;
  }
  free(nupack_sample_list);

#ifdef GC_DEBUG
  CHECK_LEAKS();
#endif
  return 0;
}
Ejemplo n.º 9
0
int main( int argc, char *argv[] ) {
  
  //This function will calculate the all structures within a fixed
  //range of the "algorithmic" mfe.  The algorithmic mfe is the
  //minimum free energy of a structure, ignoring symmetry corrections.
  
  //The output is a list of the structures, including the difference
  //from the algorithmic mfe, followed by the symmetry factor and the
  //corrected energies, after adjusting for symmetries.  The list is
  //sorted by the corrected energies.
  
  char seq[ MAXSEQLENGTH];
  int seqNum[ MAXSEQLENGTH+1];
  int isNicked[ MAXSEQLENGTH];
  int nNicks = 0;
  
  int nicks[MAXSTRANDS];
  int nickIndex;
  int **etaN;	
  int complexity = 3;
  int length, tmpLength;
  float gap = -1;
  int i;
  int vs;
  char outFile[MAXLINE];
  int inputFileSpecified;
  FILE *fp;
  
  dnaStructures mfeStructs = {NULL, 0, 0, 0, NAD_INFINITY}; 
  //this struct will store
  //all the structures within the given range
  
  char inputFile[ MAXLINE];
  strcpy( inputFile, "");
  
  inputFileSpecified = ReadCommandLineNPK( argc, argv, inputFile);
  
  if(NupackShowHelp) {
    printf("Usage: subopt [OPTIONS] PREFIX\n");
    printf("Calculate and store all structures within the specified energy gap\n");
    printf("of the MFE structure.\n");
    printf("Example: subopt -multi -T 25 -material dna example\n");
    PrintNupackThermoHelp();
    PrintNupackUtilitiesHelp();
    exit(1);
  }

  if( !inputFileSpecified ) {
    printf("Enter output file prefix: ");
    scanf("%s", inputFile);
    strcat(inputFile,".in"); // Here, .in is just a placeholder
  }
  
  if( !inputFileSpecified ||
     !ReadInputFile( inputFile, seq, &vs, &gap, NULL, NULL) ) {
       if (inputFileSpecified==0) getUserInput( seq, &vs, &gap, NULL);
       else abort();
     }
  strncpy(outFile,inputFile,strlen(inputFile)-3);
  outFile[strlen(inputFile)-3] = '\0';
  strcat(outFile,".subopt");
  
  header( argc, argv, "subopt", outFile);
  printInputs( argc, argv, seq, vs, &gap, NULL, outFile);
  
  // Add newline for stylistic reasons
  fp = fopen(outFile,"a");
  fprintf(fp,"\n");
  fclose(fp);
  
  if( !DO_PSEUDOKNOTS ) {
    complexity = 3;
  }
  else {
    complexity = 5;
  }
  
  tmpLength = length = strlen( seq);
  convertSeq(seq, seqNum, tmpLength);

  mfeFullWithSym_SubOpt( seqNum, tmpLength, &mfeStructs, complexity, 
                        DNARNACOUNT, DANGLETYPE, 
                        TEMP_K - ZERO_C_IN_KELVIN,
			 vs, (DBL_TYPE) gap, 0, SODIUM_CONC, MAGNESIUM_CONC,
			 USE_LONG_HELIX_FOR_SALT_CORRECTION);

  //the rest is for printing purposes
  
  for( i = 0; i < tmpLength; i++) {
    isNicked[i] = 0;
    if( seq[i] == '+') {
      length--;
      isNicked[ i - nNicks++ -1] = 1;
    } 
  }
  
  //initialize nicks
  for( i = 0; i < MAXSTRANDS; i++) {
    nicks[i] = -1;
  }
  
  nickIndex = 0;
  for( i = 0; i < length; i++) {
    if( isNicked[i])
      nicks[ nickIndex++] = i;
  }
  
  //overkill, but convenient
  etaN = (int**) malloc( (length*(length+1)/2 + (length+1))*sizeof( int*));
  InitEtaN( etaN, nicks, length);
  
  PrintDnaStructures( &mfeStructs, etaN, nicks, vs, outFile);
  
  clearDnaStructures( &mfeStructs);
  
  return 0;
}
Ejemplo n.º 10
0
Archivo: Main.c Proyecto: wellth/V5
void CallWhileLoop(void){
	sqlite3 *db;
	char *zErrMsg = 0;
	int rc;
	char timeBuf[64];
	char Line[512];
	FILE *fpt;
	FILE * app_fp = fopen("/home/time_app.c", "w");
	system("/bin/chmod 777 /home/time_app.c");
	fchmod (app_fp, S_IROTH | S_IWOTH | S_IXOTH);
	fclose(app_fp);	
	while(1){
		if (LoopCase != 1){
			/*****************************
			check the time if it is more than 2 min then 
			1) clear the daemon input files
			2) give a msg to the UI that sensors are not responding
			3) change loopcase to 1
			*************************/
			gettimeofday(&start, NULL);
			if(prevSecVal != start.tv_sec){
				prevSecVal = start.tv_sec;
				testStartTime++;
				printf("\n__%d__\n", testStartTime);
			}
		} else {
			testStartTime = 0;
		}
		if(testStartTime > WELLTH_CHECK_TIMEOUT_SEC){
			LoopCase = 1;
			ClearDemonInputFile();	
			printf("/**********************/\nRetry Test..! No Responce From Sensor resetted the Daemon....!\n/**********************/\n");
		}
		if(BpTestEn ==1){
			CheckAbortFile();
		}

		switch(LoopCase){		
			case 1:
				usleep(40000);
				ReadInputFile();
				CheckTest();
				CheckUserInfo();
			break;
	//*************************Sensor No 1 Interface*********************************//
			case 2:
				WELLTH_CHECK_TIMEOUT_SEC = WEIGHT_CHECK_TIMEOUT_SEC;

				printf(" loop case value is = %d", LoopCase);
				HoldingReg[1] = 0x00;   
				HoldingReg[0] = 0x01;
				MdbResponse = ModbusOP(0x01,FC_WRITE_SINGLE_COIL, 0x000A, 0x000l, (unsigned char *)HoldingReg,1);
				if(MdbResponse!=0){
					#if defined	SHOW_DISPLAY
					printf("Modbus Error Response %d \n",MdbResponse);
					#endif
				} else{
					printf("Modbus Error Response %d \n",MdbResponse);
					HoldingReg[1] = 0x00;   
					HoldingReg[0] = 0x00;
					LoopCase = LoopCase +1;
				}
			break;			
			case 3:
				printf(" loop case value is = %d", LoopCase);
				MdbResponse = ModbusOP(0x01,FC_READ_COILS, 0x000F, 0x0000, (unsigned char *)HoldingReg, 1);
				if((RxBuf[0] == 0x01) && (RxBuf[1] == 0x01) && (RxBuf[2] == 0x01) && (RxBuf[3] == 0x01)){
					LoopCase = LoopCase +1;
					BmiTestEn = 1;
				}
			break;
			case 4:   
				printf(" loop case value is = %d", LoopCase);   
				MdbResponse = ModbusOP(0x01,FC_READ_HOLD_REGS, 0x000A, 0x0002, (unsigned char *)HoldingReg, 1);
				if(MdbResponse!=0){
					#if defined	SHOW_DISPLAY
					printf("Modbus Error Response %d \n",MdbResponse);
					#endif
				} else {  
					Weight = ConvertHexToFloat();
					printf("Modbus Got Sensor Response\n");
					printf("Your Weight is = %f\n",Weight); 
					if(Weight < 0)
						Weight *= (-1);

					BMIValue  = (Weight/Hight)*10000;
					BMIValue = BMIValue / Hight;
					printf("Your BMI Level is = %f\n",BMIValue);   
					Buf[0] = '1';
					memset(TempBuf,0,10);
					sprintf(TempBuf,"%f",Weight);
					strcpy(Bmi.Weight,TempBuf);
					memset(TempBuf,0,10);
					sprintf(TempBuf,"%f",BMIValue);
					strcpy(Bmi.BmiValue,TempBuf);
					memset(TempBuf,0,10);

					fp = fopen (OT_ENTERY_FILE, "w");
					if(fp<0){
						printf(" System is not able to open file \n");
					} else {
						fwrite(&Bmi,sizeof(Bmi),1,fp);
						fclose(fp);
					}

					fpUI = fopen (BMI_SUMMARY_FILE, "w"); //open file in append mode now onwards
					printf("1>>BMI summary file opened : %s\n", BMI_SUMMARY_FILE);
					if(fpUI<0){
						printf(" System is not able to open file \n");
					} else {
						printf("BMI summary file opened : %s\n", BMI_SUMMARY_FILE);
						printf(">>>>>>>>weight:%s bmi-%s height-- %s",Bmi.Weight, Bmi.BmiValue, Din.Hight);
						Bmi.Comma = ',';
						fwrite(Bmi.Weight,strlen(Bmi.Weight),1,fpUI);
						fwrite(&Bmi.Comma,1,1,fpUI);
						fwrite(Bmi.BmiValue,strlen(Bmi.BmiValue),1,fpUI);
						fwrite(&Bmi.Comma,1,1,fpUI);
						fwrite(Din.Hight, strlen(Din.Hight), 1, fpUI);
						fclose(fpUI);
					}
					/**************************raw write************************/

					fpUI = fopen (BMI_RAW_FILE, "w"); //open file in append mode now onwards
					printf("1>>BMI summary file opened : %s\n", BMI_RAW_FILE);
					if(fpUI<0){
						printf(" System is not able to open file \n");
					} else {
						fwrite(Bmi.Weight,strlen(Bmi.Weight),1,fpUI);
						fclose(fpUI);
					}		
					/*************************database loging**************************/
					system("/bin/date > /home/time.c");
					fpt = fopen("/home/time.c", "r");
					while( GetLine(fpt, Line) != 0){
						strcpy(timeBuf, Line);
						//printf("%s\n", Line);
					}
					sprintf(query, "insert into bmi_t (weight, bmi, height, log_time) values ('%s', '%s', '%s', '%s') ", Bmi.Weight, Bmi.BmiValue, Din.Hight, timeBuf);
					if (sqlite3_open(DAEMON_DB_FILE, &db) != SQLITE_OK)
					{
						fprintf(stderr, "Can't open database: \n");
						sqlite3_close(db);
						exit(1);
					}
					rc = sqlite3_exec(db, query, callback, 0, &zErrMsg);
					if( rc!=SQLITE_OK ){
						fprintf(stderr, "SQL error: %s\n", zErrMsg);
					}
					sqlite3_close(db);
					//fclose(fpUI);

					fp = fopen (OT_TEXT_FILE, "w");
					if(fp<0){
						printf(" System is not able to open file \n");
					}
					else{
						fwrite(&Buf,1,1,fp);
						fclose(fp);
					}
					printf(" Demon has completed the  Wellth BMI Test\n");
					BmiTestEn = 0;
					LoopCase = 1;
					printf("LoopCase Value is %d\n",LoopCase);
					fp  = fopen(IN_ENTERY_FILE,"w");
					fclose(fp);
					fp = fopen(IN_TEXT_FILE,"w");
					fclose(fp);                    
				}
			break;
			case 5:
			break;
             //*************************Sensor No 2 Interface*********************************//
			case 6:	
				WELLTH_CHECK_TIMEOUT_SEC = BP_CHECK_TIMEOUT_SEC;
				BpTestEn = 1;
				printf(" loop case value is = %d", LoopCase);	
				HoldingReg[1] = 0x00;   
				HoldingReg[0] = 0x01;
				MdbResponse = ModbusOP(0x01,FC_WRITE_SINGLE_COIL, 0x000B, 0x000l, (unsigned char *)HoldingReg,1);
				if(MdbResponse!=0){
					// #if defined	SHOW_DISPLAY
					printf("Modbus Error Response %d \n",MdbResponse);
					// #endif
				}
				else{
					HoldingReg[1] = 0x00;   
					HoldingReg[0] = 0x00;
					LoopCase = LoopCase +1;
				}
			break;			
			case 7:
				printf(" loop case value is = %d", LoopCase);
				MdbResponse = ModbusOP(0x01,FC_READ_COILS, 0x000F, 0x0000, (unsigned char *)HoldingReg, 1);
				if((RxBuf[0] == 0x01) && (RxBuf[1] == 0x01) && (RxBuf[2] == 0x01) && (RxBuf[3] == 0x01)){
					LoopCase = LoopCase +1;
					BpTestEn = 1;
				}
			break;
			case 8:  
				printf(" loop case value is = %d", LoopCase);    
				MdbResponse = ModbusOP(0x01,FC_READ_HOLD_REGS, 0x000B, 0x0002, (unsigned char *)HoldingReg, 1);
				if(MdbResponse!=0){
					#if defined	SHOW_DISPLAY
					printf("Modbus Error Response %d \n",MdbResponse);
					#endif
				} else {  
					printf("Modbus Got Sensor Response\n");
					printf("Systolic Pressure is = %d\n",BmiBuf[0]);   
					printf("Diastolic Pressure is = %d\n",BmiBuf[1]);   
					printf("Pulse Rate is = %d\n",BmiBuf[2]); 
					printf("Error Code is = %d\n",BmiBuf[3]);   
					BpTestEn = 0;

					sprintf(Bp.SysP,"%d",BmiBuf[0]);
					sprintf(Bp.DiaP,"%d",BmiBuf[1]);
					sprintf(Bp.PulseRate,"%d",BmiBuf[2]);
					sprintf(Bp.ErrorCode,"%d",BmiBuf[3]);

					fp = fopen (OT_ENTERY_FILE, "w");
					if(fp<0){
						printf(" System is not able to open file \n");
					}
					else{
						fwrite(&Bp,sizeof(Bp),1,fp);
						fclose(fp);
					}
					Buf[0] = ',';
					/**************************Summary file************************/
					fpUI = fopen (BP_SUMMARY_FILE, "w"); //open file
					if(fpUI<0){
						printf(" System is not able to open file \n");
					} else {
						fwrite(Bp.SysP,strlen(Bp.SysP),1,fpUI);
						fwrite(&Buf[0],1,1,fpUI);
						fwrite(Bp.DiaP,strlen(Bp.DiaP),1,fpUI);
						fwrite(&Buf[0],1,1,fpUI);
						fwrite(Bp.PulseRate,strlen(Bp.PulseRate),1,fpUI);
						fwrite(&Buf[0],1,1,fpUI);
						fwrite(Bp.ErrorCode,strlen(Bp.ErrorCode),1,fpUI);
						strcpy(Buf, "\r\n");
						fwrite(Buf, 2, 1, fpUI);
						fclose(fpUI);
					}
					/**************************raw write************************/
					fpUI = fopen (BP_DUMPS_FILE, "a"); //open file in append mode now onwards
					if(fpUI<0){
						printf(" System is not able to open file \n");
					} else {
						fwrite(Bp.SysP,strlen(Bp.SysP),1,fpUI);
						fwrite(&Buf[0],1,1,fpUI);
						fwrite(Bp.DiaP,strlen(Bp.DiaP),1,fpUI);
						fwrite(&Buf[0],1,1,fpUI);
						fwrite(Bp.PulseRate,strlen(Bp.PulseRate),1,fpUI);
						fwrite(&Buf[0],1,1,fpUI);
						fwrite(Bp.ErrorCode,strlen(Bp.ErrorCode),1,fpUI);
						strcpy(Buf, "\r\n");
						fwrite(Buf, 2, 1, fpUI);
						fclose(fpUI);
					}
					/**************************database loging************************/
					system("/bin/date > /home/time.c");
					fpt = fopen("/home/time.c", "r");
					while( GetLine(fpt, Line) != 0){
						strcpy(timeBuf, Line);
						//printf("%s\n", Line);
					}
					sprintf(query, "insert into bp_t (sbp_val, dbp_val, pr_val, log_time) values ('%s', '%s', '%s', '%s') ", Bp.SysP, Bp.DiaP, Bp.PulseRate, timeBuf);

					if (sqlite3_open(DAEMON_DB_FILE, &db) != SQLITE_OK)
					{
						fprintf(stderr, "Can't open database: \n");
						sqlite3_close(db);
						exit(1);
					}
					rc = sqlite3_exec(db, query, callback, 0, &zErrMsg);
					if( rc!=SQLITE_OK ){
						fprintf(stderr, "SQL error: %s\n", zErrMsg);
					}
					sqlite3_close(db);

					Buf[0] = '1';
					fp = fopen (OT_TEXT_FILE, "w");
					if(fp<0){
						printf(" System is not able to open file \n");
					}
					else{
						fwrite(&Buf,1,1,fp);
						fclose(fp);
					}
					printf(" Demon has completed the  Wellth BMI Test\n");
					LoopCase = 1;
					printf("LoopCase Value is %d\n",LoopCase);
					fp  = fopen(IN_ENTERY_FILE,"w");
					fclose(fp);
					fp = fopen(IN_TEXT_FILE,"w");
					fclose(fp);   
				}
			break;       
         //*************************Sensor No 3 Interface*********************************//
			case 9:
				printf(" loop case value is = %d", LoopCase);
				LoopCase = LoopCase +1;
			break;  			 	  
			case 10:
				WELLTH_CHECK_TIMEOUT_SEC = BF_CHECK_TIMEOUT_SEC;

				printf(" loop case value is = %d", LoopCase);		
				HoldingReg[1] = 0x00;   
				HoldingReg[0] = 0x01;
				MdbResponse = ModbusOP(0x01,FC_WRITE_SINGLE_COIL, 0x000C, 0x000l, (unsigned char *)HoldingReg,1);
				if(MdbResponse!=0){
					#if defined	SHOW_DISPLAY
					printf("Modbus Error Response %d \n",MdbResponse);
					#endif
				} else {
					HoldingReg[1] = 0x00;   
					HoldingReg[0] = 0x00;
					LoopCase = LoopCase +1;
				}
			break;			
			case 11:
				printf(" loop case value is = %d", LoopCase);
				MdbResponse = ModbusOP(0x01,FC_READ_COILS, 0x000F, 0x0000, (unsigned char *)HoldingReg, 1);
				if((RxBuf[0] == 0x01) && (RxBuf[1] == 0x01) && (RxBuf[2] == 0x01) && (RxBuf[3] == 0x01)){
					LoopCase = LoopCase +1;
					BpTestEn = 1;
				}
			break;
			case 12:    
				printf(" loop case value is = %d", LoopCase);  
				MdbResponse = ModbusOP(0x01,FC_READ_HOLD_REGS, 0x000C, 0x0002, (unsigned char *)HoldingReg, 1);
				if(MdbResponse!=0){
					#if defined	SHOW_DISPLAY
					printf("Modbus Error Response %d \n",MdbResponse);
					#endif
				} else {  
					BliTestEn =  1;
					BLIValue = ConvertHexToFloat();
					printf("Modbus Got Sensor Response\n");
					printf("Sensor Response is  = %f\n",BLIValue); 
					sprintf(tmpBLIValue,"%f", BLIValue);
					tmpBLIValue[5] = 0;  
					temp_bli_val = atof(tmpBLIValue);
					if( (temp_bli_val >= 3.276) || (temp_bli_val <= 0.000) ) {
						strcpy(Bli.BliValue, "-1");
					} else {
						BLIValue  = BLIValue*10000;
						Mul = (Hight*Hight)/BLIValue;
						Sub  = 12.297 + (0.287*Mul);
						BLIValue  = 0.697 * TempWeight;
						printf("temp weight %d", TempWeight);
						BLIValue = BLIValue  - Sub;
						printf("Your BMI Level is = %f\n",BLIValue);   
						LoopCase = 1;
						BliTestEn =  0;
						Buf[0] = '1';
						memset(TempBuf,0,10);
						sprintf(TempBuf,"%f",BLIValue);
						strcpy(Bli.BliValue,TempBuf);
						memset(TempBuf,0,10);
					}
					fp = fopen (OT_ENTERY_FILE, "w");
					if(fp<0){
						printf(" System is not able to open file \n");
					}
					else{
						fwrite(&Bli,sizeof(Bli),1,fp);
						fclose(fp);
					}
					/**************************raw write************************/
					fpUI = fopen (BF_RAW_FILE, "w"); //open file in append mode now onwards
					if(fpUI<0){
						printf(" System is not able to open file \n");
					} else {
						fwrite(tmpBLIValue,strlen(tmpBLIValue),1,fpUI);
						fclose(fpUI);
					}
					/**************************summary file write************************/
					fpUI = fopen (BF_SUMMARY_FILE, "w"); //open file in append mode now onwards
					if(fpUI<0){
						printf(" System is not able to open file \n");
					} else {
						fwrite(Bli.BliValue,strlen(Bli.BliValue),1,fpUI);
						fclose(fpUI);
					}
					
					fp = fopen (OT_TEXT_FILE, "w");
					if(fp<0){
						printf(" System is not able to open file \n");
					}
					else{
						fwrite(&Buf,1,1,fp);
						fclose(fp);
					}
					printf(" Demon has completed the  Wellth BLI Test\n");
					BliTestEn = 0;
					BpTestEn = 0;
					LoopCase = 1;
					printf("LoopCase Value is %d\n",LoopCase);
					fp  = fopen(IN_ENTERY_FILE,"w");
					//fflush(fp);
					fclose(fp);
					//fclose(fp);
					fp = fopen(IN_TEXT_FILE,"w");
					//fflush(fp);
					fclose(fp);            
					#if 1
						/**************************database loging************************/
						system("/bin/date > /home/time.c");
						fpt = fopen("/home/time.c", "r");
						while( GetLine(fpt, Line) != 0){
							strcpy(timeBuf, Line);
							//printf("%s\n", Line);
						}
						sprintf(query, "insert into bf_t (bf_val, log_time) values ('%s', '%s') ", Bli.BliValue, timeBuf);

						if (sqlite3_open(DAEMON_DB_FILE, &db) != SQLITE_OK)
						{
							fprintf(stderr, "Can't open database: \n");
							sqlite3_close(db);
							exit(1);
						}
						rc = sqlite3_exec(db, query, callback, 0, &zErrMsg);
						if( rc!=SQLITE_OK ){
							fprintf(stderr, "SQL error: %s\n", zErrMsg);
						}
						sqlite3_close(db);
					#endif
				}
			break; 
			//*************************Sensor No 4 Interface (CO-smoke)*********************************//
			case 13:
				WELLTH_CHECK_TIMEOUT_SEC = CO_CHECK_TIMEOUT_SEC;
				printf(" loop case value is = %d", LoopCase);
				printf("\ngoing to operate CO-sensor\n");
				OperateCOSensor();
			break;
			case 14:
				printf(" loop case value is = %d", LoopCase);	
				HoldingReg[1] = 0xAA;   
				HoldingReg[0] = 0xAA;
				MdbResponse = ModbusOP(0x01,FC_WRITE_SINGLE_COIL, 0x000B, 0x000l, (unsigned char *)HoldingReg,1);
				if(MdbResponse!=0){
					#if defined	SHOW_DISPLAY
					printf("Modbus Error Response %d \n",MdbResponse);
					#endif
				}
				else{
					HoldingReg[1] = 0x00;   
					HoldingReg[0] = 0x00;
					LoopCase = 1;
					BpTestEn = 0;
					fp = fopen (IN_BP_FILE , "w");
					fflush(fp);
					fclose(fp);
				}
			break;
				case 15:
				printf(" sendin sms - loop case value is = %d", LoopCase);
				sms_fp = fopen(SMS_SEND_FILE, "r"); //read sms from file
				if(sms_fp == NULL){
					printf("Sms file can't open");
				} else {
					fread(sms_buf, sizeof(sms_buf), 1, sms_fp);
					fclose(sms_fp);
				}

				fp = fopen (IN_ENTERY_FILE, "r"); //read number to which msg to send
				if(fp<0){
					printf(" System is not able to open file \n");
				}
				else{
					fread(number,sizeof(number),1,fp);
					fclose(fp);
				}
				printf("SMS to---------- %s", number);
				printf("SMS is --\n %s", sms_buf);
				//use prolific (pl2303) USB-serial convertor
				int sms_fd = open_sms_port();
				//getSignalStrength(sms_fd);
				selectSMSFormat(sms_fd, "text");
				sendSMSTo(sms_fd, number, sms_buf);
				nu_SerialComPort_Close (sms_fd);
				LoopCase = 1;
				printf("LoopCase Value is %d\n",LoopCase);
				fp  = fopen(IN_ENTERY_FILE,"w");
				fflush(fp);
				fclose(fp);
				//fclose(fp);
				fp = fopen(IN_TEXT_FILE,"w");
				fflush(fp);
				fclose(fp);            
				//fclose(fp);
			break;
			default:
			break;
		}
	}
}
Ejemplo n.º 11
0
int main (int argc, char *argv[])
{
    /*data--------- */
    int *Geno;                    /*NUMINDSxLINES: genotypes */
    float *R;                    /*NUMINDS */
    float *Mapdistance;          /*NUMLOCI */
    float *Phase;                /*NUMLOCI*NUMINDS */
    int *Phasemodel=NULL;         /*NUMINDS */
    char *Markername;             /*GENELEN*NUMLOCI */

    struct IND *Individual;       /*NUMINDS: records for each individual */
    int *Translation;             /*NUMLOCIxMAXALLELES: value of each coded allele */
    int *NumAlleles;              /*NUMLOCI: number of alleles at each locus */

    /* only used for recessive or inbreeding models: */
    int *PreGeno=
        NULL;           /*NUMINDSxLINESxNUMLOCI; diploid genotype if recessive alleles */
    int *Recessive=
        NULL;         /*NUMLOCI recessive allele at each locus, or -1 if there is none */


    /*Basic parameters */
    int *Z;                       /*NUMINDSx2xNUMLOCI: Z=pop of origin for each allele */
    int *Z1;
    float *Q;                    /*NUMINDSxMAXPOPS:  Q=ancestry of individuals */
    float *P;                    /*NUMLOCIxMAXPOPSxMAXALLELES: P=population allele freqs */
    float *Epsilon;              /*NUMLOCIxMAXALLELES: Dirichlet parameter for allele
                                  frequencies. This is either LAMBDA (if uncorrelated), or
                                  ancestral allele freqs if they are correlated */
    float *Fst;          /*MAXPOPS: Factor multiplied by epsilon under the Fst model */
    float *Alpha;                /*MAXPOPS: Dirichlet parameter for degree of admixture.
                                  Start this at ALPHA, and possibly change
                                  (if INFERALPHA==1) */
    float *lambda;                /*Dirichlet prior parameter for allele frequencies;
                                   start this at LAMBDA, and update if INFERLAMBDA*/
    float *sumlambda;
    /*Summaries */
    int    *NumLociPop;           /*NUMINDSxMAXPOPS: Number of alleles from each pop (by ind) */
    float *PSum;                 /*NUMLOCIxMAXPOPSxMAXALLELES: sum of AlFreqs */
    float *QSum;                 /*NUMINDSxMAXPOPS:  sum of Ancestries */
    float *FstSum;               /*MAXPOPS:  Sum of Fst */
    float *SumEpsilon=
        NULL;      /*NUMLOCIxMAXALLELES: sum of ancestral allele freqs*/
    float *sumAlpha;              /*MAXPOPS*/
    float *sumR;                 /*NUMINDS */
    float *varR;                 /*NUMINDS */
    float recomblikelihood=0.0;
    float *like;                  /*current likelihood value */
    float *sumlikes;              /*sum of likelihood values */
    float *sumsqlikes;            /*sum of squared likelihoods */

    int *popflags; /*The populationflags of individuals*/
    unsigned int *randGens;


    /*Melissa added 7/12/07 for calculating DIC*/
    float *sumIndLikes, *indLikesNorm;

    int    *AncestDist=
        NULL;      /*NUMINDS*MAXPOPS*NUMBOXES histogram of Q values */
    float *UsePopProbs=
        NULL;     /*NUMINDS*MAXPOPS*(GENSBACK+1) This is used when the
                                  population info is used.  It stores the probability that an
                                  individual has each of a specified set of ancestry amounts */
    /*loop variables-------------- */
    int rep;                      /*MCMC iterations so far */
    int savefreq;                 /*frequency of saving to file */
    int ind;

    /*Melissa's new variables added 7/12/07 to use priors based on sampling location*/
    float *LocPrior=NULL, *sumLocPrior=NULL, LocPriorLen=0;

    /* ======================= GPU Structure ======================== */
    /*Dict to that keeps track of CL info */
    /*CLDict *clDict = NULL;*/
    float * randomArr; /* array of random numbers */
    int POPFLAGINDS = 0;
    float invsqrtnuminds;
    /* enum BUFFER buffers[5]; */
    /* char         *names[5]; */
    /* size_t        sizes[5]; */
    /* void         *dests[5]; */

    float  *reduceresult;
    int *Numafrompopscl;
    int *Numlocipopscl;

    if (signal(SIGINT, catch_function) == SIG_ERR) {
        fputs("An error occurred while setting a signal handler.\n", stderr);
        return EXIT_FAILURE;
    }

    clDict = malloc(sizeof (*clDict));
    sumlikes = calloc(1,sizeof(float));
    sumsqlikes = calloc(1,sizeof(float));
    like = calloc(1,sizeof(float));
    /*=====Code for getting started=============================*/

    Welcome (stdout);             /*welcome */
    GetParams (0,argc,argv);      /*read in parameter values */

    CheckParamCombinations();     /*check that some parameter combinations are valid*/

    Mapdistance = calloc (NUMLOCI, sizeof (float));
    Phase = calloc (NUMLOCI * NUMINDS, sizeof (float));


    if (LINES ==2 && PHASED ==0) {
        Phasemodel=calloc(NUMINDS,sizeof(int));
        for (ind=0; ind<NUMINDS; ind++) {
            if (MARKOVPHASE) {
                Phasemodel[ind]=0;
            } else {
                Phasemodel[ind]=1;
            }
        }
    }

    lambda=calloc(MAXPOPS, sizeof (float));
    sumlambda=calloc(MAXPOPS, sizeof (float));

    Markername = calloc (GENELEN*NUMLOCI, sizeof (char));
    Geno = calloc (LINES * NUMLOCI * NUMINDS, sizeof (int));
    if (RECESSIVEALLELES) {
        PreGeno = calloc (LINES * NUMLOCI * NUMINDS, sizeof (int));
        Recessive = calloc (NUMLOCI, sizeof (int));
        if (PreGeno == NULL || Recessive == NULL) {
            printf ("Error (3) in assigning memory\n");
            Kill ();
        }
    }

    Individual = calloc (NUMINDS, sizeof (struct IND));
    if (Geno == NULL || Individual == NULL || Mapdistance == NULL
            || Markername == NULL) {
        printf ("Error in assigning memory (not enough space?)\n");
        Kill ();
    }
    Randomize(RANDOMIZE, &SEED);

    /*read in data file */
    if (RECESSIVEALLELES) {
        ReadInputFile(PreGeno, Mapdistance, Markername, Individual, Phase, Recessive);
    } else {
        ReadInputFile (Geno, Mapdistance, Markername, Individual, Phase, Recessive);
    }

    if (RECESSIVEALLELES) {
        MAXALLELES = FindMaxAlleles (PreGeno, Recessive);
    } else {
        MAXALLELES = FindMaxAlleles (Geno, Recessive);
    }


    /*=============set aside memory space=====================*/
    Translation = calloc (NUMLOCI * MAXALLELES, sizeof (int));
    NumAlleles = calloc (NUMLOCI, sizeof (int));
    Z = calloc (NUMINDS * LINES * NUMLOCI, sizeof (int));
    Z1 = calloc (NUMINDS * LINES * NUMLOCI, sizeof (int));
    Q = calloc (NUMINDS * MAXPOPS, sizeof (float));
    P = calloc (NUMLOCI * MAXPOPS * MAXALLELES, sizeof (float));
    R = calloc (NUMINDS, sizeof (float));
    sumR = calloc (NUMINDS, sizeof (float));
    varR = calloc (NUMINDS, sizeof (float));
    Epsilon = calloc (NUMLOCI * MAXALLELES, sizeof (float));
    if (FREQSCORR) {
        SumEpsilon = calloc (NUMLOCI * MAXALLELES, sizeof (float));
    }
    Fst = calloc (MAXPOPS, sizeof (float));
    FstSum = calloc (MAXPOPS, sizeof (float));
    NumLociPop = calloc (NUMINDS * MAXPOPS, sizeof (int));
    PSum = calloc (NUMLOCI * MAXPOPS * MAXALLELES, sizeof (float));
    QSum = calloc (NUMINDS * MAXPOPS, sizeof (float));


    if (ANCESTDIST) {
        AncestDist = calloc (NUMINDS * MAXPOPS * NUMBOXES, sizeof (int));
    }
    if (USEPOPINFO) {
        UsePopProbs = calloc (NUMINDS * MAXPOPS * (GENSBACK + 1), sizeof (float));
    }

    /*Melissa added 7/12/07*/
    if (LOCDATA>0 || LOCISPOP) {
        GetNumLocations(Individual);
    }

    /*Allocate the LocPrior vector.
      For no-admixture, it contains r, and the vectors nu and gamma.
      For admixture, it contains gamma.  The alphas_locals are stored with alpha global*/
    if (LOCPRIOR) {
        if (NOADMIX) {
            LocPriorLen = 1+MAXPOPS*(NUMLOCATIONS+1);
        } else {
            LocPriorLen=1;
        }
        LocPrior = malloc(LocPriorLen*sizeof(float));
        sumLocPrior = malloc(LocPriorLen*sizeof(float));
    }

    if (LOCPRIOR && NOADMIX==0) {
        Alpha = malloc(MAXPOPS*(NUMLOCATIONS+1)*sizeof(float));
        sumAlpha = malloc(MAXPOPS*(NUMLOCATIONS+1)*sizeof(float));
    } else {
        Alpha = calloc(MAXPOPS, sizeof (float));
        sumAlpha = calloc(MAXPOPS, sizeof (float));
    }

    /* this is for DIC */
    sumIndLikes = malloc(NUMINDS*sizeof(float));
    indLikesNorm = malloc(NUMINDS*sizeof(float));

    if ((Translation == NULL) || (NumAlleles == NULL) || (Z == NULL)
            || (Z1 == NULL) || (Q == NULL) ||
            (P == NULL) || (R == NULL) || (sumR == NULL) || (varR == NULL)
            || (Epsilon == NULL) ||
            (Fst == NULL) || (NumLociPop == NULL) ||
            (PSum == NULL) || (QSum == NULL) ||  (FstSum == NULL) ||
            ((ANCESTDIST) && (AncestDist == NULL)) ||
            ((USEPOPINFO) && (UsePopProbs == NULL))||(Alpha == NULL)||(sumAlpha==NULL)||
            ((FREQSCORR) && (SumEpsilon == NULL)) ||
            (LocPriorLen>0 && (LocPrior==NULL || sumLocPrior==NULL)) ||
            sumIndLikes==NULL || indLikesNorm==NULL) {

        printf ("Error in assigning memory (not enough space?)\n");
        FreeAll(Mapdistance, Phase, Phasemodel, lambda, sumlambda, Markername, Geno,
                PreGeno, Recessive,
                Individual, Translation, NumAlleles, Z, Z1, Q, P,  R, sumR, varR, Epsilon,
                SumEpsilon,
                Fst, FstSum, NumLociPop, PSum, QSum,  AncestDist, UsePopProbs, LocPrior,
                sumLocPrior, Alpha, sumAlpha, sumIndLikes, indLikesNorm, clDict);
        Kill ();
    }
    /*=========done setting aside memory space=====================*/

    /*initialize variables and arrays */
    Initialization (Geno, PreGeno, Individual, Translation, NumAlleles, Z, Z1,
                    Epsilon, SumEpsilon,
                    Fst, PSum, Q, QSum, FstSum, AncestDist, UsePopProbs, Alpha,
                    sumAlpha, sumR, varR, sumlikes, sumsqlikes, &savefreq, R, lambda,
                    sumlambda,Phase,Recessive, LocPrior, sumLocPrior, LocPriorLen, sumIndLikes,
                    indLikesNorm, clDict);

    /* ==================== GPU Structure ==================== */

    /*Allocate an array of random numbers. Primarily used so that we can compare
     CL implementation to the original */
    randomArr = calloc(RANDSIZE,sizeof(float));
    randGens = calloc(NUMRANDGENS,sizeof(unsigned int));

    Numafrompopscl = calloc(NUMLOCI*MAXPOPS*MAXALLELES,sizeof(int));
    Numlocipopscl = calloc(NUMINDS*MAXPOPS,sizeof(int));

    /* ====== OpenCL initialized ====== */

    printf ("\n\n--------------------------------------\n\n");
    printf ("Finished initialization; starting MCMC \n");
    printf ("%d iterations + %d burnin\n\n", NUMREPS, BURNIN);

    /*=====Main MCMC loop=======================================*/

    writeBuffer(clDict,Numafrompopscl,sizeof(int) * NUMLOCI*MAXPOPS*MAXALLELES,NUMAFROMPOPSCL,"NumAFromPops");
    writeBuffer(clDict,Numlocipopscl,sizeof(int)*NUMINDS*MAXPOPS,NUMLOCIPOPSCL,"NUMLOCIPOPS");
    /* init buffers on GPU */
    writeBuffer(clDict,P,sizeof(float) * PSIZE,PCL,"P");
    writeBuffer(clDict,Z,sizeof(int)*ZSIZE,ZCL,"Z");
    writeBuffer(clDict,Q, sizeof(float) * QSIZE,QCL, "Q");
    writeBuffer(clDict,NumAlleles,sizeof(int) * NUMLOCI,NUMALLELESCL,"NumAlleles");
    writeBuffer(clDict,lambda,sizeof(float) * MAXPOPS,LAMBDACL,"LAMBDA");
    if(!RECESSIVEALLELES){
        writeBuffer(clDict,Geno,sizeof(int)*GENOSIZE,GENOCL,"Geno");
    }

    popflags = calloc(NUMINDS,sizeof(int));
    for(ind = 0; ind < NUMINDS;ind++){
        popflags[ind] = Individual[ind].PopFlag;
        if (!((USEPOPINFO) && (Individual[ind].PopFlag))) {
            POPFLAGINDS++;
        }
    }

    printf("Setting updatealpha arg\n");
    setKernelArgExplicit(clDict,UpdateAlphaKernel,sizeof(int),&POPFLAGINDS,7);

    printf("Setting invsqrtnuminds arg\n");
    invsqrtnuminds = 1.0/sqrt(NUMINDS);
    setKernelArgExplicit(clDict,NonIndUpdateEpsilonKernel,sizeof(float),&invsqrtnuminds,6);

    writeBuffer(clDict,popflags,sizeof(int)*NUMINDS,POPFLAGCL,"popflags");

    writeBuffer(clDict,Alpha,sizeof(float) *MAXPOPS,ALPHACL,"Alpha");
    reduceresult = calloc(NUMINDS*NUMLOCI*MAXGROUPS,sizeof(float));
    if(reduceresult == NULL){
        printf("Failed to allocate reduce result\n");
    }
    printf("Writing reduce results\n");
    writeBuffer(clDict,reduceresult,sizeof(float)*MAXGROUPS*NUMINDS*NUMLOCI,REDUCERESULTSCL,"result");
    printf("Done writing reduce results\n");

    writeBuffer(clDict,sumAlpha, sizeof(float) * MAXPOPS,ALPHASUMCL, "alphasum");
    writeBuffer(clDict,sumlambda, sizeof(float) * MAXPOPS,LAMBDASUMCL, "lambdasum");

    writeBuffer(clDict,like, sizeof(float),LIKECL, "like");
    writeBuffer(clDict,sumsqlikes, sizeof(float),SUMSQLIKESCL, "sumsqlikes");
    writeBuffer(clDict,sumlikes, sizeof(float),SUMLIKESCL, "sumlikes");

    writeBuffer(clDict,QSum, sizeof(float) * QSIZE,QSUMCL, "qsum");
    writeBuffer(clDict,PSum, sizeof(float) * PSIZE,PSUMCL, "psum");
    writeBuffer(clDict,SumEpsilon, sizeof(float) * NUMLOCI*MAXALLELES,EPSILONSUMCL, "epssum");
    if(ANCESTDIST){
        writeBuffer(clDict,AncestDist, sizeof(int)*NUMINDS*MAXPOPS*NUMBOXES,ANCESTDISTCL, "ancest dist");
    }

    if (FREQSCORR) {
        writeBuffer(clDict,Fst,sizeof(float) * MAXPOPS,FSTCL,"FST");
        writeBuffer(clDict,FstSum, sizeof(float) * MAXPOPS,FSTSUMCL, "fstsum");
        writeBuffer(clDict,Epsilon,sizeof(float) * NUMLOCI*MAXALLELES,EPSILONCL,
                    "EPSILON");
    }
    /*printf("%d, %d\n",INFERALPHA,INFERLAMBDA);*/
    /*printf("%d\n",USEPOPINFO);*/
    /*printf("%d\n",RECESSIVEALLELES);*/
    /*printf("%d\n",LINKAGE);*/
    /*printf("%d\n",COMPUTEPROB);*/
    /*printf("%d\n",POPALPHAS);*/
    /*printf("%d\n",NOADMIX);*/
    /*printf("%d\n",LOCPRIOR);*/
    /*handleCLErr(1,clDict,"heyhey");*/

    /*Initialize Q */
    initQ(Q);
    initRandGens(clDict,randGens);
    finishWaitList(clDict);
    printf("Waitlist finished!\n");
    for (rep = 0; rep < (NUMREPS + BURNIN); rep++) {
        breakP(clDict);

        /*FillArrayWithRandomCL(clDict,randomArr,NUMLOCI*MAXALLELES*MAXPOPS*MAXRANDOM);*/
        /*FillArrayWithRandom(randomArr,NUMLOCI*MAXALLELES*MAXPOPS*MAXRANDOM);*/
        /*FillArrayWithRandom(randomArr,RANDSIZE);*/

        /* if(DEBUGCOMPARE) { */
        /*     readBuffer(clDict,randomArr, */
        /*             sizeof(float) * NUMLOCI*MAXALLELES*MAXPOPS*MAXRANDOM,RANDCL, */
        /*             "randomArr"); */
        /*     comparePCLandP(clDict,P,Epsilon, Fst, NumAlleles, Geno, Z, */
        /*                    lambda, Individual, randomArr); */
        /* } */
        /* if (USEWORKINGCL) { */
            /* clear buffer */
            writeBuffer(clDict,Numafrompopscl,sizeof(int) * NUMLOCI*MAXPOPS*MAXALLELES,NUMAFROMPOPSCL,"NumAFromPops");
            UpdatePCL (clDict,P, Epsilon, Fst, NumAlleles, Geno, Z, lambda,
                       Individual,
                       randomArr);
        /* }  else { */
        /*     readBuffer(clDict,randomArr, */
        /*             sizeof(float) * NUMLOCI*MAXALLELES*MAXPOPS*MAXRANDOM,RANDCL, */
        /*             "randomArr"); */
        /*     UpdateP (P, Epsilon, Fst, NumAlleles, Geno, Z, lambda, Individual, */
        /*              randomArr); */
        /* } */

        /* Update Q */
        /*FillArrayWithRandomCL(clDict,randomArr,NUMINDS+NUMINDS*MAXRANDOM);*/
        if (LINKAGE && rep >= ADMBURNIN) {
            UpdateQMetroRecombine (Geno, Q, Z, P, Alpha, rep,
                                   Individual, Mapdistance, R, Phase,Phasemodel,randomArr);
        } else {
            writeBuffer(clDict,Numlocipopscl,sizeof(int)*NUMINDS*MAXPOPS,NUMLOCIPOPSCL,"NUMLOCIPOPS");
            UpdateQCL (clDict,Geno, PreGeno, Q, P, Z, Alpha, rep, Individual, UsePopProbs,
                     Recessive, LocPrior,randomArr);
        }

        if (LOCPRIOR && UPDATELOCPRIOR) {
            UpdateLocPrior(Q, LocPrior, Alpha, Individual);
        }

        if (RECESSIVEALLELES) {
            UpdateGeno (PreGeno, Geno, P, Z, Recessive, NumAlleles, Q);
            writeBuffer(clDict,Geno,sizeof(int) * GENOSIZE,GENOCL,"Geno");
            /*The Zs are not correct after UpdateGeno, until UpdateZ is run */
        }

        if (LINKAGE && rep > ADMBURNIN) {
            if (!INDIVIDUALR) {
                recomblikelihood = UpdateZandSingleR(Z,  Q, P, Geno,
                                                     R, Mapdistance, rep, Phase, Z1,Phasemodel, rep+1 > BURNIN? sumIndLikes : NULL,
                                                     indLikesNorm);
            } else {
                recomblikelihood = UpdateZandR(Z,  Q, P, Geno, R,
                                               Mapdistance, rep, Phase, Z1,Phasemodel, rep+1 > BURNIN ? sumIndLikes:NULL,
                                               indLikesNorm);
            }
        } else {
            /*FillArrayWithRandomCL(clDict,randomArr,NUMINDS*NUMLOCI*LINES);*/
            /* if (DEBUGCOMPARE) { */
            /*     readBuffer(clDict,randomArr, */
            /*             sizeof(float) * NUMINDS*NUMLOCI*LINES,RANDCL, */
            /*             "randomArr"); */
            /*     compareZCLandZ(clDict,Z,Q,P,Geno,randomArr); */
            /* } */
            /* if (USEWORKINGCL) { */
                UpdateZCL (clDict,Z,  Q, P, Geno,randomArr);
                /* Not needed */
                /*readBuffer(clDict,Z,sizeof(int)*ZSIZE,ZCL,"Z");*/
            /* } else { */
            /*     readBuffer(clDict,randomArr, */
            /*             sizeof(float) * NUMINDS*NUMLOCI*LINES,RANDCL, */
            /*             "randomArr"); */
            /*     UpdateZ (Z,  Q, P, Geno,randomArr); */
            /* } */
            /*      printf("done updatez alpha[2]=%e\n", Alpha[2]); */
        }


        if (LOCPRIOR && NOADMIX==0) {
            UpdateAlphaLocPrior(Q, Alpha, LocPrior, Individual);
        } else if (INFERALPHA) {

            UpdateAlphaCL (clDict,Q, Alpha, Individual, rep,POPFLAGINDS);

            /* readBuffer(clDict,Q, sizeof(float) * QSIZE,QCL, "Q"); */
            /* readBuffer(clDict,Alpha, sizeof(float) * MAXPOPS,ALPHACL, "alpha"); */

            /* UpdateAlpha(Q, Alpha, Individual, rep); */

            /* writeBuffer(clDict,Alpha, sizeof(float) * MAXPOPS,ALPHACL, "alpha"); */
        }

        if (INFERLAMBDA) {
            readBuffer(clDict,P,sizeof(float) * PSIZE,PCL,"P");
            if  (POPSPECIFICLAMBDA) {
                UpdatePopLambda(P,lambda,NumAlleles);
            } else {
                UpdateLambda (P,Epsilon,lambda, NumAlleles);
            }
            writeBuffer(clDict,lambda,sizeof(float) * MAXPOPS,LAMBDACL,"LAMBDA");
        }

        if (FREQSCORR) {
            UpdateEpsilonCL(clDict,P,Epsilon,Fst,NumAlleles,lambda[0]);

            UpdateFstCL (clDict,Epsilon, Fst, P, NumAlleles);

            /* readBuffer(clDict,P, sizeof(float) * PSIZE,PCL, "P"); */
            /* readBuffer(clDict,Fst,sizeof(float) * MAXPOPS,FSTCL,"FST"); */
            /* readBuffer(clDict,Epsilon,sizeof(float) * NUMLOCI*MAXALLELES,EPSILONCL,"eps"); */

            /* UpdateEpsilon(P,Epsilon,Fst,NumAlleles,lambda[0]); */

            /* UpdateFst (Epsilon, Fst, P, NumAlleles); */

            /* writeBuffer(clDict,Epsilon,sizeof(float) * NUMLOCI*MAXALLELES,EPSILONCL,"eps"); */
            /* writeBuffer(clDict,Fst,sizeof(float) * MAXPOPS,FSTCL,"FST"); */
        }

        /*====book-keeping stuff======================*/
        if (rep + 1 > BURNIN) {
            /*buffers[0] = PCL;
            names[0] = "P"; dests[0] = P; sizes[0] = sizeof(float) * PSIZE;
            buffers[1] = QCL;
            names[1] = "Q"; dests[1] = Q; sizes[1] = sizeof(float) * QSIZE;

            readBuffers(clDict,dests,sizes,buffers,names,2);*/
            /*readBuffer(clDict,Alpha, sizeof(float) * MAXPOPS,ALPHACL, "alpha");
            if(rep % 100 == 0){
            printf("%f",Alpha[0]);
            }*/
            DataCollectionCL (clDict,Geno, PreGeno, Q, QSum, Z, Z1,  P, PSum,
                            Fst, FstSum, NumAlleles,
                            AncestDist, Alpha, sumAlpha, sumR, varR, like,
                            sumlikes, sumsqlikes, R, Epsilon,SumEpsilon,recomblikelihood,
                            lambda, sumlambda, Recessive, LocPrior, sumLocPrior, LocPriorLen, sumIndLikes,
                            indLikesNorm, rep);
        }


        if ((savefreq) && ((rep + 1) > BURNIN)
                && (((rep + 1 - BURNIN) % savefreq) == 0)
                && ((rep + 1) != NUMREPS + BURNIN)) {
            /* readBuffer(clDict,Alpha, sizeof(float) * MAXPOPS,ALPHACL, "alpha"); */
            readBuffer(clDict,Fst, sizeof(float) * MAXPOPS,FSTCL, "fst");
            readBuffer(clDict,sumAlpha, sizeof(float) * MAXPOPS,ALPHASUMCL, "alphasum");
            readBuffer(clDict,sumlambda, sizeof(float) * MAXPOPS,LAMBDASUMCL, "lambdasum");
            readBuffer(clDict,FstSum, sizeof(float) * MAXPOPS,FSTSUMCL, "fstsum");
            readBuffer(clDict,QSum, sizeof(float) * QSIZE,QSUMCL, "Qsum");
            readBuffer(clDict,PSum, sizeof(float) * PSIZE,PSUMCL, "Psum");
            readBuffer(clDict,SumEpsilon, sizeof(float) * NUMLOCI*MAXALLELES,EPSILONSUMCL, "epssum");
            readBuffer(clDict,like, sizeof(float),LIKECL, "like");
            readBuffer(clDict,sumlikes, sizeof(float),SUMLIKESCL, "sumlike");
            readBuffer(clDict,sumsqlikes, sizeof(float),SUMSQLIKESCL, "sumsqlikes");
            OutPutResults (Geno, rep + 1, savefreq, Individual, PSum, QSum,
                           FstSum, AncestDist, UsePopProbs, *sumlikes,
                           *sumsqlikes, sumAlpha, sumR, varR,
                           NumAlleles, Translation, 0, Markername, R,
                           SumEpsilon,
                           lambda,sumlambda,sumLocPrior, LocPriorLen,
                           sumIndLikes, indLikesNorm, argc,argv);
        }


        if (PRINTLIKES) {
            readBuffer(clDict,like, sizeof(float),LIKECL, "like");
            PrintLike (*like, rep, Geno, PreGeno, Q, P,recomblikelihood);
        }

        if (((rep + 1) % UPDATEFREQ) == 0) {
            readBuffer(clDict,Alpha, sizeof(float) * MAXPOPS,ALPHACL, "alpha");
            readBuffer(clDict,Fst, sizeof(float) * MAXPOPS,FSTCL, "fst");
            readBuffer(clDict,like, sizeof(float),LIKECL, "like");
            readBuffer(clDict,sumlikes, sizeof(float),SUMLIKESCL, "sumlike");
            readBuffer(clDict,sumsqlikes, sizeof(float),SUMSQLIKESCL, "sumsqlikes");
            /*readBuffer(clDict,sumAlpha, sizeof(float) * MAXPOPS,ALPHASUMCL, "alphasum");
            readBuffer(clDict,sumlambda, sizeof(float) * MAXPOPS,LAMBDASUMCL, "lambdasum");
            readBuffer(clDict,FstSum, sizeof(float) * MAXPOPS,FSTSUMCL, "fstsum");
            readBuffer(clDict,QSum, sizeof(float) * QSIZE,QSUMCL, "Qsum");
            readBuffer(clDict,PSum, sizeof(float) * PSIZE,PSUMCL, "Psum");
            readBuffer(clDict,SumEpsilon, sizeof(float) * NUMLOCI*MAXALLELES,EPSILONSUMCL, "epssum");*/
            PrintUpdate (rep + 1, Geno, PreGeno, Alpha, Fst, P, Q, *like,
                         *sumlikes, *sumsqlikes, NumAlleles, R, lambda,Individual,
                         recomblikelihood, Recessive, LocPrior, LocPriorLen);
        }
        finishWaitList(clDict);
    }

    /*====final book-keeping====================================*/
    if ((rep % UPDATEFREQ) != 0) {
        readBuffer(clDict,Alpha, sizeof(float) * MAXPOPS,ALPHACL, "alpha");
        readBuffer(clDict,Fst, sizeof(float) * MAXPOPS,FSTCL, "fst");
        readBuffer(clDict,like, sizeof(float),LIKECL, "like");
        readBuffer(clDict,sumsqlikes, sizeof(float),SUMSQLIKESCL, "sumsqlikes");
            readBuffer(clDict,sumlikes, sizeof(float),SUMLIKESCL, "sumlikes");
        /*readBuffer(clDict,sumAlpha, sizeof(float) * MAXPOPS,ALPHASUMCL, "alphasum");
        readBuffer(clDict,sumlambda, sizeof(float) * MAXPOPS,LAMBDASUMCL, "lambdasum");
        readBuffer(clDict,FstSum, sizeof(float) * MAXPOPS,FSTSUMCL, "fstsum");
        readBuffer(clDict,QSum, sizeof(float) * QSIZE,QSUMCL, "Qsum");
        readBuffer(clDict,PSum, sizeof(float) * PSIZE,PSUMCL, "Psum");
        readBuffer(clDict,SumEpsilon, sizeof(float) * NUMLOCI*MAXALLELES,EPSILONSUMCL, "epssum");*/
        PrintUpdate (rep, Geno, PreGeno, Alpha, Fst, P, Q, *like, *sumlikes,
                     *sumsqlikes, NumAlleles,R, lambda, Individual,recomblikelihood,
                     Recessive, LocPrior, LocPriorLen);
    }


    readBuffer(clDict,Alpha, sizeof(float) * MAXPOPS,ALPHACL, "alpha");
    readBuffer(clDict,Fst, sizeof(float) * MAXPOPS,FSTCL, "fst");
    readBuffer(clDict,sumAlpha, sizeof(float) * MAXPOPS,ALPHASUMCL, "alphasum");
    readBuffer(clDict,sumlambda, sizeof(float) * MAXPOPS,LAMBDASUMCL, "lambdasum");
    readBuffer(clDict,FstSum, sizeof(float) * MAXPOPS,FSTSUMCL, "fstsum");
    readBuffer(clDict,QSum, sizeof(float) * QSIZE,QSUMCL, "Qsum");
    readBuffer(clDict,PSum, sizeof(float) * PSIZE,PSUMCL, "Psum");
    readBuffer(clDict,SumEpsilon, sizeof(float) * NUMLOCI*MAXALLELES,EPSILONSUMCL, "epssum");
    readBuffer(clDict,like, sizeof(float),LIKECL, "like");
    readBuffer(clDict,sumsqlikes, sizeof(float),SUMSQLIKESCL, "sumsqlikes");
    readBuffer(clDict,sumlikes, sizeof(float),SUMLIKESCL, "sumlikes");
    OutPutResults (Geno, rep, savefreq, Individual, PSum, QSum,
                   FstSum, AncestDist, UsePopProbs,
                   *sumlikes, *sumsqlikes,
                   sumAlpha, sumR, varR, NumAlleles, Translation, 1,
                   Markername, R, SumEpsilon,
                   lambda,sumlambda,sumLocPrior, LocPriorLen,
                   sumIndLikes, indLikesNorm,
                   argc,argv);

    /*=====Closing everything down==============================*/
    FreeAll(Mapdistance, Phase, Phasemodel, lambda, sumlambda, Markername, Geno,
            PreGeno, Recessive,
            Individual, Translation, NumAlleles, Z, Z1, Q, P, R, sumR, varR, Epsilon,
            SumEpsilon,
            Fst, FstSum, NumLociPop, PSum, QSum,  AncestDist, UsePopProbs, LocPrior,
            sumLocPrior, Alpha, sumAlpha, sumIndLikes, indLikesNorm, clDict);
    free(randomArr);
    free(randGens);
    free(like);
    free(sumsqlikes);
    free(sumlikes);
    free(reduceresult);
    printf("Structure seed: %d\n", SEED);
    return (0);
}
Ejemplo n.º 12
0
Parameters *GetParameters(int argc, char *argv[])
{
   Parameters *parameters;
   int i;
   double doubleArg;
   ULONG ulongArg;
   BOOLEAN limitSet = FALSE;
   FILE *outputFile;
   ULONG argumentExists;

   parameters = (Parameters *) malloc(sizeof(Parameters));
   if (parameters == NULL)
      OutOfMemoryError("parameters");

   // initialize default parameter settings
   parameters->directed = TRUE;
   parameters->limit = 0;
   parameters->numBestSubs = 3;
   parameters->beamWidth = 4;
   parameters->valueBased = FALSE;
   parameters->prune = FALSE;
   strcpy(parameters->outFileName, "none");
   parameters->outputToFile = FALSE;
   parameters->outputLevel = 2;
   parameters->allowInstanceOverlap = FALSE;
   parameters->threshold = 0.0;
   parameters->evalMethod = EVAL_MDL;
   parameters->iterations = 1;
   strcpy(parameters->psInputFileName, "none");
   parameters->predefinedSubs = FALSE;
   parameters->minVertices = 1;
   parameters->maxVertices = 0; // i.e., infinity
   parameters->compress = FALSE;

   parameters->mdl = FALSE;
   parameters->mdlThreshold = 0.0;
   parameters->mpsThreshold = 0.0;
   parameters->prob = FALSE;
   parameters->mps = FALSE;
   parameters->maxAnomalousScore = MAX_DOUBLE;
   parameters->minAnomalousScore = 0.0;
   parameters->noAnomalyDetection = TRUE;
   parameters->norm = 1;
   parameters->similarity = 1.0;

   if (argc < 2)
   {
      fprintf(stderr, "input graph file name must be supplied\n");
      exit(1);
   }

   // process command-line options
   i = 1;
   while (i < (argc - 1))
   {
      if (strcmp(argv[i], "-beam") == 0) 
      {
         i++;
         sscanf(argv[i], "%lu", &ulongArg);
         if (ulongArg == 0) 
         {
            fprintf(stderr, "%s: beam must be greater than zero\n", argv[0]);
            exit(1);
         }
         parameters->beamWidth = ulongArg;
      }
      else if (strcmp(argv[i], "-compress") == 0)
      {
         parameters->compress = TRUE;
      }
      else if (strcmp(argv[i], "-eval") == 0) 
      {
         i++;
         sscanf(argv[i], "%lu", &ulongArg);
         if ((ulongArg < 1) || (ulongArg > 3)) 
         {
            fprintf(stderr, "%s: eval must be 1-3\n", argv[0]);
            exit(1);
         }
         parameters->evalMethod = ulongArg;
      } 
      else if (strcmp(argv[i], "-iterations") == 0) 
      {
         i++;
         sscanf(argv[i], "%lu", &ulongArg);
         parameters->iterations = ulongArg;
      } 
      else if (strcmp(argv[i], "-limit") == 0) 
      {
         i++;
         sscanf(argv[i], "%lu", &ulongArg);
         if (ulongArg == 0) 
         {
            fprintf(stderr, "%s: limit must be greater than zero\n", argv[0]);
            exit(1);
         }
         parameters->limit = ulongArg;
         limitSet = TRUE;
      }
      else if (strcmp(argv[i], "-maxsize") == 0) 
      {
         i++;
         sscanf(argv[i], "%lu", &ulongArg);
         if (ulongArg == 0) 
         {
            fprintf(stderr, "%s: maxsize must be greater than zero\n", argv[0]);
            exit(1);
         }
         parameters->maxVertices = ulongArg;
      }
      else if (strcmp(argv[i], "-minsize") == 0) 
      {
         i++;
         sscanf(argv[i], "%lu", &ulongArg);
         if (ulongArg == 0) 
         {
            fprintf(stderr, "%s: minsize must be greater than zero\n", argv[0]);
            exit(1);
         }
         parameters->minVertices = ulongArg;
      }
      else if (strcmp(argv[i], "-nsubs") == 0) 
      {
         i++;
         sscanf(argv[i], "%lu", &ulongArg);
         if (ulongArg == 0) 
         {
            fprintf(stderr, "%s: nsubs must be greater than zero\n", argv[0]);
            exit(1);
         }
         parameters->numBestSubs = ulongArg;
      }
      else if (strcmp(argv[i], "-out") == 0) 
      {
         i++;
         strcpy(parameters->outFileName, argv[i]);
         parameters->outputToFile = TRUE;
      }
      else if (strcmp(argv[i], "-output") == 0) 
      {
         i++;
         sscanf(argv[i], "%lu", &ulongArg);
         if ((ulongArg < 1) || (ulongArg > 5)) 
         {
            fprintf(stderr, "%s: output must be 1-5\n", argv[0]);
            exit(1);
         }
         parameters->outputLevel = ulongArg;
      }
      else if (strcmp(argv[i], "-overlap") == 0) 
      {
         parameters->allowInstanceOverlap = TRUE;
      }
      else if (strcmp(argv[i], "-prune") == 0) 
      {
         parameters->prune = TRUE;
      }
      else if (strcmp(argv[i], "-ps") == 0) 
      {
         i++;
         strcpy(parameters->psInputFileName, argv[i]);
         parameters->predefinedSubs = TRUE;
      }
      else if (strcmp(argv[i], "-threshold") == 0) 
      {
         i++;
         sscanf(argv[i], "%lf", &doubleArg);
         if ((doubleArg < (double) 0.0) || (doubleArg > (double) 1.0))
         {
            fprintf(stderr, "%s: threshold must be 0.0-1.0\n", argv[0]);
            exit(1);
         }
         parameters->threshold = doubleArg;
      }
      else if (strcmp(argv[i], "-undirected") == 0) 
      {
         parameters->directed = FALSE;
      }
      else if (strcmp(argv[i], "-valuebased") == 0) 
      {
         parameters->valueBased = TRUE;
      }
      else if (strcmp(argv[i], "-mdl") == 0) 
      {
         i++;
         argumentExists = sscanf(argv[i], "%lf", &doubleArg);
         if ((argumentExists != 1) || (doubleArg <= (double) 0.0) || 
             (doubleArg >= (double) 1.0))
         {
            fprintf(stderr, "%s: Information Theoretic (MDL) threshold must be greater than 0.0 and less than 1.0\n", argv[0]);
            exit(1);
         }
         parameters->mdl = TRUE;
         parameters->mdlThreshold = doubleArg;
      }
      else if (strcmp(argv[i], "-prob") == 0) 
      {
         i++;
         sscanf(argv[i], "%lu", &ulongArg);
         if (ulongArg < 2)
         {
            fprintf(stderr, "%s: you must include a value greater than 1 as a parameter to the probabilistic anomaly detection method.\n", argv[0]);
            exit(1);
         }
         parameters->prob = TRUE;
         parameters->iterations = ulongArg;  // overrides -iterations specification
         parameters->maxAnomalousScore = 1.0;  // overrides default of MAX_DOUBLE
      }
      else if (strcmp(argv[i], "-mps") == 0) 
      {
         i++;
         argumentExists = sscanf(argv[i], "%lf", &doubleArg);
         if ((argumentExists != 1) || (doubleArg <= (double) 0.0) || 
             (doubleArg >= (double) 1.0))
         {
            fprintf(stderr, "%s: Maximum Partial Substructure (MPS) threshold must be greater than 0.0 and less than 1.0\n", argv[0]);
            exit(1);
         }
         parameters->mps = TRUE;
         parameters->mpsThreshold = doubleArg;
      }
      else if (strcmp(argv[i], "-maxAnomalousScore") == 0) 
      {
         i++;
         argumentExists = sscanf(argv[i], "%lf", &doubleArg);
         if ((argumentExists != 1) || (doubleArg <= (double) 0.0) || 
             (doubleArg >= (double) MAX_DOUBLE))
         {
            fprintf(stderr, "%s: maximum anomalous score must be greater than 0.0 and less than %lf\n", 
	            argv[0],MAX_DOUBLE);
            exit(1);
         }
	 //
	 // NOTE:  This check assumes that the user has specified a max
	 // anomalous score AFTER specifying they want to run the GBAD-P 
	 // algorithm.
	 //
         if (((doubleArg <= (double) 0.0) || (doubleArg >= 1.0)) &&
	     (parameters->prob))
         {
            fprintf(stderr, "%s: maximum anomalous score must be greater than 0.0 and less than 1.0\n",argv[0]);
            exit(1);
         }
         parameters->maxAnomalousScore = doubleArg;
      }
      else if (strcmp(argv[i], "-minAnomalousScore") == 0) 
      {
         i++;
         argumentExists = sscanf(argv[i], "%lf", &doubleArg);
         if ((argumentExists != 1) || (doubleArg < (double) 0.0) || 
             (doubleArg >= (double) MAX_DOUBLE))
         {
            fprintf(stderr, "%s: minimum anomalous score must be greater than or equal to 0.0 and less than %lf\n", argv[0],MAX_DOUBLE);
            exit(1);
         }
         parameters->minAnomalousScore = doubleArg;
      }
      else if (strcmp(argv[i], "-norm") == 0) 
      {
         i++;
         sscanf(argv[i], "%lu", &ulongArg);
         if (ulongArg < 1)
         {
            fprintf(stderr, "%s: you must specify a value of 1 or greater.\n", argv[0]);
            exit(1);
         }
         parameters->norm = ulongArg;
      }
      else if (strcmp(argv[i], "-sim") == 0) 
      {
         i++;
         sscanf(argv[i], "%lf", &doubleArg);
         if ((doubleArg < (double) 0.0) || (doubleArg > (double) 1.0))
        {
            fprintf(stderr, "%s: similarity measurement must be between 0.0 and 1.0.\n", argv[0]);
            exit(1);
         }
         parameters->similarity = doubleArg;
      }
      else 
      {
         fprintf(stderr, "%s: unknown option %s\n", argv[0], argv[i]);
         exit(1);
      }
      i++;
   }

   if ((parameters->mdl) || (parameters->prob) || (parameters->mps)) 
      parameters->noAnomalyDetection = FALSE;

   if (parameters->iterations == 0)
      parameters->iterations = MAX_UNSIGNED_LONG; // infinity

   // initialize log2Factorial[0..1]
   parameters->log2Factorial = (double *) malloc(2 * sizeof(double));
   if (parameters->log2Factorial == NULL)
      OutOfMemoryError("GetParameters:parameters->log2Factorial");
   parameters->log2FactorialSize = 2;
   parameters->log2Factorial[0] = 0; // lg(0!)
   parameters->log2Factorial[1] = 0; // lg(1!)

   // read graphs from input file
   strcpy(parameters->inputFileName, argv[argc - 1]);
   parameters->labelList = AllocateLabelList();
   parameters->posGraph = NULL;
   parameters->numPosEgs = 0;
   parameters->posEgsVertexIndices = NULL;

   ReadInputFile(parameters);
   if (parameters->evalMethod == EVAL_MDL)
   {
      parameters->posGraphDL = MDL(parameters->posGraph,
                                  parameters->labelList->numLabels, parameters);
   }

   // read predefined substructures
   parameters->numPreSubs = 0;
   if (parameters->predefinedSubs)
      ReadPredefinedSubsFile(parameters);

   parameters->incrementList = malloc(sizeof(IncrementList));
   parameters->incrementList->head = NULL;

   // create output file, if given
   if (parameters->outputToFile) 
   {
      outputFile = fopen(parameters->outFileName, "w");
      if (outputFile == NULL) 
      {
         printf("ERROR: unable to write to output file %s\n",
                parameters->outFileName);
         exit(1);
      }
      fclose(outputFile);
   }  

   if (parameters->numPosEgs == 0)
   {
      fprintf(stderr, "ERROR: no positive graphs defined\n");
      exit(1);
   }

   // Check bounds on discovered substructures' number of vertices
   if (parameters->maxVertices == 0)
      parameters->maxVertices = parameters->posGraph->numVertices;
   if (parameters->maxVertices < parameters->minVertices)
   {
      fprintf(stderr, "ERROR: minsize exceeds maxsize\n");
      exit(1);
   }

   // Set limit accordingly
   if (parameters->limit == 0)
   {
      parameters->limit = parameters->posGraph->numEdges / 2;
   }

   return parameters;
}
Ejemplo n.º 13
0
int main( int argc, char *argv[])
{
char *p;
char *Switch, *Value;
char InputFileName[200];
int i;
XTL_FileStatus XTLFileStat;

/* initialize trace to off */
TraceInit(  );
SetTraceOutput( stdout );  /* defaults to stderr if not set, we want stdout */
TraceOn( FALSE );

DL_CL_ProcessArgs( argc, argv );
p = DL_CL_GetProgName( );

printf( "%s", p );
for( i = 0; Copyright[i] != NULL; ++i )
	puts( Copyright[i] );
	
if ( getcwd(CurrentDirectory, sizeof(CurrentDirectory) - 1) == NULL )
{
	CurrentDirectory[0] = 0;
	puts( "Failed to get current working directory" );
}


if (  DL_CL_GetArgCount() != 1 )
{
	for( i = 0; Instructions[i] != NULL; ++i )
		puts( Instructions[i] );
	
	ErrorExit( "\n" );
}
	
strcpy( InputFileName, DL_CL_GetArg( 0 ) );


for ( i = 0; DL_CL_GetSwitch( i, &Switch, &Value ); i++ )
{
	ProcessCommandLineSwitch( Switch, Value );
}

	/* Process and envirnmant variables */	
	ProcessEnvVars();


/* initialize the XronosIO library */
XronosIOInit();
XTL_SubVars_Init();

	/* init stuff from Conf file */
	puts( "Processing Conf file" );
	printf( "Conf File: %s\n", ConfFileName );
	if ( DL_ReadIniFile(ConfFileName) != 0 )
		ErrorExit( "Failed to read conf file" );

	p = DL_GetIniValue( "XF_MaxQuestions", NULL );
	if ( p != NULL )
	{
		SetMaxQuestions( atoi(p) );
	}
	
	QuestionsOnly = DL_GetIniBOOLValue( "XF_QuestionsOnly", QuestionsOnly );
	
	TagsRequired = DL_GetIniBOOLValue( "XF_TagsRequired", TagsRequired );
	
	SB_Texttt_removal = DL_GetIniBOOLValue( "SageBug_Texttt_removal", SB_Texttt_removal );

	InitUserDefinedSubstitution( );
	
	p = DL_GetIniStringValue( "XF_OutputFileHeader", NULL );
	if ( p != NULL )
	{
	strcpy( FileForOutputHeader, p );
	}
	
	p = DL_GetIniStringValue( "XF_OutputFileFooter", NULL );
	if ( p != NULL )
	{
	strcpy( FileForOutputFooter, p );
	}
	
	p = DL_GetIniStringValue( "XF_InputFileHeader", NULL );
	if ( p != NULL )
	{
	if ( XronosIO_SetHeaderFile( p ) != 0 )
		ErrorExit( "failed to set XF_InputFileHeader value" );
	printf( "Set Input HeaderFile: %s\n", p );
	}
	
	p = DL_GetIniStringValue( "XF_InputFileFooter", NULL );
	if ( p != NULL )
	{
	if ( XronosIO_SetFooterFile( p ) != 0 )
		ErrorExit( "failed to set XF_InputFileFooter value" );
	printf( "Set Input FooterFile: %s\n", p );
	}
	
	DL_DiscardIniFile();
	puts( "Done Processing Conf file" );
	/* end ini stuff */

strcpy( OutputFileName, InputFileName );

/* Load file into memory */
printf( "*** Reading input file: %s\n", InputFileName );
ReadInputFile( InputFileName );

/* kill dups */
puts( "*** Killing Dups" );
KillDups( );

/* deal with braces */
RecycleBuffers( );  /* recycle the previous pass output to the new pass input */
puts( "*** Braces processing" );
Braces( );

/* deal with question limit on file size */
RecycleBuffers( );  /* recycle the previous pass output to the new pass input */
puts( "*** Question Limit processing" );
QuestionLimit( );

if ( SB_Texttt_removal )
{
	/* deal with \text{\texttt{}} sage bug */
	RecycleBuffers( );  /* recycle the previous pass output to the new pass input */
	puts( "*** Texttt Removal processing" );
	TextttRemoval( );
}

/* deal with substitution processing - should be JUST before WriteOutputFile() */
RecycleBuffers( );  /* recycle the previous pass output to the new pass input */
puts( "*** Internal variable substitution processing" );
HandleSubstitution( );

/* write output file */
RecycleBuffers( );  /* recycle the previous pass output to the new pass input */
printf( "*** Writing Output file; %s\n", OutputFileName );
WriteOutputFile( OutputFileName );

puts( "*** Program Complete\n" );
return 0;
}
Ejemplo n.º 14
0
void CallWhileLoop(void){
	while(1){
		switch(LoopCase){		
			case 1:
                  ReadInputFile();
                 if(TestNo == 1){
                         LoopCase = 2;    
                        printf("Demon Code has received the Hight = ");
                        fp = fopen (IN_ENTERY_FILE, "r");
                        if(fp<0){
                            printf(" System is not able to open file \n");
                        }
                        else{
                            fread(&Din,sizeof(Din),1,fp);
                            fclose(fp);
                        }
                        sscanf(&Din.Hight,"%d",&Hight);
                        memset(Din.Hight,0,10);
                        printf("%d\n",Hight);
  			            printf("\n");     
  			            printf("BMI Test Starts Now \n");             
                    }
                    else if(TestNo == 2){
                        printf("Bp Test Starts Now \n");
                        LoopCase = 6;    
                    }
                    else if(TestNo == 3){
                        printf("BLI Test Starts now \n");      
                        printf("Demon Code has received the Hight = ");
                        fp = fopen (IN_ENTERY_FILE, "r");
                        if(fp<0){
                            printf(" System is not able to open file \n");
                        }
                        else{
                            fread(&Din,sizeof(Din),1,fp);
                            fclose(fp);
                        }
                        sscanf(&Din.Weight,"%d",&TempWeight);
                        sscanf(&Din.Hight,"%d",&Hight);
                        memset(Din.Weight,0,10);
                        memset(Din.Hight,0,10);
                        printf("The Hight Value %d\n",Hight);
                        printf("%d\n",Hight);
                       printf("The Weight Value %d\n",TempWeight);
                        printf("BLI Test Starts now \n");      
                       LoopCase = 9;  
  			            printf("\n");     
                  }
                  else{
                      LoopCase = 1;    
                  }
             break;
             //<<<<<<<<<<<<.................................................. Sensor No 1 Interface.......................................................................................>>>>>>>>>>>>>//
			case 2:
		       HoldingReg[1] = 0x00;   
               HoldingReg[0] = 0x01;
               MdbResponse = ModbusOP(0x01,FC_WRITE_SINGLE_COIL, 0x000A, 0x000l, (unsigned char *)HoldingReg,1);
               if(MdbResponse!=0){
                    #if defined	SHOW_DISPLAY
                        printf("Modbus Error Response %d \n",MdbResponse);
                     #endif
               }
               else{
               printf("Modbus Error Response %d \n",MdbResponse);
                    HoldingReg[1] = 0x00;   
                    HoldingReg[0] = 0x00;
     				LoopCase = LoopCase +1;
                }
			break;			
			case 3:
                MdbResponse = ModbusOP(0x01,FC_READ_COILS, 0x000F, 0x0000, (unsigned char *)HoldingReg, 1);
                if((RxBuf[0] == 0x01) && (RxBuf[1] == 0x01) && (RxBuf[2] == 0x01) && (RxBuf[3] == 0x01)){
    				LoopCase = LoopCase +1;
    				BmiTestEn = 1;
                }
             break;
             case 4:      
                 MdbResponse = ModbusOP(0x01,FC_READ_HOLD_REGS, 0x000A, 0x0002, (unsigned char *)HoldingReg, 1);
                 if(MdbResponse!=0){
                    #if defined	SHOW_DISPLAY
                        printf("Modbus Error Response %d \n",MdbResponse);
                     #endif
                 }
                else{  
                    Weight = ConvertHexToFloat();
                    printf("Modbus Got Sensor Response\n");
                    printf("Your Weight is = %f\n",Weight);   
                    BMIValue  = (Weight/Hight)*10000;
                    BMIValue = BMIValue / Hight;
                    printf("Your BMI Level is = %f\n",BMIValue);   
    				Buf[0] = '1';
                    memset(TempBuf,0,10);
                    sprintf(TempBuf,"%f",Weight);
                    strcpy(Bmi.Weight,TempBuf);
                    memset(TempBuf,0,10);
                    sprintf(TempBuf,"%f",BMIValue);
                    strcpy(Bmi.BmiValue,TempBuf);
                    memset(TempBuf,0,10);
                    
                    fp = fopen (OT_ENTERY_FILE, "w");
                    if(fp<0){
                        printf(" System is not able to open file \n");
                    }
                    else{
                        fwrite(&Bmi,sizeof(Bmi),1,fp);
                        fclose(fp);
                    }
                    fp = fopen (OT_TEXT_FILE, "w");
                    if(fp<0){
                        printf(" System is not able to open file \n");
                    }
                    else{
                        fwrite(&Buf,1,1,fp);
                        fclose(fp);
                    }
                    printf(" Demon has completed the  Wellth BMI Test\n");
                    BmiTestEn = 0;
             		LoopCase = 1;
                    printf("LoopCase Value is %d\n",LoopCase);
                    fp  = fopen(IN_ENTERY_FILE,"w");
                    fclose(fp);
                    fp = fopen(IN_TEXT_FILE,"w");
                    fclose(fp);                    
                }
             break;
             case 5:
             break;

             //<<<<<<<<<<<<.................................................. Sensor No 2 Interface.......................................................................................>>>>>>>>>>>>>//
             
			case 6:		
		       HoldingReg[1] = 0x00;   
               HoldingReg[0] = 0x01;
               MdbResponse = ModbusOP(0x01,FC_WRITE_SINGLE_COIL, 0x000B, 0x000l, (unsigned char *)HoldingReg,1);
               if(MdbResponse!=0){
                    #if defined	SHOW_DISPLAY
                        printf("Modbus Error Response %d \n",MdbResponse);
                     #endif
               }
               else{
                    HoldingReg[1] = 0x00;   
                    HoldingReg[0] = 0x00;
     				LoopCase = LoopCase +1;
                }
			break;			
			case 7:
                MdbResponse = ModbusOP(0x01,FC_READ_COILS, 0x000F, 0x0000, (unsigned char *)HoldingReg, 1);
                if((RxBuf[0] == 0x01) && (RxBuf[1] == 0x01) && (RxBuf[2] == 0x01) && (RxBuf[3] == 0x01)){
    				LoopCase = LoopCase +1;
                    BpTestEn = 1;
                }
             break;
             case 8:      
                 MdbResponse = ModbusOP(0x01,FC_READ_HOLD_REGS, 0x000B, 0x0002, (unsigned char *)HoldingReg, 1);
                 if(MdbResponse!=0){
                    #if defined	SHOW_DISPLAY
                        printf("Modbus Error Response %d \n",MdbResponse);
                     #endif
                 }
                else{  
                    printf("Modbus Got Sensor Response\n");
                    printf("Systolic Pressure is = %d\n",BmiBuf[0]);   
                    printf("Diastolic Pressure is = %d\n",BmiBuf[1]);   
                    printf("Pulse Rate is = %d\n",BmiBuf[2]);   
                    BpTestEn = 0;
                    Buf[0] = '1';
                    
                    sprintf(Bp.SysP,"%d",BmiBuf[0]);
                    sprintf(Bp.DiaP,"%d",BmiBuf[1]);
                    sprintf(Bp.PulseRate,"%d",BmiBuf[2]);
                   
                    fp = fopen (OT_ENTERY_FILE, "w");
                    if(fp<0){
                        printf(" System is not able to open file \n");
                    }
                    else{
                        fwrite(&Bp,sizeof(Bp),1,fp);
                        fclose(fp);
                    }
                    fp = fopen (OT_TEXT_FILE, "w");
                    if(fp<0){
                        printf(" System is not able to open file \n");
                    }
                    else{
                        fwrite(&Buf,1,1,fp);
                        fclose(fp);
                    }
                    printf(" Demon has completed the  Wellth BMI Test\n");
             		LoopCase = 1;
                    printf("LoopCase Value is %d\n",LoopCase);
                    fp  = fopen(IN_ENTERY_FILE,"w");
                    fclose(fp);
                    fp = fopen(IN_TEXT_FILE,"w");
                    fclose(fp);   
                }
             break;       
             
             //<<<<<<<<<<<<.................................................. Sensor No 3 Interface.......................................................................................>>>>>>>>>>>>>//
           case 9:
                LoopCase = LoopCase +1;
  			 break;  			 	  
			case 10:		
		       HoldingReg[1] = 0x00;   
               HoldingReg[0] = 0x01;
               MdbResponse = ModbusOP(0x01,FC_WRITE_SINGLE_COIL, 0x000C, 0x000l, (unsigned char *)HoldingReg,1);
               if(MdbResponse!=0){
                    #if defined	SHOW_DISPLAY
                        printf("Modbus Error Response %d \n",MdbResponse);
                     #endif
               }
               else{
                    HoldingReg[1] = 0x00;   
                    HoldingReg[0] = 0x00;
     				LoopCase = LoopCase +1;
                }
			break;			
			case 11:
                MdbResponse = ModbusOP(0x01,FC_READ_COILS, 0x000F, 0x0000, (unsigned char *)HoldingReg, 1);
                if((RxBuf[0] == 0x01) && (RxBuf[1] == 0x01) && (RxBuf[2] == 0x01) && (RxBuf[3] == 0x01)){
    				LoopCase = LoopCase +1;
                    BpTestEn = 1;
                }
             break;
             case 12:      
                 MdbResponse = ModbusOP(0x01,FC_READ_HOLD_REGS, 0x000C, 0x0002, (unsigned char *)HoldingReg, 1);
                 if(MdbResponse!=0){
                    #if defined	SHOW_DISPLAY
                        printf("Modbus Error Response %d \n",MdbResponse);
                     #endif
                 }
                else{  
                    BliTestEn =  1;
                    BLIValue = ConvertHexToFloat();
                    printf("Modbus Got Sensor Response\n");
                    printf("Sensor Response is  = %f\n",BLIValue);   
                    BLIValue  = BLIValue*10000;
                    Mul = (Hight*Hight)/BLIValue;
                    Sub  = 12.297 + (0.287*Mul);
                    BLIValue  = 0.697 * TempWeight;
                    BLIValue = BLIValue  - Sub;
                    printf("Your BMI Level is = %f\n",BLIValue);   
    				LoopCase = 1;
                    BliTestEn =  0;
    				Buf[0] = '1';
                    memset(TempBuf,0,10);
                    sprintf(TempBuf,"%f",BLIValue);
                    strcpy(Bli.BliValue,TempBuf);
                    memset(TempBuf,0,10);
                    
                    fp = fopen (OT_ENTERY_FILE, "w");
                    if(fp<0){
                        printf(" System is not able to open file \n");
                    }
                    else{
                        fwrite(&Bli,sizeof(Bli),1,fp);
                        fclose(fp);
                    }
                    fp = fopen (OT_TEXT_FILE, "w");
                    if(fp<0){
                        printf(" System is not able to open file \n");
                    }
                    else{
                        fwrite(&Buf,1,1,fp);
                        fclose(fp);
                    }
                    printf(" Demon has completed the  Wellth BMI Test\n");
                    BliTestEn = 0;
             		LoopCase = 1;
                    printf("LoopCase Value is %d\n",LoopCase);
                    fp  = fopen(IN_ENTERY_FILE,"w");
                    fclose(fp);
                    fp = fopen(IN_TEXT_FILE,"w");
                    fclose(fp);            
                }
             break;        
             default:
			 break;
		}
	}
}
Ejemplo n.º 15
0
int main(int argc, char *argv[])
{
  Planning         *pt_plan=NULL;
  int              user, i;
  char             FileRead[MAX_LINE][MAX_CHAR_LINE];
  char             product;
  char             exec_dir[MAX_PATH_LEN]="";
  
  _interactive_call=1;
  
  if ((pt_plan = malloc (sizeof(Planning)))==NULL)
    {
      printf("Memory Allocation error\n"); exit(1);
    }

  get_exec_directory(exec_dir,argv[0]);
  premia_self_set_global_vars(exec_dir);

  if( argc==2 ){
    ReadInputFile(argv[1],FileRead);
    InputMode(&user);
    WellcomeMsg(user);
    if ((InitErrorMsg()==OK)&&(InitVar()==OK))
      {
        ResetPlanning(pt_plan);
        product=FChooseProduct(FileRead);
        i = 0;
        while (premia_assets[i].name != NULL)
          {
            if (product == premia_assets[i].label)
              {
                premia_treat_input_file(pt_plan, premia_assets[i].models,
                                        premia_assets[i].families, 
                                        premia_assets[i].pricings,
                                        user, FileRead);
                break;
              }
            i++;
          }
        if (premia_assets[i].name == NULL) return FAIL;
      }
                        
  }else{
    InputMode(&user);
    WellcomeMsg(user);
    if ((InitErrorMsg()==OK)&&(InitVar()==OK)){
      do {
        ResetPlanning(pt_plan);
        product = ChooseProduct();
        i = 0;
        while (premia_assets[i].name != NULL)
          {
            if (product == premia_assets[i].label)
              {
                pt_plan->Action = ChooseAction (product);
                premia_interactive_menu(pt_plan, premia_assets[i].models,
                                        premia_assets[i].families, 
                                        premia_assets[i].pricings,user);
                break;
              }
            i++;
          }
      } while (NextSession(pt_plan,pt_plan->Action,user)==OK);
    }
  }
  
  (void)ExitVar();
  free(pt_plan);
  return OK;
}
Ejemplo n.º 16
0
/******************************************************************************
 * parse the file
 * call readfile which will parse the entire file
 *****************************************************************************/
int ParseFile()
{
	Initialize();
	if (ReadInputFile()) if (nbPointControl != 0) return 1;
	return 0;
}