Beispiel #1
0
void TranslDlg::OnCommand(wxCommandEvent& event)
{//=============================================
	#define N_PH_LIST  N_PHONEME_LIST

	void *vp;
	int translate_text = 0;
	char buf[1000];
	char phon_out[N_PH_LIST*2];
	int clause_tone;
	int clause_count;
	FILE *f;
	int  fd_temp;
	char fname_temp[100];
	static int n_ph_list;
	static PHONEME_LIST ph_list[N_PH_LIST+1];

	if(translator==NULL)
	{
		wxLogError(_T("Voice not set"));
		return;
	}

	option_phonemes = 0;

	switch(event.GetId())
	{
	case T_RULES:
	case MENU_SPEAK_RULES:
#ifdef PLATFORM_POSIX
		strcpy(fname_temp,"/tmp/espeakXXXXXX");
		if((fd_temp = mkstemp(fname_temp)) >= 0)
		{
			close(fd_temp);

			if((f = fopen(fname_temp,"w+")) != NULL)
			{
				f_trans = f;   // write translation rule trace to a temp file
			}
		}
#else
		strcpy(fname_temp,tmpnam(NULL));
		if((f = fopen(fname_temp,"w+")) != NULL)
		{
			f_trans = f;   // write translation rule trace to a temp file
		}
#endif
		t_phonetic->SetDefaultStyle(style_phonetic);
		translate_text = 2;
		break;

	case T_TRANSLATE:
	case MENU_SPEAK_TRANSLATE:
		t_phonetic->SetDefaultStyle(style_phonetic);
		translate_text = 1;
		break;

	case T_TRANSLATE_IPA:
	case MENU_SPEAK_IPA:
		t_phonetic->SetDefaultStyle(style_phonetic_large);

		translate_text = 3;
		break;

	case T_PROCESS:
	case MENU_SPEAK_TEXT:
		if(prosodycanvas == NULL)
		{
			myframe->OnProsody(event);
		}
		prosodycanvas->LayoutData(ph_list,n_ph_list);
		option_phoneme_events = 1;
		option_log_frames = 1;
		MakeWave2(ph_list,n_ph_list);
		option_log_frames = 0;
		break;
	}

	if(translate_text)
	{
		option_phonemes = translate_text;

		option_multibyte = espeakCHARS_AUTO;
		SpeakNextClause(NULL,NULL,2);  // stop speaking file

		strncpy0(buf,t_source->GetValue().mb_str(wxConvUTF8),sizeof(buf));
		phon_out[0] = 0;
		n_ph_list = 0;
		clause_count = 0;

		vp = buf;
		InitText(0);
		while((vp != NULL) && (n_ph_list < N_PH_LIST))
		{
			vp = TranslateClause(translator,NULL,vp,&clause_tone,NULL);
			CalcPitches(translator,clause_tone);
			CalcLengths(translator);

			GetTranslatedPhonemeString(translator->phon_out,sizeof(translator->phon_out));
			if(clause_count++ > 0)
				strcat(phon_out," ||");
			strcat(phon_out,translator->phon_out);
			t_phonetic->SetValue(wxString(translator->phon_out,wxConvUTF8));

			if((n_ph_list + n_phoneme_list) >= N_PH_LIST)
			{
				n_phoneme_list = N_PH_LIST - n_ph_list - n_phoneme_list;
			}

			memcpy(&ph_list[n_ph_list],phoneme_list,sizeof(PHONEME_LIST)*n_phoneme_list);
			n_ph_list += n_phoneme_list;
		}

		t_phonetic->Clear();
		if(option_phonemes == 2)
		{
			option_phonemes=0;
			rewind(f_trans);
			while(fgets(buf,sizeof(buf),f_trans) != NULL)
			{
				t_phonetic->AppendText(wxString(buf,wxConvUTF8));
			}
			t_phonetic->AppendText(_T("---\n"));
			if(f_trans != NULL)
				fclose(f_trans);
			remove(fname_temp);
		}
		t_phonetic->AppendText(wxString(phon_out,wxConvUTF8));
	}
}  // end of TranslDlg::OnCommand
Beispiel #2
0
/*
*	Reads a scoring matrix from the specified file.
*
*	File should be of the following format:
*
*	A	3	-2	-1	-2
*	C	-2	3	-2	-1
*	G	-1	-2	3	-2
*	T	-2	-1	-2	3
*
*	Returns the scoring matrix as a ScoringMatrix struct containting the scoring matrix,
*	a lookup table for indexing into the matrix, and a reverse lookup table for converting
*	the numerical index back to a char.
*/
ScoringMatrix* read_scoring_file(char* scoreFile)
{
	ScoringMatrix* scoring = malloc(sizeof(ScoringMatrix));
	scoring->numChars = 0;
	
	char line[256];
	char* temp;
	int lineLength;
	int numLines = 0;
	int i;
	int j;
	
	FILE* file = fopen(scoreFile, "r");
	
	if (fgets(line, 256, file) != NULL)
	{
		strtok(line, " 	\t\n");
		
		while (strtok(NULL, " 	\t\n") != NULL)
		{
			scoring->numChars++;
		}
	} else
	{
		printf("Unable to read from score file. Exiting.\n");
		exit(1);
	}
	
	rewind(file);
	
	scoring->matrix = malloc(sizeof(int) * (scoring->numChars) * (scoring->numChars));
	scoring->lookupTable = malloc( sizeof(char) * 128 );
	memset(scoring->lookupTable, -1, sizeof(char) * 128);
	
	// setup characters to ignore: space, tab, carriage return, and newline
	scoring->lookupTable[' '] = scoring->lookupTable['\t'] = scoring->lookupTable['\r'] = scoring->lookupTable['\n'] = -19;

	scoring->lookupTableReverse = malloc (sizeof(char) * (scoring->numChars));
	
	for (i = 0; i < scoring->numChars; i++)
	{
		fgets(line, 256, file);

		temp = strtok(line, " \t\n");

		j = 0;
		scoring->lookupTable[temp[0]] = i;
		scoring->lookupTable[temp[0] ^ 32 ] = i;
		
		scoring->lookupTableReverse[i] = temp[0];
		
		while (((temp = strtok(NULL, " \t\n")) != NULL) && j <= scoring->numChars)
		{
			scoring->matrix[ i * (scoring->numChars) + j++] = atoi(temp);
		}
	}

	fclose(file);

	return scoring;
}
Properties::Properties(Data* data, ssize_t* dataIdx)
    : _variables(NULL), _dirPath(NULL), _parent(NULL), _dataIdx(dataIdx), _data(data)
{
    readProperties();
    rewind();
}
/****************************************************************//**
Evaluate the given foreign key SQL statement.
@return	error code or DB_SUCCESS */
static
ulint
dict_foreign_eval_sql(
/*==================*/
	pars_info_t*	info,	/*!< in: info struct, or NULL */
	const char*	sql,	/*!< in: SQL string to evaluate */
	dict_table_t*	table,	/*!< in: table */
	dict_foreign_t*	foreign,/*!< in: foreign */
	trx_t*		trx)	/*!< in: transaction */
{
	ulint		error;
	FILE*		ef	= dict_foreign_err_file;

	error = que_eval_sql(info, sql, FALSE, trx);

	if (error == DB_DUPLICATE_KEY) {
		mutex_enter(&dict_foreign_err_mutex);
		rewind(ef);
		ut_print_timestamp(ef);
		fputs(" Error in foreign key constraint creation for table ",
		      ef);
		ut_print_name(ef, trx, TRUE, table->name);
		fputs(".\nA foreign key constraint of name ", ef);
		ut_print_name(ef, trx, TRUE, foreign->id);
		fputs("\nalready exists."
		      " (Note that internally InnoDB adds 'databasename'\n"
		      "in front of the user-defined constraint name.)\n"
		      "Note that InnoDB's FOREIGN KEY system tables store\n"
		      "constraint names as case-insensitive, with the\n"
		      "MySQL standard latin1_swedish_ci collation. If you\n"
		      "create tables or databases whose names differ only in\n"
		      "the character case, then collisions in constraint\n"
		      "names can occur. Workaround: name your constraints\n"
		      "explicitly with unique names.\n",
		      ef);

		mutex_exit(&dict_foreign_err_mutex);

		return(error);
	}

	if (error != DB_SUCCESS) {
		fprintf(stderr,
			"InnoDB: Foreign key constraint creation failed:\n"
			"InnoDB: internal error number %lu\n", (ulong) error);

		mutex_enter(&dict_foreign_err_mutex);
		ut_print_timestamp(ef);
		fputs(" Internal error in foreign key constraint creation"
		      " for table ", ef);
		ut_print_name(ef, trx, TRUE, table->name);
		fputs(".\n"
		      "See the MySQL .err log in the datadir"
		      " for more information.\n", ef);
		mutex_exit(&dict_foreign_err_mutex);

		return(error);
	}

	return(DB_SUCCESS);
}
Beispiel #5
0
int config_parser_t::read_config(char ***cv, FILE *f)
{
	*cv = (char **)calloc(MAX_CONFIG_LINES, sizeof(char *));
	if(!*cv)
		return -1;

	if(!f)
	{
		free((*cv));
		(*cv) = NULL;
		return -2;
	}

	fseek(f, 0, SEEK_END);
	int len = ftell(f);
	(*cv)[0] = (char *)malloc(len+1);
	if(!(*cv)[0])
	{
		rewind(f);
		free(*cv);
		*cv = NULL;
		return -3;
	}
	rewind(f);
	if(fread((*cv)[0], len, 1, f) < 0)
	{
		free(*cv[0]);
		free(*cv);
		*cv = NULL;
		return -4;
	}
	(*cv)[0][len] = 0;

	char *v = (*cv)[0];
	scanstate_t state = SS_BLANK;
	int arg = 1;
	int start_arg = 0;
	while(*v)
	{
		switch(state)
		{
		  case SS_BLANK:
			if(*v == '"')
			{
				start_arg = 1;
				state = SS_QUOTE;
			}
			else if(*v == '#')
				state = SS_COMMENT;
			else if(*v > ' ')
			{
				start_arg = 1;
				state = SS_WORD;
			}
			break;
		  case SS_QUOTE:
			if(*v == '"')
			{
				*v = 0;
				state = SS_BLANK;
			}
			break;
		  case SS_WORD:
			if(*v <= ' ')
			{
				*v = 0;
				state = SS_BLANK;
			}
			break;
		  case SS_COMMENT:
			if((*v == 10) || (*v == 13))
				state = SS_BLANK;
			break;
		}
		if(start_arg)
		{
			if(arg < MAX_CONFIG_LINES)
			{
				if(state == SS_QUOTE)
					(*cv)[arg++] = v+1;
				else
					(*cv)[arg++] = v;
			}
			start_arg = 0;
		}
		++v;
	}
	rewind(f);
	return arg;
}
Beispiel #6
0
int CFile::PImpl::open(const char *name, long openflags)
{
	char buf[512];
	const char *openstring;

	if ((openflags & CL_OPEN_READ) && (openflags & CL_OPEN_WRITE)) {
		openstring = "rwb";
	} else if (openflags & CL_OPEN_READ) {
		openstring = "rb";
	} else if (openflags & CL_OPEN_WRITE) {
		openstring = "wb";
	} else {
		DebugPrint("Bad CLopen flags");
		Assert(0);
		return -1;
	}

	cl_type = CLF_TYPE_INVALID;

	if (openflags & CL_OPEN_WRITE) {
#ifdef USE_BZ2LIB
		if ((openflags & CL_WRITE_BZ2)
			&& (cl_bz = BZ2_bzopen(strcat(strcpy(buf, name), ".bz2"), openstring))) {
			cl_type = CLF_TYPE_BZIP2;
		} else
#endif
#ifdef USE_ZLIB
			if ((openflags & CL_WRITE_GZ)
				&& (cl_gz = gzopen(strcat(strcpy(buf, name), ".gz"), openstring))) {
				cl_type = CLF_TYPE_GZIP;
			} else
#endif
				if ((cl_plain = fopen(name, openstring))) {
					cl_type = CLF_TYPE_PLAIN;
				}
	} else {
		if (!(cl_plain = fopen(name, openstring))) { // try plain first
#ifdef USE_ZLIB
			if ((cl_gz = gzopen(strcat(strcpy(buf, name), ".gz"), "rb"))) {
				cl_type = CLF_TYPE_GZIP;
			} else
#endif
#ifdef USE_BZ2LIB
				if ((cl_bz = BZ2_bzopen(strcat(strcpy(buf, name), ".bz2"), "rb"))) {
					cl_type = CLF_TYPE_BZIP2;
				} else
#endif
				{ }

		} else {
			cl_type = CLF_TYPE_PLAIN;
			// Hmm, plain worked, but nevertheless the file may be compressed!
			if (fread(buf, 2, 1, cl_plain) == 1) {
#ifdef USE_BZ2LIB
				if (buf[0] == 'B' && buf[1] == 'Z') {
					fclose(cl_plain);
					if ((cl_bz = BZ2_bzopen(name, "rb"))) {
						cl_type = CLF_TYPE_BZIP2;
					} else {
						if (!(cl_plain = fopen(name, "rb"))) {
							cl_type = CLF_TYPE_INVALID;
						}
					}
				}
#endif // USE_BZ2LIB
#ifdef USE_ZLIB
				if (buf[0] == 0x1f) { // don't check for buf[1] == 0x8b, so that old compress also works!
					fclose(cl_plain);
					if ((cl_gz = gzopen(name, "rb"))) {
						cl_type = CLF_TYPE_GZIP;
					} else {
						if (!(cl_plain = fopen(name, "rb"))) {
							cl_type = CLF_TYPE_INVALID;
						}
					}
				}
#endif // USE_ZLIB
			}
			if (cl_type == CLF_TYPE_PLAIN) { // ok, it is not compressed
				rewind(cl_plain);
			}
		}
	}

	if (cl_type == CLF_TYPE_INVALID) {
		//fprintf(stderr, "%s in ", buf);
		return -1;
	}
	return 0;
}
Beispiel #7
0
/* Function: SetValueToEtcFile(const char* pEtcFile, const char* pSection,
 *                               const char* pKey, char* pValue);
 * Parameter:
 *     pEtcFile: etc file path name.
 *     pSection: Section name.
 *     pKey:     Key name.
 *     pValue:   Value.
 * Return:
 *     int                      meaning
 *     ETC_FILENOTFOUND         The etc file not found.
 *     ETC_TMPFILEFAILED        Create tmp file failure.
 *     ETC_OK                   OK.
 */
int GUIAPI SetValueToEtcFile (const char* pEtcFile, const char* pSection,
                               const char* pKey, char* pValue)
{
    FILE* etc_fp;
    FILE* tmp_fp;
    int rc;
    char tempSection [ETC_MAXLINE + 2];

#ifndef HAVE_TMPFILE
    char tmp_nam [256];

    sprintf (tmp_nam, "/tmp/mg-etc-tmp-%x", time(NULL));
    if ((tmp_fp = fopen (tmp_nam, "w+")) == NULL)
        return ETC_TMPFILEFAILED;
#else
    if ((tmp_fp = tmpfile ()) == NULL)
        return ETC_TMPFILEFAILED;
#endif

    if (!(etc_fp = fopen (pEtcFile, "r+"))) {
        fclose (tmp_fp);
#ifndef HAVE_TMPFILE
        unlink (tmp_nam);
#endif
        if (!(etc_fp = fopen (pEtcFile, "w"))) {
            return ETC_FILEIOFAILED;
        }
        fprintf (etc_fp, "[%s]\n", pSection);
        fprintf (etc_fp, "%s=%s\n", pKey, pValue);
        fclose (etc_fp);
        return ETC_OK;
    }

    switch (etc_CopyAndLocate (etc_fp, tmp_fp, pSection, pKey, tempSection)) {
    case ETC_SECTIONNOTFOUND:
        fprintf (tmp_fp, "\n[%s]\n", pSection);
        fprintf (tmp_fp, "%s=%s\n", pKey, pValue);
        break;
    
    case ETC_KEYNOTFOUND:
        fprintf (tmp_fp, "%s=%s\n\n", pKey, pValue);
        fprintf (tmp_fp, "%s\n", tempSection);
    break;

    default:
        fprintf (tmp_fp, "%s=%s\n", pKey, pValue);
        break;
    }

    if ((rc = etc_FileCopy (etc_fp, tmp_fp)) != ETC_OK)
        goto error;
    
    // replace etc content with tmp file content
    // truncate etc content first
    fclose (etc_fp);
    if (!(etc_fp = fopen (pEtcFile, "w"))) {
        fclose (tmp_fp);
#ifndef HAVE_TMPFILE
        unlink (tmp_nam);
#endif
        return ETC_FILEIOFAILED;
    }
    
    rewind (tmp_fp);
    rc = etc_FileCopy (tmp_fp, etc_fp);

error:
    fclose (etc_fp);
    fclose (tmp_fp);
#ifndef HAVE_TMPFILE
    unlink (tmp_nam);
#endif
    return rc;
}
Beispiel #8
0
int booksave(void)
{
    struct book library[MAXBKS]; /* array of structures     */
    int count = 0;
    int index, filecount;
    FILE * pbooks;
    int size = sizeof (struct book);

    if ((pbooks = fopen("book.txt", "a+b")) == NULL)
    {
        fputs("Can't open book.txt file\n",stderr);
        exit(1);
    }
    
    rewind(pbooks);            /* go to start of file     */
    while (count < MAXBKS &&  fread(&library[count], size,
                1, pbooks) == 1)
    {
        if (count == 0)
            puts("Current contents of book.dat:");
        printf("%s by %s: $%.2f\n",library[count].title,
            library[count].author, library[count].value);
        count++;
    }
    filecount = count;
    if (count == MAXBKS)
    {
        fputs("The book.dat file is full.", stderr);
        exit(2);
    }
    
    puts("Please add new book titles.");
    puts("Press [enter] at the start of a line to stop.");
    while (count < MAXBKS && gets(library[count].title) != NULL
                          && library[count].title[0] != '\0')
    {
        puts("Now enter the author.");
        gets(library[count].author);
        puts("Now enter the value.");
		scanf("%f", &library[count++].value);
        while (getchar() != '\n')
            continue;                /* clear input line  */
         if (count < MAXBKS)
             puts("Enter the next title.");
    }
    
    if (count > 0)
    { 	
        puts("Here is the list of your books:");
        for (index = 0; index < count; index++)
            printf("%s by %s: $%.2f\n",library[index].title,
                   library[index].author, library[index].value);
        fwrite(&library[filecount], size, count - filecount,
                pbooks);
    }
    else
    	puts("No books? Too bad.\n");
    
    puts("Bye.\n");
    fclose(pbooks);
    
    return 0;
}
Beispiel #9
0
static void
init_ram_segments(void)
{
	int i, errflag;
        FILE *iomem; 
	char buf[BUFSIZE], *p1, *p2;
	physaddr_t start, end;

	if ((iomem = fopen("/proc/iomem", "r")) == NULL)
		goto fail_iomem;

	while (fgets(buf, BUFSIZE, iomem)) {
		if (strstr(buf, "System RAM")) {
			console(buf);
			nr_segments++;
		}
	}
	if (!nr_segments)
		goto fail_iomem;

	ram_segments = (struct ram_segments *)
		GETBUF(sizeof(struct ram_segments) * nr_segments);

	rewind(iomem);
	i = 0;
	while (fgets(buf, BUFSIZE, iomem)) {
		if (strstr(buf, "System RAM")) {
			if (!(p1 = strstr(buf, ":")))
				goto fail_iomem;
			*p1 = NULLCHAR;
			clean_line(buf);
			if (strstr(buf, " "))
				goto fail_iomem;
			p1 = buf;
			if (!(p2 = strstr(buf, "-")))
				goto fail_iomem;
			*p2 = NULLCHAR;
			p2++;
			errflag = 0;
			start = htoll(p1, RETURN_ON_ERROR|QUIET, &errflag);
			end = htoll(p2, RETURN_ON_ERROR|QUIET, &errflag);
			if (errflag)
				goto fail_iomem;
			ram_segments[i].start = PHYSPAGEBASE(start);
			if (PAGEOFFSET(start))
				ram_segments[i].start += PAGESIZE();
			ram_segments[i].end = PHYSPAGEBASE(end);
			if (PAGEOFFSET(end) == (PAGESIZE()-1))
				ram_segments[i].end += PAGESIZE();
			console("ram_segments[%d]: %016llx %016llx [%s-%s]\n", i,
				(ulonglong)ram_segments[i].start, 
				(ulonglong)ram_segments[i].end, p1, p2);
			i++;
		}
	}

	fclose(iomem);
	return;

fail_iomem:
	fclose(iomem);
	nr_segments = 0;
	if (ram_segments)
		FREEBUF(ram_segments);

	return; 
}
void* set_value_thread(void *context)
{
	sensor_context *sensor = NULL;
	message msg;
	int return_value;
	char *tokens[10];
	char line[LINE_MAX];
	int count = 0;
	int start, end, value;

	sensor = (sensor_context*)context;

	msg.type = CURRENT_VALUE;
	while(sensor->run)
	{
		if(!(start <= sensor->clock && sensor->clock < end))
		{
			/* Figure out the value from file */
			if(fgets(line, LINE_MAX, sensor->sensor_value_file_pointer) == NULL)
			{
				LOG_DEBUG(("DEBUG: Seeking to beginning of file"));
				rewind(sensor->sensor_value_file_pointer);
				sensor->clock = 0;
				continue;
			}

			str_tokenize(line, ";\n\r", tokens, &count);
			if(count != 3)
			{
				LOG_ERROR(("ERROR: Wrong sensor temperature value file\n"));
				break;
			}

			start = atoi(tokens[0]);
			end = atoi(tokens[1]);
			if(strcmp (tokens[2], "true") == 0)
			{
				value = 1; 
			}
			else
			{
				value = 0;
			}
			sensor->value = value;
		}

		msg.u.value = sensor->value;
		msg.timestamp = time(NULL);

		pthread_mutex_lock(&sensor->mutex_lock);

		sensor->logical_clock[2]++;
		LOG_SCREEN(("INFO: Event Sent, "));
		LOG_INFO(("INFO: Event Sent, "));
		print_logical_clock_to_screen(sensor->logical_clock);
		print_logical_clock(sensor->logical_clock);
		LOG_INFO(("timestamp: %lu, Motion: %s\n", msg.timestamp, tokens[2]));
		LOG_SCREEN(("timestamp: %lu, Motion: %s\n", msg.timestamp, tokens[2]));
		return_value = write_message(sensor->socket_fd, sensor->logical_clock, &msg);
		if(E_SUCCESS != return_value)
		{
			LOG_ERROR(("ERROR: Error in sending sensor temperature value to gateway\n"));
		}

		for(int index=0; index<sensor->send_peer_count; index++)
		{
			return_value = write_message(sensor->send_peer[index]->comm_socket_fd,
					sensor->logical_clock,
					&msg);
			if(E_SUCCESS != return_value)
			{
				LOG_ERROR(("ERROR: Error in sending sensor temperature value to peer\n"));
			}
		}
		pthread_mutex_unlock(&sensor->mutex_lock);

		sleep(sensor->interval);
		sensor->clock += sensor->interval;
	}

	LOG_DEBUG(("Exiting SetValueThread...\n"));
	return (NULL);
}
Beispiel #11
0
/****************************************************************************
 * Creator: T. M. Farrington
 * Purpose: To search a binary file that contains command syntaxes.
 *
 * Inputs:  One binary file, the name of which is defined in the include file.
 *          Character pointer to the function name to be looked up.
 *          Character pointer to a buffer where the full command syntax will
 *             be placed if it is found.
 *          Maximum string size that the buffer can receive.
 *
 * Outputs: Return TRUE if search was successful, FALSE if not.
 *          If TRUE, places full command syntax in the buffer.
 *
 ****************************************************************************/
int W_EXPORT KpeGetKALHelp(LPSTR fnameptr, LPSTR buffer, int maxsiz)
{
    FILE *finptr;
    int iFile;
    OFSTRUCT of;
    char pFullPath[FILENAME_MAX];
    unsigned short csfname = lstrlen(fnameptr) + 1;
    unsigned short ssfname, ssrecord;
    unsigned short found = FALSE;

    /* First look for the file in KAPPA's system directory. *
     * If not there, then use the PATH.                     */
    KppGetSystemDirectory(pFullPath, FILENAME_MAX);
    strncat(pFullPath, binary_file, FILENAME_MAX - strlen(pFullPath) - 1);
    if ((iFile = OpenFile(pFullPath, &of, OF_READ)) == -1)
        iFile = OpenFile(binary_file, &of, OF_READ);

    if ((iFile == -1) || ((finptr = fdopen(iFile, "rb")) == NULL))
    {
        RegisterKappaMessage(IDE_FCANTOPEN,
                             KppAddAtom(binary_file), NULLID, NULLID);
        KppIncrementPopupCountCB(EDITW);
        PostKappaMessage();
        KppDecrementPopupCountCB(EDITW);
        return FALSE;
    }

    rewind(finptr);

    /* While not found, get the two string length values (2 bytes each)
     * at the begining of the record. 
     */
    while (!found)
    {
        fread(&ssfname, 2, 1, finptr);
        if (feof(finptr))
            break;

        fread(&ssrecord, 2, 1, finptr);
        if (feof(finptr))
            break;

        /* If the size of the parameter function name ==
            * size of the scanned function name,
                */
        if (csfname == ssfname)
        {
            char data[MAX_RECORD_LENGTH];

            /* then read the function name and if the strings match, */
            if ((fread(data, ssfname, 1, finptr) != NULL) &&
                (!lstrcmp(fnameptr, data)))
            {
                /* get the rest of the record and concatenate both strings
                    into the output file,
                        RBP: Do not concatenate */
                /* kstrcpy (buffer, data, maxsiz); */
                if (fread(data, ssrecord - ssfname - 4, 1, finptr) != NULL)
                    _fstrncpy(buffer, data, maxsiz);

                /* Stop the search. */
                found = TRUE;
            }
            else
                /* otherwise advance the file pointer to the next record.*/
                fseek(finptr, (long) ssrecord - 4 - ssfname, SEEK_CUR);
        }
        else                        /* otherwise advance the file pointer to the next record. */
            fseek(finptr, (long) ssrecord - 4, SEEK_CUR);
    }

    fclose(finptr);

    if (!found && (KppGetKalFunctionSyntaxCB(KppCheckAtom(fnameptr),
                                             buffer, maxsiz) != -1 ||
                   KppGetDLLFunctionSyntax(fnameptr, buffer, maxsiz) != -1))
        found = TRUE;

    return found;
}
Beispiel #12
0
/*Initial run, read in given file and save sorted blocks to temporary files*/
BOOLEAN initialRun(char * filePath, int bufferMemoryCount, Schema * schema, FileList * fileL, int * totalRecordCount){
	FILE * initialFP;
	char line[LINE_LENGTH];
	char * tokenPtr;
	int i;

/*Open path file*/
	if((initialFP = fopen(filePath,"r")) == NULL){
		fprintf(stderr, "Error: Failed to open file %s\n",filePath);
		return FALSE;
	}

/*Determine and set type of file data*/
/*Get first line of file and count number of ','*/
	fgets(line, LINE_LENGTH, initialFP);
/*rewind to start of file for future use*/
	rewind(initialFP);
/*Determine first occurrence of ',' in line*/
	tokenPtr = strchr(line,',');
/*Determine if there is a second occurrence of ',' in line*/
	tokenPtr = strchr(tokenPtr+1,',');
/*if NULL then file contains guild records*/
/*(since there is only 1 ',' for every guild file line)*/
	if(tokenPtr == NULL)
		*schema = GUILD;
/*else then file contains character records*/
	else
		*schema = CHARACTER;

/*While there is still more of the file to read*/
	while (line[0] != '\0'){
		FILE * tempFP;
		int recordCount = bufferMemoryCount;
		Record * records = calloc(bufferMemoryCount, sizeof(Record));
		if (!records){
			fprintf(stderr, "Error: Failed to allocate memory for records\n");
			return FALSE;
		}

		for(i = 0; i < bufferMemoryCount; i++){
			char * tempString = NULL;
/*If reached end of file*/
			if(fgets(line, LINE_LENGTH, initialFP) == NULL){
/*set record size to index reached*/
				recordCount = i;
				line[0] = '\0';
				break;
			}

			if(*schema == CHARACTER){
				strcpy(records[i].field.character.cname,strtok(line,","));

				tempString = strtok(NULL,",");
				records[i].field.character.team = (unsigned short int) strtoul(tempString, NULL, 0);

				tempString = strtok(NULL,",");
				records[i].field.character.level = (unsigned short int) strtoul(tempString, NULL, 0);

				tempString = strtok(NULL,",");
				records[i].field.character.cid = (unsigned int) strtoul(tempString, NULL, 0);

				tempString = strtok(NULL,",");
				records[i].GuildID = (unsigned int) strtoul(tempString, NULL, 0);
			}
			else{ /*If GUILD schema*/
				int lineLen = strlen(line);
				/*Remove new line from end of string*/
				if (lineLen > 0 && line[lineLen-1] == '\n')
					line[lineLen-1] = '\0';

				tempString = strtok(line,",");
				records[i].GuildID = (unsigned int) strtoul(tempString, NULL, 0);

				strcpy(records[i].field.g_name,strtok(NULL,","));
			}
			*totalRecordCount = *totalRecordCount +1;
		}

		/*Sort the blocks*/
		quickSort(records, 0, recordCount-1);
		/*insertionSort(records, recordCount);*/
	/*Write out buffers run of B blocks to temp files*/
	/*create temporary file*/
		if((tempFP = tmpfile()) == NULL){
			fprintf(stderr, "Error: Failed to create temporary file\n");
			return FALSE;
		}

/*Write array of records to binary file*/
		fwrite(records, sizeof(Record), recordCount, tempFP);
/*no need to loop through records array*/
/*for (i = 0; i < recordCount; i++){
fwrite(&records[i], sizeof(Record), 1, tempFP);
}*/

		/*Rewind temp file pointer for later merging*/
		rewind(tempFP);
		/*add file pointer to file list*/
		addFile(fileL, tempFP);

		free(records);
	}
	fclose(initialFP);
	return TRUE;
}
Beispiel #13
0
BOOLEAN mergeRuns(FILE ** sorted, int pagesize, int availableBuffers, FileList currentFiles, int * passes, int * runs, int totalRecordCount){
	RecordHeap rHeap;
	Buffer * bufferNodes;
	int bufferIndex;

/*Determine max files that can be merged in a run*/
/*That is available buffers -1 for the output buffer*/
/*This is also the output buffer indes*/
	int outputBuffIndex = availableBuffers -1;

/*Buffer array (of buffer nodes) where size of which is the number
of buffers available to store in memory*/
	bufferNodes = calloc(availableBuffers, sizeof(Buffer));
	if(!bufferNodes){
		fprintf(stderr, "Error: Failed to allocate buffer array\n");
		return FALSE;
	}

/*Allocate memory for record arrays for each buffer*/
	for(bufferIndex = 0; bufferIndex < availableBuffers; bufferIndex++){
		initBuffer(&bufferNodes[bufferIndex], pagesize);
	}

/*Initialise priority queue
It's size is the amount of files that can be merged in a run*/
/*outputBuffIndex is the last index in the buffer array*/
	if(initHeap(&rHeap, outputBuffIndex * pagesize) == FALSE){
		return FALSE;
	}

/*while more merging required, (more than 1 temporary file)*/
/*go through a pass*/
	while(currentFiles.fileCount > 1){
		int runCount = 0;
		/*Define first file to be the start of the file linked list*/
		FileNode * firstFileForRun = currentFiles.fileHeadNode;

		/*Run file list, is the files to be merged in the next pass*/
		FileList runFileList;/*= calloc(1, sizeof(FileList));*/

		float runsInPassFloat = ((float)currentFiles.fileCount/(float)(availableBuffers-1));
		int runsInPass = ceil(runsInPassFloat);

		initFileList(&runFileList);


/*while still merging required for pass*/
/*go through a run*/
		while(runCount < runsInPass){
			int buffersInUse = 0;
			int bufferIndex = 0;
			int init = 0;
			FileNode * currentRunFile = firstFileForRun;
			FILE * outputFile;
			
/*create new temp file for merge run, written to when output buffer is full*/
			if((outputFile = tmpfile()) == NULL){
				fprintf(stderr, "Error: Failed to create output temporary file for run\n");
				return FALSE;
			}

/*add file pointer to the file list for the next pass*/
			addFile(&runFileList,outputFile);

/*Read in pages from current files to buffers*/
			for(bufferIndex = 0; bufferIndex < outputBuffIndex; bufferIndex++){
				int recordPageIndex;
/*fill buffer with records from file*/
				if(currentRunFile->fp != NULL){
					for(recordPageIndex = 0; recordPageIndex < pagesize; recordPageIndex++){
						/*read in record*/
						Record record;
						if(fread(&record, sizeof(Record), 1, currentRunFile->fp) == 1){
							/*add record to page (records array)*/
							init++;
							if(addRecord(&bufferNodes[bufferIndex], record, pagesize, recordPageIndex) == FALSE)
								return FALSE;
		/*add record index to heap*/
							if(addToHeap(&rHeap, &bufferNodes[bufferIndex], recordPageIndex) == FALSE)
								return FALSE;
						}
		/*else reached file end*/
						else{
							/*temp file will be automatically deleted by the system*/
							fclose(currentRunFile->fp);
							currentRunFile->fp = NULL;
							/*removeFile(currentFiles, currentRunFile);*/
							/*add blank records*/
							/*int blankRecordCount;
							for(blankRecordCount = recordCount; blankRecordCount < pagesize; blankRecordCount++){
								int recordPageIndex = addBlankRecord(&bufferNodes[bufferIndex], pagesize);
								
								if(recordPageIndex < 0)
									return FALSE;
							}*/
							break;
						}
					}
					bufferNodes[bufferIndex].fileNode = currentRunFile;
					buffersInUse++;
					currentRunFile = currentRunFile->nextFileNode;
					if (currentRunFile == NULL)
						break;
				}
				else
					break;
			}
/*set firstFileForRun for next run*/
			firstFileForRun = currentRunFile;

/*while all buffers are not empty (there is still records in pages in
some buffer not including the output buffer)*/
			while(buffersInUse > 0 && rHeap.count > 0){
/*keep getting min record and writing to output buffer*/
/*get smallest record*/
				RecordIndex minIndex = removeMinHeap(&rHeap);
				if(minIndex.guildID == 0)
					return FALSE;
/*move smallest record from main buffer memory to output buffer*/
/*add record to output buffer*/
				addRecord(&bufferNodes[outputBuffIndex],
					minIndex.buff->pageRecords[minIndex.pgIndex], pagesize, bufferNodes[outputBuffIndex].recordCount);
/*remove the same record from original buffer*/
				removeRecord(minIndex.buff, minIndex.pgIndex);
/*if output buffer is full, write page to file*/
				if(bufferNodes[outputBuffIndex].recordCount == pagesize){
/*write page to file*/
					int written;
					written = fwrite(bufferNodes[outputBuffIndex].pageRecords, sizeof(Record),
						pagesize, outputFile);
					if(written !=pagesize){
						fprintf(stderr, "Error: Failed to write to output file, wrote %i records\n",written);
						return FALSE;
					}

					/*clear page in output buffer*/
					clearPage(&bufferNodes[outputBuffIndex], pagesize);
				}

/*if original buffer is empty, read in another page*/
				if(minIndex.buff->recordCount == 0){
					int recordPageIndex;
/*fill buffer with records from file*/
					for(recordPageIndex = 0; recordPageIndex < pagesize; recordPageIndex++){
						Record record;
						if(minIndex.buff->fileNode->fp != NULL){
							if(fread(&record, sizeof(Record), 1, minIndex.buff->fileNode->fp) == 1){
		/*add record to page (records array)*/
								if(addRecord(minIndex.buff, record, pagesize, recordPageIndex) == FALSE)
									return FALSE;
		/*add record index to heap*/
								if(addToHeap(&rHeap, minIndex.buff, recordPageIndex) == FALSE)
									return FALSE;
							}
		/*else reached file end*/
							else{
								/*temp file will be automatically deleted by the system*/
								fclose(minIndex.buff->fileNode->fp);
								minIndex.buff->fileNode->fp = NULL;
								/*removeFile(currentFiles, minIndex.buff->fileNode);*/
								break;
							}
						}
					}
				}
/*if buffer is still empty, then 0 records were read in,
therefore file is empty and the buffer is now free*/
				if(minIndex.buff->recordCount == 0)
					/*decrement buffers in use counter*/
					buffersInUse--;
			}

/*All files for run have been fully read*/
/*Write out records still in output buffer*/
			if(bufferNodes[outputBuffIndex].recordCount > 0){
/*Output buffer page was not full*/
				int i = 0;
				for(i = 0; i < pagesize; i++){
					if(bufferNodes[outputBuffIndex].pageRecords[i].GuildID != 0){
						fwrite(&bufferNodes[outputBuffIndex].pageRecords[i],
							sizeof(Record), 1, outputFile);
						removeRecord(&bufferNodes[outputBuffIndex], i);
					}
				}
			}
			/*Rewind outfile for future merge*/
			rewind(outputFile);
			runCount++;
		}
		/*set runFileListas new current file list*/
		freeFileNode(&currentFiles);
		currentFiles = runFileList;
		*passes = *passes+1;
		*runs = *runs + runCount;
		printf("Pass %i resulted in %i runs\n",*passes,runCount);
	}


/*FileList will contain link to only 1 temporary binary file*/
	if(currentFiles.fileCount != 1){
		fprintf(stderr, "Error: Number of files:%i is invalid\n",currentFiles.fileCount);
		return FALSE;
	}
	*sorted = currentFiles.fileHeadNode->fp;

	/*free allocated memory*/

	for(bufferIndex = 0; bufferIndex < availableBuffers; bufferIndex++){
		freeBuffer(&bufferNodes[bufferIndex]);
	}
	free(bufferNodes);

	freeHeap(&rHeap);

	freeFileNode(&currentFiles);

	/*free(currentFiles);*/

	return TRUE;
}
Beispiel #14
0
int main(int argc, char **argv)
{
	char dumpTableFile[] = "table.txt" ;	  
	char inputFile[] = "../test/data/test_input" ;
	char patternFile[] = "../test/pattern/space_pattern" ;
	PFAC_handle_t handle ;
	PFAC_status_t PFAC_status ;
	int input_size ;    
	char *h_inputString = NULL ;
	int  *h_matched_result = NULL ;
	
	char *h_inputString_buf = NULL;

	// step 1: create PFAC handle 
	PFAC_status = PFAC_create( &handle ) ;
	assert( PFAC_STATUS_SUCCESS == PFAC_status );

	// step 2: read patterns and dump transition table
	PFAC_status = PFAC_readPatternFromFile( handle, patternFile) ;
	if ( PFAC_STATUS_SUCCESS != PFAC_status ){
		printf("Error: fails to read pattern from file, %s\n", PFAC_getErrorString(PFAC_status) );
		exit(1) ;
	}

	// dump transition table 
	FILE *table_fp = fopen( dumpTableFile, "w") ;
	assert( NULL != table_fp ) ;
	PFAC_status = PFAC_dumpTransitionTable( handle, table_fp );
	fclose( table_fp ) ;
	if ( PFAC_STATUS_SUCCESS != PFAC_status ){
		printf("Error: fails to dump transition table, %s\n", PFAC_getErrorString(PFAC_status) );
		exit(1) ;	
	}

	if (argc <= 1){
		printf("no input arguments, using default value\n"); 	

		//step 3: prepare input stream
		FILE* fpin = fopen( inputFile, "rb");
		assert ( NULL != fpin ) ;

		// obtain file size
		fseek (fpin , 0 , SEEK_END);
		input_size = ftell (fpin)-1;
		rewind (fpin);  

		printf("input_size is %d\n", input_size);
		// allocate memory to contain the whole file
		h_inputString = (char *) malloc (sizeof(char)*input_size);
		assert( NULL != h_inputString );

		h_matched_result = (int *) malloc (sizeof(int)*input_size);
		assert( NULL != h_matched_result );
		memset( h_matched_result, 0, sizeof(int)*input_size ) ;

		// copy the file into the buffer
		input_size = fread (h_inputString, 1, input_size, fpin);
		fclose(fpin);    
	}
	else{
		// step 3: prepare input string
		processCommandOption(argc, argv, &h_inputString);		

		input_size = strlen(h_inputString);	

		h_matched_result = (int *) malloc (sizeof(int)*input_size);	
				
		memset (h_matched_result, 0, sizeof(int)*input_size);	
	}

	// step 4: run PFAC on GPU           
	PFAC_status = PFAC_matchFromHost( handle, h_inputString, input_size, h_matched_result ) ;
	if ( PFAC_STATUS_SUCCESS != PFAC_status ){
		printf("Error: fails to PFAC_matchFromHost, %s\n", PFAC_getErrorString(PFAC_status) );
		exit(1) ;	
	}     

	// step 5: output matched result
	// parse in serial, GPU version should be considered
	std::vector<int> positionQ;
	int keylen, i;
	for (int i = 0; i < input_size; i++) {
		if (h_matched_result[i] != 0)  {
			positionQ.push_back(i+1);
		}
		else if (i == 0) {
			positionQ.push_back(i);
		}
	}
	
	for (i = 0; i < positionQ.size(); i++){
		keylen = positionQ[i+1]-positionQ[i];

		// if keylen < 0, this means this is the last element
		// in h_inputString array,
		if (keylen == 1){
			continue;
		} else if (keylen < 0){
			keylen = input_size - positionQ[i];

			if (keylen == 0)
				break;
		}

		if (i != positionQ.size()-1)
			printf("%.*s\t%d\n", keylen, &h_inputString[positionQ[i]], 1);

	}

	// parse in parallel
	

	PFAC_status = PFAC_destroy( handle ) ;
	assert( PFAC_STATUS_SUCCESS == PFAC_status );
	
	if (argc <= 1)
		free(h_inputString);	

	free(h_matched_result); 

	return 0;
}
Beispiel #15
0
void CastleGame::seeker(char *sstring)
{
	rewind(fptr);
	while(fseeker(sstring) != FSUCCESS){}
}
Beispiel #16
0
int LuaObfuscator::addFalseComment() {
	int size = 0;
	// The list of false comment...
	// or
	// generate the false comment...

	char szFileNameNew[MAX_PATH];

	// read global functions
	StringListConstIter iter = m_luaFiles.begin();
	while (iter != m_luaFiles.end()) {
		FILE *file = fopen(iter->c_str(), "rt");
		if (!file) {
			print("File not found: %s", iter->c_str());
			++iter;
			continue;
		}
		fseek(file, 0, SEEK_END);
		long fileSize = ftell(file);
		rewind(file);
		char *pDataInSource = new char[fileSize + 20];
		char *pDataIn = pDataInSource + 10;
		memset(pDataInSource, 0, 10);
		size_t realSize = fread(pDataIn, sizeof(char), fileSize, file);
		memset(pDataIn + realSize, 0, 10);
		fclose(file);

		generateNewFileName(szFileNameNew, iter->c_str());

		file = fopen(szFileNameNew, "wt");
		char *p = pDataIn;
		while (*p) {
			if (isStringStart(p)) {
				char *pStart = p;
				size_t stringSize = skipStringAndMove(&p, NULL);
				if (stringSize) {
					fwrite(pStart, 1, stringSize, file);
					//obfuscateSize += len + 1;
					continue;
				}
				else {
					print("Start of line are found, but end of line not found\n");
					break;
				}
			}
			if (strchr(";,\n+*/%^", *p)) {
				char szAddComment[100];
				size_t len = generateFalseComment(szAddComment);
				fwrite(szAddComment, 1, len, file);
				fputc(*p, file);
				++p;
			//obfuscateSize += len + 1;
				continue;
			}
			fputc(*p, file);
			//++obfuscateSize;
			++p;
		}
		long obfuscateSize = ftell(file);
		fclose(file);
		delete[] pDataInSource;

		print("%8d %s\n", obfuscateSize - fileSize, szFileNameNew);
		size += obfuscateSize - fileSize;
		++iter;
	}

	return size;
}
Beispiel #17
0
// Calling this function will generate a public and private key and store them in the pointers
// it is given. 
void rsa_gen_keys(struct public_key_class *pub, struct private_key_class *priv, char *PRIME_SOURCE_FILE)
{
  FILE *primes_list;
  if(!(primes_list = fopen(PRIME_SOURCE_FILE, "r"))){
    fprintf(stderr, "Problem reading %s\n", PRIME_SOURCE_FILE);
    exit(1);
  }

  // count number of primes in the list
  long long prime_count = 0;
  do{
    int bytes_read = fread(buffer,1,sizeof(buffer)-1, primes_list);
    buffer[bytes_read] = '\0';
    for (i=0 ; buffer[i]; i++){
      if (buffer[i] == '\n'){
	prime_count++;
      }
    }
  }
  while(feof(primes_list) == 0);
  
  
  // choose random primes from the list, store them as p,q

  long long p = 0;
  long long q = 0;

  long long e = powl(2, 8) + 1;
  long long d = 0;
  char prime_buffer[MAX_DIGITS];
  long long max = 0;
  long long phi_max = 0;
  
  srand(time(NULL));
  
  do{
    // a and b are the positions of p and q in the list
    int a =  (double)rand() * (prime_count+1) / (RAND_MAX+1.0);
    int b =  (double)rand() * (prime_count+1) / (RAND_MAX+1.0);
    
    // here we find the prime at position a, store it as p
    rewind(primes_list);
    for(i=0; i < a + 1; i++){
    //  for(j=0; j < MAX_DIGITS; j++){
    //	prime_buffer[j] = 0;
    //  }
      fgets(prime_buffer,sizeof(prime_buffer)-1, primes_list);
    }
    p = atol(prime_buffer); 
    
    // here we find the prime at position b, store it as q
    rewind(primes_list);
    for(i=0; i < b + 1; i++){
      for(j=0; j < MAX_DIGITS; j++){
	prime_buffer[j] = 0;
      }
      fgets(prime_buffer,sizeof(prime_buffer)-1, primes_list);
    }
    q = atol(prime_buffer); 

    max = p*q;
    phi_max = (p-1)*(q-1);
  }
  while(!(p && q) || (p == q) || (gcd(phi_max, e) != 1));
 
  // Next, we need to choose a,b, so that a*max+b*e = gcd(max,e). We actually only need b
  // here, and in keeping with the usual notation of RSA we'll call it d. We'd also like 
  // to make sure we get a representation of d as positive, hence the while loop.
  d = ExtEuclid(phi_max,e);
  while(d < 0){
    d = d+phi_max;
  }

  printf("primes are %lld and %lld\n",(long long)p, (long long )q);
  // We now store the public / private keys in the appropriate structs
  pub->modulus = max;
  pub->exponent = e;

  priv->modulus = max;
  priv->exponent = d;
}
Beispiel #18
0
/*
 * Obfuscate the Lua's code in the files in list <fileList>
 * <excludeFunctions> contatins name of global function, for which don't make obfuscating
 * <obf> contains the some options
 */
int LuaObfuscator::obfuscate(const stObfuscatorSetting &settings) {
	FILE *fileNew, *fileOld;
	char szFileNameNew[FILENAME_MAX];
	ptrdiff_t commentSize, spaceSize, newLineSize, duplicateCharsSize;
	ptrdiff_t localVarsSize;
	size_t constIntSize, constFloatSize, constStringSize;

	if (m_luaFiles.empty())
		return 0;

	StringListConstIter iter = m_luaFiles.begin();
	while (iter != m_luaFiles.end()) {
		const char *szFileName = getFileName(iter);
		fileOld = fopen(szFileName, "rt");
		if (!fileOld) {
			print("ERROR: Open file fail\n");
			++iter;
			continue;
		}

		fseek(fileOld, 0, SEEK_END);
		long size = ftell(fileOld);
		rewind(fileOld);

		char *pDataInSource = new char[size + 5];
		char *pDataIn = pDataInSource + 2; // for delete/clear data
		if (!pDataInSource) {
			fclose(fileOld);
			print("Try to alloc memory failed, size %d\n", size + 5);
			return 0;
		}

		size_t realSize = fread(pDataIn, 1, size, fileOld);
		pDataInSource[0] = 0; // \0\0...............\0\0
		pDataInSource[1] = 0;
		pDataIn[realSize] = 0;
		pDataIn[realSize + 1] = 0;

		char szFileBakup[FILENAME_MAX];
		if (settings.bCreateBakFile) {
			strcpy(szFileBakup, szFileName);
			strcat(szFileBakup, ".bak");
			FILE *fileBakup = fopen(szFileBakup, "wt");
			if (fileBakup) {
				fwrite(pDataIn, 1, strlen(pDataIn), fileBakup);
				fclose(fileBakup);
			}
		}

		commentSize = 0;
		duplicateCharsSize = 0;
		spaceSize = 0;
		newLineSize = 0;
		constIntSize = 0;
		constFloatSize = 0;
		constStringSize = 0;
		localVarsSize = 0;

		commentSize = removeComments(pDataIn);
#ifdef _DEBUG
		SaveToFile(pDataIn, szFileName, "1_comment");
#endif
		duplicateCharsSize = removeDumplicatedChars(pDataIn);
#ifdef _DEBUG
		SaveToFile(pDataIn, szFileName, "2_dublicate");
#endif

		spaceSize = removeExtraWhitespace(pDataIn);
#ifdef _DEBUG
		SaveToFile(pDataIn, szFileName, "3_spaces");
#endif

		newLineSize = removeNewLines(pDataIn);
#ifdef _DEBUG
		SaveToFile(pDataIn, szFileName, "4_endline");
#endif

		StringStream strIn, strOut;

		if (settings.ObfuscateConstInt || settings.ObfuscateConstFloat ||
			settings.ObfuscateConstString)
		{
			obfuscateConst(pDataIn, strOut, settings.ObfuscateConstInt, settings.ObfuscateConstFloat,
			settings.ObfuscateConstString);
#ifdef _DEBUG
			SaveToFile(strOut.str().c_str(), szFileName, "5_const");
#endif
		}
		else {
			strOut.str("");
			strOut << pDataIn;
		}

		strIn.str("");
		strIn << strOut.str();
		if (settings.ObfuscateLocalVasAndParam) {
			try {
				localVarsSize = obfuscateLocalVarsAndParameters(strIn.str().c_str(), strOut);
			}
			catch (std::exception e) {
				printf(strOut.str().c_str());
				printf(e.what());
			}
#ifdef _DEBUG
			SaveToFile(strOut.str().c_str(), szFileName, "6_local_vars");
#endif
		}

		printObfuscateResilt("Remove the comments", commentSize);
		printObfuscateResilt("Remove the duplicate chars", duplicateCharsSize);
		printObfuscateResilt("Remove the spaces", spaceSize);
		printObfuscateResilt("Remove the \"New line\"", newLineSize);
		printObfuscateResilt("Obfuscate constant integer numbers", constIntSize);
		printObfuscateResilt("Obfuscate constant float numbers", constFloatSize);
		printObfuscateResilt("Obfuscate constant strings", constStringSize);
		printObfuscateResilt("Obfuscate local vars", localVarsSize);

		generateNewFileName(szFileNameNew, szFileName);

		fileNew = fopen(szFileNameNew, "wt");
		if (!fileNew) {
			print("Couldn't create file %s\n", szFileNameNew);
			fclose(fileOld);
			return -1;
		}
		const std::string &sTmp = strOut.str();
		const char *p = sTmp.c_str(); // TODO: correct code
		size_t lenCstr = strlen(p);
		fwrite(p, 1, lenCstr, fileNew);

		delete[] pDataInSource;

		fclose(fileOld);
		fclose(fileNew);

	/*	if (settings.bCreateBakFile) {
			unlink(szFileName);
			rename(szFileNameNew, szFileName);
		}*/

		++iter;
	}

	if (settings.ObfuscateGlobalFunctionName) {
		print("\nObfuscate global functions\n");
		ptrdiff_t globalFunctionSize = obfuscateGlobalFunctionNames();
		print("size: %+d\n", globalFunctionSize);
	}

	int addCommentSize = 0;
	// TODO: may be replace this code in loop of each file (see above, local)
	if (settings.ObfuscateAddFalseComment) {
		print("\nAdd comment\n");
		addCommentSize = addFalseComment();
		print("Total size: %d\n", addCommentSize);
	}

	char szAddonFilename[MAX_PATH];
	strcpy(szAddonFilename, m_sAddonDir.c_str());
	strcat(szAddonFilename, "addon.lua");
	FILE *addonFile = fopen(szAddonFilename, "wb");
	if (!addonFile) {
		printf("Couldn't create addon.lua file\n");
		return 1;
	}
	iter = m_luaFiles.begin();
	while (iter != m_luaFiles.end()) {
		const char *szFileName = getFileName(iter);
		generateNewFileName(szFileNameNew, szFileName);
		fileNew = fopen(szFileNameNew, "rb");
		char buf[4096];
		char cLast = 0;
		while (size_t size = fread(buf, 1, 4096, fileNew)) {
			fwrite(buf, size, 1, addonFile);
			cLast = buf[size - 1];
		}
		fclose(fileNew);

		// add ; to divide files
		if (!settings.linesBetweenFiles) {
			if (cLast != ';') {
				fwrite(";", 1, 1, addonFile);
			}
		}
		else {
			for (size_t i = 0; i < settings.linesBetweenFiles; ++i) {
				fwrite("\n", 1, 1, addonFile);
			}
		}

		++iter;
	}
	fclose(addonFile);

	return 0;
}
Beispiel #19
0
int main(int argc, char **argv)
{
	FILE *file;
	int i, j;
	unsigned file_size;
	pthread_mutex_init(&mutex, NULL);
	j = 0;
	hash_sum = 1;
	unsigned short cpu_count = sysconf(_SC_NPROCESSORS_ONLN);
	struct sysinfo si;
	sysinfo(&si);
	printf("Free RAM\t=\t%lu B or %f MB\n", si.freeram,
			((double)si.freeram * (double)si.mem_unit) / 1048576.0);
	printf("Core(s) avaible =\t%u\n", cpu_count);
	file = fopen(argv[1], "rb");
	if (file < 0) {
		perror("Cant open file");
		print("Usage: chsum /full/path/to/file [force_num_threads]");
		exit(EXIT_FAILURE);
	}
	fseek(file, 0, SEEK_END);
	file_size = ftell(file);
	rewind(file);
	printf("Size of file\t=\t%u\n", file_size);
	unsigned num_size = ceil(file_size / (0.3 * si.freeram));
	unsigned free_size = file_size;
	struct timespec t_before, t_after;
	clock_gettime(CLOCK_BOOTTIME, &t_before);
	printf("Start time\t=\t%lu sec and %lu nsec\n",
			t_before.tv_sec, t_before.tv_nsec);
	while (j < num_size) {
		if (free_size < 0.3 * si.freeram) {
			n = ceil(free_size / sizeof(short));
			mas = (short *)malloc(n * sizeof(short));
			sum_exp = (float *)malloc(n * sizeof(float));
		} else {
			n = ceil(0.3 * si.freeram / sizeof(short));
			mas = (short *)malloc(n * sizeof(short));
			sum_exp = (float *)malloc(n * sizeof(float));
			free_size = free_size - 0.3 * si.freeram;
		}
		fread(mas, n * sizeof(short), 1, file);
		fseek(file, n * sizeof(short), SEEK_CUR);
		if (argc == 3)
			cpu_count = atoi(argv[2]);
		printf("Threads number\t=\t%d\n", cpu_count);
		pthread_t id[cpu_count];
		for (i = 0; i < cpu_count; i++) {
			if (pthread_create(&id[i], NULL, work, NULL)) {
					printf("Thread creating error\n");
					exit(EXIT_FAILURE);
			}
		}
		for (i = 0; i < cpu_count; i++)
			pthread_join(id[i], NULL);
		j++;
	}
	clock_gettime(CLOCK_BOOTTIME, &t_after);
	printf("End time\t=\t%lu sec and %lu nsec\n",
			t_after.tv_sec, t_after.tv_nsec);
	long long start, end, diff, res_in_microsec;
	start = t_before.tv_sec*NANOS + t_before.tv_nsec;
	end = t_after.tv_sec*NANOS + t_after.tv_nsec;
	diff = end - start;
	res_in_microsec = diff / 1000 + (diff % 1000 >= 500);
	printf("Elapse time\t=\t%lld microsec\n", res_in_microsec);
	printf("Hash\t\t=\t%.20f\n", hash_sum);
	fclose(file);
	return 0;
}
Beispiel #20
0
/*
 * Scaning all text
 * Skip the "string"
 * Why do finds the function name:
 *   function call:
 *     foo(arg1, arg2, ...)
 *     a = foo(arg1, arg2, ...)
 *   when function send to other function
 *     trycall(foo)
 * ---------------------
 * therefore function name is near '(' and ')'
 */
ptrdiff_t replaceGlobalFunctions(const char *szFileName, FakeFunctions &globalFunctions,
	const StringList &excludeFunctions)
{
	if (!szFileName || !szFileName[0])
		return 0;

	FILE *file = fopen(szFileName, "rt");
	if (!file)
		return 0;
	fseek(file, 0, SEEK_END);
	int size = ftell(file);
	rewind(file);

	char *pDataInSource = new char[size + 20]; // + 20 for additional 10_"data"_10
	memset(pDataInSource, 0, 10);
	char *pDataIn = pDataInSource + 10; // for delete/clear data

	size_t realSize = fread(pDataIn, 1, size, file);
	memset(pDataIn + realSize, 0, 10);

	fclose(file);

	StringStream stream;
	char *p = pDataIn;

	while (*p) {
		if (isStringStart(p)) {
			size_t size = skipStringAndMove(&p, NULL);
			stream.write(p - size, size);
			continue;
		}

		if (!strncmp(p, "tostring", sizeof("tostring") - 1))
			*p = *p;

		char *pStart = p;
		while (isAlphaFun(*p)) {
			++p;
		}

		size_t wordSize = p - pStart;
		if (wordSize) {
			if (isFunctionNameInCode(pStart, p)) {
				std::string str(pStart, wordSize);
				StringMapConstIter iter = globalFunctions.find(str);
				if (iter != globalFunctions.end()) {
					StringListConstIter IterFunExclude = std::find(excludeFunctions.begin(), excludeFunctions.end(), str);
					if (IterFunExclude == excludeFunctions.end()) {
						// replace
						stream.write(iter->second.c_str(), FAKE_FUNCTION_LEN);
						continue;
					}
				}
			}
			stream.write(pStart, wordSize);
			if (!p[0]) {
				break;
			}
		}
		stream << *p;

		++p;
	}

	file = fopen(szFileName, "wt");
	const std::string& str = stream.str();
	size_t obfuscateSize = str.length();
	if (file) {
		fwrite(str.c_str(), 1, obfuscateSize, file);
		fclose(file);
	}

	delete[] pDataInSource;

	print("%8d %s\n", obfuscateSize - realSize, szFileName);

	return obfuscateSize - realSize;
}
Beispiel #21
0
/* CHILD PROCEDURE, WHICH ACTUALLY DOES THE FILE TRANSFER */
doftp(int newsd)
  {
        
    int i,fsize,fd,msg_ok,fail,fail1,req,c,ack;
    int no_read ,num_blks , num_blks1,num_last_blk,num_last_blk1,tmp;
    char fname[MAXLINE];
    char out_buf[MAXSIZE];
    FILE *fp;
       
     no_read = 0;
     num_blks = 0;
     num_last_blk = 0; 
 
     
     /* START SERVICING THE CLIENT */
   
     /* get command code from client.*/
     /* only one supported command: 100 -  get a file */
     req = 0;
     if((readn(newsd,(char *)&req,sizeof(req))) < 0)
 {
printf("server: read error %d\n",errno);exit(0);
}
     req = ntohs(req);
     printf("server: client request code is: %d\n",req);
     if (req!=REQUESTFILE) {
 
 printf("server: unsupported operation. goodbye\n");
         /* reply to client: command not OK  (code: 150) */
         msg_ok = COMMANDNOTSUPPORTED; 
         msg_ok = htons(msg_ok);
         if((writen(newsd,(char *)&msg_ok,sizeof(msg_ok))) < 0)
            {
printf("server: write error :%d\n",errno);exit(0);
}
         exit(0);
          
}
 
     /* reply to client: command OK  (code: 160) */
     msg_ok = COMMANDSUPPORTED; 
     msg_ok = htons(msg_ok);
     if((writen(newsd,(char *)&msg_ok,sizeof(msg_ok))) < 0)
             {
printf("server: write error :%d\n",errno);exit(0);
}
   
    fail = FILENAMEOK;
    if((read(newsd,fname,MAXLINE)) < 0) {
 
        printf("server: filename read error :%d\n",errno);
        fail = BADFILENAME ;
         
}
    
     /* IF SERVER CANT OPEN FILE THEN INFORM CLIENT OF THIS AND TERMINATE */
     if((fp = fopen(fname,"r")) == NULL) /*cant open file*/
        fail = BADFILENAME;
 
     tmp = htons(fail);
     if((writen(newsd,(char *)&tmp,sizeof(tmp))) < 0)
        {
printf("server: write error :%d\n",errno);exit(0);   
}
     if(fail == BADFILENAME) {
printf("server cant open file\n");
                            close(newsd);exit(0);
}
     printf("server: filename is %s\n",fname);
   
    req = 0;
    if ((readn(newsd,(char *)&req,sizeof(req))) < 0)
             {
printf("server: read error :%d\n",errno);exit(0);
}
    printf("server: start transfer command, %d, received\n", ntohs(req));
 
    
   /*SERVER GETS FILESIZE AND CALCULATES THE NUMBER OF BLOCKS OF 
     SIZE = MAXSIZE IT WILL TAKE TO TRANSFER THE FILE. ALSO CALCULATE
     NUMBER OF BYTES IN THE LAST PARTIALLY FILLED BLOCK IF ANY. 
     SEND THIS INFO TO CLIENT, RECEIVING ACKS */
    printf("server: starting transfer\n");
    fsize = 0;ack = 0;   
    while ((c = getc(fp)) != EOF) {
fsize++;
}
    num_blks = fsize / MAXSIZE; 
    num_blks1 = htons(num_blks);
    num_last_blk = fsize % MAXSIZE; 
    num_last_blk1 = htons(num_last_blk);
    if((writen(newsd,(char *)&num_blks1,sizeof(num_blks1))) < 0)
             {
printf("server: write error :%d\n",errno);exit(0);
}
    printf("server: told client there are %d blocks\n", num_blks);  
    if((readn(newsd,(char *)&ack,sizeof(ack))) < 0)
        {
printf("server: ack read error :%d\n",errno);exit(0); 
}          
    if (ntohs(ack) != ACK) {
 
      printf("client: ACK not received on file size\n");
      exit(0);
       
}
    if((writen(newsd,(char *)&num_last_blk1,sizeof(num_last_blk1))) < 0)
       {
printf("server: write error :%d\n",errno);exit(0);
}
    printf("server: told client %d bytes in last block\n", num_last_blk);  
    if((readn(newsd,(char *)&ack,sizeof(ack))) < 0)
        {
printf("server: ack read error :%d\n",errno);exit(0); 
}
    if (ntohs(ack) != ACK) {
 
      printf("server: ACK not received on file size\n");
      exit(0);
       
}
    rewind(fp);    
     
   
    /* ACTUAL FILE TRANSFER STARTS  BLOCK BY BLOCK*/      
        
   
  for(i= 0; i < num_blks; i ++) {
  
      no_read = fread(out_buf,sizeof(char),MAXSIZE,fp);
      if (no_read == 0) {
printf("server: file read error\n");exit(0);
}
      if (no_read != MAXSIZE)
              {
printf("server: file read error : no_read is less\n");exit(0);
}
      if((writen(newsd,out_buf,MAXSIZE)) < 0)
                 {
printf("server: error sending block:%d\n",errno);exit(0);
}
      if((readn(newsd,(char *)&ack,sizeof(ack))) < 0)
                 {
printf("server: ack read  error :%d\n",errno);exit(0);
}
      if (ntohs(ack) != ACK) {
 
          printf("server: ACK not received for block %d\n",i);
          exit(0);
           
}
      printf(" %d...",i);
       
}
 
   if (num_last_blk > 0) {
  
      printf("%d\n",num_blks);
      no_read = fread(out_buf,sizeof(char),num_last_blk,fp); 
      if (no_read == 0) {
printf("server: file read error\n");exit(0);
}
      if (no_read != num_last_blk) 
            {
printf("server: file read error : no_read is less 2\n");exit(0);
}
      if((writen(newsd,out_buf,num_last_blk)) < 0)
                 {
printf("server: file transfer error %d\n",errno);exit(0);
}
      if((readn(newsd,(char *)&ack,sizeof(ack))) < 0)
         {
printf("server: ack read  error %d\n",errno);exit(0);
}
      if (ntohs(ack) != ACK) {
 
          printf("server: ACK not received last block\n");
          exit(0);
           
}
       
}
    else printf("\n");
                                                   
   /* FILE TRANSFER ENDS */
   printf("server: FILE TRANSFER COMPLETE on socket %d\n",newsd);
   fclose(fp);
   close(newsd);
   
}
Beispiel #22
0
int main( int argc, char *argv[] )
{
	static int  nlen[M];	
	static char **name, **seq;
	static char **oseq;
	static double **pscore;
	static double *eff;
	static double **node0, **node1;
	static double *gapc;
	static double *avgap;
	double tmpavgap;
	int i, j, m, goffset;
	static int ***topol;
	static double **len;
	FILE *prep;
	char c;
	int corestart, coreend;
	int alloclen;
	int winsize;
	char *pt, *ot;
	double gapmin;

	arguments( argc, argv );

	getnumlen( stdin );
	rewind( stdin );

	if( njob < 2 )
	{
		fprintf( stderr, "At least 2 sequences should be input!\n"
						 "Only %d sequence found.\n", njob ); 
		exit( 1 );
	}

	seq = AllocateCharMtx( njob, nlenmax*9+1 );
	name = AllocateCharMtx( njob, B+1 );
	oseq = AllocateCharMtx( njob, nlenmax*9+1 );
	alloclen = nlenmax*9;

	topol = AllocateIntCub( njob, 2, njob );
	len = AllocateDoubleMtx( njob, 2 );
	pscore = AllocateDoubleMtx( njob, njob );
	eff = AllocateDoubleVec( njob );
	node0 = AllocateDoubleMtx( njob, njob );
	node1 = AllocateDoubleMtx( njob, njob );
	gapc = AllocateDoubleVec( alloclen );
	avgap = AllocateDoubleVec( alloclen );

#if 0
	Read( name, nlen, seq );
#else
	readData_pointer( stdin, name, nlen, seq );
#endif

	constants( njob, seq );

#if 0
	fprintf( stderr, "params = %d, %d, %d\n", penalty, penalty_ex, offset );
#endif

	initSignalSM();

	initFiles();

	WriteOptions( trap_g );

	c = seqcheck( seq );
	if( c )
	{
		fprintf( stderr, "Illeagal character %c\n", c );
		exit( 1 );
	}

	writePre( njob, name, nlen, seq, 0 );

	if( tbutree == 0 )
	{
		for( i=1; i<njob; i++ ) 
		{
			if( nlen[i] != nlen[0] ) 
			{
				fprintf( stderr, "Input pre-aligned seqences or make hat2.\n" );
				exit( 1 );
			}
		}
		for( i=0; i<njob-1; i++ ) for( j=i+1; j<njob; j++ ) 
		{
		/*
			pscore[i][j] = (double)score_calc1( seq[i], seq[j] );
		*/
			pscore[i][j] = (double)substitution_hosei( seq[i], seq[j] );
		}
	}
	else
	{
		fprintf( stderr, "Loading 'hat2' ... " );
		prep = fopen( "hat2", "r" );
		if( prep == NULL ) ErrorExit( "Make hat2." );
		readhat2_pointer( prep, njob, name, pscore );
		fclose( prep );
		fprintf( stderr, "done.\n" );

#if 0
		prep = fopen( "hat2_check", "w" );
		WriteHat2( prep, njob, name, pscore );
		fclose( prep );
#endif

	}

	fprintf( stderr, "Constructing dendrogram ... " );
	if( treemethod == 'x' )
		supg( njob, pscore, topol, len );
	else if( treemethod == 's' )
		spg( njob, pscore, topol, len );
	else if( treemethod == 'p' )
		upg2( njob, pscore, topol, len );
	else 
		ErrorExit( "Incorrect tree\n" );
	fprintf( stderr, "done.\n" );

	countnode( njob, topol, node0 );
	if( tbrweight )
	{
		weight = 3; 
#if 0
		utree = 0; counteff( njob, topol, len, eff ); utree = 1;
#else
		counteff_simple( njob, topol, len, eff );
#endif
	}
	else
	{
		for( i=0; i<njob; i++ ) eff[i] = 1.0;
	}


	for( i=0; i<nlenmax; i++ )
	{
		gapc[i] = 0.0;
		for( j=0; j<njob; j++ )
		{
			if( seq[j][i] == '-' ) gapc[i] += eff[j];
		}
	}

	gapmin = 1.0;
	winsize = fftWinSize;
	goffset = winsize/2;
	tmpavgap = 0.0;
	corestart = coreend = -1;
	for( i=0; i<winsize; i++ )
	{
		tmpavgap += gapc[i];
	}
	for( i=winsize; i<nlenmax; i++ )
	{
		m = i - goffset;
		avgap[m] = tmpavgap / winsize;
//		fprintf( stdout, "%d %f %f\n", m, avgap[m], gapc[i] );
		if( avgap[m] < corethr )
		{
			if( corestart == -1 )
				corestart = i - winsize;
//			fprintf( stdout, "ok, gapmin = %f, corestart = %d, coreend = %d\n", gapmin, corestart, coreend );
			if( avgap[m] < gapmin )
			{ 
				gapmin = avgap[m];
			}
			coreend = i;
		}
		tmpavgap -= gapc[i-winsize];
		tmpavgap += gapc[i];
	}
	if( corestart == -1 || coreend == -1 )
	{
		corestart = 0;
		coreend = nlenmax-1;
	}

	for( i=0; i<njob; i++ )
	{
		pt = oseq[i];
		m = winsize;
		while( m-- ) *pt++ = '-';
		for( j=corestart; j<=coreend; j++ )
			*pt++ = seq[i][j];
		m = winsize;
		while( m-- ) *pt++ = '-';
		*pt = 0;

		ot = oseq[i]+winsize-1;
		pt = seq[i]+corestart-1;
		if( coreext ) m = winsize;
		else m = 0;
		while( m && --pt > seq[i] )
			if( *pt != '-' )
			{
				*ot-- = *pt;
				m--;
			}

		ot = oseq[i]+winsize+coreend-corestart+1;
		pt = seq[i]+coreend;
		if( coreext ) m = winsize;
		else m = 0;
		while( m && *(++pt) )
		{
			if( *pt != '-' ) 
			{
				*ot++ = *pt;
				m--;
			}
		}
		fprintf( stdout, ">%s\n", name[i] );
		fprintf( stdout, "%s\n", oseq[i] );
	}

	exit( 1 );

	SHOWVERSION;
	return( 0 );
}
Beispiel #23
0
int main()
{
	FILE *f;
	int arr[]={-6, 7, -4, 8, -3, 0, 7, 10, 3};

	if ( !( f=fopen("sort.dat", "w+b") ) )
	{
		printf("FATAL ERROR IN FILE CREATING");
		_getch();
		return 0;
	}

	fwrite(arr, sint, sizeof(arr)/sint, f);
	rewind(f);

// Блок первоначального вывода

	int i,j;
	puts("sourse file");
	for (i = 0; i < sizeof(arr)/sint && !feof(f); i++)
	{
		fread(&j, sint, 1, f);
		printf("%d  ", j);
	}
	rewind(f);

// Сортировка отбором

	int  min, num, i1;
	for ( i = 0; i < sizeof(arr)/sint-1; i++)
	{
		i1=i;
		fseek(f,i*sint,0);
		fread(&min, sint, 1, f);			// перемещаемся на первый элемент итерации и считываем его
		while (true)
		{
			fread(&num, sint, 1, f);		
			if (feof(f)) break;				// считываем следующий элемент с проверкой выхода из файла
			if(num<=min)					// если следующее число больше максимума
			{
				i1=ftell(f)/sint-1;			// запоминаем его местоположение
				min=num;					// меняем максимум
			}
		}
		rewind(f);
		if (i1!=i)							// если новый максимум находится не там, где первый элемент итерации
			if(swap(f, i, i1))
			{
				printf("FATAL ERROR IN TRANSFERING FILE TO FUNCTION");
				_getch();
			}
	}

// сортировка пузырьком

	//int n1, n2;
	//for (i = 0; i < sizeof(arr)/sint-1; i++)
	//	for (j = sizeof(arr)/sint-1; j > i; j--)
	//	{
	//		fseek(f, (j-1)*sint, 0);
	//		fread(&n1, sint, 1, f);
	//		fread(&n2, sint, 1, f);
	//		if (n1>n2)
	//			if(swap(f, j-1, j))
	//			{
	//				printf("FATAL ERROR IN TRANSFERING FILE TO FUNCTION");
	//				_getch();
	//			}
	//	}


// Блок вывода
	rewind(f);
	puts("\nsorted sourse file");
	for (i = 0; i < sizeof(arr)/sint && !feof(f); i++)
	{
		fread(&j, sint, 1, f);
		printf("%d  ", j);
	}


	fclose(f);
	_getch();
	return 0;

}
bool QgsPostgresFeatureIterator::declareCursor( const QString& whereClause )
{
  mFetchGeometry = !( mRequest.flags() & QgsFeatureRequest::NoGeometry ) && !mSource->mGeometryColumn.isNull();

#if 0
  // TODO: check that all field indexes exist
  if ( !hasAllFields )
  {
    rewind();
    return false;
  }
#endif

  QString query( "SELECT " ), delim( "" );

  if ( mFetchGeometry )
  {
    QString geom = QgsPostgresConn::quotedIdentifier( mSource->mGeometryColumn );

    if ( mSource->mSpatialColType == sctGeography ||
         mSource->mSpatialColType == sctPcPatch )
      geom += "::geometry";

    if ( mSource->mForce2d )
    {
      geom = QString( "%1(%2)" )
             // Force_2D before 2.0
             .arg( mConn->majorVersion() < 2 ? "force_2d"
                   // ST_Force2D since 2.1.0
                   : mConn->majorVersion() > 2 || mConn->minorVersion() > 0 ? "st_force2d"
                   // ST_Force_2D in 2.0.x
                   : "st_force_2d",
                   geom );
    }

    if ( !mRequest.simplifyMethod().forceLocalOptimization() &&
         mRequest.simplifyMethod().methodType() != QgsSimplifyMethod::NoSimplification &&
         QGis::flatType( QGis::singleType( mSource->mRequestedGeomType != QGis::WKBUnknown
                                           ? mSource->mRequestedGeomType
                                           : mSource->mDetectedGeomType ) ) != QGis::WKBPoint )
    {
      geom = QString( "%1(%2,%3)" )
             .arg( mRequest.simplifyMethod().methodType() == QgsSimplifyMethod::OptimizeForRendering
                   ? ( mConn->majorVersion() < 2 ? "snaptogrid" : "st_snaptogrid" )
                       : ( mConn->majorVersion() < 2 ? "simplifypreservetopology" : "st_simplifypreservetopology" ),
                       geom )
                 .arg( mRequest.simplifyMethod().tolerance() * 0.8 ); //-> Default factor for the maximum displacement distance for simplification, similar as GeoServer does
    }

    geom = QString( "%1(%2,'%3')" )
           .arg( mConn->majorVersion() < 2 ? "asbinary" : "st_asbinary",
                 geom,
                 QgsPostgresProvider::endianString() );

    query += delim + geom;
    delim = ",";
  }

  switch ( mSource->mPrimaryKeyType )
{
    case pktOid:
      query += delim + "oid";
      delim = ",";
      break;

    case pktTid:
      query += delim + "ctid";
      delim = ",";
      break;

    case pktInt:
      query += delim + QgsPostgresConn::quotedIdentifier( mSource->mFields[ mSource->mPrimaryKeyAttrs[0] ].name() );
      delim = ",";
      break;

    case pktFidMap:
      Q_FOREACH ( int idx, mSource->mPrimaryKeyAttrs )
      {
        query += delim + mConn->fieldExpression( mSource->mFields[idx] );
        delim = ",";
      }
      break;

    case pktUnknown:
      QgsDebugMsg( "Cannot declare cursor without primary key." );
      return false;
      break;
  }

  bool subsetOfAttributes = mRequest.flags() & QgsFeatureRequest::SubsetOfAttributes;
  Q_FOREACH ( int idx, subsetOfAttributes ? mRequest.subsetOfAttributes() : mSource->mFields.allAttributesList() )
  {
    if ( mSource->mPrimaryKeyAttrs.contains( idx ) )
      continue;

    query += delim + mConn->fieldExpression( mSource->mFields[idx] );
  }

  query += " FROM " + mSource->mQuery;

  if ( !whereClause.isEmpty() )
    query += QString( " WHERE %1" ).arg( whereClause );

  if ( !mConn->openCursor( mCursorName, query ) )
  {

    // reloading the fields might help next time around
    // TODO how to cleanly force reload of fields?  P->loadFields();
    close();
    return false;
  }

  return true;
}
Beispiel #25
0
void iorm_use(io_desc *iod, mval *pp)
{
	unsigned char	c;
	int4		width, length, blocksize;
	int4		status;
	d_rm_struct	*rm_ptr;
	struct RAB	*r;
	struct FAB	*f;
	int 		p_offset;
	boolean_t	shared_seen = FALSE;

	error_def(ERR_DEVPARMNEG);
	error_def(ERR_RMWIDTHPOS);
	error_def(ERR_RMWIDTHTOOBIG);
	error_def(ERR_RMNOBIGRECORD);
	error_def(ERR_RMBIGSHARE);
	error_def(ERR_MTBLKTOOBIG);
	error_def(ERR_MTBLKTOOSM);

	p_offset = 0;
	rm_ptr = (d_rm_struct *)iod->dev_sp;
	r  = &rm_ptr->r;
	f  = &rm_ptr->f;
	assert(r->rab$l_fab == f);
	while (*(pp->str.addr + p_offset) != iop_eol)
	{
		assert(*(pp->str.addr + p_offset) < n_iops);
		switch ((c = *(pp->str.addr + p_offset++)))
		{
		case iop_allocation:
			if (iod->state != dev_open)
				f->fab$l_alq = *(int4*)(pp->str.addr + p_offset);
			break;
		case iop_append:
			if (iod->state != dev_open)
				r->rab$l_rop |= RAB$M_EOF;
			break;
		case iop_blocksize:
			if (iod->state != dev_open)
			{
				GET_LONG(blocksize, pp->str.addr + p_offset);
				if (MAX_RMS_ANSI_BLOCK < blocksize)
					rts_error(VARLSTCNT(1) ERR_MTBLKTOOBIG);
				else if (MIN_RMS_ANSI_BLOCK > blocksize)
					rts_error(VARLSTCNT(3) ERR_MTBLKTOOSM, 1, MIN_RMS_ANSI_BLOCK);
				else
					f->fab$w_bls = (unsigned short)blocksize;
			}
			break;
		case iop_contiguous:
			if (iod->state != dev_open)
			{
				f->fab$l_fop &= ~FAB$M_CBT;
				f->fab$l_fop |= FAB$M_CTG;
			}
			break;
		case iop_delete:
			f->fab$l_fop |= FAB$M_DLT;
			break;
		case iop_extension:
			GET_USHORT(f->fab$w_deq, pp->str.addr + p_offset);
			break;
		case iop_exception:
			iod->error_handler.len = *(pp->str.addr + p_offset);
			iod->error_handler.addr = pp->str.addr + p_offset + 1;
			s2pool(&iod->error_handler);
			break;
		case iop_fixed:
			if (iod->state != dev_open)
				rm_ptr->f.fab$b_rfm = rm_ptr->b_rfm = FAB$C_FIX;
			break;
		case iop_length:
			GET_LONG(length, pp->str.addr + p_offset);
			if (length < 0)
				rts_error(VARLSTCNT(1) ERR_DEVPARMNEG);
			iod->length = length;
			break;
		case iop_newversion:
			if (iod->state != dev_open)
			{
				f->fab$l_fop |= FAB$M_MXV;
				f->fab$l_fop &= ~(FAB$M_CIF | FAB$M_SUP);
			}
			break;
		case iop_nosequential:
			break;
		case iop_s_protection:
			rm_ptr->promask &= ~(0x0F << XAB$V_SYS);
			rm_ptr->promask |= ((~(unsigned char)*(pp->str.addr + p_offset) & 0x0000000F) << XAB$V_SYS);
			break;
		case iop_w_protection:
			rm_ptr->promask &= ~(0x0F << XAB$V_WLD);
			rm_ptr->promask |= ((~(unsigned char)*(pp->str.addr + p_offset) & 0x0000000F) << XAB$V_WLD);
			break;
		case iop_g_protection:
			rm_ptr->promask &= ~(0x0F << XAB$V_GRP);
			rm_ptr->promask |= ((~(unsigned char)*(pp->str.addr + p_offset) & 0x0000000F) << XAB$V_GRP);
			break;
		case iop_o_protection:
			rm_ptr->promask &= ~(0x0F << XAB$V_OWN);
			rm_ptr->promask |= ((~(unsigned char)*(pp->str.addr + p_offset) & 0x0000000F) << XAB$V_OWN);
			break;
		case iop_readonly:
			if (iod->state != dev_open)
				f->fab$b_fac = FAB$M_GET;
			break;
		case iop_noreadonly:
			if (iod->state != dev_open)
				f->fab$b_fac = FAB$M_GET | FAB$M_PUT | FAB$M_TRN;
			break;
		case iop_recordsize:
			if (iod->state != dev_open)
			{
				GET_LONG(width, pp->str.addr + p_offset);
				if (width <= 0)
					rts_error(VARLSTCNT(1) ERR_RMWIDTHPOS);
				iod->width = width;
				if (MAX_RMS_RECORDSIZE >= width)
					r->rab$w_usz = f->fab$w_mrs = (unsigned short)width;
				else if (MAX_STRLEN < width)
					rts_error(VARLSTCNT(1) ERR_RMWIDTHTOOBIG);
				else if (!rm_ptr->largerecord)
					rts_error(VARLSTCNT(1) ERR_RMNOBIGRECORD);
				rm_ptr->l_usz = rm_ptr->l_mrs = width;
			}
			break;
		case iop_shared:
			if (iod->state != dev_open)
				shared_seen = TRUE;
			break;
		case iop_spool:
			f->fab$l_fop |= FAB$M_SPL;
			break;
		case iop_submit:
			f->fab$l_fop |= FAB$M_SCF;
			break;
		case iop_rfa:
			break;
		case iop_space:
			if (iod->state == dev_open && f->fab$l_dev & DEV$M_SQD)
			{
				GET_LONG(r->rab$l_bkt, pp->str.addr + p_offset);
				if ((status = sys$space(r, 0, 0)) != RMS$_NORMAL)
					rts_error(VARLSTCNT(1) status);
				r->rab$l_bkt = 0;
			}
			break;
		case iop_uic:
		{
			unsigned char	*ch, ct, *end;
			uic_struct	uic;
			struct XABPRO	*xabpro;

			ch = pp->str.addr + p_offset;
			ct = *ch++;
			end = ch + ct;
			uic.grp = uic.mem = 0;
			xabpro = malloc(SIZEOF(struct XABPRO));
			*xabpro = cc$rms_xabpro;
/* g,m are octal - no matter currently since iorm_open overwrites fab xab */
			while (*ch != ',' &&	ch < end)
				uic.grp = (10 * uic.grp) + (*ch++ - '0');
			if (*ch == ',')
			{
				while (++ch < end)
					uic.mem = (10 * uic.mem) + (*ch - '0');
			}
			xabpro->xab$l_uic = *((int4 *)&uic);
			f->fab$l_xab = xabpro;
			break;
		}
		case iop_width:
			if (iod->state == dev_open)
			{
				GET_LONG(width, pp->str.addr + p_offset);
				if (width <= 0)
					rts_error(VARLSTCNT(1) ERR_RMWIDTHPOS);
				else  if (width <= rm_ptr->l_mrs)
				{
					iorm_flush(iod);
					rm_ptr->l_usz = iod->width = width;
					if (!rm_ptr->largerecord)
						r->rab$w_usz = (short)width;
					iod->wrap = TRUE;
				}
			}
			break;
		case iop_wrap:
			iod->wrap = TRUE;
			break;
		case iop_nowrap:
			iod->wrap = FALSE;
			break;
		case iop_convert:
			r->rab$l_rop |= RAB$M_CVT;
			break;
		case iop_rewind:
			if (iod->state == dev_open && rm_ptr->f.fab$l_dev & DEV$M_FOD)
			{
				if (iod->dollar.zeof && rm_ptr->outbuf_pos > rm_ptr->outbuf)
					iorm_wteol(1, iod);
				sys$rewind(r);
				iod->dollar.zeof = FALSE;
				iod->dollar.y = 0;
				iod->dollar.x = 0;
				rm_ptr->outbuf_pos = rm_ptr->outbuf;
				rm_ptr->r.rab$l_ctx = FAB$M_GET;
			}
			break;
		case iop_truncate:
			r->rab$l_rop |= RAB$M_TPT;
			break;
		case iop_notruncate:
			r->rab$l_rop &= ~RAB$M_TPT;
			break;
		case iop_bigrecord:
			if (iod->state != dev_open)
				rm_ptr->largerecord = TRUE;
			break;
		case iop_nobigrecord:
			if (iod->state != dev_open)
			{
				if (MAX_RMS_RECORDSIZE < rm_ptr->l_mrs)
					rts_error(ERR_RMNOBIGRECORD);
				rm_ptr->largerecord = FALSE;
			}
			break;
		case iop_rfm:
			break;
		default:
			break;
		}
		p_offset += ((IOP_VAR_SIZE == io_params_size[c]) ?
			(unsigned char)*(pp->str.addr + p_offset) + 1 : io_params_size[c]);
	}
	if (shared_seen)
	{
		f->fab$b_shr = FAB$M_SHRGET;
		if (rm_ptr->largerecord)
		{
			if (f->fab$b_fac & FAB$M_PUT)
			{
				rts_error(VARLSTCNT(1) ERR_RMBIGSHARE);
			}
		} else if ((f->fab$b_fac & FAB$M_PUT) == FALSE)
			f->fab$b_shr |= FAB$M_SHRPUT;
	}
}/* eor */
Beispiel #26
0
void
closecal(FILE *fp)
{
	uid_t uid;
	struct stat sbuf;
	int nread, pdes[2], status;
	char buf[1024];

	if (!doall)
		return;

	rewind(fp);
	if (fstat(fileno(fp), &sbuf) || !sbuf.st_size)
		goto done;
	if (pipe(pdes) < 0)
		goto done;
	switch (fork()) {
	case -1:			/* error */
		(void)close(pdes[0]);
		(void)close(pdes[1]);
		goto done;
	case 0:
		/* child -- set stdin to pipe output */
		if (pdes[0] != STDIN_FILENO) {
			(void)dup2(pdes[0], STDIN_FILENO);
			(void)close(pdes[0]);
		}
		(void)close(pdes[1]);
		uid = geteuid();
		if (setuid(getuid()) < 0) {
			warnx("setuid failed");
			_exit(1);
		}
		if (setgid(getegid()) < 0) {
			warnx("setgid failed");
			_exit(1);
		}
		if (setuid(uid) < 0) {
			warnx("setuid failed");
			_exit(1);
		}
		execl(_PATH_SENDMAIL, "sendmail", "-i", "-t", "-F",
		    "\"Reminder Service\"", (char *)NULL);
		warn(_PATH_SENDMAIL);
		_exit(1);
	}
	/* parent -- write to pipe input */
	(void)close(pdes[0]);

	write(pdes[1], "From: \"Reminder Service\" <", 26);
	write(pdes[1], pw->pw_name, strlen(pw->pw_name));
	write(pdes[1], ">\nTo: <", 7);
	write(pdes[1], pw->pw_name, strlen(pw->pw_name));
	write(pdes[1], ">\nSubject: ", 11);
	write(pdes[1], dayname, strlen(dayname));
	write(pdes[1], "'s Calendar\nPrecedence: bulk\n\n", 30);

	while ((nread = read(fileno(fp), buf, sizeof(buf))) > 0)
		(void)write(pdes[1], buf, nread);
	(void)close(pdes[1]);
done:	(void)fclose(fp);
	(void)unlink(path);
	while (wait(&status) >= 0);
}
Beispiel #27
0
int main(int argc, char* argv[])
{
  int i;
  FILE *hmmfile, *outfile, *alphafile, *outfile_tmp;
  int nr_alphabets;
  int alphabet_nr;
  int hmmfiletype;

  struct gengetopt_args_info args_info;

  hmmfile = NULL;
  outfile = NULL;
  alphafile = NULL;
  outfile_tmp = NULL;
  verbose = NO;
  
  /* parse command line */

  if(cmdline_parser(argc, argv, &args_info) != 0) {
    exit(1);
  }
  
  /* compulsory options */
  if(args_info.hmminfile_given) {
    if((hmmfile = fopen(args_info.hmminfile_arg, "r")) == NULL) {
      perror(args_info.hmminfile_arg);
      exit(0);

    }
    else {
      printf("Opened file %s for reading model file\n",args_info.hmminfile_arg);
    }
  }
  if(args_info.outfile_given) {
    if((outfile = fopen(args_info.outfile_arg, "w")) == NULL) {
      perror(args_info.outfile_arg);
      exit(0);
    }
    else {
      printf("Opened file %s for writing\n",args_info.outfile_arg);
    }
  }
  

  
  if(args_info.alphafile_given) {
    if((alphafile = fopen(args_info.alphafile_arg, "r")) == NULL) {
      perror(args_info.alphafile_arg);
      exit(0);
    }
    else {
      printf("Opened file %s for reading alphabet file\n",args_info.alphafile_arg);
    }
  }
  
  if(args_info.verbose_given) {
    verbose = YES;
  }
  
  
  /* find out nr of alphabets */
  nr_alphabets = get_nr_alphabets(hmmfile);
  rewind(hmmfile);
  

  
  /* get hmm from file */
  printf("starting reading\n");  
  if(hmmfile != NULL) {
    hmmfiletype = readhmm_check(hmmfile);
    if(hmmfiletype == SINGLE_HMM) {
      readhmm(hmmfile, &hmm);
    }
    else if(hmmfiletype == MULTI_HMM) {
      readhmm_multialpha(hmmfile, &hmm);
    }
  }
  else {
    /* cannot happen */
    printf("Internal error: hmmfile not found, should have been detected earlier\n");
  }



  /* read additional alphabet info */
  if(hmm.nr_alphabets > 3) {
    printf("Error: maximum number of alphabets is 4\n");
    exit(0);
  }
  else {
    alphabet_nr = hmm.nr_alphabets + 1;
    read_additional_alphabet(alphafile, &hmm, alphabet_nr);
  }
  


  /* save adjusted hmm */
  printf("finished reading, starting save\n");
  savehmm_multialpha(outfile, &hmm);
  printf("finished save\n");
  

  /* garbage collection */
  hmm_garbage_collection_multi(hmmfile, &hmm);
  fclose(outfile);
  fclose(alphafile);
 
  /*****************************************************************************************/
  /* remember that garbage collection has not been done here */

}
Beispiel #28
0
void data_init()
{
	int i;

	data.Nth = 4;

	data.iord = 2;

	data.lb = -1e38;
	data.ub = +1e38;

	data.lowerbound = malloc(data.Nth*sizeof(double));
	data.upperbound = malloc(data.Nth*sizeof(double));
	data.theta = malloc(data.Nth*sizeof(double));

	for (i = 0; i < data.Nth; i++) data.lowerbound[i] = data.lb;
	for (i = 0; i < data.Nth; i++) data.upperbound[i] = data.ub;
	for (i = 0; i < data.Nth; i++) data.theta[i] = 1.0;

	data.uh = 1e-4;
	data.diffstep = malloc(data.Nth*sizeof(double));
	for (i = 0; i < data.Nth; i++) data.diffstep[i] = data.uh;
	data.posdef = -1;


/**********************************************/
// PARAMS
/**********************************************/

	/* USER-DEFINED VALUES */
	FILE *f = fopen("grad.par", "r");
	if (f == NULL) {
		return;
	}

	/*
	Nth		4
	order		2
	Bdef		-4	4

	lb		0 0 0 0 
	ub		2 2 2 2
	theta		1 1 1 1

	Hdef		1e-4
	diffstep	1-e4 1e-4 1e-4 1e-4 
	posdef		-1
	*/

	char line[256];

	int line_no = 0;
	while (fgets(line, 256, f)!= NULL) {
		line_no++;
		if ((line[0] == '#')||(strlen(line)==0)) {
			printf("ignoring line %d\n", line_no);
			continue;
		}

		if (strstr(line, "Nth")) {
			sscanf(line, "%*s %d", &data.Nth);
		}
		else if (strstr(line, "order")) {
			sscanf(line, "%*s %d", &data.iord);
		}
		else if (strstr(line, "Bdef")) {
			sscanf(line, "%*s %lf %lf", &data.lb, &data.ub);
		}
		else if (strstr(line, "Hdef")) {
			sscanf(line, "%*s %lf", &data.uh);
		}
		else if (strstr(line, "posdef")) {
			sscanf(line, "%*s %d", &data.posdef);
		}
	}

	rewind(f);
	line_no = 0;

	free(data.lowerbound);
	free(data.upperbound);
	free(data.theta);
	free(data.diffstep);
	data.lowerbound = (double *)malloc(data.Nth*sizeof(double));
	data.upperbound = (double *)malloc(data.Nth*sizeof(double));
	data.theta = (double *)malloc(data.Nth*sizeof(double));
	data.diffstep = (double *)malloc(data.Nth*sizeof(double));

	for (i = 0; i < data.Nth; i++) data.lowerbound[i] = data.lb;
	for (i = 0; i < data.Nth; i++) data.upperbound[i] = data.ub;
	for (i = 0; i < data.Nth; i++) data.theta[i] = 1.0;
	for (i = 0; i < data.Nth; i++) data.diffstep[i] = data.uh;

	rewind(f);
	while (fgets(line, 256, f)!= NULL) {
		line_no++;

		if ((line[0] == '#')||(strlen(line)==0)) continue;

		if (strstr(line, "theta")) {
			char *p;
			p = strtok(line, " \t\n");
			for (i = 0; i < data.Nth; i++) {
				p = strtok(NULL, " \t\n");
				if (!p) break;
				data.theta[i] = atof(p);
                        }
                }
		else if (strstr(line, "lb")) {
			char *p;
			p = strtok(line, " \t\n");
			for (i = 0; i < data.Nth; i++) {
				p = strtok(NULL, " \t\n");
				if (!p) break;
				data.lowerbound[i] = atof(p);
                        }
                }
		else if (strstr(line, "ub")) {
			char *p;
			p = strtok(line, " \t\n");
			for (i = 0; i < data.Nth; i++) {
				p = strtok(NULL, " \t\n");
				if (!p) break;
				data.upperbound[i] = atof(p);
                        }
                }
		else if (strstr(line, "diffstep")) {
			char *p;
			p = strtok(line, " \t\n");
			for (i = 0; i < data.Nth; i++) {
				p = strtok(NULL, " \t\n");
				if (!p) break;
				data.diffstep[i] = atof(p);
                        }
                }
        }

	for (i = 0; i < data.Nth; i++) {
                printf("param %d: %f < %f < %f: %f\n", i, data.lowerbound[i], data.theta[i], data.upperbound[i], data.diffstep[i]);
        }

	fclose(f);


}
Beispiel #29
0
struct cat* read_cat(const char* fname, int64 nside, double radius_arcsec, int verbose) {

    int barsize=70;

    FILE* fptr=open_file(fname);


    size_t nlines=countlines(fptr);
    if (verbose) wlog("    found %lu lines\n", nlines);
    rewind(fptr);

    struct cat* cat = alloc_or_die(sizeof(struct cat), "catalog struct");

    double radius_radians=0;
    if (radius_arcsec <= 0) {
        cat->radius_in_file=1;
        cat->cos_radius = alloc_or_die(nlines*sizeof(double), "cos_radius array");
    } else {
        cat->radius_in_file=0;
        cat->cos_radius = alloc_or_die(sizeof(double), "cos_radius");

        radius_radians = radius_arcsec/3600.*D2R;
        cat->cos_radius[0] = cos(radius_radians);
    }

    cat->hpix=NULL;
    cat->tree=NULL;

    cat->pts = alloc_or_die(nlines*sizeof(struct point),"points");
    cat->size = nlines;

    if (verbose) wlog("    creating hpix\n");
    cat->hpix = hpix_new(nside);

    if (verbose) {
        wlog("    reading and building tree\n");
        repeat_char('.', barsize); wlog("\n");
    }

    double ra=0, dec=0;
    struct i64stack* listpix = i64stack_new(0);

    // this will produce a more balanced tree across the whole sky
    int64 half_npix=cat->hpix->npix/2;

    size_t count=0;
    struct point* pt = &cat->pts[0];
    for (size_t i=0; i<cat->size; i++) {
        if (2 != fscanf(fptr, "%lf %lf", &ra, &dec)) {
            wlog("expected to read point at line %lu\n", i);
            exit(EXIT_FAILURE);
        }
        if (cat->radius_in_file) {
            if (1 != fscanf(fptr, "%lf", &radius_arcsec)) {
                wlog("expected to read radius at line %lu\n", i);
                exit(EXIT_FAILURE);
            }
            radius_radians = radius_arcsec/3600.*D2R;
            cat->cos_radius[i] = cos(radius_radians);
        }

        hpix_eq2xyz(ra,dec,&pt->x,&pt->y,&pt->z);

        hpix_disc_intersect(cat->hpix, pt->x, pt->y, pt->z, radius_radians, 
                            listpix);

        int64* ptr=listpix->data;
        while (ptr < listpix->data + listpix->size) {
            tree_insert(&cat->tree, (*ptr)-half_npix, count);
            ptr++;
        }

        pt++;
        count++;
        if (verbose) incr_bar(i+1, cat->size, barsize, '=');
    }
    listpix=i64stack_delete(listpix);

    if (verbose) wlog("\n");

    if (count != nlines) {
        wlog("expected %lu lines but read %lu\n", nlines, count);
        exit(EXIT_FAILURE);
    }

    if (verbose)
        wlog("fullest node has %lu members\n", tree_most_members(cat->tree));

    fclose(fptr);
    return cat;
}
Beispiel #30
0
int main( int argc , char * argv[ ] )
{
  FILE * pdxdr , * pfreq , * patomlist , * pfakefreq ;
  
  FILE * debug ;
  
  char dxdrname [ 50 ] , atomlistname [ 50 ] , freqname [ 50 ], outfreqname [ 50 ] ;
  
  char ** pcmd ; pcmd = argv ;
  
  int icmd , itmp ;
  
  int natom , ncart , nmode , nfreqprovide;
  
  int natomSelect , ncartSelect , nmodeSelect ;
  
  int icart , iatom , imode , ifreq ;
  
  int exfreq , exatomlist , exselect ;
  
  
  char buffer[ MAXCHARINLINE ] ;

  int lenBuff ;

  char cache[ MAXCHARINLINE ] ;

  char stmp[ 150 ] , stmp2[ 150 ] , tmpString[ 150 ];
  
  

  time_t current_time;

  time( &current_time );

  char now[ 300 ] ;

  strcpy( now , ctime( &current_time ) );

  int lennow = strlen( now ) ;

  *( now + lennow - 1 ) = ' ';

   
  // ========> Recording Command-Line Arguments ...
  
    printf("\n**********************************************************************\n");
      printf("* G_FAKEFREQ_D : Organize (DX/DR) into G09 Format for visualization. *\n");
      printf("*                                                                    *\n");
      printf("*  ");
  for( icmd = 0 ; icmd < argc ; icmd ++ )
  {
    printf("%s " , *( pcmd + icmd ) );
  }
  printf("\n");
      printf("*                                                                    *\n");
      printf("*                                                                    *\n");
      printf("* Current Time : %s                           *\n" , now );
      printf("*                                                                    *\n");
      printf("*                                                                    *\n");
      printf("**********************************************************************\n");

 

  // =====> Setting up default file names ... 
  
  
  strcpy( dxdrname , "dxdr.deb" );
  
  strcpy( freqname , "vibfrequency.deb" );
  
  strcpy( outfreqname , "fakeg09.freq" );
  
  strcpy( atomlistname , "atom.list" );
  
  // =====> Parsing command line input arguments ...
  
  exselect = 20 ;
  
  if( argc == 1 )
  {
    printf("\n\nNo command-line arguments provided ... Mission aborting ...\n\n");
    
    printf("\nPlease refer to the usage by typing ' %s -h '\n\n" , * argv );
    
    exit(1); 

  }

  char * flag ;
  
  icmd = 1 ;

  while( icmd < argc )
  {  
    pcmd ++ ; 

    flag = * pcmd ;

    printf("\nNo.%d argument , Currently @ flag = %s ...\n\n" , icmd , flag );

    if( ( * flag == '-' ) && ( strlen( flag ) == 2 ) )
    {
      switch ( *( flag + 1 ) )
      {
	      
	      case 'f' : strcpy( dxdrname , *( ++ pcmd ) ) ; 
			 
			         printf("\nCommand-line argument indicates : Input dxdr File name : %s ...\n" , dxdrname ); 
	      
	                 icmd = icmd + 2 ; 
	                 
	                 break ;

	      case 'o' : strcpy( outfreqname , *( ++ pcmd ) ); 
	      
	                 printf("\nCommand-line argument indicates : Output File name : %s ...\n" , outfreqname ); 
	                 
	                 icmd = icmd + 2 ; 
	                 
	                 break ; 
	                 
	      case 'w' : strcpy( freqname , *( ++ pcmd ) );
	      
	                 printf("\nCommand-line argument indicates : Input frequency File name : %s ...\n" , freqname ); 
	                 
	                 icmd = icmd + 2 ;
	                 
	                 break ;

	      case 'l' : strcpy( atomlistname , *( ++ pcmd ) );
	      
	                 printf("\nCommand-line argument indicates : Input atom list File name : %s ...\n" , atomlistname ); 
	                 
	                 icmd = icmd + 2 ;
	                 
	                 break ;
	      
	      case 's' : strcpy( tmpString , *( ++ pcmd ) ) ;
	      
	                 if( strcmp( tmpString , "all" ) == 0 || strcmp( tmpString , "All" ) == 0 )
	                 {
	                   exselect = 22 ;
	                   
	                   printf("\nCommand-line argument indicates : All atoms will be chosen as solute ...\n" );
	                 }
	                 else
	                 {
	                   printf("\nReceived information : %s ...\n" , tmpString ) ;
	                   
	                   natomSelect = atoi( tmpString ); 
	                  
	                   exselect = 21 ;
	                   
	                   printf("\nCommand-line argument indicates : First %d atoms will be chosen as solute ...\n" , natomSelect );
	                 
	                 }

	                 
	                 icmd = icmd + 2 ; 
	                 
	                 break ;
          

          
	      case 'h' : printf("\nUsage:  %s [ -f 'input dxdr file name' ] [(optional) -o 'output NM assignment file name' ] [ -l atom list file (listing the atomic number of all atoms in system)] [ -s # of atom selected to output ] [ -w 'input vibrational frequency file' ]\n\n" , * argv ); 
	                 
	                 printf("\n\n==> NOTE : In order to be fool-proof , if there is mis-match on the NAtom between dxdr file and any other file , this code will set NAtom to be the number from dxdr automatically ...\n\n");
	                 
	                 //printf("\nUsage:  %s [ -t G09 calculation type : 1=ONIOM ; 2=Point Charge ] [ -f 'input gro file name' ] [(optional) -o 'output g09 file name' ] [ -n # of layers (integer) ] [ (optional) -r radius of middle layer (real) ] [-R radius of lower layer (real) ] [ -H method for Highest layer (string) ] [ (optional) -M method for Middle layer (string) ] [ -L method for Lower layer (string) ] [ -x input GMX .itp file ]\n\n" , * argv ); 
	      
	                 //exh = 9 ;
	                 
	                 icmd = icmd + 1 ; 
	                 
	                 exit(1) ;

	      default : printf("\n\nInvalid option ' %s ' ... Please refer to the usage by typing ' %s -h '\n\n" , flag , * argv ); 
	      
	                icmd = argc ; 
	                
	                exit(1);

      
      
      
      }
    
    }
    else
    {
        printf("\n\nInvalid option ' %s ' ... Please refer to the usage by typing ' %s -h '\n\n" , flag , * argv );

	    exit(1);
      
      
    }
    
 
  } 
  

  // =====> Open the files ...


  if( ( pdxdr = fopen( dxdrname , "r" ) ) == NULL )
  {
    printf("\nUser-defined dxdr file %s does not exist ...\n\n" , dxdrname );
    
    exit( 1 );
  
  }

  double * freq ;

  if( ( pfreq = fopen( freqname , "r" ) ) == NULL )
  {
    printf("\nUser-defined frequency file %s does not exist ...\n\n" , freqname );
    
    printf("\nBut it's OK , we will procede without frequency information ... \n");
    
    exfreq = 0 ;
  
  }
  else
  {
    nfreqprovide = flength( pfreq );
    
    rewind( pfreq ) ;
    
    freq = ( double * ) calloc( nfreqprovide , sizeof( double ) ) ;
    
    fload( pfreq , freq );
    
    rewind( pfreq );
    
    exfreq = 1 ;

  }


  int * atomlist , natomlistprovide ;
  

  if( ( patomlist = fopen( atomlistname , "r" ) ) == NULL )
  {
    printf("\nUser-defined atom list file %s does not exist ...\n\n" , atomlistname );
    
    printf("\nMeaning ... All of your atoms will be carbon ...\n");
    
    exatomlist = 0 ;
  
  }
  else
  {
    natomlistprovide = flength( patomlist );
    
    rewind( patomlist );
    
    atomlist = ( int * ) calloc( natomlistprovide , sizeof( int ) ) ;
    
    int_fload( patomlist , atomlist );
    
    exatomlist = 1 ;
  }




  
  // =====> Loading the eigenvectors ( dxdr file ) ... 
  
  printf("\n--------------------------> Begin reading dxdr file ...  <----------------------------" );
  
  int len_dxdr = flength( pdxdr ) ;
  
  printf("\nThere are %d numbers in eigenvectors file ... \n" , len_dxdr );
  
  ncart = sqrt( len_dxdr );
  
  natom = ncart / 3 ;
  
  double * dxdr = calloc( len_dxdr , sizeof( double ) ) ;
  
  rewind( pdxdr );
  
  fload( pdxdr , dxdr ) ;
  
  rewind( pdxdr ) ;  
  
  printf("\nDone with loading dxdr file ... \n");
  
  switch( natom )
  {
    case 1 : printf("\nSeriously? Only ONE atom? ...\n") ; exit( 9 ) ; break ;
    
    case 2 : nmode = 6 ; break ;
    
    default : nmode = ncart - 0 ; break ;
  
  }

  if( exfreq == 0 )
  {
    freq = ( double * ) calloc( nmode , sizeof( double ) ) ;
    
    dzeros( nmode , 1 , freq ) ;
  }
  else
  {
    if( nfreqprovide > nmode )
    {
      printf("\nOkay ... The number of vibrational frequency you provided is more than the normal mode we have from eigenvectors ...\n");
      
      printf("\nSo I will take only the first #_of_eigenvectors frequencies from the file you provided ...\n");
    }
    else if( nfreqprovide < nmode )
    {
      printf("\nOkay ... The number of vibrational frequency you provided is less than the normal mode we have from eigenvectors ...\n");
      
      printf("\nThe rest will be padded with zeros ... Sorry, I really don't want to do the diagonalization ...\n");
      
      free( freq ) ;
      
      freq = ( double * ) calloc( nmode , sizeof( double ) ) ;
      
      rewind( pfreq );
      
      fload( pfreq , freq ) ;
      
      dzeros( nmode - nfreqprovide , 1 , freq + nfreqprovide ) ;

    }
  
  
  }
  
  
  
  if( exatomlist == 0 )
  {
    for( iatom = 0 ; iatom < natom ; iatom ++ ) 
    {
      *( atomlist + iatom ) = 6 ;
    }
    
  }
  else
  {
    if( natomlistprovide > natom )
    {
      printf("\nOkay ... The number of atom you provided is more than the NAtom we have from eigenvectors ...\n");
      
      printf("\nSo I will take only the first #_of_atoms from the file you provided ...\n");
    
    }
    else if( natomlistprovide < natom )
    {
      printf("\nOkay ... The number of atom you provided is less than the NAtom we have from eigenvectors ...\n");
      
      printf("\nSo all the rest will be automatically set as Carbon ... \n");
      
      free( atomlist );
      
      atomlist = ( int * ) calloc( natom , sizeof( int ) ) ;
      
      rewind( patomlist );
      
      int_fload( patomlist , atomlist );
      
      for( iatom = natom - natomlistprovide ; iatom < natom ; iatom ++ )
      {
        *( atomlist + iatom ) = 6 ;
      }
      
      
    
    }
  
  }
  
  if( exselect == 20 )
  {
    printf("\nBy default , all %d atoms are selected as solute ... \n\n" , natom ) ;

    natomSelect = natom ;

  }
  else if( exselect == 22 )
  {
    printf("\nPer user's request , all %d atoms are selected as solute ... \n\n" , natom ) ;

    natomSelect = natom ;
  }
  else if( exselect == 21 )
  {
    if( natomSelect > natom )
    {
      printf("\nOops ... you requested %d atoms as solute but we only have %d atoms in G09 .inp file ... By default , all atoms are selected as solute ... \n\n" , natomSelect , natom ) ;

      natomSelect = natom ;

    }
    else if( natomSelect <= natom && natomSelect > 0 )
    {
      printf("\nPer user's request , the first %d atoms are selected as solute ... \n\n" , natomSelect ) ;
    }
    else if( natomSelect <= 0 )
    {
      printf("\n# of solute atom must be a positive integer!!!\n\n") ;

      exit( 52 ) ;
    }


  }
  
  
  ncartSelect = natomSelect * 3 ;
  
  switch( natomSelect )
  {
    case 1 : printf("\nSeriously? Only ONE atom selected ? ...\n") ; exit( 9 ) ; break ;
    
    case 2 : nmodeSelect = 6 ; break ;
    
    default : nmodeSelect = ncartSelect - 0 ; break ;
  
  }

  

  // =====> Writing the output file ( MATLAB loadable pure number array file ) ... 
  
 printf("\n--------------------------> Begin organizing dxdr file into G09 format...  <----------------------------\n\n\n" );

 pfakefreq = fopen( outfreqname , "wb+" );
 
 int ibatch = 0 ;  
 
 int nbatch = nmodeSelect / 3 ;
 
 
 
 if( natomSelect == 1 )
 {
   printf("\nReally? Really?? Really???\n\n");
   
   exit( 1 ) ;
 }
 else if( natomSelect == 2 )
 {
   fprintf( pfakefreq , "                  1\n                    A\nFrequencies -- %10.4f\n" , *( freq + 5 ) ) ;
   
   fprintf( pfakefreq , "Red. masses -- %10.4f\nFrc consts  -- %10.4f\nIR Inten    -- %10.4f\n Atom  AN      X      Y      Z     \n" , 1.00 , 1.00 , 1.00 );
 
   for( iatom = 0 ; iatom < natomSelect ; iatom ++ )
   {
     fprintf( pfakefreq , "%5d%4d  % 8.4f  % 8.4f  %8.4f\n" , iatom + 1 , *( atomlist + iatom ) , *( dxdr + 3 * iatom + 0 ) , *( dxdr + 3 * iatom + 1 ) , *( dxdr + 3 * iatom + 2 ) );
   
   }
 
 }
 else
 {
   for( ibatch = 2 ; ibatch < nbatch ; ibatch ++ )
   {
     fprintf( pfakefreq , "                      %5d                             %5d                             %5d\n" , 3 * ( ibatch - 2 ) + 1 , 3 * ( ibatch - 2 ) + 2 , 3 * ( ibatch - 2 ) + 3 );
     
     fprintf( pfakefreq , "                      %5c                             %5c                             %5c\n" , 'A' , 'A', 'A' );
     
     fprintf( pfakefreq , "%-12s --  %10.4f                        %10.4f                        %10.4f\n" , " Frequencies" , *( freq + 3 * ibatch + 0 ) , *( freq + 3 * ibatch + 1 ) , *( freq + 3 * ibatch + 2 ) );
     
     fprintf( pfakefreq , "%-12s --  %10.4f                        %10.4f                        %10.4f\n" , " Red. masses" , 1.00 , 1.00 , 1.00 );
     
     fprintf( pfakefreq , "%-12s --  %10.4f                        %10.4f                        %10.4f\n" , " Frc consts" , 10.00 , 10.00 , 10.00 );
     
     fprintf( pfakefreq , "%-12s --  %10.4f                        %10.4f                        %10.4f\n" , " IR Inten" , 10.00 , 10.00 , 10.00 );
     
     fprintf( pfakefreq , "   Atom  AN     X         Y         Z             X         Y         Z             X         Y         Z\n");
     
     for( iatom = 0 ; iatom < natomSelect ; iatom ++ )
     {
       fprintf( pfakefreq , "%5d%4d" , iatom + 1 , *( atomlist + iatom ) ) ;
     
       fprintf( pfakefreq , "   % 8.4f  % 8.4f  %8.4f" , *( dxdr + nmode * ( 3 * iatom + 0 ) + ( 3 * ( ibatch + 0 ) + 0 ) ) , *( dxdr + nmode * ( 3 * iatom + 1 ) + ( 3 * ( ibatch + 0 ) + 0 ) ) , *( dxdr + nmode * ( 3 * iatom + 2 ) + ( 3 * ( ibatch + 0 ) + 0 ) )  ) ;
       
       fprintf( pfakefreq , "      % 8.4f  % 8.4f  %8.4f" , *( dxdr + nmode * ( 3 * iatom + 0 ) + ( 3 * ( ibatch + 0 ) + 1 ) ) , *( dxdr + nmode * ( 3 * iatom + 1 ) + ( 3 * ( ibatch + 0 ) + 1 ) ) , *( dxdr + nmode * ( 3 * iatom + 2 ) + ( 3 * ( ibatch + 0 ) + 1 ) )  ) ;    

       fprintf( pfakefreq , "      % 8.4f  % 8.4f  %8.4f\n" , *( dxdr + nmode * ( 3 * iatom + 0 ) + ( 3 * ( ibatch + 0 ) + 2 ) ) , *( dxdr + nmode * ( 3 * iatom + 1 ) + ( 3 * ( ibatch + 0 ) + 2 ) ) , *( dxdr + nmode * ( 3 * iatom + 2 ) + ( 3 * ( ibatch + 0 ) + 2 ) )  ) ;    
       
     }
   
   }

   
 }

  printf("\n==============> ALL DONE !!! ^-^ !!! <===============\n\n\n\n\n\n");


  return( 0 );

} // The End ...