Пример #1
0
int _do_setenv (int flag, int argc, char *argv[])
{
	DECLARE_GLOBAL_DATA_PTR;

	int   i, len, oldval;
	int   console = -1;
	uchar *env, *nxt = NULL;
	uchar *name;
	bd_t *bd = gd->bd;

	uchar *env_data = env_get_addr(0);

	if (!env_data)	/* need copy in RAM */
		return 1;

	name = argv[1];

	/*
	 * search if variable with this name already exists
	 */
	oldval = -1;
	for (env=env_data; *env; env=nxt+1) {
		for (nxt=env; *nxt; ++nxt)
			;
		if ((oldval = envmatch(name, env-env_data)) >= 0)
			break;
	}

	/*
	 * Delete any existing definition
	 */
	if (oldval >= 0) {
#ifndef CONFIG_ENV_OVERWRITE

		/*
		 * Ethernet Address and serial# can be set only once,
		 * ver is readonly.
		 */
		if ( (strcmp (name, "serial#") == 0) ||
		    ((strcmp (name, "ethaddr") == 0)
#if defined(CONFIG_OVERWRITE_ETHADDR_ONCE) && defined(CONFIG_ETHADDR)
		     && (strcmp (env_get_addr(oldval),MK_STR(CONFIG_ETHADDR)) != 0)
#endif	/* CONFIG_OVERWRITE_ETHADDR_ONCE && CONFIG_ETHADDR */
		    ) ) {
			printf ("Can't overwrite \"%s\"\n", name);
			return 1;
		}
#endif

		/* Check for console redirection */
		if (strcmp(name,"stdin") == 0) {
			console = stdin;
		} else if (strcmp(name,"stdout") == 0) {
			console = stdout;
		} else if (strcmp(name,"stderr") == 0) {
			console = stderr;
		}

		if (console != -1) {
			if (argc < 3) {		/* Cannot delete it! */
				printf("Can't delete \"%s\"\n", name);
				return 1;
			}

			/* Try assigning specified device */
			if (console_assign (console, argv[2]) < 0)
				return 1;

#ifdef CONFIG_SERIAL_MULTI
			if (serial_assign (argv[2]) < 0)
				return 1;
#endif
		}

		/*
		 * Switch to new baudrate if new baudrate is supported
		 */
		if (strcmp(argv[1],"baudrate") == 0) {
			int baudrate = simple_strtoul(argv[2], NULL, 10);
			int i;
			for (i=0; i<N_BAUDRATES; ++i) {
				if (baudrate == baudrate_table[i])
					break;
			}
			if (i == N_BAUDRATES) {
				printf ("## Baudrate %d bps not supported\n",
					baudrate);
				return 1;
			}
			printf ("## Switch baudrate to %d bps and press ENTER ...\n",
				baudrate);
			udelay(50000);
			gd->baudrate = baudrate;
#ifdef CONFIG_PPC
			gd->bd->bi_baudrate = baudrate;
#endif

#if defined(RT6855A_ASIC_BOARD) || defined(RT6855A_FPGA_BOARD)
			bbu_uart_init();
#else
			serial_setbrg ();
#endif

			udelay(50000);
			for (;;) {
				if (getc() == '\r')
				      break;
			}
		}

		if (*++nxt == '\0') {
			if (env > env_data) {
				env--;
			} else {
				*env = '\0';
			}
		} else {
			for (;;) {
				*env = *nxt++;
				if ((*env == '\0') && (*nxt == '\0'))
					break;
				++env;
			}
		}
		*++env = '\0';
	}

#ifdef CONFIG_NET_MULTI
	if (strncmp(name, "eth", 3) == 0) {
		char *end;
		int   num = simple_strtoul(name+3, &end, 10);

		if (strcmp(end, "addr") == 0) {
			eth_set_enetaddr(num, argv[2]);
		}
	}
#endif


	/* Delete only ? */
	if ((argc < 3) || argv[2] == NULL) {
		env_crc_update ();
		return 0;
	}

	/*
	 * Append new definition at the end
	 */
	for (env=env_data; *env || *(env+1); ++env)
		;
	if (env > env_data)
		++env;
	/*
	 * Overflow when:
	 * "name" + "=" + "val" +"\0\0"  > ENV_SIZE - (env-env_data)
	 */
	len = strlen(name) + 2;
	/* add '=' for first arg, ' ' for all others */
	for (i=2; i<argc; ++i) {
		len += strlen(argv[i]) + 1;
	}
	if (len > (&env_data[ENV_SIZE]-env)) {
		printf ("## Error: environment overflow, \"%s\" deleted\n", name);
		return 1;
	}
	while ((*env = *name++) != '\0')
		env++;
	for (i=2; i<argc; ++i) {
		char *val = argv[i];

		*env = (i==2) ? '=' : ' ';
		while ((*++env = *val++) != '\0')
			;
	}

	/* end is marked with double '\0' */
	*++env = '\0';

	/* Update CRC */
	env_crc_update ();

	/*
	 * Some variables should be updated when the corresponding
	 * entry in the enviornment is changed
	 */

	if (strcmp(argv[1],"ethaddr") == 0) {
		char *s = argv[2];	/* always use only one arg */
		char *e;
		for (i=0; i<6; ++i) {
			bd->bi_enetaddr[i] = s ? simple_strtoul(s, &e, 16) : 0;
			if (s) s = (*e) ? e+1 : e;
		}
#ifdef CONFIG_NET_MULTI
		eth_set_enetaddr(0, argv[2]);
#endif
		return 0;
	}

	if (strcmp(argv[1],"ipaddr") == 0) {
		char *s = argv[2];	/* always use only one arg */
		char *e;
		unsigned long addr;
		bd->bi_ip_addr = 0;
		for (addr=0, i=0; i<4; ++i) {
			ulong val = s ? simple_strtoul(s, &e, 10) : 0;
			addr <<= 8;
			addr  |= (val & 0xFF);
			if (s) s = (*e) ? e+1 : e;
		}
		bd->bi_ip_addr = htonl(addr);
		return 0;
	}
	if (strcmp(argv[1],"loadaddr") == 0) {
		load_addr = simple_strtoul(argv[2], NULL, 16);
		return 0;
	}
#if (CONFIG_COMMANDS & CFG_CMD_NET)
	if (strcmp(argv[1],"bootfile") == 0) {
		copy_filename (BootFile, argv[2], sizeof(BootFile));
		return 0;
	}
#endif	/* CFG_CMD_NET */

#ifdef CONFIG_AMIGAONEG3SE
	if (strcmp(argv[1], "vga_fg_color") == 0 ||
	    strcmp(argv[1], "vga_bg_color") == 0 ) {
		extern void video_set_color(unsigned char attr);
		extern unsigned char video_get_attr(void);

		video_set_color(video_get_attr());
		return 0;
	}
#endif	/* CONFIG_AMIGAONEG3SE */

#if 0
	if (strcmp(argv[1],"twe0") == 0) {
		printf("\n Reset  to Flash environment  \n");
	{

		unsigned int regvalue,kk0;


		kk0 = simple_strtoul(argv[2], NULL, 16);
		
		regvalue = *(volatile u_long *)(RALINK_SYSCTL_BASE + 0x0308);

	printf("\n Default FLASH_CS1_CFG = %08X \n",regvalue);

    regvalue &= ~(0x3 << 26);
	regvalue |= (0x1 << 26);

	regvalue |= (0x1 << 24);

	regvalue &= ~(0x3 << 20);
	regvalue |= (0x1 << 20);

	regvalue &= ~(0x3 << 16);
	regvalue |= (0x1 << 16);

	regvalue &= ~(0xF << 12);
	regvalue |= (kk0 << 12);


	*(volatile u_long *)(RALINK_SYSCTL_BASE + 0x0308) = regvalue;

	regvalue = *(volatile u_long *)(RALINK_SYSCTL_BASE + 0x0308);

		}
	}
#endif

	return 0;
}
Пример #2
0
void main(){
   setup_oscillator( OSC_8MHZ );
   setup_adc_ports(sAN6|VSS_VDD);
   setup_adc(ADC_CLOCK_INTERNAL);
   setup_counters(RTCC_INTERNAL,RTCC_DIV_1);
   setup_timer_1(T1_DISABLED);
   setup_comparator(NC_NC_NC_NC);
   setup_vref(FALSE);

//Software workaround for the power switch floating
onewire_init();
onewire_sendbyte(0xCC);
onewire_sendbyte(0x6C);    //Write Data Command
onewire_sendbyte(0x31);    //Eeprom address but actually gets written to Shadow Ram
onewire_sendbyte(0xE7);    //Value to make PMOD1 SWEN=0 RNAOP=0

//Copy the shadow Ram written above over to actual EEPROM
onewire_init();
onewire_sendbyte(0xCC);
onewire_sendbyte(0x48);    //send the copy command
onewire_sendbyte(0x30);    //copy shadow ram to the block containing 31

while(true){
/*-------------------------------------------------------------------
Pull Reading From Temp Probe
-------------------------------------------------------------------*/
//Use the following to determine the state of the one wire net
//Will report if device present, not, or shorted
//Comment out rest of code
//onewire_init_with_error_check();
//read_status();
//printf("status byte is ====>(%x)\n\r",status);
printf("Please enter a command (h for help):\n\r");

command = getc();  //Gets a key from the keyboard
   switch (command){
   case 'h' :
         printf("Type any of the following commands:\n\r");
         printf("h     This Help Message\n\r");
         printf("C     Ambiant Temp in deg. C\n\r");
         printf("c     Ambiant Temp in deg. C(No Formatting)\n\r");
         printf("F     Ambiant Temp in deg. F\n\r");
         printf("f     Ambiant Temp in deg. F(No Formatting)\n\r");
         printf("N     64 bit node address in Hex\n\r");
         printf("K     Thermo millivolts\n\r");
         printf("k     Thermo millivolts(No Formatting)\n\r");
         printf("s     One line scroll test\n\r");
         break;
   case 'C' :
         read_temp();
         printf("    deg C===>(%3.2f)\n\r",temp_float);
         break;
   case 'c' :
         read_temp();
         printf("%3.2f\n\r",temp_float);
         break;
   case 'F' :
         read_temp();
         printf("    deg F===>(%3.2f)\n\r",temp_float_faren);
         break;
   case 'f' :
         read_temp();
         printf("%4.2f",temp_float_faren);
         break;
   case 'K' :
         read_current();
         printf("mV===>(%4.3f)\n\r",current_float);
         break;
   case 'k' :
         read_current();
         printf("%4.3f\n\r",current_float);
         break;
   case 's' :
         scroll_test();
         break;
   default :
         printf("Not a valid command:\n\r");
         }
         
delay_ms(1000);
}
}
Пример #3
0
void PdmsFileSession::skipComment()
{
	switch (currentToken)
	{
	case PDMS_COMMENT_LINE:
		//skip line only if the end of line has not been read in current buffer
		if (!m_eol)
		{
			int n = 0;
			int car = 0;
			do {
				car = getc(m_file);
				if (car == '\t') car = ' ';
				tokenBuffer[n] = car;
				if (((n + 1) < c_max_buff_size) && ((car != ' ') || (n > 0 && tokenBuffer[n - 1] != ' '))) n++;
			} while (car != EOF && car != '\n');
			if (car == '\n')
				m_currentLine++;
			tokenBuffer[n - 1] = '\0';
		}
		m_eol = false;
		break;
	case PDMS_COMMENT_BLOCK:
	{
		//comment block opening symbol has been met. Search for comment block ending symbol
		//don't forget that some other comments could be embedded in this comment
		bool commentSymb = false;
		int commentBlockLevel = 1;
		int n = 0;
		int car = 0;
		do {
			car = getc(m_file);
			if (car == '\n') m_currentLine++;
			if (car == '\n' || car == '\t') car = ' ';
			if (car == '$') commentSymb = true;
			else if (car == '(' && commentSymb) commentBlockLevel++;
			else if (car == ')' && commentSymb) commentBlockLevel--;
			else
			{
				commentSymb = false;
				tokenBuffer[n] = car;
				if (((n + 1) < c_max_buff_size) && ((car != ' ') || (n > 0 && tokenBuffer[n - 1] != ' '))) n++;
			}
		} while (car != EOF && commentBlockLevel > 0);
		tokenBuffer[n - 1] = '\0';
		m_eol = false;
	}
	break;
	default:
		break;
	}

	upperStr(tokenBuffer);
	if (strncmp(tokenBuffer, "ENTERING IN GROUP:", 18) == 0)
	{
		currentToken = PDMS_ENTER_METAGROUP;
		//The meta group name starts after the "entering in group:" statement, after the last slash
		//But we still store the whole path
		char* ptr2 = &(tokenBuffer[18]);
		while ((*ptr2) == ' ') { ptr2++; }
		//Copy the meta group name at the beginning of tokenbuffer
		tokenBuffer[0] = '/';
		char* ptr1 = &(tokenBuffer[1]);
		while ((*ptr2) && (*ptr2) != ' ')
		{
			*ptr1 = *ptr2;
			ptr1++;
			ptr2++;
		}
		*ptr1 = '\0';
		metaGroupMask = 0;
	}
	else if (strncmp(tokenBuffer, "LEAVING GROUP", 13) == 0)
	{
		currentToken = PDMS_LEAVE_METAGROUP;
		metaGroupMask = 0;
	}
}
Пример #4
0
void do_predict(FILE *input, FILE *output, struct model* model_)
{
	int correct = 0;
	int total = 0;

	int nr_class=get_nr_class(model_);
	double *prob_estimates=NULL;
	int j, n;
	int nr_feature=get_nr_feature(model_);
	if(model_->bias>=0)
		n=nr_feature+1;
	else
		n=nr_feature;

	if(flag_predict_probability)
	{
		int *labels;

		if(model_->param.solver_type!=L2_LR)
		{
			fprintf(stderr, "probability output is only supported for logistic regression\n");
			return;
		}

		labels=(int *) malloc(nr_class*sizeof(int));
		get_labels(model_,labels);
		prob_estimates = (double *) malloc(nr_class*sizeof(double));
		fprintf(output,"labels");		
		for(j=0;j<nr_class;j++)
			fprintf(output," %d",labels[j]);
		fprintf(output,"\n");
		free(labels);
	}
	while(1)
	{
		int i = 0;
		int c;
		double target;
		int target_label, predict_label;

		if (fscanf(input,"%lf",&target)==EOF)
			break;
		target_label=(int)target;

		while(1)
		{
			if(i>=max_nr_attr-2)	// need one more for index = -1
			{
				max_nr_attr *= 2;
				x = (struct feature_node *) realloc(x,max_nr_attr*sizeof(struct feature_node));
			}

			do {
				c = getc(input);
				if(c=='\n' || c==EOF) goto out2;
			} while(isspace(c));
			ungetc(c,input);
			if (fscanf(input,"%d:%lf",&x[i].index,&x[i].value) < 2)
			{
				fprintf(stderr,"Wrong input format at line %d\n", total+1);
				exit(1);
			}
			// feature indices larger than those in training are not used
			if(x[i].index<=nr_feature)
				++i;
		}

out2:
		if(model_->bias>=0)
		{
			x[i].index = n;
			x[i].value = model_->bias;
			i++;
		}
		x[i].index = -1;

		if(flag_predict_probability)
		{
			int j;
			predict_label = predict_probability(model_,x,prob_estimates);
			fprintf(output,"%d ",predict_label);
			for(j=0;j<model_->nr_class;j++)
				fprintf(output,"%g ",prob_estimates[j]);
			fprintf(output,"\n");
		}
		else
		{
			predict_label = predict(model_,x);
			fprintf(output,"%d\n",predict_label);
		}

		if(predict_label == target_label)
			++correct;
		++total;
	}
	printf("Accuracy = %g%% (%d/%d)\n", (double)correct/total*100,correct,total);
	if(flag_predict_probability)
		free(prob_estimates);
}
Пример #5
0
void parse_next(parse_struct * ps)
{
	int type, c, p, d;
	char * tok1 = NULL;
	char * tok2 = NULL;
	parse_struct sub;
	
	ps->owner = 0;
	ps->name = NULL;

	ignore_whitespace();
	p = type = getc(stdin);
	if (type == EOF) {
		ps->valid = 0;
		return;
	}

	ignore_whitespace();
	c = getc(stdin);
	if (c != ':') error(EXPECTED_COLON, &p);
	p = c;

	ignore_whitespace();
	c = getc(stdin);
	if (c != '[') error(EXPECTED_LBRACKET, &p);

	switch (type)
	{
	////////// Parse Branches \\\\\\\\\\/
	case 'b':
		ps->flags = FL_BRANCH;
		ps->u.dir.size = 0;
	
		do {
			if (tok1 != NULL) free(tok1);
			p = d = next_token(&tok1);

			if (tok1[0] == '#') {
				if (strcmp(tok1, "#protected") == 0) ps->flags |= FL_PROTECTED;
				else error(BAD_BRANCH_FLAG, tok1);
			} else {
				if (d != '=') error(EXPECTED_EQUALS, tok1);
				
				ignore_whitespace();

				if (strcmp(tok1, "contents") == 0) {
					c = getc(stdin);
					if (c != '{') error(EXPECTED_LBRACE, NULL);
					
					ps->u.dir.contents = NULL;
					
					while (1) {
						ignore_whitespace();

						c = getc(stdin);
						if (c == EOF) error(UNEXPECTED_EOF, NULL);
						if (c == '}') break;
						ungetc(c, stdin);
						
						parse_next(&sub);
						if (!sub.valid) error(UNEXPECTED_EOF, NULL);
						
						if (ps->u.dir.size % (0x20 * sizeof(parse_struct)) == 0) {
							ps->u.dir.contents = realloc(ps->u.dir.contents,
								ps->u.dir.size + (0x20 * sizeof(parse_struct)));
						}
						
						ps->u.dir.contents[ps->u.dir.size++] = sub;
					}
					
					ignore_whitespace();
					d = getc(stdin);
				} else {
					if (tok2 != NULL) free(tok2);
					d = next_token(&tok2);
					
					if (strcmp(tok1, "name") == 0) {
						ps->name = tok2;
						tok2 = NULL;
					}
					else if (strcmp(tok1, "owner") == 0) {
						ps->owner = atoi(tok2);
					}
					else error(BAD_BRANCH_FIELD, tok1);
				}
			}
		}
		while (p != ']' && d != ']');

		break;

	////////// Parse Files \\\\\\\\\\/
	case 'f':
		ps->flags = 0;

		do {
			if (tok1 != NULL) free(tok1);
			d = next_token(&tok1);

			if (tok1[0] == '#') {
				if (strcmp(tok1, "#protected") == 0) ps->flags |= FL_PROTECTED;
				else if (strcmp(tok1, "#executable") == 0) ps->flags |= FL_EXECUTABLE;
				else error(BAD_FILE_FLAG, tok1);
			} else {
				if (d != '=') error(EXPECTED_EQUALS, tok1);

				if (tok2 != NULL) free(tok2);
				d = next_token(&tok2);
				
				if (strcmp(tok1, "name") == 0) {
					ps->name = tok2;
					tok2 = NULL;
				}
				else if (strcmp(tok1, "owner") == 0) {
					ps->owner = atoi(tok2);
				}
				else if (strcmp(tok1, "actual") == 0) {
					ps->u.actual_file = tok2;
					tok2 = NULL;
				}
				else error(BAD_FILE_FIELD, tok1);
			}
		}
		while (p != ']' && d != ']');
		
		break;

	////////// Parse Indirects \\\\\\\\\\/
	case 'i':
		ps->flags = FL_INDIRECT;

		break;
	
	default:
		error(UNRECOGNIZED_TYPE, &type);
	}
	
	if (tok1 == NULL) free(tok1);
	if (tok2 == NULL) free(tok2);
	
	ps->valid = 1;
}
Пример #6
0
/*
 * return end of string - WARNING: malloc!
 */
int
xpmGetString(xpmData *mdata, char **sptr, unsigned int *l)
{
    unsigned int i, n = 0;
    int c;
    char *p, *q, buf[BUFSIZ];

    if (!mdata->type || mdata->type == XPMBUFFER) {
	if (mdata->cptr) {
	    char *start;

	    while (isspace(c = *mdata->cptr) && c != mdata->Eos)
		mdata->cptr++;
	    start = mdata->cptr;
	    while ((c = *mdata->cptr) && c != mdata->Eos)
		mdata->cptr++;
	    n = mdata->cptr - start + 1;
	    p = (char *) XpmMalloc(n);
	    if (!p)
		return (XpmNoMemory);
	    strncpy(p, start, n);
	    if (mdata->type)		/* XPMBUFFER */
		p[n - 1] = '\0';
	}
    } else {
	FILE *file = mdata->stream.file;

	while ((c = getc(file)) != EOF && isspace(c) && c != mdata->Eos);
	if (c == EOF)
	    return (XpmFileInvalid);
	p = NULL;
	i = 0;
	q = buf;
	p = (char *) XpmMalloc(1);
	while (c != mdata->Eos && c != EOF) {
	    if (i == BUFSIZ) {
		/* get to the end of the buffer */
		/* malloc needed memory */
		q = (char *) XpmRealloc(p, n + i);
		if (!q) {
		    XpmFree(p);
		    return (XpmNoMemory);
		}
		p = q;
		q += n;
		/* and copy what we already have */
		strncpy(q, buf, i);
		n += i;
		i = 0;
		q = buf;
	    }
	    *q++ = c;
	    i++;
	    c = getc(file);
	}
	if (c == EOF) {
	    XpmFree(p);
	    return (XpmFileInvalid);
	}
	if (n + i != 0) {
	    /* malloc needed memory */
	    q = (char *) XpmRealloc(p, n + i + 1);
	    if (!q) {
		XpmFree(p);
		return (XpmNoMemory);
	    }
	    p = q;
	    q += n;
	    /* and copy the buffer */
	    strncpy(q, buf, i);
	    n += i;
	    p[n++] = '\0';
	} else {
	    *p = '\0';
	    n = 1;
	}
	ungetc(c, file);
    }
    *sptr = p;
    *l = n;
    return (XpmSuccess);
}
Пример #7
0
/*
 * Scan the named file, createing a grid_info struct for each grid.  Store
 * the grid_info structs in the grid data base.
 * Input:  name - name of UW VIS file.
 *         db - the grid data base
 * Return:  number of grids found.
 */
int get_uwvis_info( char *name, struct grid_db *db )
{
    static int init_flag = 0;
    FILE *f;
    int grids = 0;
    int var, numvars, nr, nc, nl;
    float height[MAXLEVELS];
    char ch;
    int i, vcs;

    if (init_flag==0) {
        init_visreader();
        init_flag = 1;
    }


    /* Open the file */
    f = fopen( name, "r" );
    if (!f) {
        return 0;
    }

    fscanf( f, "%d", &numvars );
    if (numvars>MAXVARS) {
        printf("ERROR: %s contains too many variables, limit is %d\n",
               name, MAXVARS );
    }

    /* grid size */
    fscanf( f, "%d", &nc );
    fscanf( f, "%d", &nr );
    fscanf( f, "%d", &nl );
    (void) getc(f);  /* get '\n' */

    /* this is tricky:
     * We look at the next character:
     * if it's a letter then
     *     we read the variable name and extract the height info from header
     * else
     *     read the height values for each grid level (variable delta Z).
     * endif
     */
    ch = getc(f);
    ungetc(ch, f);

    if (isalpha(ch)) {
        vcs = 1;
    }
    else {
        /* Read the height (in meters) of each grid level */
        for (i=0; i<nl; i++) {
            fscanf( f, "%8f", &height[i] );
            height[i] /= 1000.0;    /* convert from meters to km */
        }
        (void) getc(f);  /* get '\n' */
        vcs = 2;
    }


    for (var=0; var<numvars; var++) {
        int *header, header_size;
        char varname[100];
        struct grid_info *info;
        float args[100];

        /* read variable name */
        fgets( varname, 40, f );
        for (i=7; i>=0 && varname[i]==' '; i--) {
            varname[i] = '\0';
        }
        varname[8] = 0;

        /* read data header */
        header = read_int_block( f, &header_size );


        /*
         * Allocate grid info struct and initialize it.
         */
        info = alloc_grid_info();

        /* 01Feb06  Phil McDonald */
        info->FileName = TMP_STRDUP (name);
        /* end PM */
        info->Format = FILE_UWVIS;
        info->Position = ftell(f);    /* save position of data in file */

        info->Nr = nr;
        info->Nc = nc;
        info->Nl = nl;

        info->DateStamp = header[5];
        info->TimeStamp = header[6];
        /* 01Feb06  Phil McDonald */
        info->VarName = TMP_STRDUP (varname);
        /* end PM */

        args[0] = (float) header[22] / 10000.0;
        args[1] = (float) header[23] / 10000.0;
        args[2] = (float) header[24] / 10000.0;
        args[3] = (float) header[25] / 10000.0;
        info->Proj = new_projection( db, PROJ_LINEAR, nr, nc, args );

        if (vcs==1) {
            /* equally spaced km */
            float tophgt = (float) header[31] / 1000.0;
            float hgtinc = (float) header[32] / 1000.0;
            args[0] = tophgt - hgtinc*(nl-1);
            args[1] = hgtinc;
        }
        else {
            /* vcs==2 */
            /* unequally spaced km */
            memcpy( args, height, sizeof(float)*nl );
        }
        info->Vcs = new_vcs( db, vcs, nl, 0, args );

        /*
         * done with this grid
         */
        append_grid( info, db );
        grids++;

        /* 01Feb06  Phil McDonald */
        TMP_FREE (header);
        /* end PM */

#ifdef LEAVEOUT
        {
            float *data;
            int data_size;
            /* read and skip data */
            data = read_float_block( f, &data_size );
            /* 01Feb06  Phil McDonald */
            TMP_FREE (data);
            /* end PM */
        }
#else
        skip_float_block( f );
#endif
    }

    fclose(f);

    return grids;
}
Пример #8
0
int read_model(const char* model_file_name, svm_model *model)
{
	FILE *fp = fopen(model_file_name,"rb");
	if(fp==NULL) return 0;
	const char *svm_type_table[] = { "c_svc","nu_svc","one_class","epsilon_svr","nu_svr",0 };
	const char *kernel_type_table[] = { "rbf","linear","polynomial","sigmoid","precomputed",0 };
	// read parameters
	model->SV = NULL;
	model->ind = NULL;
	model->ia = NULL;
	model->sv_coef = NULL;
	model->label_set = NULL;
	model->b = NULL;
	char cmd[81];
	while(1)
	{
		fscanf(fp,"%80s",cmd);

		if(strcmp(cmd,"svm_type")==0)
		{
			fscanf(fp,"%80s",cmd);
			int i;
			for(i=0; svm_type_table[i]!=0;i++)
			{
				if(strcmp(svm_type_table[i],cmd)==0)
				{
					model->svm_type=i;
					break;
				}
			}
			if(svm_type_table[i] == NULL)
			{
				fprintf(stderr,"unknown svm type.\n");
				return 0;
			}
		}
		else if(strcmp(cmd,"kernel_type")==0)
		{		
			fscanf(fp,"%80s",cmd);
			int i;
			for(i=0;kernel_type_table[i];i++)
			{
				if(strcmp(kernel_type_table[i],cmd)==0)
				{
					model->kernel_type=i;
					break;
				}
			}
			if(kernel_type_table[i] == NULL)
			{
				fprintf(stderr,"unknown kernel function.\n");
				return 0;
			}
		}
		else if(strcmp(cmd,"degree")==0)
			fscanf(fp,"%f",&model->coef_d);
		else if(strcmp(cmd,"gamma")==0)
			fscanf(fp,"%f",&model->coef_gamma);
		else if(strcmp(cmd,"coef0")==0)
			fscanf(fp,"%f",&model->coef_b);
		else if(strcmp(cmd,"nr_class")==0)
			fscanf(fp,"%d",&model->nr_class);
		else if(strcmp(cmd,"total_sv")==0)
			fscanf(fp,"%d",&model->nSV);
		else if(strcmp(cmd,"rho")==0)
			fscanf(fp,"%f",&model->b);
		else if(strcmp(cmd,"label")==0)
		{
			int n = model->nr_class;
			model->label_set = (int*)malloc(n*sizeof(int));
			for(int i=0;i<n;i++)
				fscanf(fp,"%d",&model->label_set[i]);
		}
		else if(strcmp(cmd,"nr_sv")==0)
		{
			int n = model->nr_class;
			model->SVperclass = (int*)malloc(n*sizeof(int));
			for(int i=0;i<n;i++)
				fscanf(fp,"%d",&model->SVperclass[i]);
		}
		else if(strcmp(cmd,"SV")==0)
		{
			while(1)
			{
				int c = getc(fp);
				if(c==EOF || c=='\n') break;	
			}
			break;
		}
		else
		{
			fprintf(stderr,"unknown text in model file: [%s]\n",cmd);
			//free_model(model);
			return 0;
		}
	}
	// read sv_coef and SV

	int elements = 0;		// # of presented features
	long pos = ftell(fp);

	unsigned int max_line_len = 1024;
	char *line = (char*)malloc(max_line_len*sizeof(char));
	char *p,*endptr,*idx,*val;

	while(readline(fp, &line, &max_line_len)!=NULL)
	{
		p = strtok(line,":");
		while(1)
		{
			p = strtok(NULL,":");
			if(p == NULL)
				break;
			++elements;
		}
	}

	fseek(fp,pos,SEEK_SET);

	int m = model->nr_class - 1;
	int l = model->nSV;
	model->sv_coef = (float*)malloc(l*sizeof(float));
	int i;
	model->SV = (float*)malloc(elements*sizeof(float));
	model->ind = (int*)malloc(elements*sizeof(int));
	model->ia = (int*)malloc((model->nSV+1)*sizeof(int));

	int *index = model->ind;
	float* value = model->SV;
	int *ia = model->ia;
	int j = 0;
	ia[0] = 0;
	for(i=0;i<l;i++)
	{
		readline(fp, &line, &max_line_len);
		p = strtok(line, " \t");
		model->sv_coef[i] = (float)strtod(p,&endptr);

		while(1)
		{
			idx = strtok(NULL, ":");
			val = strtok(NULL, " \t");

			if(val == NULL)
				break;
			index[j] = (int) strtol(idx,&endptr,10)-1;
			value[j] = (float)strtod(val,&endptr);
			++j;
		}		
		ia[i+1] = j;
	}
	free(line);
	if (ferror(fp) != 0 || fclose(fp) != 0)
	{
		return 1;
	}
	return 0;
}
Пример #9
0
globle int EnvGetcRouter(
  void *theEnv,
  char *logicalName)
  {
   struct router *currentPtr;
   int inchar;

   /*===================================================*/
   /* If the "fast load" option is being used, then the */
   /* logical name is actually a pointer to a file and  */
   /* getc can be called directly to bypass querying    */
   /* all of the routers.                               */
   /*===================================================*/

   if (((char *) RouterData(theEnv)->FastLoadFilePtr) == logicalName)
     {
      inchar = getc(RouterData(theEnv)->FastLoadFilePtr);

      if ((inchar == '\r') || (inchar == '\n'))
        {
         if (((char *) RouterData(theEnv)->FastLoadFilePtr) == RouterData(theEnv)->LineCountRouter)
           { IncrementLineCount(theEnv); }
        }

      /* if (inchar == '\r') return('\n'); */

      return(inchar);
     }

   /*===============================================*/
   /* If the "fast string get" option is being used */
   /* for the specified logical name, then bypass   */
   /* the router system and extract the character   */
   /* directly from the fast get string.            */
   /*===============================================*/

   if (RouterData(theEnv)->FastCharGetRouter == logicalName)
     {
      inchar = (unsigned char) RouterData(theEnv)->FastCharGetString[RouterData(theEnv)->FastCharGetIndex];

      RouterData(theEnv)->FastCharGetIndex++;

      if (inchar == '\0') return(EOF);

      if ((inchar == '\r') || (inchar == '\n'))
        {
         if (RouterData(theEnv)->FastCharGetRouter == RouterData(theEnv)->LineCountRouter)
           { IncrementLineCount(theEnv); }
        }

      return(inchar);
     }

   /*==============================================*/
   /* Search through the list of routers until one */
   /* is found that will handle the getc request.  */
   /*==============================================*/

   currentPtr = RouterData(theEnv)->ListOfRouters;
   while (currentPtr != NULL)
     {
      if ((currentPtr->charget != NULL) ? QueryRouter(theEnv,logicalName,currentPtr) : FALSE)
        {
         SetEnvironmentRouterContext(theEnv,currentPtr->context);
         if (currentPtr->environmentAware)
           { inchar = (*currentPtr->charget)(theEnv,logicalName); }
         else            
           { inchar = ((int (*)(char *)) (*currentPtr->charget))(logicalName); }

         if ((inchar == '\r') || (inchar == '\n'))
           {
            if ((RouterData(theEnv)->LineCountRouter != NULL) &&
                (strcmp(logicalName,RouterData(theEnv)->LineCountRouter) == 0))
              { IncrementLineCount(theEnv); }
           }

         return(inchar);
        }
      currentPtr = currentPtr->next;
     }

   /*=====================================================*/
   /* The logical name was not recognized by any routers. */
   /*=====================================================*/

   UnrecognizedRouterMessage(theEnv,logicalName);
   return(-1);
  }
Пример #10
0
int
main(int argc, char **argv)
{

    extern int found_err;	/* flag set in diag() on error */
    int     dec_ind;	/* current indentation for declarations */
    int     di_stack[20];	/* a stack of structure indentation levels */
    int     flushed_nl;	/* used when buffering up comments to remember
				 * that a newline was passed over */
    int     force_nl;	/* when true, code must be broken */
    int     hd_type;	/* used to store type of stmt for if (...),
				 * for (...), etc */
    int     i;		/* local loop counter */
    int     scase;		/* set to true when we see a case, so we will
				 * know what to do with the following colon */
    int     sp_sw;		/* when true, we are in the expressin of
				 * if(...), while(...), etc. */
    int     squest;		/* when this is positive, we have seen a ?
				 * without the matching : in a <c>?<s>:<s>
				 * construct */
    const char *t_ptr;	/* used for copying tokens */
    int	tabs_to_var = 0; /* true if using tabs to indent to var name */
    int     type_code;	/* the type of token, returned by lexi */

    int     last_else = 0;	/* true iff last keyword was an else */


    /*-----------------------------------------------*\
        |		      INITIALIZATION		      |
        \*-----------------------------------------------*/

    if (!setlocale(LC_ALL, ""))
        warnx("can't set locale.");

    hd_type = 0;
    ps.p_stack[0] = stmt;	/* this is the parser's stack */
    ps.last_nl = true;	/* this is true if the last thing scanned was
				 * a newline */
    ps.last_token = semicolon;
    combuf = (char *) malloc(bufsize);
    labbuf = (char *) malloc(bufsize);
    codebuf = (char *) malloc(bufsize);
    tokenbuf = (char *) malloc(bufsize);
    l_com = combuf + bufsize - 5;
    l_lab = labbuf + bufsize - 5;
    l_code = codebuf + bufsize - 5;
    l_token = tokenbuf + bufsize - 5;
    combuf[0] = codebuf[0] = labbuf[0] = ' ';	/* set up code, label,
							 * and comment buffers */
    combuf[1] = codebuf[1] = labbuf[1] = '\0';
    ps.else_if = 1;		/* Default else-if special processing to on */
    s_lab = e_lab = labbuf + 1;
    s_code = e_code = codebuf + 1;
    s_com = e_com = combuf + 1;
    s_token = e_token = tokenbuf + 1;

    in_buffer = (char *) malloc(10);
    in_buffer_limit = in_buffer + 8;
    buf_ptr = buf_end = in_buffer;
    line_no = 1;
    had_eof = ps.in_decl = ps.decl_on_line = break_comma = false;
    sp_sw = force_nl = false;
    ps.in_or_st = false;
    ps.bl_line = true;
    dec_ind = 0;
    di_stack[ps.dec_nest = 0] = 0;
    ps.want_blank = ps.in_stmt = ps.ind_stmt = false;


    scase = ps.pcase = false;
    squest = 0;
    sc_end = 0;
    bp_save = 0;
    be_save = 0;

    output = 0;



    /*--------------------------------------------------*\
        |   		COMMAND LINE SCAN		 |
        \*--------------------------------------------------*/

#ifdef undef
    max_col = 78;		/* -l78 */
    lineup_to_parens = 1;	/* -lp */
    ps.ljust_decl = 0;	/* -ndj */
    ps.com_ind = 33;	/* -c33 */
    star_comment_cont = 1;	/* -sc */
    ps.ind_size = 8;	/* -i8 */
    verbose = 0;
    ps.decl_indent = 16;	/* -di16 */
    ps.indent_parameters = 1;	/* -ip */
    ps.decl_com_ind = 0;	/* if this is not set to some positive value
				 * by an arg, we will set this equal to
				 * ps.com_ind */
    btype_2 = 1;		/* -br */
    cuddle_else = 1;	/* -ce */
    ps.unindent_displace = 0;	/* -d0 */
    ps.case_indent = 0;	/* -cli0 */
    format_col1_comments = 1;	/* -fc1 */
    procnames_start_line = 1;	/* -psl */
    proc_calls_space = 0;	/* -npcs */
    comment_delimiter_on_blankline = 1;	/* -cdb */
    ps.leave_comma = 1;	/* -nbc */
#endif

    for (i = 1; i < argc; ++i)
        if (strcmp(argv[i], "-npro") == 0)
            break;
    set_defaults();
    if (i >= argc)
        set_profile();

    for (i = 1; i < argc; ++i) {

        /*
         * look thru args (if any) for changes to defaults
         */
        if (argv[i][0] != '-') {	/* no flag on parameter */
            if (input == 0) {	/* we must have the input file */
                in_name = argv[i];	/* remember name of
							 * input file */
                input = fopen(in_name, "r");
                if (input == 0)	/* check for open error */
                    err(1, "%s", in_name);
                continue;
            } else if (output == 0) {
                /* we have the output
                			 * file */
                out_name = argv[i];	/* remember name of
								 * output file */
                if (strcmp(in_name, out_name) == 0) {
                    /* attempt to overwrite
                    					 * the file */
                    errx(1, "input and output files must be different");
                }
                output = fopen(out_name, "w");
                if (output == 0)	/* check for create
								 * error */
                    err(1, "%s", out_name);
                continue;
            }
            errx(1, "unknown parameter: %s", argv[i]);
        } else
            set_option(argv[i]);
    }			/* end of for */
    if (input == 0) {
        input = stdin;
    }
    if (output == 0) {
        if (troff || input == stdin)
            output = stdout;
        else {
            out_name = in_name;
            bakcopy();
        }
    }
    if (ps.com_ind <= 1)
        ps.com_ind = 2;	/* don't put normal comments before column 2 */
    if (troff) {
        if (bodyf.font[0] == 0)
            parsefont(&bodyf, "R");
        if (scomf.font[0] == 0)
            parsefont(&scomf, "I");
        if (blkcomf.font[0] == 0)
            blkcomf = scomf, blkcomf.size += 2;
        if (boxcomf.font[0] == 0)
            boxcomf = blkcomf;
        if (stringf.font[0] == 0)
            parsefont(&stringf, "L");
        if (keywordf.font[0] == 0)
            parsefont(&keywordf, "B");
        writefdef(&bodyf, 'B');
        writefdef(&scomf, 'C');
        writefdef(&blkcomf, 'L');
        writefdef(&boxcomf, 'X');
        writefdef(&stringf, 'S');
        writefdef(&keywordf, 'K');
    }
    if (block_comment_max_col <= 0)
        block_comment_max_col = max_col;
    if (ps.decl_com_ind <= 0)	/* if not specified by user, set this */
        ps.decl_com_ind = ps.ljust_decl ? (ps.com_ind <= 10 ? 2 : ps.com_ind - 8) : ps.com_ind;
    if (continuation_indent == 0)
        continuation_indent = ps.ind_size;
    fill_buffer();		/* get first batch of stuff into input buffer */

    parse(semicolon);
    {
        char   *p = buf_ptr;
        int     col = 1;

        while (1) {
            if (*p == ' ')
                col++;
            else if (*p == '\t')
                col = ((col - 1) & ~7) + 9;
            else
                break;
            p++;
        }
        if (col > ps.ind_size)
            ps.ind_level = ps.i_l_follow = col / ps.ind_size;
    }
    if (troff) {
        const char   *p = in_name, *beg = in_name;

        while (*p)
            if (*p++ == '/')
                beg = p;
        fprintf(output, ".Fn \"%s\"\n", beg);
    }
    /*
         * START OF MAIN LOOP
         */

    while (1) {
        /* this is the main loop.  it will go until we
        			 * reach eof */
        int     is_procname;

        type_code = lexi();	/* lexi reads one token.  The actual
					 * characters read are stored in
					 * "token". lexi returns a code
					 * indicating the type of token */
        is_procname = ps.procname[0];

        /*
         * The following code moves everything following an if (), while (),
         * else, etc. up to the start of the following stmt to a buffer. This
         * allows proper handling of both kinds of brace placement.
         */

        flushed_nl = false;
        while (ps.search_brace) {
            /* if we scanned an if(),
            				 * while(), etc., we might
            				 * need to copy stuff into a
            				 * buffer we must loop,
            				 * copying stuff into
            				 * save_com, until we find the
            				 * start of the stmt which
            				 * follows the if, or whatever */
            switch (type_code) {
            case newline:
                ++line_no;
                flushed_nl = true;
            case form_feed:
                break;	/* form feeds and newlines found here
					 * will be ignored */

            case lbrace:	/* this is a brace that starts the
					 * compound stmt */
                if (sc_end == 0) {
                    /* ignore buffering if a
                    			 * comment wasn't stored
                    			 * up */
                    ps.search_brace = false;
                    goto check_type;
                }
                if (btype_2) {
                    save_com[0] = '{';	/* we either want to put
								 * the brace right after
								 * the if */
                    goto sw_buffer;	/* go to common code to
							 * get out of this loop */
                }
            case comment:	/* we have a comment, so we must copy
					 * it into the buffer */
                if (!flushed_nl || sc_end != 0) {
                    if (sc_end == 0) {
                        /* if this is the first
                        			 * comment, we must set
                        			 * up the buffer */
                        save_com[0] = save_com[1] = ' ';
                        sc_end = &(save_com[2]);
                    } else {
                        *sc_end++ = '\n';	/* add newline between
									 * comments */
                        *sc_end++ = ' ';
                        --line_no;
                    }
                    *sc_end++ = '/';	/* copy in start of
								 * comment */
                    *sc_end++ = '*';

                    for (;;) {
                        /* loop until we get to
                        		 * the end of the
                        		 * comment */
                        *sc_end = *buf_ptr++;
                        if (buf_ptr >= buf_end)
                            fill_buffer();

                        if (*sc_end++ == '*' && *buf_ptr == '/')
                            break;	/* we are at end of
								 * comment */

                        if (sc_end >= &(save_com[sc_size])) {
                            /* check for temp buffer
                            					 * overflow */
                            diag(1, "Internal buffer overflow - Move big comment from right after if, while, or whatever.");
                            fflush(output);
                            exit(1);
                        }
                    }
                    *sc_end++ = '/';	/* add ending slash */
                    if (++buf_ptr >= buf_end)	/* get past / in buffer */
                        fill_buffer();
                    break;
                }
            default:	/* it is the start of a normal
					 * statment */
                if (flushed_nl)	/* if we flushed a newline,
						 * make sure it is put back */
                    force_nl = true;
                if ((type_code == sp_paren && *token == 'i'
                        && last_else && ps.else_if) ||
                        (type_code == sp_nparen && *token == 'e'
                         && e_code != s_code && e_code[-1] == '}'))
                    force_nl = false;

                if (sc_end == 0) {
                    /* ignore buffering if
                    			 * comment wasn't saved
                    			 * up */
                    ps.search_brace = false;
                    goto check_type;
                }
                if (force_nl) {
                    /* if we should insert a nl
                    		 * here, put it into the
                    		 * buffer */
                    force_nl = false;
                    --line_no;	/* this will be
							 * re-increased when the
							 * nl is read from the
							 * buffer */
                    *sc_end++ = '\n';
                    *sc_end++ = ' ';
                    if (verbose && !flushed_nl)	/* print error msg if
									 * the line was not
									 * already broken */
                        diag(0, "Line broken");
                    flushed_nl = false;
                }
                for (t_ptr = token; *t_ptr; ++t_ptr)
                    *sc_end++ = *t_ptr;	/* copy token into temp
								 * buffer */
                ps.procname[0] = 0;

sw_buffer:
                ps.search_brace = false;	/* stop looking for
								 * start of stmt */
                bp_save = buf_ptr;	/* save current input
							 * buffer */
                be_save = buf_end;
                buf_ptr = save_com;	/* fix so that
							 * subsequent calls to
							 * lexi will take tokens
							 * out of save_com */
                *sc_end++ = ' ';	/* add trailing blank,
							 * just in case */
                buf_end = sc_end;
                sc_end = 0;
                break;
            }	/* end of switch */
            if (type_code != 0)	/* we must make this check,
						 * just in case there was an
						 * unexpected EOF */
                type_code = lexi();	/* read another token */
            /* if (ps.search_brace) ps.procname[0] = 0; */
            if ((is_procname = ps.procname[0]) && flushed_nl
                    && !procnames_start_line && ps.in_decl
                    && type_code == ident)
                flushed_nl = 0;
        }		/* end of while (search_brace) */
        last_else = 0;
check_type:
        if (type_code == 0) {	/* we got eof */
            if (s_lab != e_lab || s_code != e_code
                    || s_com != e_com)	/* must dump end of line */
                dump_line();
            if (ps.tos > 1)	/* check for balanced braces */
                diag(1, "Stuff missing from end of file.");

            if (verbose) {
                printf("There were %d output lines and %d comments\n",
                       ps.out_lines, ps.out_coms);
                printf("(Lines with comments)/(Lines with code): %6.3f\n",
                       (1.0 * ps.com_lines) / code_lines);
            }
            fflush(output);
            exit(found_err);
        }
        if (
            (type_code != comment) &&
            (type_code != newline) &&
            (type_code != preesc) &&
            (type_code != form_feed)) {
            if (force_nl &&
                    (type_code != semicolon) &&
                    (type_code != lbrace || !btype_2)) {
                /* we should force a broken line here */
                if (verbose && !flushed_nl)
                    diag(0, "Line broken");
                flushed_nl = false;
                dump_line();
                ps.want_blank = false;	/* don't insert blank at
							 * line start */
                force_nl = false;
            }
            ps.in_stmt = true;	/* turn on flag which causes
						 * an extra level of
						 * indentation. this is turned
						 * off by a ; or '}' */
            if (s_com != e_com) {
                /* the turkey has embedded a
                			 * comment in a line. fix it */
                *e_code++ = ' ';
                for (t_ptr = s_com; *t_ptr; ++t_ptr) {
                    CHECK_SIZE_CODE;
                    *e_code++ = *t_ptr;
                }
                *e_code++ = ' ';
                *e_code = '\0';	/* null terminate code sect */
                ps.want_blank = false;
                e_com = s_com;
            }
        } else if (type_code != comment)	/* preserve force_nl
							 * thru a comment */
            force_nl = false;	/* cancel forced newline
							 * after newline, form
							 * feed, etc */



        /*-----------------------------------------------------*\
        |	   do switch on type of token scanned		|
        \*-----------------------------------------------------*/
        CHECK_SIZE_CODE;
        switch (type_code) {
            /* now, decide what to do with the
            			 * token */

        case form_feed:/* found a form feed in line */
            ps.use_ff = true;	/* a form feed is treated much
						 * like a newline */
            dump_line();
            ps.want_blank = false;
            break;

        case newline:
            if (ps.last_token != comma || ps.p_l_follow > 0
                    || !ps.leave_comma || ps.block_init || !break_comma || s_com != e_com) {
                dump_line();
                ps.want_blank = false;
            }
            ++line_no;	/* keep track of input line number */
            break;

        case lparen:	/* got a '(' or '[' */
            ++ps.p_l_follow;	/* count parens to make Healy
						 * happy */
            if (ps.want_blank && *token != '[' &&
                    (ps.last_token != ident || proc_calls_space
                     || (ps.its_a_keyword && (!ps.sizeof_keyword || Bill_Shannon))))
                *e_code++ = ' ';
            if (ps.in_decl && !ps.block_init) {
                if (troff && !ps.dumped_decl_indent && !is_procname && ps.last_token == decl) {
                    ps.dumped_decl_indent = 1;
                    sprintf(e_code, "\n.Du %dp+\200p \"%s\"\n", dec_ind * 7, token);
                    e_code += strlen(e_code);
                } else {
                    while ((e_code - s_code) < dec_ind) {
                        CHECK_SIZE_CODE;
                        *e_code++ = ' ';
                    }
                    *e_code++ = token[0];
                }
            } else
                *e_code++ = token[0];
            ps.paren_indents[ps.p_l_follow - 1] = e_code - s_code;
            if (sp_sw && ps.p_l_follow == 1 && extra_expression_indent
                    && ps.paren_indents[0] < 2 * ps.ind_size)
                ps.paren_indents[0] = 2 * ps.ind_size;
            ps.want_blank = false;
            if (ps.in_or_st && *token == '(' && ps.tos <= 2) {
                /*
                 * this is a kluge to make sure that declarations will be
                 * aligned right if proc decl has an explicit type on it, i.e.
                 * "int a(x) {..."
                 */
                parse(semicolon);	/* I said this was a
							 * kluge... */
                ps.in_or_st = false;	/* turn off flag for
							 * structure decl or
							 * initialization */
            }
            if (ps.sizeof_keyword)
                ps.sizeof_mask |= 1 << ps.p_l_follow;
            break;

        case rparen:	/* got a ')' or ']' */
            rparen_count--;
            if (ps.cast_mask & (1 << ps.p_l_follow) & ~ps.sizeof_mask) {
                ps.last_u_d = true;
                ps.cast_mask &= (1 << ps.p_l_follow) - 1;
            }
            ps.sizeof_mask &= (1 << ps.p_l_follow) - 1;
            if (--ps.p_l_follow < 0) {
                ps.p_l_follow = 0;
                diag(0, "Extra %c", *token);
            }
            if (e_code == s_code)	/* if the paren starts the
						 * line */
                ps.paren_level = ps.p_l_follow;	/* then indent it */

            *e_code++ = token[0];
            ps.want_blank = true;

            if (sp_sw && (ps.p_l_follow == 0)) {
                /* check for end of if
                					 * (...), or some such */
                sp_sw = false;
                force_nl = true;	/* must force newline
							 * after if */
                ps.last_u_d = true;	/* inform lexi that a
							 * following operator is
							 * unary */
                ps.in_stmt = false;	/* don't use stmt
							 * continuation
							 * indentation */

                parse(hd_type);	/* let parser worry about if,
						 * or whatever */
            }
            ps.search_brace = btype_2;	/* this should insure
							 * that constructs such
							 * as main(){...} and
							 * int[]{...} have their
							 * braces put in the
							 * right place */
            break;

        case unary_op:	/* this could be any unary operation */
            if (ps.want_blank)
                *e_code++ = ' ';

            if (troff && !ps.dumped_decl_indent && ps.in_decl && !is_procname) {
                sprintf(e_code, "\n.Du %dp+\200p \"%s\"\n", dec_ind * 7, token);
                ps.dumped_decl_indent = 1;
                e_code += strlen(e_code);
            } else {
                const char *res = token;

                if (ps.in_decl && !ps.block_init) {
                    /* if this is a unary op
                    					 * in a declaration, we
                    					 * should indent this
                    					 * token */
                    for (i = 0; token[i]; ++i);	/* find length of token */
                    while ((e_code - s_code) < (dec_ind - i)) {
                        CHECK_SIZE_CODE;
                        *e_code++ = ' ';	/* pad it */
                    }
                }
                if (troff && token[0] == '-' && token[1] == '>')
                    res = "\\(->";
                for (t_ptr = res; *t_ptr; ++t_ptr) {
                    CHECK_SIZE_CODE;
                    *e_code++ = *t_ptr;
                }
            }
            ps.want_blank = false;
            break;

        case binary_op:/* any binary operation */
            if (ps.want_blank)
                *e_code++ = ' ';
            {
                const char *res = token;

                if (troff)
                    switch (token[0]) {
                    case '<':
                        if (token[1] == '=')
                            res = "\\(<=";
                        break;
                    case '>':
                        if (token[1] == '=')
                            res = "\\(>=";
                        break;
                    case '!':
                        if (token[1] == '=')
                            res = "\\(!=";
                        break;
                    case '|':
                        if (token[1] == '|')
                            res = "\\(br\\(br";
                        else if (token[1] == 0)
                            res = "\\(br";
                        break;
                    }
                for (t_ptr = res; *t_ptr; ++t_ptr) {
                    CHECK_SIZE_CODE;
                    *e_code++ = *t_ptr;	/* move the operator */
                }
            }
            ps.want_blank = true;
            break;

        case postop:	/* got a trailing ++ or -- */
            *e_code++ = token[0];
            *e_code++ = token[1];
            ps.want_blank = true;
            break;

        case question:	/* got a ? */
            squest++;	/* this will be used when a later
					 * colon appears so we can distinguish
					 * the <c>?<n>:<n> construct */
            if (ps.want_blank)
                *e_code++ = ' ';
            *e_code++ = '?';
            ps.want_blank = true;
            break;

        case casestmt:	/* got word 'case' or 'default' */
            scase = true;	/* so we can process the later colon
					 * properly */
            goto copy_id;

        case colon:	/* got a ':' */
            if (squest > 0) {
                /* it is part of the <c>?<n>:
                			 * <n> construct */
                --squest;
                if (ps.want_blank)
                    *e_code++ = ' ';
                *e_code++ = ':';
                ps.want_blank = true;
                break;
            }
            if (ps.in_or_st) {
                *e_code++ = ':';
                ps.want_blank = false;
                break;
            }
            ps.in_stmt = false;	/* seeing a label does not
						 * imply we are in a stmt */
            for (t_ptr = s_code; *t_ptr; ++t_ptr)
                *e_lab++ = *t_ptr;	/* turn everything so
							 * far into a label */
            e_code = s_code;
            *e_lab++ = ':';
            *e_lab++ = ' ';
            *e_lab = '\0';

            force_nl = ps.pcase = scase;	/* ps.pcase will be used
							 * by dump_line to
							 * decide how to indent
							 * the label. force_nl
							 * will force a case n:
							 * to be on a line by
							 * itself */
            scase = false;
            ps.want_blank = false;
            break;

        case semicolon:/* got a ';' */
            ps.in_or_st = false;	/* we are not in an
						 * initialization or structure
						 * declaration */
            scase = false;	/* these will only need resetting in a
					 * error */
            squest = 0;
            if (ps.last_token == rparen && rparen_count == 0)
                ps.in_parameter_declaration = 0;
            ps.cast_mask = 0;
            ps.sizeof_mask = 0;
            ps.block_init = 0;
            ps.block_init_level = 0;
            ps.just_saw_decl--;

            if (ps.in_decl && s_code == e_code && !ps.block_init)
                while ((e_code - s_code) < (dec_ind - 1)) {
                    CHECK_SIZE_CODE;
                    *e_code++ = ' ';
                }

            ps.in_decl = (ps.dec_nest > 0);	/* if we were in a first
							 * level structure
							 * declaration, we
							 * aren't any more */

            if ((!sp_sw || hd_type != forstmt) && ps.p_l_follow > 0) {

                /*
                 * This should be true iff there were unbalanced parens in the
                 * stmt.  It is a bit complicated, because the semicolon might
                 * be in a for stmt
                 */
                diag(1, "Unbalanced parens");
                ps.p_l_follow = 0;
                if (sp_sw) {
                    /* this is a check for a if,
                    		 * while, etc. with unbalanced
                    		 * parens */
                    sp_sw = false;
                    parse(hd_type);	/* don't lose the if,
							 * or whatever */
                }
            }
            *e_code++ = ';';
            ps.want_blank = true;
            ps.in_stmt = (ps.p_l_follow > 0);	/* we are no longer in
								 * the middle of a stmt */

            if (!sp_sw) {	/* if not if for (;;) */
                parse(semicolon);	/* let parser know about
							 * end of stmt */
                force_nl = true;	/* force newline after a
							 * end of stmt */
            }
            break;

        case lbrace:	/* got a '{' */
            ps.in_stmt = false;	/* don't indent the {} */
            if (!ps.block_init)
                force_nl = true;	/* force other stuff on
							 * same line as '{' onto
							 * new line */
            else if (ps.block_init_level <= 0)
                ps.block_init_level = 1;
            else
                ps.block_init_level++;

            if (s_code != e_code && !ps.block_init) {
                if (!btype_2) {
                    dump_line();
                    ps.want_blank = false;
                } else if (ps.in_parameter_declaration && !ps.in_or_st) {
                    ps.i_l_follow = 0;
                    dump_line();
                    ps.want_blank = false;
                }
            }
            if (ps.in_parameter_declaration)
                prefix_blankline_requested = 0;

            if (ps.p_l_follow > 0) {
                /* check for preceding
                				 * unbalanced parens */
                diag(1, "Unbalanced parens");
                ps.p_l_follow = 0;
                if (sp_sw) {
                    /* check for unclosed if, for,
                    		 * etc. */
                    sp_sw = false;
                    parse(hd_type);
                    ps.ind_level = ps.i_l_follow;
                }
            }
            if (s_code == e_code)
                ps.ind_stmt = false;	/* don't put extra
							 * indentation on line
							 * with '{' */
            if (ps.in_decl && ps.in_or_st) {
                /* this is either a
                					 * structure declaration
                					 * or an init */
                di_stack[ps.dec_nest++] = dec_ind;
                /* ?		dec_ind = 0; */
            } else {
                ps.decl_on_line = false;	/* we can't be in the
								 * middle of a
								 * declaration, so don't
								 * do special
								 * indentation of
								 * comments */
                if (blanklines_after_declarations_at_proctop
                        && ps.in_parameter_declaration)
                    postfix_blankline_requested = 1;
                ps.in_parameter_declaration = 0;
            }
            dec_ind = 0;
            parse(lbrace);	/* let parser know about this */
            if (ps.want_blank)	/* put a blank before '{' if
						 * '{' is not at start of line */
                *e_code++ = ' ';
            ps.want_blank = false;
            *e_code++ = '{';
            ps.just_saw_decl = 0;
            break;

        case rbrace:	/* got a '}' */
            if (ps.p_stack[ps.tos] == decl && !ps.block_init)	/* semicolons can be
										 * omitted in
										 * declarations */
                parse(semicolon);
            if (ps.p_l_follow) {
                /* check for unclosed if, for,
                			 * else. */
                diag(1, "Unbalanced parens");
                ps.p_l_follow = 0;
                sp_sw = false;
            }
            ps.just_saw_decl = 0;
            ps.block_init_level--;
            if (s_code != e_code && !ps.block_init) {
                /* '}' must be first on
                						 * line */
                if (verbose)
                    diag(0, "Line broken");
                dump_line();
            }
            *e_code++ = '}';
            ps.want_blank = true;
            ps.in_stmt = ps.ind_stmt = false;
            if (ps.dec_nest > 0) {
                /* we are in multi-level
                			 * structure declaration */
                dec_ind = di_stack[--ps.dec_nest];
                if (ps.dec_nest == 0 && !ps.in_parameter_declaration)
                    ps.just_saw_decl = 2;
                ps.in_decl = true;
            }
            prefix_blankline_requested = 0;
            parse(rbrace);	/* let parser know about this */
            ps.search_brace = cuddle_else && ps.p_stack[ps.tos] == ifhead
                              && ps.il[ps.tos] >= ps.ind_level;
            if (ps.tos <= 1 && blanklines_after_procs && ps.dec_nest <= 0)
                postfix_blankline_requested = 1;
            break;

        case swstmt:	/* got keyword "switch" */
            sp_sw = true;
            hd_type = swstmt;	/* keep this for when we have
						 * seen the expression */
            goto copy_id;	/* go move the token into buffer */

        case sp_paren:	/* token is if, while, for */
            sp_sw = true;	/* the interesting stuff is done after
					 * the expression is scanned */
            hd_type = (*token == 'i' ? ifstmt :
                       (*token == 'w' ? whilestmt : forstmt));

            /*
                 * remember the type of header for later use by parser
                 */
            goto copy_id;	/* copy the token into line */

        case sp_nparen:/* got else, do */
            ps.in_stmt = false;
            if (*token == 'e') {
                if (e_code != s_code && (!cuddle_else || e_code[-1] != '}')) {
                    if (verbose)
                        diag(0, "Line broken");
                    dump_line();	/* make sure this starts
							 * a line */
                    ps.want_blank = false;
                }
                force_nl = true;	/* also, following stuff
							 * must go onto new line */
                last_else = 1;
                parse(elselit);
            } else {
                if (e_code != s_code) {
                    /* make sure this starts
                    			 * a line */
                    if (verbose)
                        diag(0, "Line broken");
                    dump_line();
                    ps.want_blank = false;
                }
                force_nl = true;	/* also, following stuff
							 * must go onto new line */
                last_else = 0;
                parse(dolit);
            }
            goto copy_id;	/* move the token into line */

        case decl:	/* we have a declaration type (int, register,
				 * etc.) */
            parse(decl);	/* let parser worry about indentation */
            if (ps.last_token == rparen && ps.tos <= 1) {
                ps.in_parameter_declaration = 1;
                if (s_code != e_code) {
                    dump_line();
                    ps.want_blank = 0;
                }
            }
            if (ps.in_parameter_declaration && ps.indent_parameters && ps.dec_nest == 0) {
                ps.ind_level = ps.i_l_follow = 1;
                ps.ind_stmt = 0;
            }
            ps.in_or_st = true;	/* this might be a structure
						 * or initialization
						 * declaration */
            ps.in_decl = ps.decl_on_line = true;
            if ( /* !ps.in_or_st && */ ps.dec_nest <= 0)
                ps.just_saw_decl = 2;
            prefix_blankline_requested = 0;
            for (i = 0; token[i++];);	/* get length of token */

            /*
                 * dec_ind = e_code - s_code + (ps.decl_indent>i ? ps.decl_indent
                 * : i);
                 */
            dec_ind = ps.decl_indent > 0 ? ps.decl_indent : i;
            tabs_to_var = (use_tabs ? ps.decl_indent > 0 : 0);
            goto copy_id;

        case ident:	/* got an identifier or constant */
            if (ps.in_decl) {
                /* if we are in a declaration,
                			 * we must indent identifier */
                if (ps.want_blank)
                    *e_code++ = ' ';
                ps.want_blank = false;
                if (is_procname == 0 || !procnames_start_line) {
                    if (!ps.block_init) {
                        if (troff && !ps.dumped_decl_indent) {
                            sprintf(e_code, "\n.De %dp+\200p\n", dec_ind * 7);
                            ps.dumped_decl_indent = 1;
                            e_code += strlen(e_code);
                            CHECK_SIZE_CODE;
                        } else {
                            int cur_dec_ind;
                            int pos, startpos;

                            /*
                             * in order to get the tab math right for
                             * indentations that are not multiples of 8 we
                             * need to modify both startpos and dec_ind
                             * (cur_dec_ind) here by eight minus the
                             * remainder of the current starting column
                             * divided by eight. This seems to be a
                             * properly working fix
                             */
                            startpos = e_code - s_code;
                            cur_dec_ind = dec_ind;
                            pos = startpos;
                            if ((ps.ind_level * ps.ind_size) % 8 != 0) {
                                pos += (ps.ind_level * ps.ind_size) % 8;
                                cur_dec_ind += (ps.ind_level * ps.ind_size) % 8;
                            }

                            if (tabs_to_var) {
                                while ((pos & ~7) + 8 <= cur_dec_ind) {
                                    CHECK_SIZE_CODE;
                                    *e_code++ = '\t';
                                    pos = (pos & ~7) + 8;
                                }
                            }
                            while (pos < cur_dec_ind) {
                                CHECK_SIZE_CODE;
                                *e_code++ = ' ';
                                pos++;
                            }
                            if (ps.want_blank && e_code - s_code == startpos)
                                *e_code++ = ' ';
                            ps.want_blank = false;
                        }
                    }
                } else {
                    if (dec_ind && s_code != e_code)
                        dump_line();
                    dec_ind = 0;
                    ps.want_blank = false;
                }
            } else if (sp_sw && ps.p_l_follow == 0) {
                sp_sw = false;
                force_nl = true;
                ps.last_u_d = true;
                ps.in_stmt = false;
                parse(hd_type);
            }
copy_id:
            if (ps.want_blank)
                *e_code++ = ' ';
            if (troff && ps.its_a_keyword) {
                e_code = chfont(&bodyf, &keywordf, e_code);
                for (t_ptr = token; *t_ptr; ++t_ptr) {
                    CHECK_SIZE_CODE;
                    *e_code++ = keywordf.allcaps
                                ? toupper((unsigned char)*t_ptr)
                                : *t_ptr;
                }
                e_code = chfont(&keywordf, &bodyf, e_code);
            } else
                for (t_ptr = token; *t_ptr; ++t_ptr) {
                    CHECK_SIZE_CODE;
                    *e_code++ = *t_ptr;
                }
            ps.want_blank = true;
            break;

        case period:	/* treat a period kind of like a binary
				 * operation */
            *e_code++ = '.';	/* move the period into line */
            ps.want_blank = false;	/* don't put a blank after a
						 * period */
            break;

        case comma:
            ps.want_blank = (s_code != e_code);	/* only put blank after
								 * comma if comma does
								 * not start the line */
            if (ps.in_decl && is_procname == 0 && !ps.block_init)
                while ((e_code - s_code) < (dec_ind - 1)) {
                    CHECK_SIZE_CODE;
                    *e_code++ = ' ';
                }

            *e_code++ = ',';
            if (ps.p_l_follow == 0) {
                if (ps.block_init_level <= 0)
                    ps.block_init = 0;
                if (break_comma && (!ps.leave_comma || compute_code_target() + (e_code - s_code) > max_col - 8))
                    force_nl = true;
            }
            break;

        case preesc:	/* got the character '#' */
            if ((s_com != e_com) ||
                    (s_lab != e_lab) ||
                    (s_code != e_code))
                dump_line();
            *e_lab++ = '#';	/* move whole line to 'label' buffer */
            {
                int     in_comment = 0;
                int     com_start = 0;
                char    quote = 0;
                int     com_end = 0;

                while (*buf_ptr == ' ' || *buf_ptr == '\t') {
                    buf_ptr++;
                    if (buf_ptr >= buf_end)
                        fill_buffer();
                }
                while (*buf_ptr != '\n' || in_comment) {
                    CHECK_SIZE_LAB;
                    *e_lab = *buf_ptr++;
                    if (buf_ptr >= buf_end)
                        fill_buffer();
                    switch (*e_lab++) {
                    case BACKSLASH:
                        if (troff)
                            *e_lab++ = BACKSLASH;
                        if (!in_comment) {
                            *e_lab++ = *buf_ptr++;
                            if (buf_ptr >= buf_end)
                                fill_buffer();
                        }
                        break;
                    case '/':
                        if (*buf_ptr == '*' && !in_comment && !quote) {
                            in_comment = 1;
                            *e_lab++ = *buf_ptr++;
                            com_start = e_lab - s_lab - 2;
                        }
                        break;
                    case '"':
                        if (quote == '"')
                            quote = 0;
                        break;
                    case '\'':
                        if (quote == '\'')
                            quote = 0;
                        break;
                    case '*':
                        if (*buf_ptr == '/' && in_comment) {
                            in_comment = 0;
                            *e_lab++ = *buf_ptr++;
                            com_end = e_lab - s_lab;
                        }
                        break;
                    }
                }

                while (e_lab > s_lab && (e_lab[-1] == ' ' || e_lab[-1] == '\t'))
                    e_lab--;
                if (e_lab - s_lab == com_end && bp_save == 0) {
                    /* comment on
                    						 * preprocessor line */
                    if (sc_end == 0)	/* if this is the first
								 * comment, we must set
								 * up the buffer */
                        sc_end = &(save_com[0]);
                    else {
                        *sc_end++ = '\n';	/* add newline between
									 * comments */
                        *sc_end++ = ' ';
                        --line_no;
                    }
                    memmove(sc_end, s_lab + com_start, com_end - com_start);
                    sc_end += com_end - com_start;
                    if (sc_end >= &save_com[sc_size])
                        abort();
                    e_lab = s_lab + com_start;
                    while (e_lab > s_lab && (e_lab[-1] == ' ' || e_lab[-1] == '\t'))
                        e_lab--;
                    bp_save = buf_ptr;	/* save current input
								 * buffer */
                    be_save = buf_end;
                    buf_ptr = save_com;	/* fix so that
								 * subsequent calls to
								 * lexi will take tokens
								 * out of save_com */
                    *sc_end++ = ' ';	/* add trailing blank,
								 * just in case */
                    buf_end = sc_end;
                    sc_end = 0;
                }
                *e_lab = '\0';	/* null terminate line */
                ps.pcase = false;
            }

            if (strncmp(s_lab, "#if", 3) == 0) {
                if (blanklines_around_conditional_compilation) {
                    int     c;
                    prefix_blankline_requested++;
                    while ((c = getc(input)) == '\n');
                    ungetc(c, input);
                }
                if (ifdef_level < (int)(sizeof state_stack / sizeof state_stack[0])) {
                    match_state[ifdef_level].tos = -1;
                    state_stack[ifdef_level++] = ps;
                } else
                    diag(1, "#if stack overflow");
            } else if (strncmp(s_lab, "#else", 5) == 0) {
                if (ifdef_level <= 0)
                    diag(1, "Unmatched #else");
                else {
                    match_state[ifdef_level - 1] = ps;
                    ps = state_stack[ifdef_level - 1];
                }
            } else if (strncmp(s_lab, "#endif", 6) == 0) {
                if (ifdef_level <= 0)
                    diag(1, "Unmatched #endif");
                else {
                    ifdef_level--;

#ifdef undef
                    /*
                         * This match needs to be more intelligent before the
                         * message is useful
                         */
                    if (match_state[ifdef_level].tos >= 0
                            && memcmp(&ps, &match_state[ifdef_level], sizeof ps))
                        diag(0, "Syntactically inconsistant #ifdef alternatives.");
#endif
                }
                if (blanklines_around_conditional_compilation) {
                    postfix_blankline_requested++;
                    n_real_blanklines = 0;
                }
            }
            break;	/* subsequent processing of the newline
				 * character will cause the line to be printed */

        case comment:	/* we have gotten a start comment */
            /* this is a biggie */
            if (flushed_nl) {
                /* we should force a broken
                			 * line here */
                flushed_nl = false;
                dump_line();
                ps.want_blank = false;	/* don't insert blank at
							 * line start */
                force_nl = false;
            }
            pr_comment();
            break;
        }		/* end of big switch stmt */

        *e_code = '\0';	/* make sure code section is null terminated */
        if (type_code != comment && type_code != newline && type_code != preesc)
            ps.last_token = type_code;
    }			/* end of main while (1) loop */
}
Пример #11
0
/* XXX - Would it make more sense to use GStrings here instead of reallocing
   our buffers? */
static gboolean
read_filters_file(FILE *f, gpointer user_data)
{
#define INIT_BUF_SIZE 128
    gchar    *name             = NULL;
    gchar    *filter_exp       = NULL;
    guint32   name_len         = INIT_BUF_SIZE;
    guint32   filter_exp_len   = INIT_BUF_SIZE;
    guint32   i                = 0;
    gint32    c;
    guint16   fg_r, fg_g, fg_b, bg_r, bg_g, bg_b;
    gboolean  disabled         = FALSE;
    gboolean  skip_end_of_line = FALSE;

    name = (gchar *)g_malloc(name_len + 1);
    filter_exp = (gchar *)g_malloc(filter_exp_len + 1);

    while (1) {

        if (skip_end_of_line) {
            do {
                c = getc(f);
            } while (c != EOF && c != '\n');
            if (c == EOF)
                break;
            disabled = FALSE;
            skip_end_of_line = FALSE;
        }

        while ((c = getc(f)) != EOF && isspace(c)) {
            if (c == '\n') {
                continue;
            }
        }

        if (c == EOF)
            break;

        if (c == '!') {
            disabled = TRUE;
            continue;
        }

        /* skip # comments and invalid lines */
        if (c != '@') {
            skip_end_of_line = TRUE;
            continue;
        }

        /* we get the @ delimiter.
         * Format is:
         * @name@filter expression@[background r,g,b][foreground r,g,b]
         */

        /* retrieve name */
        i = 0;
        while (1) {
            c = getc(f);
            if (c == EOF || c == '@')
                break;
            if (i >= name_len) {
                /* buffer isn't long enough; double its length.*/
                name_len *= 2;
                name = (gchar *)g_realloc(name, name_len + 1);
            }
            name[i++] = c;
        }
        name[i] = '\0';

        if (c == EOF) {
            break;
        } else if (i == 0) {
            skip_end_of_line = TRUE;
            continue;
        }

        /* retrieve filter expression */
        i = 0;
        while (1) {
            c = getc(f);
            if (c == EOF || c == '@')
                break;
            if (i >= filter_exp_len) {
                /* buffer isn't long enough; double its length.*/
                filter_exp_len *= 2;
                filter_exp = (gchar *)g_realloc(filter_exp, filter_exp_len + 1);
            }
            filter_exp[i++] = c;
        }
        filter_exp[i] = '\0';

        if (c == EOF) {
            break;
        } else if (i == 0) {
            skip_end_of_line = TRUE;
            continue;
        }

        /* retrieve background and foreground colors */
        if (fscanf(f,"[%hu,%hu,%hu][%hu,%hu,%hu]",
                   &bg_r, &bg_g, &bg_b, &fg_r, &fg_g, &fg_b) == 6) {

            /* we got a complete color filter */

            color_t bg_color, fg_color;
            color_filter_t *colorf;
            dfilter_t *temp_dfilter;

            if (!dfilter_compile(filter_exp, &temp_dfilter)) {
                g_warning("Could not compile \"%s\" in colorfilters file.\n%s",
                          name, dfilter_error_msg);
                prefs.unknown_colorfilters = TRUE;

                skip_end_of_line = TRUE;
                continue;
            }

            if (!initialize_color(&fg_color, fg_r, fg_g, fg_b)) {
                /* oops */
                simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
                              "Could not allocate foreground color "
                              "specified in input file for %s.", name);
                dfilter_free(temp_dfilter);
                skip_end_of_line = TRUE;
                continue;
            }
            if (!initialize_color(&bg_color, bg_r, bg_g, bg_b)) {
                /* oops */
                simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
                              "Could not allocate background color "
                              "specified in input file for %s.", name);
                dfilter_free(temp_dfilter);
                skip_end_of_line = TRUE;
                continue;
            }

            colorf = color_filter_new(name, filter_exp, &bg_color,
                                      &fg_color, disabled);
            if(user_data == &color_filter_list) {
                GSList **cfl = (GSList **)user_data;

                /* internal call */
                colorf->c_colorfilter = temp_dfilter;
                *cfl = g_slist_append(*cfl, colorf);
            } else {
                /* external call */
                /* just editing, don't need the compiled filter */
                dfilter_free(temp_dfilter);
                color_filter_add_cb (colorf, user_data);
            }
        }    /* if sscanf */

        skip_end_of_line = TRUE;
    }

    g_free(name);
    g_free(filter_exp);
    return TRUE;
}
Пример #12
0
/**
        Reads input stream until end of line, ";", or eof
        stores characters in line_save

        returns:
                EOF on empty line on end of file or
                OK otherwise
*/
PHRQ_io::LINE_TYPE PHRQ_io::
get_logical_line(void)
{
	int j;
	unsigned int pos;
	char c;

	m_line_save.erase(m_line_save.begin(), m_line_save.end());	// m_line_save.clear();
	while ((j = getc()) != EOF)
	{
		c = (char) j;
		if (c == '#')
		{
			// ignore all chars after # until newline
			do
			{
				c = (char) j;
				if (c == '\n')
				{
					break;
				}
				m_line_save += c;
			}
			while ((j = getc()) != EOF);
		}
		if (c == ';')
			break;
		if (c == '\n')
		{
			break;
		}
		if (c == '\\')
		{
			pos = (int) m_line_save.size();
			m_line_save += c;
			while ((j = getc()) != EOF)
			{
				c = (char) j;
				if (c == '\\')
				{
					pos = (int) m_line_save.size();
					m_line_save += c;
					continue;
				}
				if (c == '\n')
				{
					// remove '\\'
					m_line_save = m_line_save.substr(0,pos);
					break;
				}
				m_line_save += c;
				if (!::isspace(j))
					break;
			}
		}
		else
		{
			m_line_save += c;
		}
	}
	if (j == std::char_traits < char >::eof() && m_line_save.size() == 0)
	{
		return (LT_EOF);
	}
	return (LT_OK);
}
Пример #13
0
void WaitForKeyPress()
{
	printf("Press any key to exit...\n");
	getc(stdin);
}
Пример #14
0
static int raw_access(nand_info_t *nand, ulong addr, loff_t off, ulong count,
			int read)
{
	int ret = 0;

	while (count--) {
		/* Raw access */
		mtd_oob_ops_t ops = {
			.datbuf = (u8 *)addr,
			.oobbuf = ((u8 *)addr) + nand->writesize,
			.len = nand->writesize,
			.ooblen = nand->oobsize,
			.mode = MTD_OOB_RAW
		};

		if (read)
			ret = nand->read_oob(nand, off, &ops);
		else
			ret = nand->write_oob(nand, off, &ops);

		if (ret) {
			printf("%s: error at offset %llx, ret %d\n",
				__func__, (long long)off, ret);
			break;
		}

		addr += nand->writesize + nand->oobsize;
		off += nand->writesize;
	}

	return ret;
}

int do_nand(cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
{
	int i, ret = 0;
	ulong addr;
	loff_t off, size;
	char *cmd, *s;
	nand_info_t *nand;
#ifdef CONFIG_SYS_NAND_QUIET
	int quiet = CONFIG_SYS_NAND_QUIET;
#else
	int quiet = 0;
#endif
	const char *quiet_str = getenv("quiet");
	int dev = nand_curr_device;
	int repeat = flag & CMD_FLAG_REPEAT;

	/* at least two arguments please */
	if (argc < 2)
		goto usage;

	if (quiet_str)
		quiet = simple_strtoul(quiet_str, NULL, 0) != 0;

	cmd = argv[1];

	/* Only "dump" is repeatable. */
	if (repeat && strcmp(cmd, "dump"))
		return 0;

	if (strcmp(cmd, "info") == 0) {

		putc('\n');
		for (i = 0; i < CONFIG_SYS_MAX_NAND_DEVICE; i++) {
			if (nand_info[i].name)
				nand_print_and_set_info(i);
		}
		return 0;
	}

	if (strcmp(cmd, "device") == 0) {
		if (argc < 3) {
			putc('\n');
			if (dev < 0 || dev >= CONFIG_SYS_MAX_NAND_DEVICE)
				puts("no devices available\n");
			else
				nand_print_and_set_info(dev);
			return 0;
		}

		dev = (int)simple_strtoul(argv[2], NULL, 10);
		set_dev(dev);

		return 0;
	}

#ifdef CONFIG_ENV_OFFSET_OOB
	/* this command operates only on the first nand device */
	if (strcmp(cmd, "env.oob") == 0)
		return do_nand_env_oob(cmdtp, argc - 1, argv + 1);
#endif

	/* The following commands operate on the current device, unless
	 * overridden by a partition specifier.  Note that if somehow the
	 * current device is invalid, it will have to be changed to a valid
	 * one before these commands can run, even if a partition specifier
	 * for another device is to be used.
	 */
	if (dev < 0 || dev >= CONFIG_SYS_MAX_NAND_DEVICE ||
	    !nand_info[dev].name) {
		puts("\nno devices available\n");
		return 1;
	}
	nand = &nand_info[dev];

	if (strcmp(cmd, "bad") == 0) {
		printf("\nDevice %d bad blocks:\n", dev);
		for (off = 0; off < nand->size; off += nand->erasesize)
			if (nand_block_isbad(nand, off))
				printf("  %08llx\n", (unsigned long long)off);
		return 0;
	}

	/*
	 * Syntax is:
	 *   0    1     2       3    4
	 *   nand erase [clean] [off size]
	 */
	if (strncmp(cmd, "erase", 5) == 0 || strncmp(cmd, "scrub", 5) == 0) {
		nand_erase_options_t opts;
		/* "clean" at index 2 means request to write cleanmarker */
		int clean = argc > 2 && !strcmp("clean", argv[2]);
		int scrub_yes = argc > 2 && !strcmp("-y", argv[2]);
		int o = (clean || scrub_yes) ? 3 : 2;
		int scrub = !strncmp(cmd, "scrub", 5);
		int spread = 0;
		int args = 2;
		const char *scrub_warn =
			"Warning: "
			"scrub option will erase all factory set bad blocks!\n"
			"         "
			"There is no reliable way to recover them.\n"
			"         "
			"Use this command only for testing purposes if you\n"
			"         "
			"are sure of what you are doing!\n"
			"\nReally scrub this NAND flash? <y/N>\n";

		if (cmd[5] != 0) {
			if (!strcmp(&cmd[5], ".spread")) {
				spread = 1;
			} else if (!strcmp(&cmd[5], ".part")) {
				args = 1;
			} else if (!strcmp(&cmd[5], ".chip")) {
				args = 0;
			} else {
				goto usage;
			}
		}

		/*
		 * Don't allow missing arguments to cause full chip/partition
		 * erases -- easy to do accidentally, e.g. with a misspelled
		 * variable name.
		 */
		if (argc != o + args)
			goto usage;

		printf("\nNAND %s: ", cmd);
		/* skip first two or three arguments, look for offset and size */
		if (arg_off_size(argc - o, argv + o, &dev, &off, &size) != 0)
			return 1;

		nand = &nand_info[dev];

		memset(&opts, 0, sizeof(opts));
		opts.offset = off;
		opts.length = size;
		opts.jffs2  = clean;
		opts.quiet  = quiet;
		opts.spread = spread;

		if (scrub) {
			if (!scrub_yes)
				puts(scrub_warn);

			if (scrub_yes)
				opts.scrub = 1;
			else if (getc() == 'y') {
				puts("y");
				if (getc() == '\r')
					opts.scrub = 1;
				else {
					puts("scrub aborted\n");
					return -1;
				}
			} else {
				puts("scrub aborted\n");
				return -1;
			}
		}
		ret = nand_erase_opts(nand, &opts);
		printf("%s\n", ret ? "ERROR" : "OK");

		return ret == 0 ? 0 : 1;
	}

	if (strncmp(cmd, "dump", 4) == 0) {
		if (argc < 3)
			goto usage;

		off = (int)simple_strtoul(argv[2], NULL, 16);
		ret = nand_dump(nand, off, !strcmp(&cmd[4], ".oob"), repeat);

		return ret == 0 ? 1 : 0;
	}

	if (strncmp(cmd, "read", 4) == 0 || strncmp(cmd, "write", 5) == 0) {
		size_t rwsize;
		ulong pagecount = 1;
		int read;
		int raw;

		if (argc < 4)
			goto usage;

		addr = (ulong)simple_strtoul(argv[2], NULL, 16);

		read = strncmp(cmd, "read", 4) == 0; /* 1 = read, 0 = write */
		printf("\nNAND %s: ", read ? "read" : "write");

		nand = &nand_info[dev];

		s = strchr(cmd, '.');

		if (s && !strcmp(s, ".raw")) {
			raw = 1;

			if (arg_off(argv[3], &dev, &off, &size))
				return 1;

			if (argc > 4 && !str2long(argv[4], &pagecount)) {
				printf("'%s' is not a number\n", argv[4]);
				return 1;
			}

			if (pagecount * nand->writesize > size) {
				puts("Size exceeds partition or device limit\n");
				return -1;
			}

			rwsize = pagecount * (nand->writesize + nand->oobsize);
		} else {
			if (arg_off_size(argc - 3, argv + 3, &dev,
						&off, &size) != 0)
				return 1;

			rwsize = size;
		}

		if (!s || !strcmp(s, ".jffs2") ||
		    !strcmp(s, ".e") || !strcmp(s, ".i")) {
			if (read)
				ret = nand_read_skip_bad(nand, off, &rwsize,
							 (u_char *)addr);
			else
				ret = nand_write_skip_bad(nand, off, &rwsize,
							  (u_char *)addr, 0);
#ifdef CONFIG_CMD_NAND_TRIMFFS
		} else if (!strcmp(s, ".trimffs")) {
			if (read) {
				printf("Unknown nand command suffix '%s'\n", s);
				return 1;
			}
			ret = nand_write_skip_bad(nand, off, &rwsize,
						(u_char *)addr,
						WITH_DROP_FFS);
#endif
		} else if (!read && s !=NULL && (!strcmp(s, ".uboot")) && nand->writesize == 4096) {
			rwsize = 4096;
			nand_write(nand, off, &rwsize, (u_char *)addr);

			off += 4096;
			addr += 2048;
			nand_write(nand, off, &rwsize, (u_char *)addr);

			off += 4096;
			addr += 2048;
			nand_write(nand, off, &rwsize, (u_char *)addr);

			off += 4096;
			addr += 2048;
			nand_write(nand, off, &rwsize, (u_char *)addr);

#ifdef CONFIG_CMD_NAND_YAFFS
		} else if (!strcmp(s, ".yaffs")) {
			if (read) {
				printf("Unknown nand command suffix '%s'.\n", s);
				return 1;
			}
			ret = nand_write_skip_bad(nand, off, &rwsize,
						(u_char *)addr,
						WITH_INLINE_OOB);
#endif
		} else if (!strcmp(s, ".oob")) {
			/* out-of-band data */
			mtd_oob_ops_t ops = {
				.oobbuf = (u8 *)addr,
				.ooblen = rwsize,
				.mode = MTD_OOB_RAW
			};

			if (read)
				ret = nand->read_oob(nand, off, &ops);
			else
				ret = nand->write_oob(nand, off, &ops);
		} else if (raw) {
Пример #15
0
getchar()
{
	return(getc(stdin));
}
Пример #16
0
/**
 * @brief Reads the part of a file up to a delimiter to a string.
 * <p> 
 * Read up to (and including) a DELIMITER from FP into *LINEPTR (and NUL-terminate it).
 *
 * @param lineptr Pointer to a pointer returned from malloc (or NULL), pointing to a buffer. It is
 * realloc'ed as necessary and will receive the data read.
 * @param n Size of the buffer.  
 *
 * @return Number of characters read (not including the null terminator), or -1 on error or EOF.
*/
ssize_t
getdelim (char **lineptr, size_t *n, int delimiter, FILE *fp)
{
  int result;
  size_t cur_len = 0;

  if (lineptr == NULL || n == NULL || fp == NULL)
    {
      return -1;
    }

  flockfile (fp);

  if (*lineptr == NULL || *n == 0)
    {
      *n = 120;
      *lineptr = (char *) realloc (*lineptr, *n);
      if (*lineptr == NULL)
	{
	  result = -1;
	  goto unlock_return;
	}
    }

  for (;;)
    {
      int i;

      i = getc (fp);
      if (i == EOF)
	{
	  result = -1;
	  break;
	}

      /* Make enough space for len+1 (for final NUL) bytes.  */
      if (cur_len + 1 >= *n)
	{
	  size_t needed_max=SIZE_MAX;
	  size_t needed = 2 * *n + 1;   /* Be generous. */
	  char *new_lineptr;
	  if (needed_max < needed)
	    needed = needed_max;
	  if (cur_len + 1 >= needed)
	    {
	      result = -1;
	      goto unlock_return;
	    }

	  new_lineptr = (char *) realloc (*lineptr, needed);
	  if (new_lineptr == NULL)
	    {
	      result = -1;
	      goto unlock_return;
	    }

	  *lineptr = new_lineptr;
	  *n = needed;
	}

      (*lineptr)[cur_len] = i;
      cur_len++;

      if (i == delimiter)
	break;
    }
  (*lineptr)[cur_len] = '\0';
  result = cur_len ? cur_len : result;

 unlock_return:
  funlockfile (fp); /* doesn't set errno */

  return result;
}
Пример #17
0
static int test_eof (lua_State *L, FILE *f) {
  int c = getc(f);
  ungetc(c, f);
  lua_pushlstring(L, NULL, 0);
  return (c != EOF);
}
Пример #18
0
int
getchar(void)
{
    return getc(stdin);
}
Пример #19
0
static int
ParseComment(xpmData *mdata)
{
    if (mdata->type == XPMBUFFER) {
	register char c;
	register unsigned int n = 0;
	unsigned int notend;
	char *s, *s2;

	s = mdata->Comment;
	*s = mdata->Bcmt[0];

	/* skip the string beginning comment */
	s2 = mdata->Bcmt;
	do {
	    c = *mdata->cptr++;
	    *++s = c;
	    n++;
	    s2++;
	} while (c == *s2 && *s2 != '\0' && c && c != mdata->Bos);

	if (*s2 != '\0') {
	    /* this wasn't the beginning of a comment */
	    mdata->cptr -= n;
	    return 0;
	}
	/* store comment */
	mdata->Comment[0] = *s;
	s = mdata->Comment;
	notend = 1;
	n = 0;
	while (notend) {
	    s2 = mdata->Ecmt;
	    while (*s != *s2 && c && c != mdata->Bos) {
		c = *mdata->cptr++;
		*++s = c;
		n++;
	    }
	    mdata->CommentLength = n;
	    do {
		c = *mdata->cptr++;
		n++;
		*++s = c;
		s2++;
	    } while (c == *s2 && *s2 != '\0' && c && c != mdata->Bos);
	    if (*s2 == '\0') {
		/* this is the end of the comment */
		notend = 0;
		mdata->cptr--;
	    }
	}
	return 0;
    } else {
	FILE *file = mdata->stream.file;
	register int c;
	register unsigned int n = 0, a;
	unsigned int notend;
	char *s, *s2;

	s = mdata->Comment;
	*s = mdata->Bcmt[0];

	/* skip the string beginning comment */
	s2 = mdata->Bcmt;
	do {
	    c = getc(file);
	    *++s = c;
	    n++;
	    s2++;
	} while (c == *s2 && *s2 != '\0'
		 && c != EOF && c != mdata->Bos);

	if (*s2 != '\0') {
	    /* this wasn't the beginning of a comment */
	    /* put characters back in the order that we got them */
	    for (a = n; a > 0; a--, s--)
		ungetc(*s, file);
	    return 0;
	}
	/* store comment */
	mdata->Comment[0] = *s;
	s = mdata->Comment;
	notend = 1;
	n = 0;
	while (notend) {
	    s2 = mdata->Ecmt;
	    while (*s != *s2 && c != EOF && c != mdata->Bos) {
		c = getc(file);
		*++s = c;
		n++;
	    }
	    mdata->CommentLength = n;
	    do {
		c = getc(file);
		n++;
		*++s = c;
		s2++;
	    } while (c == *s2 && *s2 != '\0'
		     && c != EOF && c != mdata->Bos);
	    if (*s2 == '\0') {
		/* this is the end of the comment */
		notend = 0;
		ungetc(*s, file);
	    }
	}
	return 0;
    }
}
Пример #20
0
struct expression_s *
parse (FILE *input)
{
  int ch;
  do {
    ch = getc (input);
    if ( ch == '#' )
      while ( ch != '\n' && ch != EOF )
	ch = getc (input);
  } while ( ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t' );
  if ( ch == '`' )
    {
      struct expression_s *rator = parse (input);
      struct expression_s *rand = parse (input);
      struct expression_s *expr = new_expression ();

      expr->t = EXPRESSION_APPLICATION;
      init_ptr (&expr->d.expression_application_v.rator, rator);
      init_ptr (&expr->d.expression_application_v.rand, rand);
#if 0  /* Harmless but not necessary */
      free_expression (rator);
      free_expression (rand);
#endif
      return expr;
    }
  else if ( ch == 'i' || ch == 'I' )
    {
      struct function_s *fun = new_function ();
      struct expression_s *expr = new_expression ();

      fun->t = FUNCTION_I;
      expr->t = EXPRESSION_FUNCTION;
      init_ptr (&expr->d.expression_function_v, fun);
#if 0  /* Harmless but not necessary */
      free_function (fun);
#endif
      return expr;
    }
  else if ( ch == 'k' || ch == 'K' )
    {
      struct function_s *fun = new_function ();
      struct expression_s *expr = new_expression ();

      fun->t = FUNCTION_K;
      expr->t = EXPRESSION_FUNCTION;
      init_ptr (&expr->d.expression_function_v, fun);
#if 0  /* Harmless but not necessary */
      free_function (fun);
#endif
      return expr;
    }
  else if ( ch == 's' || ch == 'S' )
    {
      struct function_s *fun = new_function ();
      struct expression_s *expr = new_expression ();

      fun->t = FUNCTION_S;
      expr->t = EXPRESSION_FUNCTION;
      init_ptr (&expr->d.expression_function_v, fun);
#if 0  /* Harmless but not necessary */
      free_function (fun);
#endif
      return expr;
    }
  else if ( ch == 'v' || ch == 'V' )
    {
      struct function_s *fun = new_function ();
      struct expression_s *expr = new_expression ();

      fun->t = FUNCTION_V;
      expr->t = EXPRESSION_FUNCTION;
      init_ptr (&expr->d.expression_function_v, fun);
#if 0  /* Harmless but not necessary */
      free_function (fun);
#endif
      return expr;
    }
  else if ( ch == 'd' || ch == 'D' )
    {
      struct function_s *fun = new_function ();
      struct expression_s *expr = new_expression ();

      fun->t = FUNCTION_D;
      expr->t = EXPRESSION_FUNCTION;
      init_ptr (&expr->d.expression_function_v, fun);
#if 0  /* Harmless but not necessary */
      free_function (fun);
#endif
      return expr;
    }
  else if ( ch == 'e' || ch == 'E' )
    {
      struct function_s *fun = new_function ();
      struct expression_s *expr = new_expression ();

      fun->t = FUNCTION_E;
      expr->t = EXPRESSION_FUNCTION;
      init_ptr (&expr->d.expression_function_v, fun);
#if 0  /* Harmless but not necessary */
      free_function (fun);
#endif
      return expr;
    }
  else if ( ch == 'p' || ch == 'P' )
    {
      struct function_s *fun = new_function ();
      struct expression_s *expr = new_expression ();

      fun->t = FUNCTION_P;
      expr->t = EXPRESSION_FUNCTION;
      init_ptr (&expr->d.expression_function_v, fun);
#if 0  /* Harmless but not necessary */
      free_function (fun);
#endif
      return expr;
    }
  else if ( ch == 'f' || ch == 'F' )
    {
      struct function_s *fun = new_function ();
      struct expression_s *expr = new_expression ();

      fun->t = FUNCTION_F;
      expr->t = EXPRESSION_FUNCTION;
      init_ptr (&expr->d.expression_function_v, fun);
#if 0  /* Harmless but not necessary */
      free_function (fun);
#endif
      return expr;
    }
  else if ( ch == 'r' )
    {
      struct function_s *fun = new_function ();
      struct expression_s *expr = new_expression ();

      fun->t = FUNCTION_DOT;
      fun->d.function_dot_v = '\n';
      expr->t = EXPRESSION_FUNCTION;
      init_ptr (&expr->d.expression_function_v, fun);
#if 0  /* Harmless but not necessary */
      free_function (fun);
#endif
      return expr;
    }
  else if ( ch == '.' )
    {
      struct function_s *fun = new_function ();
      struct expression_s *expr = new_expression ();
      int ch2;

      fun->t = FUNCTION_DOT;
      ch2 = getc (input);
      if ( ch2 == EOF )
	goto ueof;
      fun->d.function_dot_v = ch2;
      expr->t = EXPRESSION_FUNCTION;
      init_ptr (&expr->d.expression_function_v, fun);
#if 0  /* Harmless but not necessary */
      free_function (fun);
#endif
      return expr;
    }
  else if ( ch == '@' )
    {
      struct function_s *fun = new_function ();
      struct expression_s *expr = new_expression ();

      fun->t = FUNCTION_AT;
      expr->t = EXPRESSION_FUNCTION;
      init_ptr (&expr->d.expression_function_v, fun);
#if 0  /* Harmless but not necessary */
      free_function (fun);
#endif
      return expr;
    }
  else if ( ch == '?' )
    {
      struct function_s *fun = new_function ();
      struct expression_s *expr = new_expression ();
      int ch2;

      fun->t = FUNCTION_QUES;
      ch2 = getc (input);
      if ( ch2 == EOF )
	goto ueof;
      fun->d.function_ques_v = ch2;
      expr->t = EXPRESSION_FUNCTION;
      init_ptr (&expr->d.expression_function_v, fun);
#if 0  /* Harmless but not necessary */
      free_function (fun);
#endif
      return expr;
    }
  else if ( ch == '|' )
    {
      struct function_s *fun = new_function ();
      struct expression_s *expr = new_expression ();

      fun->t = FUNCTION_PIPE;
      expr->t = EXPRESSION_FUNCTION;
      init_ptr (&expr->d.expression_function_v, fun);
#if 0  /* Harmless but not necessary */
      free_function (fun);
#endif
      return expr;
    }
  else if ( ch == EOF )
    {
    ueof:
      fprintf (stderr, "Unexpected end of file\n");
      exit (1);
    }
  else
    {
      fprintf (stderr, "Character not recognized: %c\n", ch);
      exit (1);
    }
  return NULL;
}
Пример #21
0
static pdf_bool
pdf_data_source_GIF_fill(PDF *p, PDF_data_source *src)
{
#define c_size	image->info.gif.c_size
#define t_size	image->info.gif.t_size
#define i_buff	image->info.gif.i_buff
#define i_bits	image->info.gif.i_bits
#define o_buff	image->info.gif.o_buff
#define o_bits	image->info.gif.o_bits

    pdf_image *		image = (pdf_image *) src->private_data;
    FILE *		fp = image->fp;
    int			n_bytes = getc(fp);	/* # of bytes to read	*/
    unsigned char *	o_curr = src->buffer_start;
    int			c_mask = (1 << c_size) - 1;
    char		filenamebuf[PDF_FILENAMELEN];
    pdf_bool		flag13 = pdf_false;

    src->bytes_available = 0;

    if (n_bytes == EOF)
    {
	strncpy(filenamebuf, image->filename, PDF_FILENAMELEN-1);
	filenamebuf[PDF_FILENAMELEN-1] = '\0';

	pdf_cleanup_image(p, image - p->images);
	pdf_error(p, PDF_IOError, "Unexpected end of GIF file '%s'",
		filenamebuf);
    }

    if (n_bytes == 0)
	return pdf_false;

    for (/* */ ; /* */ ; /* */)
    {
	int w_bits = c_size;	/* number of bits to write */
	int code;

	/* get at least c_size bits into i_buff	*/
	while (i_bits < c_size)
	{
	    if (n_bytes-- == 0)
	    {
		src->bytes_available = (size_t) (o_curr - src->buffer_start);
		return pdf_true;
	    }
	    i_buff |= getc(fp) << i_bits;	/* EOF will be caught later */
	    i_bits += 8;
	}
	code = i_buff & c_mask;
	i_bits -= c_size;
	i_buff >>= c_size;

	if (flag13 && code != 256 && code != 257)
	{
	    strncpy(filenamebuf, image->filename, PDF_FILENAMELEN-1);
	    filenamebuf[PDF_FILENAMELEN-1] = '\0';

	    pdf_cleanup_image(p, image - p->images);
	    pdf_error(p, PDF_IOError,
		"LZW code size overflow in GIF file '%s'", filenamebuf);
	}

	if (o_bits > 0)
	{
	    o_buff |= code >> (c_size - 8 + o_bits);
	    w_bits -= 8 - o_bits;
	    *(o_curr++) = (unsigned char) o_buff;
	}
	if (w_bits >= 8)
	{
	    w_bits -= 8;
	    *(o_curr++) = (unsigned char) (code >> w_bits);
	}
Пример #22
0
bool S9xLoadCrosshairFile (int idx, const char *filename)
{
	if (idx < 1 || idx > 31)
		return (false);

	char	*s = (char *) calloc(15 * 15 + 1, sizeof(char));
	if (s == NULL)
	{
		fprintf(stderr, "S9xLoadCrosshairFile: malloc error while reading ");
		perror(filename);
		return (false);
	}

	FILE	*fp = fopen(filename, "rb");
	if (fp == NULL)
	{
		fprintf(stderr, "S9xLoadCrosshairFile: Couldn't open ");
		perror(filename);
		free(s);
		return (false);
	}

	size_t	l = fread(s, 1, 8, fp);
	if (l != 8)
	{
		fprintf(stderr, "S9xLoadCrosshairFile: File is too short!\n");
		free(s);
		fclose(fp);
		return (false);
	}

#ifdef HAVE_LIBPNG
	png_structp	png_ptr;
	png_infop	info_ptr;

	if (!png_sig_cmp((png_byte *) s, 0, 8))
	{
		png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
		if (!png_ptr)
		{
			free(s);
			fclose(fp);
			return (false);
		}

		info_ptr = png_create_info_struct(png_ptr);
		if (!info_ptr)
		{
			png_destroy_read_struct(&png_ptr, (png_infopp) NULL, (png_infopp) NULL);
			free(s);
			fclose(fp);
			return (false);
		}

		png_init_io(png_ptr, fp);
		png_set_sig_bytes(png_ptr, 8);
		png_read_info(png_ptr, info_ptr);

		png_uint_32	width, height;
		int			bit_depth, color_type;

		png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, NULL, NULL, NULL);
		if (color_type != PNG_COLOR_TYPE_PALETTE)
		{
			fprintf(stderr, "S9xLoadCrosshairFile: Input PNG is not a palettized image!\n");
			png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp) NULL);
			free(s);
			fclose(fp);
			return (false);
		}

		if (bit_depth == 16)
			png_set_strip_16(png_ptr);

		if (width != 15 || height != 15)
		{
			fprintf(stderr, "S9xLoadCrosshairFile: Expecting a 15x15 PNG\n");
			png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp) NULL);
			free(s);
			fclose(fp);
			return (false);
		}

		png_color	*pngpal;
		png_byte	*trans;
		int			num_palette = 0, num_trans = 0;
		int			transcol = -1, fgcol = -1, bgcol = -1;

		png_get_PLTE(png_ptr, info_ptr, &pngpal, &num_palette);
		png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans, NULL);

		if (num_palette != 3 || num_trans != 1)
		{
			fprintf(stderr, "S9xLoadCrosshairFile: Expecting a 3-color PNG with 1 trasnparent color\n");
			png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp) NULL);
			free(s);
			fclose(fp);
			return (false);
		}

		for (int i = 0; i < 3; i++)
		{
			if (trans[0] == i)
				transcol = i;
			else
			if (pngpal[i].red ==   0 && pngpal[i].green ==   0 && pngpal[i].blue ==   0)
				bgcol = i;
			else
			if (pngpal[i].red == 255 && pngpal[i].green == 255 && pngpal[i].blue == 255)
				fgcol = i;
		}

		if (transcol < 0 || fgcol < 0 || bgcol < 0)
		{
			fprintf(stderr, "S9xLoadCrosshairFile: PNG must have 3 colors: white (fg), black (bg), and transparent.\n");
			png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp) NULL);
			free(s);
			fclose(fp);
			return (false);
		}

		png_set_packing(png_ptr);
		png_read_update_info(png_ptr, info_ptr);
		png_byte	*row_pointer = new png_byte[png_get_rowbytes(png_ptr, info_ptr)];

		for (int r = 0; r < 15 * 15; r += 15)
		{
			png_read_row(png_ptr, row_pointer, NULL);

			for (int i = 0; i < 15; i++)
			{
				if (row_pointer[i] == transcol)
					s[r + i] = ' ';
				else
				if (row_pointer[i] == fgcol)
					s[r + i] = '#';
				else
				if (row_pointer[i] == bgcol)
					s[r + i] = '.';
				else
				{
					fprintf(stderr, "S9xLoadCrosshairFile: WTF? This was supposed to be a 3-color PNG!\n");
					png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp) NULL);
					free(s);
					fclose(fp);
					return (false);
				}
			}
		}

		s[15 * 15] = 0;
		png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp) NULL);
	}
	else
#endif
	{
		l = fread(s + 8, 1, 15 - 8, fp);
		if (l != 15 - 8)
		{
			fprintf(stderr, "S9xLoadCrosshairFile: File is too short!\n");
			free(s);
			fclose(fp);
			return (false);
		}

		if (getc(fp) != '\n')
		{
			fprintf(stderr, "S9xLoadCrosshairFile: Invalid file format! (note: PNG support is not available)\n");
			free(s);
			fclose(fp);
			return (false);
		}

		for (int r = 1; r < 15; r++)
		{
			l = fread(s + r * 15, 1, 15, fp);
			if (l != 15)
			{
				fprintf(stderr, "S9xLoadCrosshairFile: File is too short! (note: PNG support is not available)\n");
				free(s);
				fclose(fp);
				return (false);
			}

			if (getc(fp) != '\n')
			{
				fprintf(stderr, "S9xLoadCrosshairFile: Invalid file format! (note: PNG support is not available)\n");
				free(s);
				fclose(fp);
				return (false);
			}
		}

		for (int i = 0; i < 15 * 15; i++)
		{
			if (s[i] != ' ' && s[i] != '#' && s[i] != '.')
			{
				fprintf(stderr, "S9xLoadCrosshairFile: Invalid file format! (note: PNG support is not available)\n");
				free(s);
				fclose(fp);
				return (false);
			}
		}
	}

	fclose(fp);

	if (crosshairs[idx] != NULL && crosshairs[idx][0] != '`')
		free((void *) crosshairs[idx]);
	crosshairs[idx] = s;

	return (true);
}
Пример #23
0
static void ignore_whitespace()
{
	int c;
	while (isspace(c = getc(stdin)) && c != EOF);
	ungetc(c, stdin);
}
Пример #24
0
int readFastq (FILE *fil, int *conv, 
	       char **seq, char **qval, char **id, char **desc, int *length)
{
  char c, *cp ;
  int n, m ;
  static FILE *oldFil = 0 ;
  static int line ;
  int buflen ;

  if (fil != oldFil)
    { line = 1 ;
      oldFil = fil ;
    }
  
/* get id */
  c = getc (fil) ;
  if (!feof(fil) && c != '@')			/* header line */
    { fprintf (stderr, "bad @ header line %d\n", line) ; return 0 ; }
  
  c = getc(fil) ;
  n = 0 ;			/* id */
  buflen = -32;
  while (!feof (fil) && c != ' ' && c != '\n' && c != '\t')
    { if (id) add (c, id, &buflen, n++) ;
      c = getc (fil) ;
    }
  if (id) add (0, id, &buflen, n) ;

				/* white space */
  while (!feof (fil) && (c == ' ' || c == '\t'))
    c = getc (fil) ;

  n = 0 ;			/* desc */
  buflen = -32 ;
  while (!feof (fil) && c != '\n')
    { if (desc) add (c, desc, &buflen, n++) ;
      c = getc (fil) ;
    }
  if (desc) add (0, desc, &buflen, n) ;
  
  if (!feof (fil) && c != '\n')
    { fprintf (stderr, "bad @ identifier line %n\n", line) ; return 0 ; }
  ++line ;

  /* ensure whitespace ignored */

  conv[' '] = conv['\t'] = -1 ;
  conv['\n'] = -3 ;

  n = 0 ;			/* sequence */
  buflen = -1024 ;

  while (!feof (fil))
    { 
      c = getc (fil) ;
      if (c == '+')
	{ ungetc (c, fil) ;
	  break ;
	}

      if (c == EOF || c == EOF + 256) /* satisfies all compilers */
	break ;
    
      switch (conv[c]) {
        case -2:
          { if (id) 
              fprintf (stderr, "Bad char 0x%x = '%c' at line %d, base %d, sequence %s\n",
          	     c, c, line, n, *id) ;
            else
              fprintf (stderr, "Bad char 0x%x = '%c' at line %d, base %d\n",
          	     c, c, line, n) ;
            return 0 ;
          }
          break;
        case -3:
          ++line;
        case -1:
          break;
        default:
	  if (seq) add (conv[c], seq, &buflen, n++) ;
	  else ++n ;
      }
    }
  if (seq) add (0, seq, &buflen, n) ;

  if (length)
    *length = n ;
  
/* second block with same identifier and matching quality values */
  c = getc (fil) ;
  if (!feof(fil) && c != '+')			/* header line */
    { fprintf (stderr, "bad + header line %d\n", line) ; return 0 ; }
  
  c = getc(fil) ; if (id) cp = *id ;
  while (!feof (fil) && c != ' ' && c != '\n' && c != '\t')
    { if (id && c != *cp++) 
	{ fprintf (stderr, "mismatching + identifier line %d\n", line) ; return 0 ; }
      c = getc (fil) ;
    }

  while (!feof (fil) && c != '\n')		/* ignore rest of line - may have desc or not */
    c = getc (fil) ;

  ++line ;

  m = 0 ;			/* qualities */
  buflen = -(n+1) ;

  while (!feof (fil))
    { 
      c = getc (fil) ;
      if (c == '@' && m == n)
	{ ungetc (c, fil) ;
	  break ;
	}
      else if (m > n)
	break ;

      if (c == EOF || c == EOF + 256) /* satisfies all compilers */
	break ;

      if (c == '\n')
	++line;
      else if (qval) 
	add (c-33, qval, &buflen, m++) ;
      else 
	++m ;
    }
  if (qval) add (0, qval, &buflen, m) ;

  if (m != n)
    { fprintf (stderr, "mismatching seq, q length line %n\n", line) ; return 0 ; }

  return n ;
}
Пример #25
0
/* ARGSUSED */
int
d_shell_command(int f, int n)
{
#ifdef MONA
  ewprintf("shell command is not supported");
  return (FALSE);
#else
	char	 command[512], fname[MAXPATHLEN], buf[BUFSIZ], *bufp, *cp;
	int	 infd, fds[2];
	pid_t	 pid;
	struct	 sigaction olda, newa;
	struct buffer	*bp;
	struct mgwin	*wp;
	FILE	*fin;

	bp = bfind("*Shell Command Output*", TRUE);
	if (bclear(bp) != TRUE)
		return (ABORT);

	if (d_makename(curwp->w_dotp, fname, sizeof(fname)) != FALSE) {
		ewprintf("bad line");
		return (ABORT);
	}

	command[0] = '\0';
	if ((bufp = eread("! on %s: ", command, sizeof(command), EFNEW,
	    basename(fname))) == NULL)
		return (ABORT);
	infd = open(fname, O_RDONLY);
	if (infd == -1) {
		ewprintf("Can't open input file : %s", strerror(errno));
		return (FALSE);
	}
	if (pipe(fds) == -1) {
		ewprintf("Can't create pipe : %s", strerror(errno));
		close(infd);
		return (FALSE);
	}

	newa.sa_handler = reaper;
	newa.sa_flags = 0;
	if (sigaction(SIGCHLD, &newa, &olda) == -1) {
		close(infd);
		close(fds[0]);
		close(fds[1]);
		return (ABORT);
	}
	pid = fork();
	switch (pid) {
	case -1:
		ewprintf("Can't fork");
		return (ABORT);
	case 0:
		close(fds[0]);
		dup2(infd, STDIN_FILENO);
		dup2(fds[1], STDOUT_FILENO);
		dup2(fds[1], STDERR_FILENO);
		execl("/bin/sh", "sh", "-c", bufp, (char *)NULL);
		exit(1);
		break;
	default:
		close(infd);
		close(fds[1]);
		fin = fdopen(fds[0], "r");
		if (fin == NULL)	/* "r" is surely a valid mode! */
			panic("can't happen");
		while (fgets(buf, sizeof(buf), fin) != NULL) {
			cp = strrchr(buf, '\n');
			if (cp == NULL && !feof(fin)) {	/* too long a line */
				int c;
				addlinef(bp, "%s...", buf);
				while ((c = getc(fin)) != EOF && c != '\n')
					;
				continue;
			} else if (cp)
				*cp = '\0';
			addline(bp, buf);
		}
		fclose(fin);
		close(fds[0]);
		break;
	}
	wp = popbuf(bp);
	if (wp == NULL)
		return (ABORT);	/* XXX - free the buffer?? */
	curwp = wp;
	curbp = wp->w_bufp;
	if (sigaction(SIGCHLD, &olda, NULL) == -1)
		ewprintf("Warning, couldn't reset previous signal handler");
	return (TRUE);
#endif
}
Пример #26
0
int readSequence (FILE *fil, int *conv, 
                  char **seq, char **id, char **desc, int *length)
{
  char c ;
  int n ;
  static FILE *oldFil = 0 ;
  static int line ;
  int buflen ;

  if (fil != oldFil)
    { line = 1 ;
      oldFil = fil ;
    }
  
/* get id, descriptor */
  c = getc (fil) ;
  if (c == '>')			/* header line */
    { c = getc(fil) ;

      n = 0 ;			/* id */
      buflen = -32;
      while (!feof (fil) && c != ' ' && c != '\n' && c != '\t')
	{ if (id) add (c, id, &buflen, n++) ;
	  c = getc (fil) ;
	}
      if (id) add (0, id, &buflen, n) ;

				/* white space */
      while (!feof (fil) && (c == ' ' || c == '\t'))
	c = getc (fil) ;

      n = 0 ;			/* desc */
      buflen = -32 ;
      while (!feof (fil) && c != '\n')
	{ if (desc) add (c, desc, &buflen, n++) ;
	  c = getc (fil) ;
	}
      if (desc) add (0, desc, &buflen, n) ;

      ++line ;
    }
  else
    { ungetc (c, fil) ;		/* no header line */
      if (id) 
	*id = "" ;
      if (desc)
	*desc = "" ;
    }

  /* ensure whitespace ignored */

  conv[' '] = conv['\t'] = -1 ;
  conv['\n'] = -3 ;

  n = 0 ;			/* sequence */
  buflen = -1024 ;

  while (!feof (fil))
    { 
      c = getc (fil) ;
      if (c == '>')
	{ ungetc (c, fil) ;
	  break ;
	}

      if (c == EOF || c == EOF + 256) /* satisfies all compilers */
	break ;

    
      switch (conv[c]) {
        case -2:
          { if (id) 
              fprintf (stderr, "Bad char 0x%x = '%c' at line %d, base %d, sequence %s\n",
          	     c, c, line, n, *id) ;
            else
              fprintf (stderr, "Bad char 0x%x = '%c' at line %d, base %d\n",
          	     c, c, line, n) ;
            return 0 ;
          }
          break;
        case -3:
          ++line;
        case -1:
          break;
        default:
	  if (seq) add (conv[c], seq, &buflen, n++) ;
	  else ++n ;
      }
    }
  if (seq) add (0, seq, &buflen, n) ;

  if (length)
    *length = n ;

  return n ;
}
Пример #27
0
void
dartstart(struct tty *tp)
{
	struct dartsoftc *sc;
	dev_t dev;
	int s;
	int port, tries;
	int c;
	bus_addr_t ptaddr;

	dev = tp->t_dev;
	port = DART_PORT(dev);
	if (dart_cd.cd_ndevs == 0 || port >= NDARTPORTS)
		return;

	if ((tp->t_state & TS_ISOPEN) == 0)
		return;

	sc = (struct dartsoftc *)dart_cd.cd_devs[0];
	ptaddr = port ? DART_B_BASE : DART_A_BASE;

	s = spltty();

	if (tp->t_state & (TS_TIMEOUT | TS_BUSY | TS_TTSTOP))
		goto bail;

	if (tp->t_outq.c_cc <= tp->t_lowat) {
		if (tp->t_state & TS_ASLEEP) {
			tp->t_state &= ~TS_ASLEEP;
			wakeup((caddr_t)&tp->t_outq);
		}
		selwakeup(&tp->t_wsel);
		if (tp->t_outq.c_cc == 0)
			goto bail;
	}

	tp->t_state |= TS_BUSY;
	while (tp->t_outq.c_cc != 0) {

		/* load transmitter until it is full */
		for (tries = 10000; tries != 0; tries --)
			if (dart_read(sc, ptaddr + DART_SRA) & TXRDY)
				break;

		if (tries == 0) {
			timeout_add(&tp->t_rstrt_to, 1);
			tp->t_state |= TS_TIMEOUT;
			break;
		} else {
			c = getc(&tp->t_outq);

			dart_write(sc, ptaddr + DART_TBA, c & 0xff);

			if (port == A_PORT)
				sc->sc_sv_reg.sv_imr |= ITXRDYA;
			else
				sc->sc_sv_reg.sv_imr |= ITXRDYB;
			dart_write(sc, DART_IMR, sc->sc_sv_reg.sv_imr);
		}
	}
	tp->t_state &= ~TS_BUSY;

bail:
	splx(s);
}
Пример #28
0
/**
 * 次のトークンを取得
 * @return Token トークン
 */
Token next_token(void) {
    LexerStatus status = INITIAL_STATUS;
    Token token = {BAD_TOKEN, "", 0};
    int c = 0;
    int out_pos = 0;
    int i = 0;
    int is_keyword = 0;
    char str[MAX_TOKEN_SIZE] = "";

    while( EOF != (c = getc(fp)) ) {
        if ((status == IN_INT_PART_STATUS)
            && !isdigit(c) && c != '.') {
            /* 整数部分 */
            ungetc(c, fp);
            sscanf_s(str, "%d", &token.of.intval, sizeof(str));
            token.t = INT_TOKEN;
            break;
        }
        if((status == IN_FRAC_PART_STATUS)
           && !isdigit(c)) {
            /* 小数点数部分 */
            ungetc(c, fp);
            sscanf_s(str, "%f", &token.of.floatval, sizeof(str));
            token.t = FLOAT_TOKEN;
            break;
        }
        if((status == DOT_STATUS) && !isdigit(c)) {
            /* 小数点部分 */
            ungetc(c, fp);
            /* 0 を補って少数として解釈する */
            str[out_pos] = '0';
            ++out_pos;
            str[out_pos] = '\0';
            sscanf_s(str, "%f", &token.of.floatval, sizeof(str));
            token.t = FLOAT_TOKEN;
            break;
        }
        if ((status == IN_ID_PART_STATUS)
            && !isalpha(c) && !isdigit(c)) {
            /* 識別子部分 */
            ungetc(c, fp);
            for(i = 0; KEYWORDS[i] != NULL && 0 == is_keyword; ++i) {
                /* キーワードか判定 */
                if(strcmp(KEYWORDS[i], str) == 0) {
                    switch(i) {
                    case LET_KEYWORD:
                        token.t = LET_TOKEN;
                        break;
                    case IN_KEYWORD:
                        token.t = IN_TOKEN;
                        break;
                    case REC_KEYWORD:
                        token.t = REC_TOKEN;
                        break;
                    case IF_KEYWORD:
                        token.t = IF_TOKEN;
                        break;
                    case THEN_KEYWORD:
                        token.t = THEN_TOKEN;
                        break;
                    case ELSE_KEYWORD:
                        token.t = ELSE_TOKEN;
                        break;
                    }
                    is_keyword = 1;
                }
            }
            if (0 == is_keyword) {
                token.t = ID_TOKEN;
                strncpy_s(token.of.var, MAX_TOKEN_SIZE, str, strlen(str));
            }
            break;
        }
        if ( (status == IN_COMMAND_STATUS)
             && !(isalpha(c)) && !isdigit(c) ) {
            /* 特殊命令部分 */
            if(';' == c) {
                if(';' == (c = getc(fp))) {
                    if( strcmp("#quit", str) == 0) {
                        exit(0);
                    } else {
                        /* それ以外の時に来たらエラー */
                        fprintf(stderr, "bad character(%c)\n", c);
                        break;
                    }                       
                } else {
                    /* それ以外の時に来たらエラー */
                    fprintf(stderr, "bad character(%c)\n", c);
                    break;
                }
            } else {
                /* それ以外の時に来たらエラー */
                fprintf(stderr, "bad character(%c)\n", c);
                break;
            }
        }
        if(isspace(c)) {
            /* 空白は読み飛ばす */
            continue;
        }
        if (out_pos >= MAX_TOKEN_SIZE-1) {
            /* 長すぎるトークンはエラー */
            fprintf(stderr, "token too long.\n"); 
            break;
        }
        str[out_pos] = (char)c;
        /* 終端文字代入。次のループで上書きされて、また終端文字が挿入される */
        ++out_pos;
        str[out_pos] = '\0';
        if ('+' == c ) {
            if('.' == (c = getc(fp))) {
                token.t = FPLUS_TOKEN;
            } else {
                ungetc(c, fp);
                token.t = PLUS_TOKEN;
            }
            break;
        } else if ('-' == c ) {
            if('.' == (c = getc(fp))) {
                token.t = FMINUS_TOKEN;
            } else {
                ungetc(c, fp);
                token.t = MINUS_TOKEN;
            }
            break;
        } else if ('*' == c) {
            if('.' == (c = getc(fp))) {
                token.t = FTIMES_TOKEN;
            } else {
                ungetc(c, fp);
                token.t = TIMES_TOKEN;
            }
            break;
        } else if (';' == c) {
            if(';' == (c = getc(fp))) {
                token.t = SEMICOLON_TOKEN;
            } else {
                /* エラー */
                fprintf(stderr, "bad character(;)\n");
            }
            break;
        }else if ('(' == c) {
            token.t = LPAREN_TOKEN;
            break;
        } else if (')' == c) {
            token.t = RPAREN_TOKEN;
            break;
        } else if ('=' == c) {
            token.t = EQ_TOKEN;
            break;
        } else if (',' == c) {
            token.t = COMMA_TOKEN;
            break;
        } else if (isdigit(c)) {
            if (status == INITIAL_STATUS) {
                status = IN_INT_PART_STATUS;
            } else if (status == DOT_STATUS) {
                status = IN_FRAC_PART_STATUS;
            }
        } else if ('.' == c) {
            if (status == IN_INT_PART_STATUS) {
                /* 整数解析中に . が来たら小数点 */
                status = DOT_STATUS;
            } else {
                /* それ以外の時に来たらエラー */
                fprintf(stderr, "bad character(%c)\n", c);
            }
        } else if (isalpha(c)) {
            if (status == SHARP_STATUS) {
                status = IN_COMMAND_STATUS;
            } else if (status == INITIAL_STATUS) {
                status = IN_ID_PART_STATUS;
            }
        } else if ('#' == c) {
            if (status == INITIAL_STATUS) {
                status = SHARP_STATUS;
            } else {
                /* それ以外の時に来たらエラー */
                fprintf(stderr, "bad character(%c)\n", c);
            }          
        }else {
            /* トークンになりえない文字が来たらエラー */
            fprintf(stderr, "bad character(%c)\n", c);
        }
    }
    if(c == EOF) {
        printf("bye.\n");
        exit(0);
    }
    strncpy_s(token.str, MAX_TOKEN_SIZE, str, strlen(str));
    return token;
}
Пример #29
0
static int
get_next_byte (void *stream)
{
  return getc (stream);
}
Пример #30
0
int main()
{
  int buffer_size = 2048;
  int counter = 0;
  int n_newline = 0;
  char *input = (char*) malloc(sizeof(char) * buffer_size);

  if (input == NULL)
    {
      fprintf(stderr, "Error allocating memory.");
      exit(1);
    }

  int c = 0;
  while(1)
    {
      c = getc(stdin);
      if ( c == EOF)
	break;
      
      input[counter] = (char) c;
      counter++;

      if (counter == buffer_size)
	{
	  input = (char*) realloc(input, buffer_size * 2);
	  if (input == NULL)
	    {
	      fprintf(stderr, "Error reallocating memory.");
	      exit(1);
	    }
	  buffer_size *= 2;
	}
    }
  
  if (counter == 0)
    exit(0);
  
  if (input[counter -1] != '\n')
    {
      if (counter == buffer_size)
	{
	  input = (char*) realloc(input, buffer_size * 2);
	  if (input == NULL)
	    {
	      fprintf(stderr, "Error reallocating memory.");
	      exit(1);
	    }
	  buffer_size *= 2;
	}
      input[counter] = '\n';
      counter++;
    }
  
  
  for (int k = 0; k < counter; k++)
    {
      if (input[k] == '\n')
	n_newline++;
    }

  char **helper = (char**)malloc(sizeof(char*) * counter);
  if (helper == NULL)
    {
      fprintf(stderr, "Error allocating memory.");
      exit(1);
    }

  char *pointer = input;
  int pos = 0;
  for (int i = 0; i < n_newline; i++)
    {
      if ( i == 0 && *pointer == '\n')
	{
	  helper[pos] = pointer;
	  pos++;
	  i++;
	  pointer++;
	}
      helper[pos] = pointer;
      pos++;
      while (*pointer != '\n')
	pointer++;
      pointer++;
    }

  qsort(helper, n_newline, sizeof(char*), cmp);

  char *temp;
  for (int k = 0; k < n_newline; k++)
    {
      temp = helper[k];
      while (*temp != '\n')
	{
	  printf("%c", *temp);
	  temp++;
	}
      printf("%c", *temp);
    }

  free(input);
  free(helper);
  return 0;

}