bool OgreSerializer::setPos( fpos_t pos )
	{
		return (fsetpos( mpfFile, &pos) == 0);
	}
////////////////////////////////////////////////////////////////////////////////////////////////
//
//  Name	 : ReadBinHeader
//
//	Description:
//  Read header from binary raw data file (.BIN).  Bin files were created for use
//	with an early version of Media Tracker.  Defintion of header file
//	proposed in email from Pelowitz defines this format for the header structure:
//		struct TRGAcquireHeader	{	// 73 characters
//			char SizeOfHeader[4];
//			char unused1[5];
//			char Version[5];
//			char StationId[3];//node number
//			char Year[3];
//			char Month[3];
//			char Day[3];
//			char Year4[4];
//			char unused2[43];
//		};
//
//	Declaration:
//	int CBinaryDataFile::ReadBinHeader(char *szFilename, short *psSta,int *piYr, int *piMon, int *piDay, FILE **pHandle, double *pdVer, unsigned long *pulFirstRecordTime)
//
//	Input:	
//			strNameWithPath		filename with full path that is to be opened
//			
//	Output:	pstrErrorMsg	error, if any
//
//			mdVersionNumber		version number read from header
//			msStaNum			station number read from header
//			miYr				year read from header
//			miMon				month read from header
//			miDay				day read from header
//			mdTimestampOfFirstRecordInFile	time of first record in the file in DATE
//
//	Return:	true (header read) / false (some kind of error, see pstrErroMsg)
//	
//  date    /	author	revision
//  -----------------	--------
//	17-Oct-2002	SFK		Created from ReadBIDHeader in GrandDataFile.cpp in GRAND COM
////////////////////////////////////////////////////////////////////////////////////////////////
bool CBinaryDataFile::ReadBinHeader(const CString &strNameWithPath, CString *pstrErrorMsg)
{

    int iHdrSize;
    char str[54];
	fpos_t pos;
	struct TRGAcquireRecord BinaryRawPt;
	CMyDateTime MyDate;

	//	Open the file
	if (!OpenDataFile(strNameWithPath, pstrErrorMsg)) return(false);

	// generate an error message in case we get an error in any of the reads,
	// will clear at end of function if all okay
	if (pstrErrorMsg) {
		miErrorNum = iFILE_READ_ERR;
		pstrErrorMsg->Format("\nError: Unexpected error reading header for file %s", strNameWithPath);
	}
	
	//	Read the first 4 bytes to get the number of bytes in header.
    if (fread(str, 4, 1, mpFile) != 1) return(false);
    str[4] = '\0';    
    iHdrSize = atoi(str);
	if (iHdrSize <= 22) return(false);

    //	The next 5 bytes no longer contain useful information,	just
    //	skip by them.
    if (fread(str, 5, 1, mpFile) != 1) return(false);
       
    //	Read past the version number in the next 5 bytes.
    if (fread(str, 5, 1, mpFile) != 1) return(false);
	str[5] = '\0';
	mdVersionNumber = atof(str);

    //  Read station.
    if (fread(str, 3, 1, mpFile) != 1) return(false);
    str[3] = '\0';
    msStaNum = atoi(str);

    //	Read year.
    if (fread(str, 3, 1, mpFile) != 1) return(false);
    str[3] = '\0';
    miYr = atoi(str);

    //	Read month.
    if (fread(str, 3, 1, mpFile) != 1) return(false);
    str[3] = '\0';
    miMon = atoi(str);
	if ((miMon < 1) || (miMon >12)) return(false);

    //	Read day and put it in return variable.
    if (fread(str, 3, 1, mpFile) != 1) return(false);
    str[3] = '\0';
    miDay = atoi(str);
	if ((miDay < 1) || (miDay >31)) return(false);

    //	Read 4 digit year.
    if (fread(str, 4, 1, mpFile) != 1) return(false);
    str[4] = '\0';
    miYr4 = atoi(str);

    //	Read past the expansion space in the header so the file pointer
    //	is positioned at the beginning of the first data point at exit.
    if (fread(str, (iHdrSize - 26), 1, mpFile)!= 1) return(false);
    
    //	Save the position of the file pointer.
	//	Read the first record in the file to get the time of it.
    //	Restore file pointer to be positioned at the first record.
	if(fgetpos(mpFile, &pos ) != 0) return(false);
	if (fread(&BinaryRawPt, sizeof(struct TRGAcquireRecord), 1, mpFile) == 0) return(false);
	mdTimestampOfFirstRecordInFile = MyDate.MyTimestampToDATETimestamp((double)BinaryRawPt.uiJulianSeconds);
	if(fsetpos(mpFile, &pos ) != 0) return(false);
                    
    if (pstrErrorMsg) pstrErrorMsg->Empty();
	miErrorNum = 0;	// no error
    return(true);
}
///////////////////////////////////////////////////////////////////////////
//	Name:	ReadEvtDataFile
//
//	Description:
//	Read the data from a single data file and put it into an Access database.
//	This routine supports the *.EVT format. 
//
//	An .EVT file can have several types of records in the file.  The first two characters 
//	determine the type of record.  The types possible are:
//							RecTypeA	RecTypeB		Number of Characters
//		BINARYEVENT_REC		"3"			"2"				13
//		VACOSSINFO_REC		"3"			"5"				31
//		VACOSSEVENT_REC		"3"			"6"				44
//		VACOSSERROR_REC		"3"			"9"				16
//		MICROGRAND_REC		"4"			"0"				17
//		GPSDATA_REC			"3"			"A"				65
//
//	The formats of these records can be found at the beginning of this file.
//
//	In addition to reading the file, information about the data read such
//	as (first record, last record, number of records read, number of records
//	out of order, number of records taken during offsets, number of records
//	with timestamps not in the day, etc) are reported and also whether the day was overwritten
//	or added to in the database.
//
//	Declaration:
//	bool CBinaryDataFile::ReadBinDataFile(CDbAccess* pDb, const CString &strNameWithPath, CString *pstrMsg)
//
//	Input:	
//			strNameWithPath		filename with full path that is to be opened
//			
//	Output:	pstrErrorMsg	error, if any
//
//			mdVersionNumber		version number read from header
//			msStaNum			station number read from header
//			miYr				year read from header
//			miMon				month read from header
//			miDay				day read from header
//			mulTimestampOfFirstRecordInFile		julian time of first record in the file
//			miErrorNum			problem during read
//				iFILE_READ_ERROR
//				iSKIP_FILE
//				iDB_BAD
//	
//	Return:	true (header read) / false (some kind of error, see pstrErroMsg and miErrorNum)
//	
//  date    /	author	revision
//  -----------------	--------
//	10-Dec-2001	SFK		Created from ImportData in DbImport.cpp
//////////////////////////////////////////////////////////////////
bool CBinaryDataFile::ReadEvtDataFile(CDbAccess* pDb, const CString &strNameWithPath, CString *pstrMsg)
{

	char szDateStr[MAX_DT_LEN+1], szFirst[MAX_DT_LEN+1], szLast[MAX_DT_LEN+1], szDum[MAX_DT_LEN+1];
	bool bOverwrote = false;
	CString TempStr;

	CFacCfgWrap FacCfg;	// 28-Sep-2005 SFK Removed static

	CDirUtilities Dir(m_bQuietMode);  //QUIET MODE IS ALWAYS OFF FOR the non-NDAR Binary Component pjm 11/27/2007 for B2R1

	CMyDateTime MyDate;
	
	//	During read of header, got the station number associated with this file.
	//	Verify from the	Facility Configuration Com that this is a valid station
	//	number and is a BINARY type.
	struct db_sta_rec dbSta;
	bool bExists = FacCfg.GetStationRecord(pDb->msFacNum, msStaNum, &dbSta);

	if (!bExists) {
		if (pstrMsg) pstrMsg->Format("\nError: Skipping file %s with unknown station %d",Dir.StripPathFromFilename(strNameWithPath), msStaNum);
		if (mpFile) fclose(mpFile);
	    return(false);
	}
	if (dbSta.s_sta_type != BINARY_TYPE) {
		if (pstrMsg) pstrMsg->Format("\nError: Skipping file %s with unexpected station type %d",Dir.StripPathFromFilename(strNameWithPath), dbSta.s_sta_type);
		if (mpFile) fclose(mpFile);
	    return(false);
	}

	// By the time get here, know we have binary data and a valid station number
	CString strStationName = dbSta.sz_sta_name;
	CBinaryData BInst(pDb, msStaNum, -1, BINARY_INST, true, m_bQuietMode);
	
    //	Determine the limits of julian times that belong in the day referred to in the file header
    sprintf(szDateStr,"%02d.%02d.%02d", miYr, miMon, miDay); 
	DB_D_INTERVAL FileDay, ActualDay;
	FileDay.dStart = MyDate.DateTimeStrsToDATETimestamp(szDateStr, "00:00:00");
	FileDay.dEnd = FileDay.dStart + 86399.0/86400.0;
	DATE dFirstTimeInNextDay = FileDay.dStart + 1.0;
    
       
	//	Check if any data already exists for this day for this node in database
	unsigned long ulPtsInDay = 0;
	bool bStatus = BInst.DayExists(FileDay.dStart, &ulPtsInDay, &ActualDay);

	//	If data already in database for the day, check if the new data can be appended to
	//	the existing data.  If not, if bOverwrite = true then delete all data for the day;
	//	if bOverwrite = false, then ask a question as to whether they want to overwrite the
	//	day's data.
	bool bDayAlreadyExists = false;
	if (ulPtsInDay > 0) {		// ulPtsInDay nonzero says some data from day in database
		if (mdTimestampOfFirstRecordInFile > ActualDay.dEnd) {	// data beyond end of db, can add to end of day
			bDayAlreadyExists = true;
		}
		else {	// our data file overlaps with data already in db
			if (!mbOverwrite) { // don't automatically overwrite data
        		TempStr.Format("File %s contains data from %s which already exists in database.  Do you want to overwrite the day?",
					mstrFilenameWithPath, szDateStr);
				if (MessageBox(NULL, TempStr, "EventCom: Day Already In Database", MB_YESNO|MB_ICONQUESTION|MB_DEFBUTTON2) == IDNO) {
					if (pstrMsg) pstrMsg->Format("\nSkipping file %s (date=%02d.%02d.%02d): day's data already in database", 
						mstrFilenameWithPath, miYr, miMon, miDay);
					if (mpFile) CloseDataFile();
					miErrorNum = iSKIP_FILE;
					return(false);
				}
			}	
			// are going to overwrite the data so delete the entire day
			bStatus = BInst.DeleteDay(FileDay.dStart);
			if (!bStatus) { //if (glpDb->DeleteData(&BInst, DayRequested)) {
				miErrorNum = bStatus;
				if (mpFile) CloseDataFile();
				return(false);	
			}
   			bOverwrote = true;
			ulPtsInDay = 0;
		}
	}	
		
	int i = 0;
	unsigned long ulPtsInFile = 0;
	BinaryEventFileRec FilePt;
	OpCode Op;
	// To do yet:  add records for other types of data in event file
	DATE dCurrentPtTime = 0;
	DATE dLastPtTime;
	int iDuplicateTimestamps = 0;
	int iInvalidData = 0;
	int iOutOfOrder = 0;
	dLastPtTime = 0.0;
	short sLastStation = -1;
	CBinaryRawDataPt PtsForDb[NUM_RAW_DATA_PTS_IN_GROUP+16];	// allow for extra records written on last raw data point
	bool bFirstPoint = true;
	DATE dFirstValidTimeInFile;

	//	Read records from the raw data file one at a time.  First read the opcode and
	//	decide what kind of record you have.  Skip past any records other than the BinaryEvent type.
	//	For each data point in the BinaryEventRecs check whether it has the same timestamp as
	//	the previous point -- if yes, add a small increment to the timestamp read from the file.
	//	Also check if the point really belongs in the day and whether it is in chronological order.
	//	After you have accumulated a bunch of points, do a write to the database.
	while (fread(&Op, sizeof(struct OpCode), 1, mpFile) != 0) {	// read the op code
		// if record is BinaryEvent type, then read the record and process it.
		if ((Op.RecTypeA == '3') && (Op.RecTypeB == '2')) {
			fread(&FilePt, sizeof(struct BinaryEventFileRec), 1, mpFile);

			dCurrentPtTime = MyDate.MyTimestampToDATETimestamp(FilePt.uiTime);
			ulPtsInFile++;		// this just counts whether there was a point to read

			// catch two raw data points from the same node with the same timestamp
			if ((dCurrentPtTime == dLastPtTime) && (sLastStation == FilePt.usNode) ){			
				dCurrentPtTime = dLastPtTime + dINCREMENT;	// the base time of this point is past the last point's time
				iDuplicateTimestamps++;						// count the number of data points with duplicate timestamps
				FilePt.bStatus = FilePt.bStatus | DUPLICATE_POINT_BIT;
			}

			//	If the point's time is not in this day, note it and skip this point.
			if ((dCurrentPtTime < FileDay.dStart) || (dCurrentPtTime > FileDay.dEnd)) {
				iInvalidData++;
				continue;
			}
			
			//	If the point is out of order count it.  
			//	If the points are in order then set a new prev point
			//  Since there can be multiple node numbers logged into a single
			//	file, check that the node numbers are the same when
			//	checking if out of order.
			if (bFirstPoint) {
				dLastPtTime = dCurrentPtTime;
				sLastStation = FilePt.usNode;
			}
			if ((dCurrentPtTime < dLastPtTime)  && (sLastStation == FilePt.usNode)){
				iOutOfOrder++;
				if (mbSkipOutOfOrder == true) continue;
				FilePt.bStatus = FilePt.bStatus | OUT_OF_ORDER_BIT;
			}
			else {
				dLastPtTime = dCurrentPtTime;			// set for the next point read
				sLastStation = FilePt.usNode;
			}

			//	The largest point in the day is the last point and the smallest
			//	point in the day is the first point.
			if (dCurrentPtTime > ActualDay.dEnd) ActualDay.dEnd = dCurrentPtTime;
			if (bFirstPoint) {
				ActualDay.dStart = dCurrentPtTime;
				dFirstValidTimeInFile = dCurrentPtTime;
				bFirstPoint = false;
			}	
			else {
				if (dCurrentPtTime < ActualDay.dStart) {
					ActualDay.dStart = dCurrentPtTime;
					dFirstValidTimeInFile = dCurrentPtTime;
				}
			}

			// generate the stuff to write into the database
			// write one data record for each bit in the mask that is set
			BYTE bTempMask = 1;
			for (int j=0; j< 8; j++) {
				if ((bTempMask & FilePt.bMask) == bTempMask) {	// check if this bit is set
					PtsForDb[i].m_dJulianTime = dCurrentPtTime;
					PtsForDb[i].m_ucStatus = FilePt.bStatus;
					//if ((FilePt.bState & bTempMask) != 0) PtsForDb[i].m_ucState = 1;	// determine state of this bit
					//else PtsForDb[i].m_ucState = 0;
					PtsForDb[i].m_ucState = FilePt.bState;
					PtsForDb[i].m_usBit = j+1;			// bit number 1-8 corresponds to channel 1-8
					PtsForDb[i].m_ucReserved = FilePt.bReserved;
					PtsForDb[i].m_usLogNodeNumber = msStaNum;				// the "station" number in the file is really the log node number
//					PtsForDb[i].m_usStationNumber = FilePt.usNode + 1000;	// this is the real station of the data -- where the binary data came from
					PtsForDb[i].m_usStationNumber = FilePt.usNode;			// this is the real station of the data -- where the binary data came from
					i++;	// count the point just read from the file
				}
				bTempMask = bTempMask << 1;		// go on to next bit
			}
		   
			// when accumulate enough data points, write the group to the database
			if (i >= NUM_RAW_DATA_PTS_IN_GROUP) {
				BInst.m_ulNumPtsRequested = i;
				BInst.m_pBinaryRawPts = PtsForDb;
				BInst.AddData(pstrMsg);
				ulPtsInDay += i;	// count points read so far
				i = 0;
			}
		}
		else {	// was not a binary record -- skip past the record
			fpos_t FilePosition;
			fgetpos(mpFile, &FilePosition);
			FilePosition += Op.sRecSize - 2;	// subtract the opcode bytes that you've already read
			fsetpos(mpFile, &FilePosition);
		}
	}


	//	Got an error reading the data file.  Are expecting an EOF
	//	error.	If it's anything else, then abort and delete the partial
	//	data already in the db.  If it's EOF, close	the raw data file
	//	and continue.
	if (feof(mpFile) == 0) {		// check for any error other than end of file
		if (pstrMsg) pstrMsg->Format("\nImport Error Reading File %s.  File Error = %s", mstrFilenameWithPath, strerror(errno));
		if (mpFile) CloseDataFile();
		BInst.DeleteDay(FileDay.dStart);
		if (mpFile) CloseDataFile();
		return(false);
	}
	if (mpFile) CloseDataFile();

	//	Are at the end of the raw data file.  So write whatever points
	//	we have read in our group to the database
	if (i > 0) {
		BInst.m_ulNumPtsRequested = i;
		BInst.m_pBinaryRawPts = PtsForDb;
		BInst.AddData(pstrMsg);
		ulPtsInDay += i;	// accumulate points read so far
	}

	//	If there was no data for this day, make sure there is nothing about
	//	this day in the database.
	//	Print out some hints for the user as to why no data points are in the day.
	if (ulPtsInDay == 0) {
		BInst.DeleteDay(FileDay.dStart);		// delete data for entire day
		if (pstrMsg) {							// Can return hints to caller
			if (ulPtsInFile == 0) {				// the file is completely empty
				pstrMsg->Format("\nImport Warning Reading File %s.  No binary data in file.", Dir.StripPathFromFilename(strNameWithPath));
			}
			else {
				if (iInvalidData> 0) {			// all times were invalid
					MyDate.DATETimestampToDateTimeStrs(dCurrentPtTime, szFirst, szDum, GEN_DTF_IAEA, GEN_DTF_HMSM);
    				pstrMsg->Format("\nImport Error Reading File %s.  Header indicates data from %s, file data from %s\n", Dir.StripPathFromFilename(strNameWithPath), szDateStr, szFirst);
				}
   				if (iOutOfOrder > 0)			// all data was out of order
					TempStr.Format("\nImport Error Reading File %s.  %5d pts out of order.", Dir.StripPathFromFilename(strNameWithPath), iOutOfOrder);
				*pstrMsg += TempStr;
			}
		}    
		return(true);
	}

	//	Log which file was just imported successfully.  Include date, station
	//	name, file name and first/last time in the file.
	//	Also log if the day's data was overwritten and if there were
	//	any points out of order or data with invalid times.
	if (pstrMsg) { 
		MyDate.DATETimestampToDateTimeStrs(dFirstValidTimeInFile, szDum, szFirst, GEN_DTF_IAEA, GEN_DTF_HMSM);
		MyDate.DATETimestampToDateTimeStrs(ActualDay.dEnd, szDum, szLast, GEN_DTF_IAEA, GEN_DTF_HMSM);		
		TempStr.Format("\n%s  %25s  %s    %s    %s    %5ld", szDateStr, strStationName, Dir.StripPathFromFilename(strNameWithPath), szFirst, szLast, ulPtsInDay);
		*pstrMsg += TempStr;
		if (bOverwrote == TRUE) {
			TempStr.Format("  Overwrote existing day's data.");
			*pstrMsg += TempStr;
		}
		if (bDayAlreadyExists == TRUE) {
			TempStr.Format("  Added to existing day's data.");
			*pstrMsg += TempStr;
		}
		if (iOutOfOrder > 0) {
			TempStr.Format("  %5d pts out of order.", iOutOfOrder);
			*pstrMsg += TempStr;
		}
		if (iInvalidData > 0) {
			TempStr.Format("  %5d rec(s) with invalid times.",iInvalidData);
			*pstrMsg += TempStr;
		}
		if (iDuplicateTimestamps > 0) {
			TempStr.Format("  %5d rec(s) with duplicate times.",iDuplicateTimestamps);
			*pstrMsg += TempStr;
		}
	}    

	//  Calculate and add the information about this day's worth of data
	TempStr.Empty();
	BInst.AddDayData(ActualDay, ulPtsInDay, &TempStr);
	*pstrMsg += TempStr;
	
    return(true);
}
Exemple #4
0
/*this writes the actual data*/
static void writestructs(SDF *sdfp1, SDF *sdfp2, FILE *fp, fpos_t pos_npart)
{
    int i, j, nvecs1, nvecs2, nmembers1, nmembers2, nmembers;
    char **vecs1, **vecs2, **members1, **members2;
    SDF_type_t *types;
    SDF_type_t type2;
    size_t stride = 0, outstride = 0;
    void *btab;
    void **addrs;
    int *inoffsets, *strides, *starts, *lines;
    int flag=0, incr=1;
    int npart1, npart2, newnpart, countnpart, max;
    int ident, idindex, ident_last, ident_max, identnew;
    fpos_t pos1_npart;
    double x, y, z;
    float radius, R0, maxR0, disk_h;
    /*make INCR and nlines user input */

    nvecs1 = SDFnvecs(sdfp1);
    vecs1 = SDFvecnames(sdfp1);
    max = nvecs1;

    nvecs2 = SDFnvecs(sdfp2);
    vecs2 = SDFvecnames(sdfp2);

    /* Count structure members */
    /* don't use SDFnrecs, since that reads in the entire file which I'm trying to
       avoid. But I know that the structure (so far) always has "x" as the first
       member, so I can start counting from there -CE */
    for (i = 0, nmembers1 = 0; i < nvecs1; ++i) {
        if (strncmp(vecs1[i], "x", strlen(vecs1[i])) == 0) {
            /* x is the first member of the structure */
            flag=1;
        }
	if (flag) ++nmembers1;
    }

    flag=0;
    for (i = 0, nmembers2 = 0; i < nvecs2; ++i) {
        if (strncmp(vecs2[i], "x", strlen(vecs2[i])) == 0) {
            /* x is the first member of the structure */
            flag=1;
        }
	if (flag) ++nmembers2;
    }

    if( nmembers1 != nmembers2) {
        fprintf(stderr, "non-matching headers: %d and %d\n",nvecs1,nvecs2);
//        exit(1);
    }

    printf("Enter disk radius: ");
    scanf("%f", &R0);
    printf(" %f\n", R0);

    printf("Enter disk height: ");
    scanf("%f", &disk_h);
    printf(" %f\n", disk_h);

    printf("Enter max r: ");
    scanf("%f",&maxR0);
    printf("%f\n",maxR0); 

    SDFgetint(sdfp1, "npart", &npart1);
    SDFgetint(sdfp2, "npart", &npart2);
    printf("%d and %d particles\n", npart1, npart2);

/*malloc memory space for the respective features of the struct-CE*/
    members1 = (char **)malloc(nmembers1 * sizeof(char *));
    members2 = (char **)malloc(nmembers2 * sizeof(char *));
    addrs = (void **)malloc(nmembers1 * sizeof(void *));
    types = (SDF_type_t *)malloc(nmembers1 * sizeof(SDF_type_t));
    inoffsets = (int *)malloc(nmembers1 * sizeof(int));
    strides = (int *)malloc(nmembers1 * sizeof(int));
    starts = (int *)malloc(nmembers1 * sizeof(int));
    lines = (int *)malloc(nmembers1 * sizeof(int));

    printf("done malloc'ing\n");
    flag=0;
/*one by one, go through the fields in the column, i.e. members of the struct?-CE*/
    for (i = 0, stride = 0, nmembers = 0; i < nvecs1; ++i) {
        if (strncmp(vecs1[i], "x", strlen(vecs1[i])) == 0) flag=1;
        if (strncmp(vecs1[i], "ident", strlen(vecs1[i])) == 0) idindex=nmembers;
        if(flag) {
	    members1[nmembers] = vecs1[i];
//	    members2[nmembers] = vecs2[i];
	    types[nmembers] = SDFtype(members1[nmembers], sdfp1);
	    inoffsets[nmembers] = stride;/* offsets (from beginning of 'line'?) of each column
                                            of data (struct member) */
	    stride += SDFtype_sizes[types[nmembers]];
            lines[nmembers] = incr;
            nmembers++;
	}
    }

    /* unnecesary, just use 'stride' ? CE */
    outstride = 0;
    for(i=0; i< nmembers1; i++) outstride += SDFtype_sizes[ types[i] ];

    printf("outstride = %d\n", outstride);

    btab = (void *)malloc( outstride*incr );

    printf("printing header\n");
    /*print the struct declaration part from the header-CE*/
    fprintf(fp, "struct {\n");
    for (i = 0; i < nmembers1; ++i) {
        strides[i] = stride;
	switch (types[i]) {
	case SDF_INT:
	    fprintf(fp, "\tint %s;\n", members1[i]);
	    break;
	case SDF_FLOAT:
            fprintf(fp, "\tfloat %s;\n", members1[i]);
	    break;
	case SDF_DOUBLE:
	    fprintf(fp, "\tdouble %s;\n", members1[i]);
	    break;
	default:
	    fprintf(stderr, "%s: type not supported\n", members1[i]);
	    exit(-1);
	}
    }
    fgetpos(fp, &pos1_npart);
    fprintf(fp, "}[%d];\n", npart1); /*figure out how to save the location of the file position
                                       indicator, so we can come back and update npart -CE */
    fprintf(fp, "#\n");
    fprintf(fp, "# SDF-EOH\n");

    /*calculate the byte offset in memory to the address of the next member-CE*/
    addrs[0] = (char *)btab;
    for (i=1; i< nmembers1; i++) addrs[i] = addrs[i-1] + SDFtype_sizes[ types[i-1] ];

    /* writing ISM material with cut out disk; assume whole ISM file is kept */
    /* cut out a disk for r<R0 and z<disk_h */

    printf("getting file 1 .... ");
    for( i=0, countnpart = 0; i < npart1-1; i++) {
        /* need to increment starts-array */
        for( j = 0; j < nmembers1; j++)
            starts[j] = i;

        /* read data into btab (via addrs) */
        SDFseekrdvecsarr(sdfp1, nmembers1, members1, starts, lines, addrs, strides);

        x = *((double *)(btab + inoffsets[0]));
        y = *((double *)(btab + inoffsets[1]));
        z = *((double *)(btab + inoffsets[2]));
        radius = sqrt(x*x + y*y);

	/*dump the btab data into the file now-CE*/
        if( radius > R0 || fabs(z) > disk_h ) {
            ident_last=ident;
            ident = *((int *)(btab + inoffsets[idindex]));
            if(ident_last==ident)printf("same ident\n");
            identnew = countnpart; /* renumber the idents */
            memcpy( btab + inoffsets[idindex], &identnew, sizeof(ident) );
	    fwrite(btab, outstride, 1, fp);
            countnpart++;
        }

    }
    newnpart = countnpart-1;
    ident_max=identnew;

    /* add the disk */
    printf("got %d lines, last ident=%d\n",countnpart,ident_max);
    printf("getting file 2 .... ");
    for( i=0, countnpart = 0; i < npart2-1; i++) {
        /* need to increment starts-array */
        for( j = 0; j < nmembers1; j++)
            starts[j] = i;

        /* read data into btab (via addrs) */
        SDFseekrdvecsarr(sdfp2, nmembers1, members1, starts, lines, addrs, strides);

        x = *((double *)(btab + inoffsets[0]));
        y = *((double *)(btab + inoffsets[1]));
        z = *((double *)(btab + inoffsets[2]));
        radius = sqrt(x*x + y*y);

	/*dump the btab data into the file now-CE*/
        if( radius < R0 && fabs(z) < disk_h) { /* radius is always greater than -99., no extra case needed*/
            /* update the particle id, so it does not start at 1 again */
            ident_last=ident;
            ident = *((int *)(btab + inoffsets[idindex]));
            if(ident_last==ident)printf(" same ident ");
            ++countnpart;
            identnew = countnpart + ident_max; /* so there aren't duplicate particle ids */
            memcpy( btab + inoffsets[idindex], &identnew, sizeof(ident) );

	    fwrite(btab, outstride, 1, fp);
        } 

    }
    newnpart += countnpart-1;
    printf("got %d lines\n",countnpart);

    /* update npart to the new value */
    fsetpos(fp, &pos1_npart);
    fprintf(fp, "}[%d];", newnpart);

    fsetpos(fp, &pos_npart);
    fprintf(fp, "int %s = %d;", "npart", newnpart);

/*and we're done! clean up now -CE: if it ever works*/
/*    free(members);
    free(btab);
    free(addrs);
    free(types);
    free(inoffsets);
*/
    /*free(outbtab);*/
}
static enum nss_status
internal_getgrent_r (ent_t *ent, char *buffer, size_t buflen, const char *user,
		     gid_t group, long int *start, long int *size,
		     gid_t **groupsp, long int limit, int *errnop)
{
  struct parser_data *data = (void *) buffer;
  struct group grpbuf;

  if (!ent->files)
    return getgrent_next_nss (ent, buffer, buflen, user, group,
			      start, size, groupsp, limit, errnop);

  while (1)
    {
      fpos_t pos;
      int parse_res = 0;
      char *p;

      do
	{
	  /* We need at least 3 characters for one line.  */
	  if (__builtin_expect (buflen < 3, 0))
	    {
	    erange:
	      *errnop = ERANGE;
	      return NSS_STATUS_TRYAGAIN;
	    }

	  fgetpos (ent->stream, &pos);
	  buffer[buflen - 1] = '\xff';
	  p = fgets_unlocked (buffer, buflen, ent->stream);
	  if (p == NULL && feof_unlocked (ent->stream))
	    return NSS_STATUS_NOTFOUND;

	  if (p == NULL || __builtin_expect (buffer[buflen - 1] != '\xff', 0))
	    {
	    erange_reset:
	      fsetpos (ent->stream, &pos);
	      goto erange;
	    }

	  /* Terminate the line for any case.  */
	  buffer[buflen - 1] = '\0';

	  /* Skip leading blanks.  */
	  while (isspace (*p))
	    ++p;
	}
      while (*p == '\0' || *p == '#' ||	/* Ignore empty and comment lines. */
	     /* Parse the line.  If it is invalid, loop to
	        get the next line of the file to parse.  */
	     !(parse_res = _nss_files_parse_grent (p, &grpbuf, data, buflen,
						   errnop)));

      if (__builtin_expect (parse_res == -1, 0))
	/* The parser ran out of space.  */
	goto erange_reset;

      if (grpbuf.gr_name[0] != '+' && grpbuf.gr_name[0] != '-')
	/* This is a real entry.  */
	break;

      /* -group */
      if (grpbuf.gr_name[0] == '-' && grpbuf.gr_name[1] != '\0'
	  && grpbuf.gr_name[1] != '@')
	{
	  blacklist_store_name (&grpbuf.gr_name[1], ent);
	  continue;
	}

      /* +group */
      if (grpbuf.gr_name[0] == '+' && grpbuf.gr_name[1] != '\0'
	  && grpbuf.gr_name[1] != '@')
	{
	  if (in_blacklist (&grpbuf.gr_name[1],
			    strlen (&grpbuf.gr_name[1]), ent))
	    continue;
	  /* Store the group in the blacklist for the "+" at the end of
	     /etc/group */
	  blacklist_store_name (&grpbuf.gr_name[1], ent);
	  if (nss_getgrnam_r == NULL)
	    return NSS_STATUS_UNAVAIL;
	  else if (nss_getgrnam_r (&grpbuf.gr_name[1], &grpbuf, buffer,
				   buflen, errnop) != NSS_STATUS_SUCCESS)
	    continue;

	  check_and_add_group (user, group, start, size, groupsp,
			       limit, &grpbuf);

	  return NSS_STATUS_SUCCESS;
	}

      /* +:... */
      if (grpbuf.gr_name[0] == '+' && grpbuf.gr_name[1] == '\0')
	{
	  ent->files = FALSE;
	  return getgrent_next_nss (ent, buffer, buflen, user, group,
				    start, size, groupsp, limit, errnop);
	}
    }

  check_and_add_group (user, group, start, size, groupsp, limit, &grpbuf);

  return NSS_STATUS_SUCCESS;
}
Exemple #6
0
void mm_loc_donereading(struct mm_loc *p)
{
	fsetpos(p->fp, &p->pos);
}
Exemple #7
0
/* pc_resetsrc()
 * "position" may only hold a pointer that was previously obtained from
 * pc_getpossrc()
 */
void pc_resetsrc(void *handle,void *position)
{
	assert(handle!=NULL);
	fsetpos((FILE*)handle,(fpos_t *)position);
}
/* DB_Search
 * Search the DB for any entry related to the file being received
 */
int DB_Search(char *f_name, char *c_sum, Eventinfo *lf)
{
    int p = 0;
    int sn_size;
    int agent_id;
    
    char *saved_sum;
    char *saved_name;
    
    FILE *fp;


    /* Getting db pointer */
    fp = DB_File(lf->location, &agent_id);
    if(!fp)
    {
        merror("%s: Error handling integrity database.",ARGV0);
        sdb.db_err++; /* Increment db error */
        return(0);
    }


    /* Reads the integrity file and search for a possible
     * entry
     */
    if(fgetpos(fp, &sdb.init_pos) == -1)
    {
        merror("%s: Error handling integrity database (fgetpos).",ARGV0);
        return(0);
    }
    
    
    /* Looping the file */
    while(fgets(sdb.buf, OS_MAXSTR, fp) != NULL)
    {
        /* Ignore blank lines and lines with a comment */
        if(sdb.buf[0] == '\n' || sdb.buf[0] == '#')
        {
            fgetpos(fp, &sdb.init_pos); /* getting next location */
            continue;
        }


        /* Getting name */    
        saved_name = strchr(sdb.buf, ' ');
        if(saved_name == NULL)
        {
            merror("%s: Invalid integrity message in the database.",ARGV0);
            fgetpos(fp, &sdb.init_pos); /* getting next location */
            continue;
        }
        *saved_name = '\0';
        saved_name++;
        
        
        /* New format - with a timestamp */
        if(*saved_name == '!')
        {
            saved_name = strchr(saved_name, ' ');
            if(saved_name == NULL)
            {
                merror("%s: Invalid integrity message in the database",ARGV0);
                fgetpos(fp, &sdb.init_pos); /* getting next location */
                continue;
            }
            saved_name++;
        }


        /* Removing new line from saved_name */
        sn_size = strlen(saved_name);
        sn_size -= 1;
        if(saved_name[sn_size] == '\n')
            saved_name[sn_size] = '\0';


        /* If name is different, go to next one. */
        if(strcmp(f_name,saved_name) != 0)
        {
            /* Saving currently location */
            fgetpos(fp, &sdb.init_pos);
            continue;
        }
        

        saved_sum = sdb.buf;


        /* First three bytes are for frequency check */
        saved_sum+=3;


        /* checksum match, we can just return and keep going */
        if(strcmp(saved_sum, c_sum) == 0)
            return(0);


        /* If we reached here, the checksum of the file has changed */
        if(saved_sum[-3] == '!')
        {
            p++;
            if(saved_sum[-2] == '!')
            {
                p++;
                if(saved_sum[-1] == '!')    
                    p++;
                else if(saved_sum[-1] == '?')
                    p+=2;    
            }
        }


        /* Checking the number of changes */
        if(!Config.syscheck_auto_ignore)
        {
            sdb.syscheck_dec->id = sdb.id1;
        }
        else
        {
            switch(p)
            {
                case 0:
                sdb.syscheck_dec->id = sdb.id1;
                break;

                case 1:
                sdb.syscheck_dec->id = sdb.id2;
                break;

                case 2:
                sdb.syscheck_dec->id = sdb.id3;
                break;

                default:
                return(0);
                break;
            }
        }


        /* Adding new checksum to the database */
        /* Commenting the file entry and adding a new one latter */
        fsetpos(fp, &sdb.init_pos);
        fputc('#',fp);


        /* Adding the new entry at the end of the file */
        fseek(fp, 0, SEEK_END);
        fprintf(fp,"%c%c%c%s !%d %s\n",
                '!',
                p >= 1? '!' : '+',
                p == 2? '!' : (p > 2)?'?':'+',
                c_sum,
                lf->time,
                f_name);
        fflush(fp);


        /* File deleted */
        if(c_sum[0] == '-' && c_sum[1] == '1')
        {
            sdb.syscheck_dec->id = sdb.idd;
            snprintf(sdb.comment, OS_MAXSTR,
                    "File '%.756s' was deleted. Unable to retrieve "
                    "checksum.", f_name);
        }
        
        /* If file was re-added, do not compare changes */
        else if(saved_sum[0] == '-' && saved_sum[1] == '1')
        {
            sdb.syscheck_dec->id = sdb.idn;
            snprintf(sdb.comment, OS_MAXSTR,
                     "File '%.756s' was re-added.", f_name);
        }

        else    
        {
            int oldperm = 0, newperm = 0;
            
            /* Providing more info about the file change */
            char *oldsize = NULL, *newsize = NULL;
            char *olduid = NULL, *newuid = NULL;
            char *c_oldperm = NULL, *c_newperm = NULL;
            char *oldgid = NULL, *newgid = NULL;
            char *oldmd5 = NULL, *newmd5 = NULL;
            char *oldsha1 = NULL, *newsha1 = NULL;

            oldsize = saved_sum;
            newsize = c_sum;

            c_oldperm = strchr(saved_sum, ':');
            c_newperm = strchr(c_sum, ':');

            /* Get old/new permissions */
            if(c_oldperm && c_newperm)
            {
                *c_oldperm = '\0';
                c_oldperm++;

                *c_newperm = '\0';
                c_newperm++;

                /* Get old/new uid/gid */
                olduid = strchr(c_oldperm, ':');
                newuid = strchr(c_newperm, ':');

                if(olduid && newuid)
                {
                    *olduid = '\0';
                    *newuid = '\0';

                    olduid++;
                    newuid++;

                    oldgid = strchr(olduid, ':');
                    newgid = strchr(newuid, ':');

                    if(oldgid && newgid)
                    {
                        *oldgid = '\0';
                        *newgid = '\0';

                        oldgid++;
                        newgid++;


                        /* Getting md5 */
                        oldmd5 = strchr(oldgid, ':');
                        newmd5 = strchr(newgid, ':');

                        if(oldmd5 && newmd5)
                        {
                            *oldmd5 = '\0';
                            *newmd5 = '\0';

                            oldmd5++;
                            newmd5++;

                            /* getting sha1 */
                            oldsha1 = strchr(oldmd5, ':');
                            newsha1 = strchr(newmd5, ':');

                            if(oldsha1 && newsha1)
                            {
                                *oldsha1 = '\0';
                                *newsha1 = '\0';

                                oldsha1++;
                                newsha1++;
                            }
                        }
                    }
                }
            }

            /* Getting integer values */
            if(c_newperm && c_oldperm)
            {
                newperm = atoi(c_newperm);
                oldperm = atoi(c_oldperm);
            }

            /* Generating size message */
            if(!oldsize || !newsize || strcmp(oldsize, newsize) == 0)
            {
                sdb.size[0] = '\0';
            }
            else
            {
                snprintf(sdb.size, OS_FLSIZE,
                        "Size changed from '%s' to '%s'\n",
                        oldsize, newsize);

                #ifdef PRELUDE
                os_strdup(oldsize, lf->size_before);
                os_strdup(newsize, lf->size_after);
                #endif
            }

            /* Permission message */
            if(oldperm == newperm)
            {
                sdb.perm[0] = '\0';
            }
            else if(oldperm > 0 && newperm > 0)
            {

                snprintf(sdb.perm, OS_FLSIZE, "Permissions changed from "
                        "'%c%c%c%c%c%c%c%c%c' "
                        "to '%c%c%c%c%c%c%c%c%c'\n",
                        (oldperm & S_IRUSR)? 'r' : '-',
                        (oldperm & S_IWUSR)? 'w' : '-',
                        
                        (oldperm & S_ISUID)? 's' :
                        (oldperm & S_IXUSR)? 'x' : '-',
                        
                        (oldperm & S_IRGRP)? 'r' : '-',
                        (oldperm & S_IWGRP)? 'w' : '-',

                        (oldperm & S_ISGID)? 's' :
                        (oldperm & S_IXGRP)? 'x' : '-',
                        
                        (oldperm & S_IROTH)? 'r' : '-',
                        (oldperm & S_IWOTH)? 'w' : '-',

                        (oldperm & S_ISVTX)? 't' :
                        (oldperm & S_IXOTH)? 'x' : '-',



                        (newperm & S_IRUSR)? 'r' : '-',
                        (newperm & S_IWUSR)? 'w' : '-',

                        (newperm & S_ISUID)? 's' :
                        (newperm & S_IXUSR)? 'x' : '-',

                        
                        (newperm & S_IRGRP)? 'r' : '-',
                        (newperm & S_IWGRP)? 'w' : '-',
                        
                        (newperm & S_ISGID)? 's' :
                        (newperm & S_IXGRP)? 'x' : '-',

                        (newperm & S_IROTH)? 'r' : '-',
                        (newperm & S_IWOTH)? 'w' : '-',

                        (newperm & S_ISVTX)? 't' :
                        (newperm & S_IXOTH)? 'x' : '-');

                #ifdef PRELUDE
                lf->perm_before = oldperm;
                lf->perm_after = newperm;
                #endif
            }

            /* Ownership message */
            if(!newuid || !olduid || strcmp(newuid, olduid) == 0)
            {
                sdb.owner[0] = '\0';
            }
            else
            {
                snprintf(sdb.owner, OS_FLSIZE, "Ownership was '%s', "
                        "now it is '%s'\n",
                        olduid, newuid);


                #ifdef PRELUDE
                os_strdup(olduid, lf->owner_before);
                os_strdup(newuid, lf->owner_after);
                #endif
            }    

            /* group ownership message */
            if(!newgid || !oldgid || strcmp(newgid, oldgid) == 0)
            {
                sdb.gowner[0] = '\0';
            }
            else
            {
                snprintf(sdb.gowner, OS_FLSIZE,"Group ownership was '%s', "
                        "now it is '%s'\n",
                        oldgid, newgid);
                #ifdef PRELUDE
                os_strdup(oldgid, lf->gowner_before);
                os_strdup(newgid, lf->gowner_after);
                #endif
            }

            /* md5 message */
            if(!newmd5 || !oldmd5 || strcmp(newmd5, oldmd5) == 0)
            {
                sdb.md5[0] = '\0';
            }
            else
            {
                snprintf(sdb.md5, OS_FLSIZE, "Old md5sum was: '%s'\n"
                        "New md5sum is : '%s'\n",
                        oldmd5, newmd5);
                #ifdef PRELUDE
                os_strdup(oldmd5, lf->md5_before);
                os_strdup(newmd5, lf->md5_after);
                #endif
            }

            /* sha1 */
            if(!newsha1 || !oldsha1 || strcmp(newsha1, oldsha1) == 0)
            {
                sdb.sha1[0] = '\0';
            }
            else
            {
                snprintf(sdb.sha1, OS_FLSIZE, "Old sha1sum was: '%s'\n"
                        "New sha1sum is : '%s'\n",
                        oldsha1, newsha1);
                #ifdef PRELUDE
                os_strdup(oldsha1, lf->sha1_before);
                os_strdup(newsha1, lf->sha1_after);
                #endif
            }
            #ifdef PRELUDE
            os_strdup(f_name, lf->filename);
            #endif


if(lf->data)
{
    merror("XXX changed: %s",lf->data);
}
            /* Provide information about the file */    
            snprintf(sdb.comment, OS_MAXSTR, "Integrity checksum changed for: "
                    "'%.756s'\n"
                    "%s"
                    "%s"
                    "%s"
                    "%s"
                    "%s"
                    "%s"
                    "%s%s",
                    f_name, 
                    sdb.size,
                    sdb.perm,
                    sdb.owner,
                    sdb.gowner,
                    sdb.md5,
                    sdb.sha1,
                    lf->data == NULL?"":"What changed:\n",
                    lf->data == NULL?"":lf->data
                    );
        }


        /* Creating a new log message */
        free(lf->full_log);
        os_strdup(sdb.comment, lf->full_log);
        lf->log = lf->full_log;
        lf->data = NULL;

        
        /* Setting decoder */
        lf->decoder_info = sdb.syscheck_dec;
                        

        return(1); 

    } /* continuiing... */


    /* If we reach here, this file is not present on our database */
    fseek(fp, 0, SEEK_END);
    
    fprintf(fp,"+++%s !%d %s\n", c_sum, lf->time, f_name);


    /* Alert if configured to notify on new files */
    if((Config.syscheck_alert_new == 1) && (DB_IsCompleted(agent_id)))
    {
        sdb.syscheck_dec->id = sdb.idn;

        /* New file message */
        snprintf(sdb.comment, OS_MAXSTR,
                              "New file '%.756s' "
                              "added to the file system.", f_name);
        

        /* Creating a new log message */
        free(lf->full_log);
        os_strdup(sdb.comment, lf->full_log);
        lf->log = lf->full_log;


        /* Setting decoder */
        lf->decoder_info = sdb.syscheck_dec;

        return(1);
    }

    return(0);
}
/* Read multiline logs. */
void *read_multiline(int pos, int *rc, int drop_it)
{
    int __ms = 0;
    int linecount;
    int linesgot = 0;
    size_t buffer_size = 0;
    char *p;
    char str[OS_MAXSTR + 1];
    char buffer[OS_MAXSTR +1];

    fpos_t fp_pos;

    buffer[0] = '\0';
    buffer[OS_MAXSTR] = '\0';
    str[OS_MAXSTR]= '\0';
    *rc = 0;

    linecount = atoi(logff[pos].logformat);

    /* Getting initial file location */
    fgetpos(logff[pos].fp, &fp_pos);

    while(fgets(str, OS_MAXSTR - OS_LOG_HEADER, logff[pos].fp) != NULL)
    {
        linesgot++;

        /* Getting the last occurence of \n */
        if ((p = strrchr(str, '\n')) != NULL)
        {
            *p = '\0';
        }

        /* If we didn't get the new line, because the
         * size is large, send what we got so far.
         */
        else if(strlen(str) >= (OS_MAXSTR - OS_LOG_HEADER - 2))
        {
            /* Message size > maximum allowed */
            __ms = 1;
        }
        else
        {
            /* Message not complete. Return. */
            debug1("%s: Message not complete. Trying again: '%s'", ARGV0,str);
            fsetpos(logff[pos].fp, &fp_pos);
            break;
        }

        #ifdef WIN32
        if ((p = strrchr(str, '\r')) != NULL)
        {
            *p = '\0';
        }
        #endif

        debug2("%s: DEBUG: Reading message: '%s'", ARGV0, str);


        /* Adding to buffer. */
        buffer_size = strlen(buffer);
        if(buffer[0] != '\0')
        {
            buffer[buffer_size] = ' ';
            buffer_size++;
        }

        strncpy(buffer + buffer_size, str, OS_MAXSTR - buffer_size -2);


        if(linesgot < linecount)
        {
            continue;
        }


        /* Sending message to queue */
        if(drop_it == 0)
        {
            if(SendMSG(logr_queue, buffer, logff[pos].file,
                        LOCALFILE_MQ) < 0)
            {
                merror(QUEUE_SEND, ARGV0);
                if((logr_queue = StartMQ(DEFAULTQPATH,WRITE)) < 0)
                {
                    ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH);
                }
            }
        }

        buffer[0] = '\0';


        /* Incorrectly message size */
        if(__ms)
        {
            merror("%s: Large message size: '%s'", ARGV0, str);
            while(fgets(str, OS_MAXSTR - 2, logff[pos].fp) != NULL)
            {
                /* Getting the last occurence of \n */
                if ((p = strrchr(str, '\n')) != NULL)
                {
                    break;
                }
            }
            __ms = 0;
        }

        fgetpos(logff[pos].fp, &fp_pos);
        continue;
    }

    return(NULL);
}
Exemple #10
0
static void GetSRF(LWOBInfo *object, char *buf, int siz)
{
   fsetpos(object->fp,&object->srfPos);
   fread(buf,1,siz,object->fp);
}
Exemple #11
0
static void GetSDat(LWOBInfo *object, char *buf, int siz,fpos_t *datpos)
{
   fsetpos(object->fp,datpos);
   fread(buf,1,siz,object->fp);
}
Exemple #12
0
static int GetPolygon(LWOBInfo *object, LWPolygon *poly)
{
   unsigned short pntcnt;
   unsigned short pointval;
   unsigned short junk;
   unsigned short detail;
   short surface;
   int k,x;


   fsetpos(object->fp,&object->polPosCur);
   if (object->polSizeCur<object->polSize){


      fread(&pntcnt,2,1,object->fp);


      BSWAP_W(pntcnt)   ;


      object->polSizeCur = object->polSizeCur + 2;


      poly->npoints = pntcnt;


      for(x=0;x<pntcnt;x++){
         fread(&pointval,2,1,object->fp);
         BSWAP_W(pointval);


         object->polSizeCur = object->polSizeCur + 2;
         poly->plist[x]=pointval;
         }


      fread(&surface,2,1,object->fp);
      BSWAP_W(surface);


      object->polSizeCur = object->polSizeCur + 2;


      if (surface<0)
      {
         fread(&detail,2,1,object->fp);
         BSWAP_W(detail);
         object->polSizeCur = object->polSizeCur + 2;


         for(k=0;k<detail;k++)
         {
            fread(&junk,2,1,object->fp);
            BSWAP_W(junk);


            fseek(object->fp,(junk+1)*2,SEEK_CUR);
            object->polSizeCur = object->polSizeCur + ((junk+2)*2);
         }
         poly->surface = abs(surface);
      }
      else
         poly->surface=surface;


      fgetpos(object->fp,&object->polPosCur);
      }
   else
      return(0);


   return(1);
}
Exemple #13
0
void read_data(FILE *inf, wave_object_t *obj) {
    double xt, yt, zt;
    double it, jt, kt;
    double st, tt;
    size_t num_pts;

    size_t i;
    size_t j;
    size_t type_pos;
    size_t next_space;
    char tmp;
    size_t cur_vert = 0;
    size_t cur_norm = 0;
    size_t cur_text = 0;
    size_t cur_face = 0;
    char in_buffer[512] = "";
    size_t blen = 0;
    char *fgs = NULL;
    enum obj_entry_type obj_type;
    int end = 0;
    size_t pt_cnt = 0;

    char *end_ptr;
    size_t vert;
    size_t text;
    size_t norm;
            
    // Assume no faces will ever have more than 20 points
    char *pts[20];
    size_t cur_pt = 0;
    int in_word = 0;
    char *num_start;
    char *num_end;
    
    
    // Save original file positon
    fpos_t original_pos;
    fgetpos(inf, &original_pos);

    // Go to the beginnning
    rewind(inf);

    do {
        fgs = fgets(in_buffer, 512, inf);
        if (fgs == NULL) continue;
        blen = strlen(in_buffer);
        in_buffer[blen-1] = '\0';
        --blen;
        if (in_buffer[blen-1] == '\r') {
            in_buffer[blen-1] ='\0';
            --blen;
        }
        obj_type = get_entry_type(in_buffer);

        switch (obj_type) {
        case vertex:
            // Find the 'v' and skip it and the white space after it
            num_start = strchr(in_buffer, 'v')+1;

            xt = strtod(num_start, &num_end);
            yt = strtod(num_end, &num_end);
            zt = strtod(num_end, &num_end);

            obj->verts[cur_vert][0] = (RtFloat)xt;
            obj->verts[cur_vert][1] = (RtFloat)yt;
            obj->verts[cur_vert][2] = (RtFloat)zt;
            
            ++cur_vert;
            break;

        case normal:
            // Find the 'n' and skip it and the white space after it
            num_start = strchr(in_buffer, 'n')+1;

            it = strtod(num_start, &num_end);
            jt = strtod(num_end, &num_end);
            kt = strtod(num_end, &num_end);

            obj->norms[cur_norm][0] = it;
            obj->norms[cur_norm][1] = jt;
            obj->norms[cur_norm][2] = kt;

            ++cur_norm;
            
            break;

        case text_coord:
            // Find the "vt" and skip it and the white space after it
            num_start = strchr(in_buffer, 'v')+2;

            st = strtod(num_start, &num_end);
            tt = strtod(num_end, &num_end);

            obj->text_coords[cur_text].s = st;
            obj->text_coords[cur_text].t = tt;

            ++cur_text;

            break;

        case face:
            // Find the 'f' and skip it and the white space after it
            i = strchr(in_buffer, 'f')  - in_buffer + 1;
            while (isspace(in_buffer[i])) ++i;

            end = 0;
            pt_cnt = 0;
            
            cur_pt = 0;
            in_word = 0;
            while (in_buffer[i] != '\0') {
                if (!isspace(in_buffer[i]) && in_word == 1) {
                    in_word = 1;
                }
                if (!isspace(in_buffer[i]) && in_word == 0) {
                    pts[cur_pt++] = in_buffer+i;
                    in_word = 1;
                    pt_cnt++;
                }
                if (isspace(in_buffer[i]) && in_word == 1) {
                    in_word = 0;
                    in_buffer[i] = '\0';
                }
                if (isspace(in_buffer[i]) && in_word == 0) {
                    in_word = 0;
                    in_buffer[i] = '\0';
                }
                ++i;
            }
            obj->faces[cur_face].size = pt_cnt;
            obj->faces[cur_face].verts = malloc(sizeof(size_t)*pt_cnt);
            obj->faces[cur_face].norms = malloc(sizeof(size_t)*pt_cnt);
            obj->faces[cur_face].texts = malloc(sizeof(size_t)*pt_cnt);

            for (j=0; j<pt_cnt; ++j) {
                vert = strtoul(pts[j], &end_ptr, 10);
                text = strtoul(end_ptr+1, &end_ptr, 10);
                norm = strtoul(end_ptr+1, &end_ptr, 10);
                if (vert) vert -= 1;
                if (norm) norm -= 1;
                if (text) text -= 1;
                obj->faces[cur_face].verts[j] = vert;
                obj->faces[cur_face].norms[j] = norm;
                obj->faces[cur_face].texts[j] = text;
            }
            if (pt_cnt>obj->largest_face) {
                obj->largest_face = pt_cnt;
            }
            ++cur_face;
            
            break;

        case object:
            break;

        default:
            break;
        }
            
    } while (!feof(inf));

    // Return to original position
    fsetpos(inf, &original_pos);
}
Exemple #14
0
void preprocess(FILE* inf, wave_object_t *obj) {
    /*
      Scan through the file and count the number of vertices, texture
      coordinates, normals and faces
    */
    // Save original position in file
    size_t nv=0;
    size_t nn=0;
    size_t nt=0;
    size_t nf=0;
    size_t no = 0;
    char in_buffer[512] = "";
    size_t blen = 0;
    
    fpos_t original_pos;
    fgetpos(inf, &original_pos);

    // Go to the beginnning
    rewind(inf);

    while (!feof(inf)) {
        char *fgs = fgets(in_buffer, 512, inf);
        if (fgs == NULL) continue;
        blen = strlen(in_buffer);
        in_buffer[blen-1] = '\0';
        --blen;
        if (in_buffer[blen-1] == '\r') {
            in_buffer[blen-1] ='\0';
            --blen;
        }
        if (blen == 0) continue;
        enum obj_entry_type obj_type = get_entry_type(in_buffer);

        switch (obj_type) {
        case vertex:
            ++nv;
            break;
        case normal:
            ++nn;
            break;
        case text_coord:
            ++nt;
            break;
        case face:
            ++nf;
            break;
        case object:
            ++no;
            read_object_type(in_buffer, obj);
            break;
        default:
            break;
        }
    }
    obj->num_verts = nv;
    obj->verts = malloc(sizeof(RtPoint) * nv);
    
    obj->num_norms = nn;
    obj->norms = malloc(sizeof(RtPoint) * nn);
    
    obj->num_texts = nt;
    obj->text_coords = malloc(sizeof(text_coord_t) * nt);
    
    obj->num_faces = nf;
    obj->faces = malloc(sizeof(face_t) * nf);

    // Return to original position
    fsetpos(inf, &original_pos);
}
Exemple #15
0
static void keyboard(unsigned char key, int x, int y) {
    
    switch (key) {
        case 'a':
            povray = pix = -9999;
            makePov(MOLDYN_EXPORT_TO_PNG);
            break;
            
        case 'r':
            if (magstep <= 10) {
                magstep++;
                magnification = pow(1.2, (double) magstep);
                zeye = -2 * range * magnification;
                glutPostRedisplay();
            }
            break;
            
        case 'm':
            if (magstep >= -10) {
                magstep--;
                magnification = pow(1.2, (double) magstep);
                zeye = -2 * range * magnification;                
                glutPostRedisplay();
            }
            break;
            
        case 's':
            if (move_stat == ROTATE) {
                move_stat = TRANSLATE;
            } else if (move_stat == TRANSLATE) {
                move_stat = ROTATE;
            }
            break;
            
        case 'n':
            if (file_done && last_init_done) {
                break;
            } else {
                show_stat = SHOW_NEXT;
                read_cycle();
                moldyn_update_graphics();
                glutPostRedisplay();
                break;
            }
            
        case 'b':
            if (current_cycle == 1) {
                break;
            }
            show_stat = SHOW_PREV;
            current_cycle -= 2;
            file_done = 0;
            if (feof(fptr))
                rewind(fptr);
            
            if (fsetpos(fptr, &cycle_position[current_cycle]))
                moldyn_error("can't position file");
            
            read_cycle();
            moldyn_update_graphics();
            glutPostRedisplay();
            break;
            
        case 'h':
        case 'j':
            if (show_stat == HOLD && !file_done)
            {
                if (key == 'j')
                {
                    jpeg = True;
                    moldyn_export_(MOLDYN_EXPORT_TO_JPEG, window_width, window_height);
                }
                
                glutIdleFunc(animate);
                show_stat = SHOW_ALL;
            }
            else if (show_stat == SHOW_ALL)
            {
                jpeg = False;
                show_stat = HOLD;
                moldyn_update_graphics();
                glutPostRedisplay();
            }
            break;
            
        case 'c':
        case 'C':
            moldyn_export_(MOLDYN_EXPORT_TO_JPEG, 800, 800);
            break;
            
        case 'J':
            moldyn_export_(MOLDYN_EXPORT_TO_JPEG, window_width, window_height);
            break;
            
        case 'p':
        {
            char *argv[] = {"jpeg2ps", "-o", "moldyn.eps", path};
            moldyn_export_(MOLDYN_EXPORT_TO_JPEG, 2000, 2000);
            jpeg2ps_main(sizeof(argv)/sizeof(char *),argv);
        }
#ifdef _WIN32
            system("copy moldyn.eps %PRINTER%");
#else
            system("lpr -h moldyn.eps");
#endif
            break;
            
        case '0':
            xeye = 0.0;
            yeye = 0.0;
            zeye = -2.0 * range;
            glutPostRedisplay();
            break;
            
        case '?':
            hint = (hint) ? False : True;
            glutPostRedisplay();
            break;
            
        case 'T':
        case 't':
            numbers = (numbers) ? False : True;
            glutPostRedisplay();
            break;
            
        case 'q':
        case 'Q':
        case GLUT_KEY_ESCAPE:
            moldyn_exit(0);
            break;
            
    }
}
/*
 * Output handler
 */
static void opng_write_data(png_structp png_ptr, png_bytep data, size_t length)
{
    struct opng_codec_context * context = (struct opng_codec_context *)png_get_io_ptr(png_ptr);
    struct opng_encoding_stats * stats = context->stats;
    FILE * stream = context->stream;

    unsigned io_state = png_get_io_state(png_ptr);
    unsigned io_state_loc = io_state & PNG_IO_MASK_LOC;
    OPNG_ASSERT((io_state & PNG_IO_WRITING) && (io_state_loc != 0), "Incorrect info in png_ptr->io_state");

    /* Handle the optipng-specific events. */
    if (io_state_loc == PNG_IO_CHUNK_HDR)
    {
        OPNG_ASSERT(length == 8, "Writing chunk header, expecting 8 bytes");
        png_bytep chunk_sig = data + 4;
        context->crt_chunk_is_allowed = opng_allow_chunk(context, chunk_sig);
        if (memcmp(chunk_sig, opng_sig_IDAT, 4) == 0)
        {
            context->crt_chunk_is_idat = 1;
            stats->idat_size += png_get_uint_32(data);
        }
        else  /* not IDAT */
        {
            context->crt_chunk_is_idat = 0;
        }
    }
    if (context->no_write) {
        return;
    }

    /* Continue only if the current chunk type is allowed. */
    if (io_state_loc != PNG_IO_SIGNATURE && !context->crt_chunk_is_allowed)
        return;

    /* Here comes an elaborate way of writing the data, in which all IDATs
     * are joined into a single chunk.
     * Normally, the user-supplied I/O routines are not so complicated.
     */
    switch (io_state_loc)
    {
    case PNG_IO_CHUNK_HDR:
        if (context->crt_chunk_is_idat)
        {
            if (context->crt_idat_offset == 0)
            {
                /* This is the header of the first IDAT. */
                context->crt_idat_offset = ftell(stream);
                context->crt_idat_size = length;
                png_save_uint_32(data, (png_uint_32)context->crt_idat_size);
                /* Start computing the CRC of the final IDAT. */
                context->crt_idat_crc = crc32(0, opng_sig_IDAT, 4);
            }
            else
            {
                /* This is not the first IDAT. Do not write its header. */
                return;
            }
        }
        else
        {
            if (context->crt_idat_offset != 0)
            {
                png_byte buf[4];
                /* This is the header of the first chunk after IDAT.
                 * Finalize IDAT before resuming the normal operation.
                 */
                png_save_uint_32(buf, context->crt_idat_crc);
                fwrite(buf, 1, 4, stream);
                if (stats->idat_size != context->crt_idat_size)
                {
                    /* The IDAT size, unknown at the start of encoding,
                     * has not been guessed correctly.
                     * It must be updated in a non-streamable way.
                     */
                    png_save_uint_32(buf, (png_uint_32)stats->idat_size);
                    fpos_t pos;
                    if (fgetpos(stream, &pos) != 0 || fflush(stream) != 0 || (fseek(stream, context->crt_idat_offset, SEEK_SET) != 0) ||
                            (fwrite(buf, 1, 4, stream)!=4) || (fflush(stream) != 0) || (fsetpos(stream, &pos) != 0)) {
                        io_state = 0;
                    }
                }
                if (io_state == 0)
                    png_error(png_ptr, "Can't finalize IDAT");
                context->crt_idat_offset = 0;
            }
        }
        break;
    case PNG_IO_CHUNK_DATA:
        if (context->crt_chunk_is_idat)
            context->crt_idat_crc = crc32(context->crt_idat_crc, data, length);
        break;
    case PNG_IO_CHUNK_CRC:
        if (context->crt_chunk_is_idat)
            return;  /* defer writing until the first non-IDAT occurs */
        break;
    }

    /* Write the data. */
    if (fwrite(data, 1, length, stream) != length)
        png_error(png_ptr, "Can't write file");
}
bool CpuProfileInputStream::setCurrentPosition(fpos_t* pPos)
{
    return 0 == fsetpos(m_fileStream.getHandler(), pPos);
}
Exemple #18
0
// Added by Amir Szekely 8th July 2002
// replace_icon, must get an initialized resource editor
// return values:
//   0  - All OK
//   -1 - Bad icon file
int replace_icon(CResourceEditor* re, WORD wIconId, char* filename)
{
  FILE* f = fopen(filename, "rb");
  if (!f) return -1;

  IconGroupHeader igh;
  fread(&igh, sizeof(IconGroupHeader), 1, f);

  if (igh.wIsIcon != 1 && igh.wReserved != 0) return -1;

  BYTE* rsrcIconGroup = (BYTE*)malloc(sizeof(IconGroupHeader) + igh.wCount*SIZEOF_RSRC_ICON_GROUP_ENTRY);
  if (!rsrcIconGroup) throw bad_alloc();

  CopyMemory(rsrcIconGroup, &igh, sizeof(IconGroupHeader));

  RsrcIconGroupEntry* ige = (RsrcIconGroupEntry*)(rsrcIconGroup + sizeof(IconGroupHeader));

  int i = 1;

  // Delete old icons
  while (re->UpdateResource(RT_ICON, MAKEINTRESOURCE(i++), MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), 0, 0));

  int iNewIconSize = 0;

  for (i = 0; i < igh.wCount; i++) {
    fread(ige, sizeof(FileIconGroupEntry)-sizeof(DWORD), 1, f);
    ige->wRsrcId = i+1;

    DWORD dwOffset;
    fread(&dwOffset, sizeof(DWORD), 1, f);

    fpos_t pos;
    fgetpos(f, &pos);

    if (fseek(f, dwOffset, SEEK_SET)) {
      free(rsrcIconGroup);
      return -1;
    }
    BYTE* iconData = (BYTE*)malloc(ige->dwRawSize);
    if (!iconData) {
      free(rsrcIconGroup);
      throw bad_alloc();
    }
    fread(iconData, sizeof(BYTE), ige->dwRawSize, f);
    re->UpdateResource(RT_ICON, MAKEINTRESOURCE(i+1), MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), iconData, ige->dwRawSize);
    free(iconData);

    fsetpos(f, &pos);

    // Every icon entry should be 8 aligned
    iNewIconSize += ((ige->dwRawSize%8 == 0) ? ige->dwRawSize : ige->dwRawSize - (ige->dwRawSize%8) + 8);

    // Seems like the compiler refuses to increase the pointer by just 14.
    // If you'll replace this line by ige++ you will get unwanted results.
    ige = (RsrcIconGroupEntry*)((BYTE*)ige + SIZEOF_RSRC_ICON_GROUP_ENTRY);
  }

  fclose(f);

  re->UpdateResource(RT_GROUP_ICON, MAKEINTRESOURCE(wIconId), MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), rsrcIconGroup, sizeof(IconGroupHeader) + igh.wCount*SIZEOF_RSRC_ICON_GROUP_ENTRY);

  free(rsrcIconGroup);

  icondata_size = iNewIconSize;

  return 0;
}
/* extract base64 for a specific agent */
int k_extract(char *cmdextract)
{
    FILE *fp;
    char *user_input;
    char *b64_enc;
    char line_read[FILE_SIZE +1];
    char n_id[USER_SIZE +1];


    if(cmdextract)
    {
        user_input = cmdextract;

        if(!IDExist(user_input))
        {
            printf(NO_ID, user_input);
            exit(1);
        }
    }

    else
    {
        if(!print_agents(0, 0, 0))
        {
            printf(NO_AGENT);
            printf(PRESS_ENTER);
            read_from_user();
            return(0);
        }

        do
        {
            printf(EXTRACT_KEY);
            fflush(stdout);
            user_input = read_from_user();

            /* quit */
            if(strcmp(user_input, QUIT) == 0)
                return(0);

            if(!IDExist(user_input))
                printf(NO_ID, user_input);

        } while(!IDExist(user_input));
    }


    /* Trying to open the auth file */
    fp = fopen(AUTH_FILE, "r");
    if(!fp)
    {
        ErrorExit(FOPEN_ERROR, ARGV0, AUTH_FILE);
    }

    fsetpos(fp, &fp_pos);

    memset(n_id, '\0', USER_SIZE +1);
    strncpy(n_id, user_input, USER_SIZE -1);


    if(fgets(line_read, FILE_SIZE, fp) == NULL)
    {
        printf(ERROR_KEYS);
        fclose(fp);
        exit(1);
    }
    chomp(line_read);


    b64_enc = encode_base64(strlen(line_read),line_read);
    if(b64_enc == NULL)
    {
        printf(EXTRACT_ERROR);
        fclose(fp);
        exit(1);
    }

    printf(EXTRACT_MSG, n_id, b64_enc);
    if(!cmdextract)
    {
        printf("\n" PRESS_ENTER);
        read_from_user();
    }

    free(b64_enc);
    fclose(fp);

    return(0);
}
Exemple #20
0
/*
 * We use a simple registry for now by using dir/files as our index table.
 * For every file registered we create a file under "/tmp/indsvr/" (if it does
 * not exist already). And append the name of the peer-node to that file.
 */
int add_peer (char *fname, char *peername)
{
    FILE *fh;
    char filepath[MAXPATHLEN];
    char peer[MAXHOSTNAME+2];
    int old_bw, ret, found = 0;
    int fd;
    fpos_t fpos; 
    static init_done = 0;

    /*
     * Create the server index directory for the first time.
     */
    if (init_done == 0) {
        ret = mkdir(SERVER_DIR, 0755);

        /*
         * If we failed to create the index directory and failed for any other
         * reason other than EEXIST we exit.
         */
        if (ret == -1 && errno != EEXIST) {
            char errorstr[512];
            sprintf(errorstr, "Failed to create the index directory : %s", SERVER_DIR);
            perror(errorstr);
        }
        close(ret);
        init_done = 1;
    }


    /*
     * Try to open the name of the file under the index diorectory. If it
     * already exists we open it else we create a new one.
     */
    sprintf(filepath, "%s/%s", SERVER_DIR, fname);
    fh = fopen(filepath, "rw");
    if (fh == NULL) {
        /*
         * The file does not exist. Hence try creating it.
         */
        if ((fh = fopen(filepath, "a+")) == NULL) {
            printf("index-server : Failed to make an entry : errno = %d : %s\n", errno, strerror(errno));
            return (errno);
        }
    }

    fd = fileno(fh);
    /*
     * Lock the file in exclusive mode so that other contending threads don't
     * modify it while we are searching.
     */
    flock(fd, LOCK_EX);

    /*
     * Search through the file to make sure the peer is not already registered.
     * If it is already registered do nothing. Else, append the peers name to
     * the file.
     */
#ifdef DEBUG
    printf("Walking through current entries for %s: ", fname);
#endif

    fgetpos(fh, &fpos);

    while ((fscanf(fh, "%s %d", peer, &old_bw)) != EOF) {
#ifdef DEBUG
        printf("peer %s oldbw = %d\n", peer, old_bw);
#endif

        if (strcmp(peer, peername) == 0) {
            found = 1;
            break;
        }
        fgetpos(fh, &fpos);
    }

    if (found == 0) {
        fprintf(fh, "%s %d\n", peername, bw);
        printf("Registering file : %s from peer %s\n", fname, peername);
    } else {
        /*
         * We found an entry. We check if the new b/w is different from
         * old_bw and record the change.
         */
        if (bw != old_bw) {
            fsetpos(fh, &fpos);
            printf("errno = %d\n", errno);
            fprintf(fh, "%s %d\n", peername, bw);
            printf("errno = %d\n", errno);
            printf("Registering file with new bandwidth: %s from peer %s BW = %d\n",
                    fname, peername, bw);
        }
    }

    flock(fd, LOCK_UN);
    fclose(fh);

    return (0);
}
// returns -1 for error, 0 if not found (end of section or file)
// and 1 if found
static int prv_read_key_value(FILE * fd,
                              char ** keyP,
                              char ** valueP)
{
    char * line;
    fpos_t prevPos;
    ssize_t res;
    size_t length;
    size_t start;
    size_t middle;
    size_t end;

    *keyP = NULL;
    *valueP = NULL;

    line = NULL;
    if (fgetpos(fd, &prevPos) != 0) return -1;
    while ((res = getline(&line, &length, fd)) != -1)
    {
        length = strlen(line);

        start = 0;
        while (start < length && isspace(line[start]&0xff)) start++;
        // ignore empty and commented lines
        if (start != length
         && line[start] != ';'
         && line[start] != '#')
        {
            break;
        }

        lwm2m_free(line);
        line = NULL;
        length = 0;
        if (fgetpos(fd, &prevPos) != 0) return -1;
    }

    if (res == -1) return -1;

    // end of section
    if (line[start] == '[')
    {
        lwm2m_free(line);
        fsetpos(fd, &prevPos);
        return 0;
    }

    middle = start;
    while (middle < length && line[middle] != '=') middle++;
    // invalid lines
    if (middle == start
     || middle == length)
    {
        lwm2m_free(line);
        return -1;
    }

    end = length - 2;
    while (end > middle && isspace(line[end]&0xff)) end--;
    // invalid lines
    if (end == middle)
    {
        lwm2m_free(line);
        return -1;
    }
    end += 1;

    line[middle] = 0;
    *keyP = strdup(line + start);
    if (*keyP == NULL)
    {
        lwm2m_free(line);
        return -1;
    }

    middle +=1 ;
    while (middle < end && isspace(line[middle]&0xff)) middle++;
    line[end] = 0;
    *valueP = strdup(line + middle);
    if (*valueP == NULL)
    {
        lwm2m_free(*keyP);
        *keyP = NULL;
        lwm2m_free(line);
        return -1;
    }

    lwm2m_free(line);

    return 1;
}
Exemple #22
0
//-----------------------------------------------------------------------------
// The variable class constructor.
//-----------------------------------------------------------------------------
Variable::Variable( char *name, FILE *file )
{
	// Store the name of the variable
	m_name = new char[strlen( name ) + 1];
	strcpy( m_name, name );

	// Ensure the file pointer is valid.
	if( file == NULL )
		return;

	// Read the variable's type.
	char buffer[MAX_PATH];
	fscanf( file, "%s", buffer );
	if( strcmp( buffer, "bool" ) == 0 )
	{
		// The variable is a boolean.
		m_type = VARIABLE_BOOL;

		// Read and set the bool for the variable.
		bool value;
		fscanf( file, "%s", buffer );
		if( strcmp( buffer, "true" ) == 0 )
			value = true;
		else
			value = false;
		m_data = new bool;
		memcpy( m_data, &value, sizeof( bool ) );
	}
	else if( strcmp( buffer, "colour" ) == 0 )
	{
		// The variable is a colour.
		m_type = VARIABLE_COLOUR;

		// Read and set the colour for the variable.
		D3DCOLORVALUE colour;
		fscanf( file, "%s", buffer );
		colour.r = (float)atof( buffer );
		fscanf( file, "%s", buffer );
		colour.g = (float)atof( buffer );
		fscanf( file, "%s", buffer );
		colour.b = (float)atof( buffer );
		fscanf( file, "%s", buffer );
		colour.a = (float)atof( buffer );
		m_data = new D3DCOLORVALUE;
		memcpy( m_data, &colour, sizeof( D3DCOLORVALUE ) );
	}
	else if( strcmp( buffer, "float" ) == 0 )
	{
		// The variable is a float.
		m_type = VARIABLE_FLOAT;

		// Read and set the float for the variable.
		float value;
		fscanf( file, "%s", buffer );
		value = (float)atof( buffer );
		m_data = new float;
		memcpy( m_data, &value, sizeof( float ) );
	}
	else if( strcmp( buffer, "number" ) == 0 )
	{
		// The variable is a number.
		m_type = VARIABLE_NUMBER;

		// Read and set the number for the variable.
		long value;
		fscanf( file, "%s", buffer );
		value = atol( buffer );
		m_data = new long;
		memcpy( m_data, &value, sizeof( long ) );
	}
	else if( strcmp( buffer, "string" ) == 0 )
	{
		// The variable is a string.
		m_type = VARIABLE_STRING;

		// Find the opening inverted commas.
		bool commasFound = false;
		ZeroMemory( buffer, MAX_PATH * sizeof( char ) );
		fscanf( file, "%c", buffer );
		while( true )
		{
			if( strcmp( buffer, "\"" ) == 0 )
			{
				commasFound = true;
				break;
			}

			if( strcmp( buffer, " " ) != 0 )
			{
				fpos_t pos;
				fgetpos( file, &pos );
				fsetpos( file, &--pos );
				break;
			}

			fscanf( file, "%c", buffer );
		}

		// Read and set the string for the variable.
		char completeString[MAX_PATH];
		ZeroMemory( completeString, MAX_PATH * sizeof( char ) );
		bool addSpacing = false;
		do
		{
			fscanf( file, "%s", buffer );
			if( strcmp( &buffer[strlen( buffer ) - 1], "\"" ) == 0 )
			{
				buffer[strlen( buffer ) - 1] = 0;
				commasFound = false;
			}

			if( addSpacing == false )
				addSpacing = true;
			else
				strcat( completeString, " " );

			strcat( completeString, buffer );
		} while( commasFound == true );

		m_data = new char[strlen( completeString ) + 1];
		strcpy( (char*)m_data, completeString );
	}
	else if( strcmp( buffer, "vector" ) == 0 )
	{
		// The variable is a vector.
		m_type = VARIABLE_VECTOR;

		// Read and set the vector for the variable.
		D3DXVECTOR3 vector;
		fscanf( file, "%s", buffer );
		vector.x = (float)atof( buffer );
		fscanf( file, "%s", buffer );
		vector.y = (float)atof( buffer );
		fscanf( file, "%s", buffer );
		vector.z = (float)atof( buffer );
		m_data = new D3DXVECTOR3;
		memcpy( m_data, &vector, sizeof( D3DXVECTOR3 ) );
	}
	else
	{
		// The variable has an unknown type.
		m_type = VARIABLE_UNKNOWN;

		// Read and set the data (same as a string) for the variable.
		fscanf( file, "%s", buffer );
		m_data = new char[strlen( buffer ) + 1];
		strcpy( (char*)m_data, buffer );
	}
}
Exemple #23
0
void read_cycle() {
    static int dim;
    static double scale;
    static Bool init = False;
    double dummy1, dummy2;
    double meanx, meany, meanz;
    char c, s[4], *cp, *temp;
    int i, j, k;
    char line[MAX_STRING];
    Bool read_it = False;
    Bool done = False;
    int nbonds;
    fpos_t fpos;
    float dt;
    
    if (file_done) {
        return;
    }
    
    if (current_cycle < MAX_CYCLES) {
        fgetpos(fptr, &cycle_position[current_cycle++]);
    } else {
        moldyn_error("too many cycles");
    }
        
    for (k = 0; k < step; k++) {
        if (format == normal) {
            fgets(line, MAX_STRING, fptr);
            
            if (feof(fptr)) {
                file_done = True;
                if (read_it) {
                    break;
                }
                current_cycle--;
                return;
            } else if (*line == '#') {
                fgets(line, MAX_STRING, fptr);
            }
            
            if (sscanf(line, "%d %lg %lg %lg", &icycle, &dummy1, &energy, &dummy2) < 4) {
                moldyn_error("can't read cycle record");
            }
            read_it = True;
            
            num_atoms = 0;
        } else if (format == xyz) {
            fgets(line, MAX_STRING, fptr);
            if (feof(fptr)) {
                file_done = True;
                if (read_it)
                    break;
                current_cycle--;
                return;
            } else if (*line == '#') {
                fgets(line, MAX_STRING, fptr);
                sscanf(line, "%d", &num_atoms);
            } else {
                sscanf(line, "%d", &num_atoms);
            }
            fgets(title, MAX_STRING, fptr);
            strtok(title, "\n");
            
            read_it = True;
        } else {
            fgets(line, MAX_STRING, fptr);
            if (feof(fptr))
            {
                file_done = True;
                if (read_it) {
                    break;
                }
                current_cycle--;
                return;
            }
            else if (*line == '#')
                fgets(line, MAX_STRING, fptr);
            
            strcpy(title, line);
            strtok(title, "\n");
            if (!isalnum(*title))
                *title = '\0';
            
            fgets(line, MAX_STRING, fptr);
            sscanf(line, "%d", &num_atoms);
            
            if (feof(fptr)) {
                file_done = True;
                if (read_it) {
                    break;
                }
                return;
                
            }
            read_it = True;
        }
        
        if (format != normal) {
            if (num_atoms > max_atoms) {
                max_atoms = num_atoms;
                allocate_atom_memory();
            } else {
                max_atoms = num_atoms;
            }
        }
        
        for (i = 0; i < max_atoms; i++) {
            fgetpos(fptr, &fpos);
            
            fgets(line, MAX_STRING, fptr);
            if (feof(fptr)) {
                file_done = True;
                if (read_it) {
                    done = True;
                    break;
                }
                
                moldyn_error("missing data record");
                return;
            }
            
            if (format == normal) {
                atom_numbers[i] = atoi(strtok(line, SEPARATORS));
                temp = strtok(NULL, SEPARATORS);
                if (strchr(temp, '.') != NULL) {
                    fsetpos(fptr, &fpos);
                    break;
                }
                
                atom_numbers2[i] = atoi(temp);
                atom_positions[0+3*i] = atof(strtok(NULL, SEPARATORS));
                atom_positions[1+3*i] = atof(strtok(NULL, SEPARATORS));
                atom_positions[2+3*i] = atof(strtok(NULL, SEPARATORS));
                
                atom_colors[0+3*i] = element_colors[atom_numbers[i] - 1][0] / 255.0;
                atom_colors[1+3*i] = element_colors[atom_numbers[i] - 1][1] / 255.0;
                atom_colors[2+3*i] = element_colors[atom_numbers[i] - 1][2] / 255.0;
                
                num_atoms++;
            } else if (format == xyz) {
                cp = line;
                while (isspace(*cp)) {
                    cp++;
                }
                if (sscanf(cp, "%3s %g %g %g", s, &atom_positions[0+3*i], &atom_positions[1+3*i], &atom_positions[2+3*i]) != 4) {
                    moldyn_error("can't read data record");
                }
                c = s[0];
                atom_numbers[i] = atomname2atomnumber(s);
                atom_numbers2[i] = 1;
                atom_colors[0+3*i] = element_colors[atom_numbers[i] - 1][0] / 255.0;
                atom_colors[1+3*i] = element_colors[atom_numbers[i] - 1][1] / 255.0;
                atom_colors[2+3*i] = element_colors[atom_numbers[i] - 1][2] / 255.0;
                if (sscanf(cp, "%3s %g %g %g %g %g %g", s, &atom_positions[0+3*i], &atom_positions[1+3*i], &atom_positions[2+3*i], &atom_spins[0+3*i], &atom_spins[1+3*i], &atom_spins[2+3*i]) != 7) {
                    atom_spins[3*i] = 0;
                    atom_spins[3*i+1] = 0;
                    atom_spins[3*i+2] = 0;
                }
                
                strcpy(atom_names[i], s);
            } else {
                cp = line;
                while (isspace(*cp)) {
                    cp++;
                }
                if (sscanf(cp, "%d %g %g %g", &atom_numbers[i], &atom_positions[0+3*i], &atom_positions[1+3*i], &atom_positions[2+3*i]) != 4) {
                    moldyn_error("can't read data record");
                }
                atom_colors[0+3*i] = element_colors[atom_numbers[i] - 1][0] / 255.0;
                atom_colors[1+3*i] = element_colors[atom_numbers[i] - 1][1] / 255.0;
                atom_colors[2+3*i] = element_colors[atom_numbers[i] - 1][2] / 255.0;
                atom_numbers2[i] = 1;
            }
            atom_positions[2+3*i] = -atom_positions[2+3*i];
        }
        if (done) {
            break;
        }
    }
    
    if (!init) {
        init = True;
        energy0 = energy;
    }
    
    xmin = atom_positions[0+3*0];
    xmax = atom_positions[0+3*0];
    ymin = atom_positions[1+3*0];
    ymax = atom_positions[1+3*0];
    zmin = atom_positions[2+3*0];
    zmax = atom_positions[2+3*0];
    
    for (i = 0; i < num_atoms; i++) {
        if (atom_positions[0+3*i] < xmin)
            xmin = atom_positions[0+3*i];
        if (atom_positions[0+3*i] > xmax)
            xmax = atom_positions[0+3*i];
        if (atom_positions[1+3*i] < ymin)
            ymin = atom_positions[1+3*i];
        if (atom_positions[1+3*i] > ymax)
            ymax = atom_positions[1+3*i];
        if (atom_positions[2+3*i] < zmin)
            zmin = atom_positions[2+3*i];
        if (atom_positions[2+3*i] > zmax)
            zmax = atom_positions[2+3*i];
    }
    
    meanx = (xmin + xmax) / 2;
    meany = (ymin + ymax) / 2;
    meanz = (zmin + zmax) / 2;
    
    xmin -= meanx;
    xmax -= meanx;
    ymin -= meany;
    ymax -= meany;
    zmin -= meanz;
    zmax -= meanz;
    
    if (size > 0) {
        xmin = -size;
        xmax = size;
        ymin = -size;
        ymax = size;
        zmin = -size;
        zmax = size;
    }
    
    dim = 3;
    if (xmax == xmin || ymax == ymin || zmax == zmin) {
        dim--;
    }
    scale = (xmax - xmin + ymax - ymin + zmax - zmin) / dim;
    while (scale < (zmax - zmin) / 2) {
        scale = scale * 1.5;
    }
    dist = 3 * scale;
    sscale = 1 / scale;
    
    if (delta <= 0) {
        if (bonds && delta < 0) {
            delta = 0;
            for (j = 1; j < num_atoms; j++) {
                i = j - 1;
                delta += sqrt((atom_positions[0+3*i] - atom_positions[0+3*j]) * (atom_positions[0+3*i] - atom_positions[0+3*j]) +
                              (atom_positions[1+3*i] - atom_positions[1+3*j]) * (atom_positions[1+3*i] - atom_positions[1+3*j]) +
                              (atom_positions[2+3*i] - atom_positions[2+3*j]) * (atom_positions[2+3*i] - atom_positions[2+3*j]));
            }
            
            delta = 1.125 * delta / (num_atoms - 1);
        } else {
            delta = 2.25 * scale / sqrt((double) num_atoms);
        }
        
        while (bonds) {
            nbonds = 0;
            for (i = 0; i < num_atoms; i++)
                for (j = i + 1; j < num_atoms; j++)
                    if (sqrt((atom_positions[0+3*i] - atom_positions[0+3*j]) * (atom_positions[0+3*i] - atom_positions[0+3*j]) +
                             (atom_positions[1+3*i] - atom_positions[1+3*j]) * (atom_positions[1+3*i] - atom_positions[1+3*j]) +
                             (atom_positions[2+3*i] - atom_positions[2+3*j]) * (atom_positions[2+3*i] - atom_positions[2+3*j])) < delta)
                        nbonds++;
            
            if (nbonds > 3 * num_atoms) {
                delta *= 0.75;
            } else {
                break;
            }
        }
    }
    
    if (radius == 0) {
        radius = 0.15 * scale / ((num_atoms > 3) ? log(0.5 * num_atoms) : 1);
        while (radius > 0.25 * delta) {
            radius *= 0.75;
        }
    }
    cyl_rad = 0.15 * radius;
    
    if (autoscale) {
        xmin = global_xmin;
        xmax = global_xmax;
        ymin = global_ymin;
        ymax = global_ymax;
        zmin = global_zmin;
        zmax = global_zmax;
        
        meanx = global_meanx;
        meany = global_meany;
        meanz = global_meanz;
    }
    
    if (size <= 0) {
        double rmax;
        rmax = 0;
        for (i = 0; i < 8; i++)
            if (radius * element_radii[i] > rmax)
                rmax = radius * element_radii[i];
        
        xmin -= rmax;
        xmax += rmax;
        ymin -= rmax;
        ymax += rmax;
        zmin -= rmax;
        zmax += rmax;
    }
    
    for (i = 0; i < num_atoms; i++) {
        atom_positions[0+3*i] -= meanx;
        atom_positions[1+3*i] -= meany;
        atom_positions[2+3*i] -= meanz;
        atom_radii[i] = atom_numbers[i] > 0 ? radius * element_radii[atom_numbers[i] - 1] : 0;
    }
    if (atom_adjacency_matrix != NULL)
    {
        double del = delta * delta;
        double tol = tolerance * tolerance;
        
        if (tolerance > 0) {
            for (i = 0; i < num_atoms; i++) {
                for (j = i; j < num_atoms; j++) {
                    dt = fabs((atom_positions[0+3*i] - atom_positions[0+3*j]) * (atom_positions[0+3*i] - atom_positions[0+3*j]) +
                              (atom_positions[1+3*i] - atom_positions[1+3*j]) * (atom_positions[1+3*i] - atom_positions[1+3*j]) +
                              (atom_positions[2+3*i] - atom_positions[2+3*j]) * (atom_positions[2+3*i] - atom_positions[2+3*j]) - del);
                    atom_adjacency_matrix[i * num_atoms + j] = atom_adjacency_matrix[j * num_atoms + i] =
                    ((dt - del) < tol) || (atom_numbers2[i] < 0 && atom_numbers2[j] < 0) ? True : False;
                }
            }
        } else if (!chain) {
            for (i = 0; i < num_atoms; i++) {
                for (j = i; j < num_atoms; j++) {
                    dt = (atom_positions[0+3*i] - atom_positions[0+3*j]) * (atom_positions[0+3*i] - atom_positions[0+3*j]) +
                    (atom_positions[1+3*i] - atom_positions[1+3*j]) * (atom_positions[1+3*i] - atom_positions[1+3*j]) +
                    (atom_positions[2+3*i] - atom_positions[2+3*j]) * (atom_positions[2+3*i] - atom_positions[2+3*j]);
                    atom_adjacency_matrix[i * num_atoms + j] = atom_adjacency_matrix[j * num_atoms + i] =
                    (dt < del) || (atom_numbers2[i] < 0 && atom_numbers2[j] < 0) ? True : False;
                }
            }
        } else {
            for (i = 0; i < num_atoms; i++) {
                for (j = i; j < num_atoms; j++) {
                    atom_adjacency_matrix[i * num_atoms + j] = atom_adjacency_matrix[j * num_atoms + i] = (j == i + 1) ? True : False;
                }
            }
        }
    }
    return;
}
Exemple #24
0
void
epi_init_agent(void)
{
    FILE		*g;
    FILE		*f;
    fpos_t		 pos;

    tw_memory	*b;
    tw_memory	*next;

    epi_agent	*a;

    int		*home_to_ct;
    int		 nagents = 0;
    int		 nlp = -1;
    int		 i;
    int		 j;
    int		 h;
    int		 o;
    int		 t;

    printf("\nEPI Agent Initialization: \n\n");

    home_to_ct = tw_calloc(TW_LOC, "home to ct", sizeof(*home_to_ct), 3363607);
    // create census tract table, hard-coded to 2214 (all CT) for Chicago
    g_epi_nregions = 2215;
    g_epi_regions = tw_calloc(TW_LOC, "", sizeof(unsigned int *), g_epi_nregions);

    // need to read in homes.dat to get CT ids
    if(NULL == (g = fopen("homes.dat", "r")))
        tw_error(TW_LOC, "Unable to open: homes.dat");

    i = 0;
    while(EOF != (fscanf(g, "%d", &home_to_ct[i++])))
        ;

    for(i = 0; i < g_epi_nregions; i++)
    {
        g_epi_regions[i] = tw_calloc(TW_LOC, "", sizeof(unsigned int *), g_epi_ndiseases);

        for(j = 0; j < g_epi_ndiseases; j++)
            g_epi_regions[i][j] = tw_calloc(TW_LOC, "", sizeof(unsigned int),
                                            g_epi_diseases[j].nstages);
    }

    if(NULL == (f = fopen("agents.dat", "r")))
        tw_error(TW_LOC, "Unable to open: agents.dat");

    i = 0;

    if(!g_epi_nagents)
    {
        fgetpos(f, &pos);
        while(EOF != fscanf(f, "%d %d %*d", &h, &o))
            g_epi_nagents++;
        fsetpos(f, &pos);
    }

    if(0 == g_epi_nagents)
        tw_error(TW_LOC, "No agents in agents.dat!");

    g_epi_agents = tw_calloc(TW_LOC, "", sizeof(tw_memoryq), 1);
    g_epi_agents->start_size = g_epi_nagents;
    g_epi_agents->d_size = sizeof(epi_agent);
    g_epi_agents->grow = 1;

    tw_memory_allocate(g_epi_agents);

    b = g_epi_agents->head;
    while(EOF != (fscanf(f, "%d %d %d", &h, &o, &t)))
    {
        // allocate the agent
        a = tw_memory_data(b);
        a->id = nagents++;

        if(h && h > nlp)
            nlp = h;

        if(o != -1 && o > nlp)
            nlp = o;

        // the CT id is stored on the h-th line of the homes.dat file
        a->region = home_to_ct[h];

        if(a->region > 2214)
            tw_error(TW_LOC, "Bad Home to CT Mapping!");

        a->pathogens = NULL;

#if 0
        // default disease stats
        a->stage = EPI_SUSCEPTIBLE;
        a->ts_stage_tran = DBL_MAX;
#endif

        a->curr = 0;
        //a->ts_last_tran = 0.0;

        // go to work at 9am on first day
        a->ts_next = a->ts_remove = (double) 32400.0;
        //a->n_infected = 0;

        if(-1 != o)
            a->nloc = 3;
        else
            a->nloc = 2;

        // only two locs =(
        a->loc[1] = o;
        a->loc[0] = a->loc[a->nloc-1] = h;

        a->dur[0] = 9 * 3600;
        a->dur[1] = 8 * 3600;
        a->dur[a->nloc-1] += 7 * 3600;

        a->behavior_flags = 0;
        a->ts_remove = a->ts_next = a->dur[a->curr];

        for(i = 0; i < g_epi_ndiseases; i++)
            g_epi_regions[a->region][i][0]++;

        if(g_epi_nagents == nagents)
            break;

        b = b->next;
    }

    if(nlp == 0)
        tw_error(TW_LOC, "No locations!");
    else
        printf("\t%-48s %11d\n", "Max Location", ++nlp);

    g_epi_pq = tw_calloc(TW_LOC, "", sizeof(void *), nlp);

    for(i = 0; i < nlp; i++)
        g_epi_pq[i] = pq_create();

    for(b = g_epi_agents->head; b; b = next)
    {
        a = tw_memory_data(b);
        next = b->next;
        pq_enqueue(g_epi_pq[a->loc[0]], b);
    }

    g_tw_nlp = nlp;

}
Exemple #25
0
int read_ctrees(char * filename, struct treeData ** galacticusTrees, int * nOutputTrees,
		struct nodeData*** nodeArray, int * totalNodes) {
  /*  */
  /* open the file obtained from consistent_trees */
  FILE * file;
  file=fopen(filename,"r");
  if(file==0) {
    printf("Could not find file %s\n", filename);
    return 1;
  }

  /* make a struct for the tree, as read in from the ctrees output  */
  /* this is necessary, as ctrees outputs a seperated tree for each */
  /* subhalo. Galacticus expects the subhalos to be within the tree */
  /* of their parent halo. */
  struct inputTreeData {
    int id;
    int nNodes;
    int mainNodeId;
    int parentId;
    int upId;
    int upmostId;
    int gTreeIndex;	/* index of the corresponding galacticus tree */
    int gNodeIndex;	/* nodeIndex within the corresponding galacticus tree */
    fpos_t startPos;
    fpos_t endPos;
  };

  /* get the number of data fields */
  /* for information purposes only */
  char line[800];
  int nfields=0;
  int i=0;
  while((line[i] = fgetc(file))!='\n') {
    i++;
  }
  strtok(line, " ");
  nfields=1;
  while(strtok(NULL," ")) {
    nfields++;
  }
  printf("%s has %i fields\n",filename,nfields);

  /* go to the beginning of the data section */
  /* ATTENTION! This may change with future  */
  /* versions of consistent_trees */
  skipline(file,24);

  /* get the number of trees in the ctrees output file */
  /* as subhalos have their own trees, this number     */
  /* will not correspond to the number of trees in the */
  /* galacticus input file */
  int nTreesInput;

  fscanf(file,"%i\n",&nTreesInput);

  printf("%s contains %i trees\n",filename,nTreesInput);


  /* fill struct inputTreeData with the data from the input file */
  struct inputTreeData cTrees[nTreesInput];
  for(i=0; i<nTreesInput; i++) {
    cTrees[i].id=i;
    fscanf(file,"%*s %i\n",&cTrees[i].mainNodeId);
    fgetpos(file,&cTrees[i].startPos);
    fscanf(file,"%*f %*i %*f %*i %*i %i %i", &cTrees[i].parentId, &cTrees[i].upId);
    fsetpos(file, &cTrees[i].startPos);
    cTrees[i].nNodes = countNodes(file);
    fgetpos(file,&cTrees[i].endPos);
  }

    int nTrees;
  nTrees = 0;
  /* get the number of trees (without subhalo trees) */
  for(i=0; i<nTreesInput; i++) {
    if(cTrees[i].parentId==-1)
      nTrees++;
  }
  printf("%s contains %i distinct trees\n", filename,nTrees);

  /* make the array of galacticus trees */
  (*galacticusTrees) = malloc(nTrees*sizeof(struct treeData));

  if((*galacticusTrees)==NULL){
    fprintf(stdout, "Problem with the allocation\n");
    exit(1);
}

  /* give the galacticus trees an id */
  for(i=0; i<nTrees; i++) {
    (*galacticusTrees)[i].id=i;
  }

  /* fill the galacticus tree struct     */
  /* with the non-subhalo tree data from */
  /* the input file */
  int j=0;
  for(i=0; i<nTreesInput; i++) {
    if(cTrees[i].parentId==-1) { /* true if cTree is a non subhalo tree */
      (*galacticusTrees)[j].mainNodeId=cTrees[i].mainNodeId;
      (*galacticusTrees)[j].nNodes=cTrees[i].nNodes;
      cTrees[i].gTreeIndex=j;
      cTrees[i].gNodeIndex=0;
      j++;
    }
  }


  for(i=0; i<nTreesInput;i++) {
    cTrees[i].upmostId=cTrees[i].upId;
  }
  /* Get upmost Id, because a subhalo can have an upId         */
  /* which is not a distinct halo if the subhalo lies out      */
  /* of the virial radius of the host halo of the upId halo    */
  /* therefore make a loop to determine the really upmost halo */
  /* attention, several levels might be necessary              */

  int levels;
  int n_changed;
  int top_found;
  n_changed=0;
  for(levels=0; levels<4; levels++) {

    for(i=0; i<nTreesInput; i++) {
    top_found =0;
#ifdef PATCH
      if(cTrees[i].upmostId!=-1) {
#else
      if(cTrees[i].upId!=-1) {
#endif
	for(j=0; j<nTreesInput; j++) {
	  if(cTrees[i].upId==cTrees[j].mainNodeId) {
	    top_found=1;
	    if(cTrees[j].upId!=-1) {
	      cTrees[i].upmostId=cTrees[j].upId;
	      n_changed++;
	    }
	  }
	}
      
#ifdef PATCH
      if(top_found==0){
	fprintf(stderr, "upmostId for itree %i not found\n",i);
	exit(1);
      }
#endif
      }
    }

      
  }

    fprintf(stdout, "FInished the upmost ID calculation: %d changes\n",n_changed);


  /* correct the nNodes field for subhalo trees belonging */
  /* to this galacticus tree */
  for(j=0; j<nTrees; j++) {
    for(i=0; i<nTreesInput; i++) {
      if(cTrees[i].upmostId==(*galacticusTrees)[j].mainNodeId) {
	cTrees[i].gNodeIndex=(*galacticusTrees)[j].nNodes;
	(*galacticusTrees)[j].nNodes+=cTrees[i].nNodes;
      }
    }
  }
  fprintf(stdout, "Fnished correction 1\n");
  /* set the galacticus tree index in the inputTreeData struct */
  for(i=0; i<nTreesInput; i++) {
    if(cTrees[i].parentId!=-1) { /* true if tree is a subhalo tree */
      for(j=0; j<nTrees; j++) {
	if((*galacticusTrees)[j].mainNodeId==cTrees[i].upmostId)
	  cTrees[i].gTreeIndex=j;
      }
    }

  }
  fprintf(stdout, "Fnished correction 2\n");

  /* set the first node field for the galacticus tree data */
  /* needed, for galacticus to know, where a tree starts   */
  /* in the node data array */
  (*galacticusTrees)[0].firstNode=0;
  for(i=1; i<nTrees; i++) {
    (*galacticusTrees)[i].firstNode=(*galacticusTrees)[i-1].firstNode+(*galacticusTrees)[i-1].nNodes;
  }
  fprintf(stdout, "Fnished correction 3\n");

  /* allocate the memory for the node array */
  /* the node array has two dimensions, the */
  /* first for each tree, the second for    */
  /* the nodes within a tree */
  (*nodeArray) = (struct nodeData**)malloc(sizeof(struct nodeData *)*nTrees);
  if((*nodeArray)==NULL){
    fprintf(stderr,"Problem with node alllocation\n");
    exit(1);
  }
  for(i=0;i<nTrees;i++) {
    (*nodeArray)[i] = (struct nodeData*)malloc(sizeof(struct nodeData)*(*galacticusTrees)[i].nNodes);
    if((*nodeArray)[i]==NULL){
      fprintf(stdout, "Problem with the nodeArray allocation (%i nodes)\n", (*galacticusTrees)[i].nNodes);
      exit(1);
    }
  }
  fprintf(stdout, "Fnished allocation 3\n");
  /* fill the node array */
  for(i=0;i<nTreesInput;i++) {   /* loop over the input trees */
    /*
    fprintf(stdout, "%i %i [%i,%i]\n", i, cTrees[i].nNodes, 
	    cTrees[i].gTreeIndex, cTrees[i].gNodeIndex);
    */
    fsetpos(file,&cTrees[i].startPos); /* set file pointer to the start of tree i */
    for(j=0;j<cTrees[i].nNodes;j++) { /* loop over the node in each input tree */
      //      fprintf(stdout,"%i %i %f\n",j,cTrees[i].nNodes,&(*nodeArray)[cTrees[i].gTreeIndex][cTrees[i].gNodeIndex+j].scale);
      fscanf(file,"%f",&(*nodeArray)[cTrees[i].gTreeIndex][cTrees[i].gNodeIndex+j].scale);
      fscanf(file,"%i",&(*nodeArray)[cTrees[i].gTreeIndex][cTrees[i].gNodeIndex+j].id);
      fscanf(file,"%f",&(*nodeArray)[cTrees[i].gTreeIndex][cTrees[i].gNodeIndex+j].desc_scale);
      fscanf(file,"%i",&(*nodeArray)[cTrees[i].gTreeIndex][cTrees[i].gNodeIndex+j].desc_id);
      fscanf(file,"%i",&(*nodeArray)[cTrees[i].gTreeIndex][cTrees[i].gNodeIndex+j].num_prog);
      fscanf(file,"%i",&(*nodeArray)[cTrees[i].gTreeIndex][cTrees[i].gNodeIndex+j].pid);
      fscanf(file,"%i",&(*nodeArray)[cTrees[i].gTreeIndex][cTrees[i].gNodeIndex+j].upid);
      fscanf(file,"%i",&(*nodeArray)[cTrees[i].gTreeIndex][cTrees[i].gNodeIndex+j].desc_pid);
      fscanf(file,"%i",&(*nodeArray)[cTrees[i].gTreeIndex][cTrees[i].gNodeIndex+j].phantom);
      fscanf(file,"%f",&(*nodeArray)[cTrees[i].gTreeIndex][cTrees[i].gNodeIndex+j].mVir);
      fscanf(file,"%f",&(*nodeArray)[cTrees[i].gTreeIndex][cTrees[i].gNodeIndex+j].mVirOrig);
      fscanf(file,"%f",&(*nodeArray)[cTrees[i].gTreeIndex][cTrees[i].gNodeIndex+j].rVir);
      fscanf(file,"%f",&(*nodeArray)[cTrees[i].gTreeIndex][cTrees[i].gNodeIndex+j].scaleRadius);
      fscanf(file,"%f",&(*nodeArray)[cTrees[i].gTreeIndex][cTrees[i].gNodeIndex+j].vRMS);
      fscanf(file,"%i",&(*nodeArray)[cTrees[i].gTreeIndex][cTrees[i].gNodeIndex+j].mmp);
      fscanf(file,"%f",&(*nodeArray)[cTrees[i].gTreeIndex][cTrees[i].gNodeIndex+j].scaleLastMM);
      fscanf(file,"%f",&(*nodeArray)[cTrees[i].gTreeIndex][cTrees[i].gNodeIndex+j].vMax);
      fscanf(file,"%f",&(*nodeArray)[cTrees[i].gTreeIndex][cTrees[i].gNodeIndex+j].pos[0]);
      fscanf(file,"%f",&(*nodeArray)[cTrees[i].gTreeIndex][cTrees[i].gNodeIndex+j].pos[1]);
      fscanf(file,"%f",&(*nodeArray)[cTrees[i].gTreeIndex][cTrees[i].gNodeIndex+j].pos[2]);
      fscanf(file,"%f",&(*nodeArray)[cTrees[i].gTreeIndex][cTrees[i].gNodeIndex+j].v[0]);
      fscanf(file,"%f",&(*nodeArray)[cTrees[i].gTreeIndex][cTrees[i].gNodeIndex+j].v[1]);
      fscanf(file,"%f",&(*nodeArray)[cTrees[i].gTreeIndex][cTrees[i].gNodeIndex+j].v[2]);
      fscanf(file,"%f",&(*nodeArray)[cTrees[i].gTreeIndex][cTrees[i].gNodeIndex+j].l[0]);
      fscanf(file,"%f",&(*nodeArray)[cTrees[i].gTreeIndex][cTrees[i].gNodeIndex+j].l[1]);
      fscanf(file,"%f",&(*nodeArray)[cTrees[i].gTreeIndex][cTrees[i].gNodeIndex+j].l[2]);
      fscanf(file,"%f",&(*nodeArray)[cTrees[i].gTreeIndex][cTrees[i].gNodeIndex+j].spin);
      fscanf(file,"\n");
    }
  }

  fclose(file);
  /* set nOutputTrees and totalNodes */
  /* which are needed, so, that the  */
  /* other functions know about the  */
  /* length of the arrays */
  *nOutputTrees = nTrees;
  *totalNodes = 0;
  for(i=0;i<nTrees;i++) {
    *totalNodes += (*galacticusTrees)[i].nNodes;
  }
  printf("%s contains %i nodes\n",filename,*totalNodes);


#ifdef PATCH
  fprintf(stdout, "started the new ID\n");
  /*calculate the parent ID to be the corresponding most up ID*/
  /*
  int l, m;
  for(i=0;i<nTrees;i++){
    for(j=0;j<(*galacticusTrees)[i].nNodes;j++){
      (*nodeArray)[i][j].pid = (*nodeArray)[i][j].upid;
    }
  }
  
  fprintf(stdout, "started the new ID for subs\n");
  for(i=0;i<nTrees;i++){
    for(j=0;j<(*galacticusTrees)[i].nNodes;j++){

      if((*nodeArray)[i][j].pid!=-1){
	levels = 0;
	do{
	  for(l=0;l<nTrees;l++){
	    for(m=0;m<(*galacticusTrees)[l].nNodes;m++){
	      if((*nodeArray)[i][j].pid==(*nodeArray)[l][m].id){		
		(*nodeArray)[i][j].pid = (*nodeArray)[l][m].upid;
		if((*nodeArray)[l][m].upid==-1){
		  levels = 5;
		}
	      }
	    }
	  }
	  levels++;
	}while(levels<4);
	if(levels!=6){
	  fprintf(stdout, "the host wast not found for tree %i node %i (%i)levels %i\n", 
		  i, j, (*nodeArray)[i][j].pid, levels);
	  exit(1);
	}
      }
    }
  }
  */  
#endif

#ifdef PATCH
  int search;
  int found;
  int l;
  int notfound;
  notfound=0;
  for(i=0;i<nTrees;i++){
    for(j=0;j<(*galacticusTrees)[i].nNodes;j++){
      search = (*nodeArray)[i][j].pid;
      if(search!=-1){

	found = 0;
	l = 0;
	do{
	  if((*nodeArray)[i][l].id==search)
	    found = 1;
	  l++;
	}while(!found && l<(*galacticusTrees)[i].nNodes);
	
	if(!found){
	  //	  fprintf(stderr, "Couldn't find pid %d for halo %d\n", search, (*nodeArray)[i][j].id);
	  (*nodeArray)[i][j].pid = -1;
	  notfound++;
	}	      
      }
    }
  }
  fprintf(stdout, "The number of not found parent ids %d\n", notfound);
  
 notfound=0;
  for(i=0;i<nTrees;i++){
    for(j=0;j<(*galacticusTrees)[i].nNodes;j++){
      search = (*nodeArray)[i][j].desc_id;
      if(search!=-1){

	found = 0;
	l = 0;
	do{
	  if((*nodeArray)[i][l].id==search)
	    found = 1;
	  l++;
	}while(!found && l<(*galacticusTrees)[i].nNodes);
	
	if(!found){
	  //	  fprintf(stderr, "Couldn't find pid %d for halo %d\n", search, (*nodeArray)[i][j].id);
	  (*nodeArray)[i][j].desc_id = -1;
	  notfound++;
	  fprintf(stdout, "Not found desc in tree %i - node %i out of %i\n", 
		  i, j,(*galacticusTrees)[i].nNodes);
	}	      
      }
    }
  }
  fprintf(stdout, "The number of not found desc ids %d\n", notfound);
  
#endif

  for(i=0;i<nTrees;i++) {
    for(j=0;j<(*galacticusTrees)[i].nNodes;j++) {
      /* if host node has no parent node, consistent_trees sets parent id field to -1  */
      /* galacticus, in such a case expects parent id field to be equal to the node id */
      if((*nodeArray)[i][j].pid==-1) {
	(*nodeArray)[i][j].pid=(*nodeArray)[i][j].id;
      }
    }
  }



  return 0;

}
Exemple #26
0
bool
play_pcm_file (playable_pcm_file_t *file)
{
  int                 status;
  snd_pcm_t          *handle;
  snd_pcm_format_t    format;
  snd_pcm_sframes_t   frames_wrote;
  uint8_t             playback_buf[BUFSIZ];
  int                 frames_count;
  size_t              read_bytes;


  format = determine_pcm_format (&(file->info));
  if (format == SND_PCM_FORMAT_UNKNOWN)
    {
      fprintf (stderr, "%s: Unable to determine the beep's PCM data format.\n",
               progname);

      return false;
    }

  if (fsetpos (file->stream, &(file->pcm_start_pos)) != 0)
    {
      fprintf (stderr, "%s: Failed to seek to the PCM data of `%s': %s.\n",
               progname, file->name, strerror (errno));

      return false;
    }

  status = snd_pcm_open (&handle, "default", SND_PCM_STREAM_PLAYBACK, 0);
  if (status < 0)
    {
      fprintf (stderr, "%s: Failed to open the playback device: %s\n",
               progname, snd_strerror (status));

      return false;
    }

  status = snd_pcm_set_params (handle, format, SND_PCM_ACCESS_RW_INTERLEAVED,
                               file->info.channels, file->info.sample_rate,
                               1,          /* soft_resample */
                               0);         /* latency (us).*/
  if (status < 0)
    {
      fprintf (stderr, "%s: Failed to configure the playback device: %s.\n",
               progname, snd_strerror (status));

      snd_pcm_close (handle);
      return false;
    }

  while (true)
    {
      read_bytes = fread (playback_buf, 1, BUFSIZ, file->stream);
      if (read_bytes == 0)
        {
          if (ferror (file->stream))
            {
              fprintf (stderr, "%s: An error occured while reading from `%s': %s.\n",
                       progname, file->name, strerror (errno));

              snd_pcm_close (handle);
              return false;
            }

          break;
        }
      frames_count = snd_pcm_bytes_to_frames (handle, read_bytes);
      frames_wrote = snd_pcm_writei (handle, playback_buf, frames_count);
      if (frames_wrote < 0)
        frames_wrote = snd_pcm_recover (handle, frames_wrote, 0);

      if (frames_wrote < 0)
        {
          fprintf (stderr, "%s: Writing to the playback device failed: %s.\n",
                   progname, snd_strerror (frames_wrote));

          snd_pcm_close (handle);
          return false;
        }

      if (frames_wrote > 0 && frames_wrote < frames_count)
        {
          fprintf (stderr, "%s: Warning: Wrote only %ld frames instead of the "
                   "expected %d to the playback device.\n",
                   progname, frames_wrote, frames_count);
        }
    }

  snd_pcm_drain (handle);
  snd_pcm_close (handle);

  return true;
}
//
//	Declaration:
//	bool CBinaryDataFile::ReadEvtHeader(const CString &strNameWithPath, CString *pstrErrorMsg)
//
//	Input:	strNameWithPath		filename with full path that is to be opened
//			
//	Output:	pstrErrorMsg	error, if any
//
//			mdVersionNumber		version number read from header
//			msStaNum			station number read from header
//			miYr				year read from header
//			miMon				month read from header
//			miDay				day read from header
//			mulTimestampOfFirstRecordInFile		julian time of first record in the file
//
//	Return:	true (header read) / false (some kind of error, see pstrErroMsg)
//	
//  date    /	author	revision
//  -----------------	--------
//	17-Oct-2002	SFK		Created from ReadBIDHeader in GrandDataFile.cpp in GRAND COM
//	21-Jun-2005 SFK		Pick up station number from first record rather than getting it
//						out of the header due to a problem in MIC 1.9.0.7
//////////////////////////////////////////////////////////////////
bool CBinaryDataFile::ReadEvtHeader(const CString &strNameWithPath, CString *pstrErrorMsg)
{
    int iHdrSize;
    char str[54];
	struct BinaryEventFileRec Rec;
	struct OpCode OpRec;
	fpos_t pos;
	CMyDateTime MyDate;

   /* ------------------------------------------------------------------
    *	Open the file
    * ----------------------------------------------------------------*/
	if (!OpenDataFile(strNameWithPath, pstrErrorMsg)) return(false);

	// generate an error message in case we get an error in any of the reads,
	// will clear at end of function if all okay
	if (pstrErrorMsg) {
		miErrorNum = iFILE_READ_ERR;
		pstrErrorMsg->Format("\nError: Unexpected error reading header for file %s", strNameWithPath);
	}
	
   /* ------------------------------------------------------------------
    *	Read the first 4 bytes to get the number of bytes in header.
    *	Based on the location of the number, determine whether the data
    *	file is from CDMPC or LANL GRAND Collect.  The CDMPC number
    *	must be decremented by 1.
    * ----------------------------------------------------------------*/
    if (fread(str, 4, 1, mpFile) != 1) return(false);
    str[4] = '\0';    
    iHdrSize = atoi(str);
    if (str[3] == ' ') iHdrSize = iHdrSize - 1; // this file formed by CDMPC
	if (iHdrSize <= 22) return(false);

   /* ------------------------------------------------------------------
    *	The next 5 bytes no longer contain useful information,	just
    *	skip by them.
    * ----------------------------------------------------------------*/
    if (fread(str, 5, 1, mpFile) != 1) return(false);
       
   /* ------------------------------------------------------------------
    *	Read past the version number in the next 5 bytes.
    * ----------------------------------------------------------------*/
    if (fread(str, 5, 1, mpFile) != 1) return(false);
	str[5] = '\0';
	mdVersionNumber = atof(str);

   /* ------------------------------------------------------------------
    *  Read station of logging node and put it in return variable.
    * ----------------------------------------------------------------*/
    if (fread(str, 3, 1, mpFile) != 1) return(false);
    str[3] = '\0';
    msStaNum = atoi(str);
//	msStaNum += 1000;

   /* ------------------------------------------------------------------
    *	Read year and put it in return variable.
    * ----------------------------------------------------------------*/
    if (fread(str, 3, 1, mpFile) != 1) return(false);
    str[3] = '\0';
    miYr = atoi(str);
	//3-aug-2005 hn Added a four digit year.
	if (miYr < 86)
	{
		miYr4 = miYr + 2000;
	}
	else
	{
		miYr4 = miYr + 1900;
	}


   /* ------------------------------------------------------------------
    *	Read month and put it in return variable.
    * ----------------------------------------------------------------*/
    if (fread(str, 3, 1, mpFile) != 1) return(false);
    str[3] = '\0';
    miMon = atoi(str);
	if ((miMon < 1) || (miMon >12)) return(false);

   /* ------------------------------------------------------------------
    *	Read day and put it in return variable.
    * ----------------------------------------------------------------*/
    if (fread(str, 3, 1, mpFile) != 1) return(false);
    str[3] = '\0';
    miDay = atoi(str);
	if ((miDay < 1) || (miDay >31)) return(false);

	/* ------------------------------------------------------------------
    *	Read past the expansion space in the header so the file pointer
    *	is positioned at the beginning of the first data point at exit.
    * ----------------------------------------------------------------*/
    if (fread(str, (iHdrSize - 22), 1, mpFile)!= 1) return(false);
    
   /* ------------------------------------------------------------------
    *	Save the position of the file pointer.
	*	Read the first record in the file to get the time of it.  Will
	*	read the first record as if it is a binary record since we are
	*	only interested in the julian time in the record and that is in
	*	the same position in all types of records in an .evt/.bny file.
    *	Restore file pointer to just at the first record.
    * ----------------------------------------------------------------*/
	if(fgetpos(mpFile, &pos ) != 0) return(false);
	// 01-Sep-2005 SFK Fixed for reading old files that might have other types
	//					of records interspersed with binary records.
	bool bFoundBinaryRecord = false;
	do {
		if (fread(&OpRec, sizeof(struct OpCode), 1, mpFile) == 0) return(false);
		if ((OpRec.RecTypeA == '3') && (OpRec.RecTypeB == '2')) {
			if (fread(&Rec, sizeof(struct BinaryEventFileRec), 1, mpFile) == 0) return(false);
			msStaNum = Rec.usNode;		// 21-Jun-2005 SFK  Pick up station number from first record
			mdTimestampOfFirstRecordInFile = MyDate.MyTimestampToDATETimestamp((double)Rec.uiTime);
			if(fsetpos(mpFile, &pos ) != 0) return(false);
			bFoundBinaryRecord = true;
		}
		else {	// was not a binary record -- skip past the record
			fpos_t FilePosition;
			fgetpos(mpFile, &FilePosition);
			FilePosition += OpRec.sRecSize - 2;	// subtract the opcode bytes that you've already read
			fsetpos(mpFile, &FilePosition);
		}
	} while (!bFoundBinaryRecord);
               
	if (pstrErrorMsg) pstrErrorMsg->Empty();
	miErrorNum = 0;	// no error
    return(true);

}
Exemple #28
0
/** Write this table.
 *  @param wr the file writer
 *  @param td table data to be written
 *  @return -1 on error, or bytes written on success.
 */
int yytbl_data_fwrite (struct yytbl_writer *wr, struct yytbl_data *td)
{
    int  rv;
    flex_int32_t bwritten = 0;
    flex_int32_t i, total_len;
    fpos_t  pos;

    if ((rv = yytbl_write16 (wr, td->td_id)) < 0)
        return -1;
    bwritten += rv;

    if ((rv = yytbl_write16 (wr, td->td_flags)) < 0)
        return -1;
    bwritten += rv;

    if ((rv = yytbl_write32 (wr, td->td_hilen)) < 0)
        return -1;
    bwritten += rv;

    if ((rv = yytbl_write32 (wr, td->td_lolen)) < 0)
        return -1;
    bwritten += rv;

    total_len = yytbl_calc_total_len (td);
    for (i = 0; i < total_len; i++) {
        switch (YYTDFLAGS2BYTES (td->td_flags)) {
        case sizeof (flex_int8_t):
            rv = yytbl_write8 (wr, yytbl_data_geti (td, i));
            break;
        case sizeof (flex_int16_t):
            rv = yytbl_write16 (wr, yytbl_data_geti (td, i));
            break;
        case sizeof (flex_int32_t):
            rv = yytbl_write32 (wr, yytbl_data_geti (td, i));
            break;
        default:
            flex_die (_("invalid td_flags detected"));
        }
        if (rv < 0) {
            flex_die (_("error while writing tables"));
            return -1;
        }
        bwritten += rv;
    }

    /* Sanity check */
    if (bwritten != (int) (12 + total_len * YYTDFLAGS2BYTES (td->td_flags))) {
        flex_die (_("insanity detected"));
        return -1;
    }

    /* add padding */
    if ((rv = yytbl_write_pad64 (wr)) < 0) {
        flex_die (_("pad64 failed"));
        return -1;
    }
    bwritten += rv;

    /* Now go back and update the th_hsize member */
    if (fgetpos (wr->out, &pos) != 0
            || fsetpos (wr->out, &(wr->th_ssize_pos)) != 0
            || yytbl_write32 (wr, wr->total_written) < 0
            || fsetpos (wr->out, &pos)) {
        flex_die (_("get|set|fwrite32 failed"));
        return -1;
    }
    else
        /* Don't count the int we just wrote. */
        wr->total_written -= sizeof (flex_int32_t);
    return bwritten;
}
static
int
globus_l_job_manager_parse_events(
    globus_l_job_manager_logfile_state_t *      state)
{
    int                                 rc;
    int                                 protocol_msg_type;
    time_t                              stamp;
    char                                jobid[129];
    char                                nl[2];
    int                                 job_state;
    int                                 exit_code;
    struct tm                           gmstamp, *gmstampp;
    fpos_t                              pos;

    SEG_JOB_MANAGER_DEBUG(SEG_JOB_MANAGER_DEBUG_INFO,
            ("globus_l_job_manager_parse_events() called\n"));


    fgetpos(state->fp, &pos);
    while ((rc = fscanf(state->fp, "%d;%ld;%128[^;];%d;%d%1[\n]",
                    &protocol_msg_type,
                    &stamp,
                    jobid,
                    &job_state,
                    &exit_code,
                    nl)) > 4)
    {
        if (rc == 4 && fscanf(state->fp, "%1[\n]", nl) != 1)
        {
            goto bad_line;
        }

        if (protocol_msg_type != 1)
        {
            goto bad_line;
        }

        gmstampp = globus_libc_gmtime_r(&stamp, &gmstamp);

        if (globus_l_time_is_newer(&state->start_timestamp, &gmstamp))
        {
            /* Ignore events that occur before our start timestamp */
            goto bad_line;
        }

        switch(job_state)
        {
        case GLOBUS_GRAM_PROTOCOL_JOB_STATE_PENDING:
            globus_scheduler_event_pending(stamp, jobid);
            break;

        case GLOBUS_GRAM_PROTOCOL_JOB_STATE_ACTIVE:
            globus_scheduler_event_active(stamp, jobid);
            break;

        case GLOBUS_GRAM_PROTOCOL_JOB_STATE_DONE:
            globus_scheduler_event_done(stamp, jobid, exit_code);
            break;

        case GLOBUS_GRAM_PROTOCOL_JOB_STATE_FAILED:
            globus_scheduler_event_failed(stamp, jobid, exit_code);
            break;

        default:
            goto bad_line;
        }
bad_line:
        fgetpos(state->fp, &pos);
    }
    if (feof(state->fp))
    {
        clearerr(state->fp);
        rc = SEG_JOB_MANAGER_ERROR_LOG_EOF;
    }
    else
    {
        rc = 0;
    }
    fsetpos(state->fp, &pos);

    SEG_JOB_MANAGER_DEBUG(SEG_JOB_MANAGER_DEBUG_INFO,
            ("globus_l_job_manager_parse_events() exits\n"));
    return rc;
}
Exemple #30
0
int main(int argc, char** argv)
{
    char ifile[255];
    char ofile[255];
    /* clock_t start; */
    if(argc < 2)
	{
	    printf("%s", "Enter Text File Name: ");
	    scanf("%s",ifile);

	    printf("%s", "Enter save file name: ");
	    scanf("%s", ofile);
	}
    else
	{
	    strcpy(ifile, argv[1]);
	    strcpy(ofile, argv[2]);
	}

    /* create new file */
    spfile* fp = spfile_new(ifile);

    if(!fp)
	return 1;
    
    /* set out file name */
    spfile_set_outpath(fp, ofile);


    /* read file */
    spfile_read(fp);

    int rt_val = 0;
    if(!spfile_exe(fp))
	{
	    rt_val = 1;
	}

    /* delete spfile object */
    spfile_delete(&fp);

    /* printf("%s%f\n", "Exec time: ", */
    /* 	   ((double) clock() - start) / CLOCKS_PER_SEC); */
    
    /* char ch[2]; */
    /* printf("%s", "press any key: "); */
    /* scanf("%c", ch); */
    time_t st;
    time_t et;
    double t = 0.0;
    double l_t = 0.0;	/* last time */
    time(&st);
    char* buff = (char*) malloc(sizeof(double) * sizeof(char));
    fpos_t pos;	     	/* file position */

    /* get position */
    fgetpos(stdout, &pos);
    
    while(1)
	{
	    time(&et);
	    t = difftime(et, st);
	    if(t > 3)
		break;
	    else if(l_t != t)
		{
		    sprintf(buff, "%f", t);
		    fputs(buff, stdout);
		    fsetpos(stdout, &pos);
		}

	    l_t = t;
	}
    return rt_val;
}