Ejemplo n.º 1
0
int subsfile_set_subscribed(struct mailbox_list *list, const char *path,
			    const char *temp_prefix, const char *name, bool set)
{
	const struct mail_storage_settings *mail_set = list->mail_set;
	struct dotlock_settings dotlock_set;
	struct dotlock *dotlock;
	const char *line, *origin;
	struct istream *input;
	struct ostream *output;
	int fd_in, fd_out;
	mode_t mode;
	gid_t gid;
	bool found, changed = FALSE, failed = FALSE;

	if (strcasecmp(name, "INBOX") == 0)
		name = "INBOX";

	memset(&dotlock_set, 0, sizeof(dotlock_set));
	dotlock_set.use_excl_lock = mail_set->dotlock_use_excl;
	dotlock_set.nfs_flush = mail_set->mail_nfs_storage;
	dotlock_set.temp_prefix = temp_prefix;
	dotlock_set.timeout = SUBSCRIPTION_FILE_LOCK_TIMEOUT;
	dotlock_set.stale_timeout = SUBSCRIPTION_FILE_CHANGE_TIMEOUT;

	mailbox_list_get_permissions(list, NULL, &mode, &gid, &origin);
	fd_out = file_dotlock_open_group(&dotlock_set, path, 0,
					 mode, gid, origin, &dotlock);
	if (fd_out == -1 && errno == ENOENT) {
		/* directory hasn't been created yet. */
		if (mailbox_list_create_parent_dir(list, NULL, path) < 0)
			return -1;
		fd_out = file_dotlock_open_group(&dotlock_set, path, 0,
						 mode, gid, origin, &dotlock);
	}
	if (fd_out == -1) {
		if (errno == EAGAIN) {
			mailbox_list_set_error(list, MAIL_ERROR_TEMP,
				"Timeout waiting for subscription file lock");
		} else {
			subswrite_set_syscall_error(list, "file_dotlock_open()",
						    path);
		}
		return -1;
	}

	fd_in = nfs_safe_open(path, O_RDONLY);
	if (fd_in == -1 && errno != ENOENT) {
		subswrite_set_syscall_error(list, "open()", path);
		(void)file_dotlock_delete(&dotlock);
		return -1;
	}

	input = fd_in == -1 ? NULL :
		i_stream_create_fd(fd_in, list->mailbox_name_max_length+1,
				   TRUE);
	output = o_stream_create_fd_file(fd_out, 0, FALSE);
	o_stream_cork(output);
	found = FALSE;
	while ((line = next_line(list, path, input,
				 &failed, FALSE)) != NULL) {
		if (strcmp(line, name) == 0) {
			found = TRUE;
			if (!set) {
				changed = TRUE;
				continue;
			}
		}

		(void)o_stream_send_str(output, line);
		(void)o_stream_send(output, "\n", 1);
	}

	if (!failed && set && !found) {
		/* append subscription */
		line = t_strconcat(name, "\n", NULL);
		(void)o_stream_send_str(output, line);
		changed = TRUE;
	}

	if (changed && !failed) {
		if (o_stream_flush(output) < 0) {
			subswrite_set_syscall_error(list, "write()", path);
			failed = TRUE;
		} else if (mail_set->parsed_fsync_mode != FSYNC_MODE_NEVER) {
			if (fsync(fd_out) < 0) {
				subswrite_set_syscall_error(list, "fsync()",
							    path);
				failed = TRUE;
			}
		}
	}

	if (input != NULL)
		i_stream_destroy(&input);
	o_stream_destroy(&output);

	if (failed || !changed) {
		if (file_dotlock_delete(&dotlock) < 0) {
			subswrite_set_syscall_error(list,
				"file_dotlock_delete()", path);
			failed = TRUE;
		}
	} else {
		enum dotlock_replace_flags flags =
			DOTLOCK_REPLACE_FLAG_VERIFY_OWNER;
		if (file_dotlock_replace(&dotlock, flags) < 0) {
			subswrite_set_syscall_error(list,
				"file_dotlock_replace()", path);
			failed = TRUE;
		}
	}
	return failed ? -1 : (changed ? 1 : 0);
}
static int
mtree_bid(struct archive_read *a, int best_bid)
{
	const char *signature = "#mtree";
	const char *p;
	ssize_t avail, ravail;
	ssize_t len, nl;
	int detected_bytes = 0, entry_cnt = 0, multiline = 0;

	(void)best_bid; /* UNUSED */

	/* Now let's look at the actual header and see if it matches. */
	p = __archive_read_ahead(a, strlen(signature), &avail);
	if (p == NULL)
		return (-1);

	if (memcmp(p, signature, strlen(signature)) == 0)
		return (8 * (int)strlen(signature));

	/*
	 * There is not a mtree signature. Let's try to detect mtree format.
	 */
	ravail = avail;
	for (;;) {
		len = next_line(a, &p, &avail, &ravail, &nl);
		/* The terminal character of the line should be
		 * a new line character, '\r\n' or '\n'. */
		if (len <= 0 || nl == 0)
			break;
		if (!multiline) {
			/* Leading whitespace is never significant,
			 * ignore it. */
			while (len > 0 && (*p == ' ' || *p == '\t')) {
				++p;
				--avail;
				--len;
			}
			/* Skip comment or empty line. */ 
			if (p[0] == '#' || p[0] == '\n' || p[0] == '\r') {
				p += len;
				avail -= len;
				continue;
			}
		} else {
			/* A continuance line; the terminal
			 * character of previous line was '\' character. */
			if (bid_keyword_list(p, len, 0) <= 0)
				break;
			if (multiline == 1)
				detected_bytes += len;
			if (p[len-nl-1] != '\\') {
				if (multiline == 1 &&
				    ++entry_cnt >= MAX_BID_ENTRY)
					break;
				multiline = 0;
			}
			p += len;
			avail -= len;
			continue;
		}
		if (p[0] != '/') {
			if (bid_entry(p, len) >= 0) {
				detected_bytes += len;
				if (p[len-nl-1] == '\\')
					/* This line continues. */
					multiline = 1;
				else {
					/* We've got plenty of correct lines
					 * to assume that this file is a mtree
					 * format. */
					if (++entry_cnt >= MAX_BID_ENTRY)
						break;
				}
			} else
				break;
		} else if (strncmp(p, "/set", 4) == 0) {
			if (bid_keyword_list(p+4, len-4, 0) <= 0)
				break;
			/* This line continues. */
			if (p[len-nl-1] == '\\')
				multiline = 2;
		} else if (strncmp(p, "/unset", 6) == 0) {
			if (bid_keyword_list(p+6, len-6, 1) <= 0)
				break;
			/* This line continues. */
			if (p[len-nl-1] == '\\')
				multiline = 2;
		} else
			break;

		/* Test next line. */
		p += len;
		avail -= len;
	}
	if (entry_cnt >= MAX_BID_ENTRY || (entry_cnt > 0 && len == 0))
		return (32);

	return (0);
}
Ejemplo n.º 3
0
/***************************************************
  next_token.
  
  Get the next word in the corpus.
  
  Try to copy the next word from the line currently held
  in line_buffer to the outbuffer.
  If lin_buffer doesn't have any more words, 
  invoke next_line to replenish it.

  Arguments:	1 outbuffer	the target buffer
				to copy the next word to
		2 curr_pos	the current file location
				in the corpus (will be recorded
				in the wordlist file at
				document breaks)

  Return Values:	-1 if next_line returns -1 
				(i.e., document break)
			 0 if next_line returns 0 
				(i.e., EOF encountered)
			 1 when returning a word.
			 */
int next_token( char *outbuffer, int *curr_pos) {
  int i;
  int in_word = FALSE;
  int my_isalpha( int c) { return valid_chars[c]; };

  while( !in_word) {
    /* Go to the beginning of the next word. */
    while( (buffer_reader[0] != '\0')  &&
	   !(my_isalpha( (int) *buffer_reader))) {

      if( CORPUS_TYPE == ONE_FILE) {

        /* End of a document; return INT_E_DOC_TAG to indicate this. */
        if( !strncmp( buffer_reader, E_DOC_TAG,
		      strlen(E_DOC_TAG))) {
          buffer_reader += strlen( E_DOC_TAG);
          IntIndoc = FALSE;
          return INT_E_DOC_TAG;
        }
        /* End of text */
        if( !strncmp( buffer_reader, E_TEXT_TAG,
		      strlen(E_TEXT_TAG))) {
          buffer_reader += strlen( E_TEXT_TAG);
          IntIntext = FALSE;
          return INT_E_TEXT_TAG;
        }
        /* Beginning of a document; return INT_B_DOC_TAG to indicate this. */
        if( !strncmp( buffer_reader, B_DOC_TAG,
		      strlen(B_DOC_TAG))) {
          buffer_reader += strlen( B_DOC_TAG);
          IntIndoc = TRUE;
          IntDoccntr++;
          return INT_B_DOC_TAG;
        }
        /* Beginning of text */
        if( !strncmp( buffer_reader, B_TEXT_TAG,
		      strlen(B_TEXT_TAG))) {
          buffer_reader += strlen( B_TEXT_TAG);
          IntIntext = TRUE;
          return INT_B_TEXT_TAG;
        }
      }

      buffer_reader++;

    }

    /* Do we have a word? */
    if( IntIntext && my_isalpha( (int) *buffer_reader)) {
      in_word = TRUE;
    }
    
    /* Otherwise we need to read a fresh line. */
    else {
      /* buffer_reader = linebuffer;*/
      if( !next_line( linebuffer, curr_pos))
	return 0;
      buffer_reader = linebuffer;
    }
  }
    
  /* Copy the next word to the return buffer. */
  for( i=0; my_isalpha( (int) *buffer_reader); buffer_reader++) {
    /* Truncate monster words. */
    if( i >= MAXWORDLEN) {
      outbuffer[MAXWORDLEN] = '\0';
      /*fprintf( stderr, "Word near fpos %d exceeding buffer size;"
	       "truncated:\n%s\n",
	       *curr_pos, outbuffer);*/
      return 1;
    }

    /* Copy along. */
    outbuffer[i++] = tolower( *buffer_reader);
    
    /* Use this to keep word-internal apostrophes. */
    if( buffer_reader[1] == '\'' && my_isalpha( (int) buffer_reader[2])) {
      outbuffer[i++] = '\'';
      buffer_reader++;
    }
  } 
  
  outbuffer[i] = '\0';
  return 1;
}
static int
detect_form(struct archive_read *a, int *is_form_d)
{
	const char *p;
	ssize_t avail, ravail;
	ssize_t detected_bytes = 0, len, nl;
	int entry_cnt = 0, multiline = 0;
	int form_D = 0;/* The archive is generated by `NetBSD mtree -D'
			* (In this source we call it `form D') . */

	if (is_form_d != NULL)
		*is_form_d = 0;
	p = __archive_read_ahead(a, 1, &avail);
	if (p == NULL)
		return (-1);
	ravail = avail;
	for (;;) {
		len = next_line(a, &p, &avail, &ravail, &nl);
		/* The terminal character of the line should be
		 * a new line character, '\r\n' or '\n'. */
		if (len <= 0 || nl == 0)
			break;
		if (!multiline) {
			/* Leading whitespace is never significant,
			 * ignore it. */
			while (len > 0 && (*p == ' ' || *p == '\t')) {
				++p;
				--avail;
				--len;
			}
			/* Skip comment or empty line. */ 
			if (p[0] == '#' || p[0] == '\n' || p[0] == '\r') {
				p += len;
				avail -= len;
				continue;
			}
		} else {
			/* A continuance line; the terminal
			 * character of previous line was '\' character. */
			if (bid_keyword_list(p, len, 0, 0) <= 0)
				break;
			if (multiline == 1)
				detected_bytes += len;
			if (p[len-nl-1] != '\\') {
				if (multiline == 1 &&
				    ++entry_cnt >= MAX_BID_ENTRY)
					break;
				multiline = 0;
			}
			p += len;
			avail -= len;
			continue;
		}
		if (p[0] != '/') {
			int last_is_path, keywords;

			keywords = bid_entry(p, len, nl, &last_is_path);
			if (keywords >= 0) {
				detected_bytes += len;
				if (form_D == 0) {
					if (last_is_path)
						form_D = 1;
					else if (keywords > 0)
						/* This line is not `form D'. */
						form_D = -1;
				} else if (form_D == 1) {
					if (!last_is_path && keywords > 0)
						/* This this is not `form D'
						 * and We cannot accept mixed
						 * format. */
						break;
				}
				if (!last_is_path && p[len-nl-1] == '\\')
					/* This line continues. */
					multiline = 1;
				else {
					/* We've got plenty of correct lines
					 * to assume that this file is a mtree
					 * format. */
					if (++entry_cnt >= MAX_BID_ENTRY)
						break;
				}
			} else
				break;
		} else if (strncmp(p, "/set", 4) == 0) {
			if (bid_keyword_list(p+4, len-4, 0, 0) <= 0)
				break;
			/* This line continues. */
			if (p[len-nl-1] == '\\')
				multiline = 2;
		} else if (strncmp(p, "/unset", 6) == 0) {
			if (bid_keyword_list(p+6, len-6, 1, 0) <= 0)
				break;
			/* This line continues. */
			if (p[len-nl-1] == '\\')
				multiline = 2;
		} else
			break;

		/* Test next line. */
		p += len;
		avail -= len;
	}
	if (entry_cnt >= MAX_BID_ENTRY || (entry_cnt > 0 && len == 0)) {
		if (is_form_d != NULL) {
			if (form_D == 1)
				*is_form_d = 1;
		}
		return (32);
	}

	return (0);
}
Ejemplo n.º 5
0
/*
 * Filter an entire file, writing the result to the standard output.
 */
static void
ManFilter(FILE *ifp)
{
	int	c;
	int	level = 0;
	int	ident = CS_NORMAL;
	int	esc_mode = ATR_NORMAL;

	while ((c = fgetc(ifp)) != EOF) {
		switch (c) {
		case '\b':
			backspace();
			break;

		case '\r':
			if (cur_line != 0)
				cur_line->l_this = 0;
			break;

		case '\n':
			next_line();
			cur_line->l_this = 0;
			break;

		case '\t':
			do {
				put_cell(SPACE, level, ident);
			} while (cur_line->l_this & 7);
			break;

		case '\v':
			prev_line();
			break;

		case SHIFT_IN:
			ident = CS_NORMAL;
			break;

		case SHIFT_OUT:
			ident = CS_ALTERNATE;
			break;

		case ESCAPE:
			switch (fgetc(ifp)) {
			case '[':
				esc_mode = ansi_escape(ifp, ident, level);
				break;
			case '\007':
			case '7':
				prev_line();
				break;
			case '\010':
			case '8':
				level = half_up(level);
				break;
			case '\011':
			case '9':
				level = half_down(level);
				break;
			default: /* ignore everything else */
				break;
			}
			break;

		default: /* ignore other nonprinting characters */
			if (isprint(c)) {
				put_cell(c, level, ident);
				if (c != SPACE) {
					if (esc_mode & ATR_BOLD) {
						backspace();
						put_cell(c, level, ident);
					}
					if (esc_mode & ATR_UNDER) {
						backspace();
						put_cell('_', level, ident);
					}
				}
			}
			break;
		}
	}

	while (all_lines != 0)
		flush_line();

	total_lines = 0;
}
Ejemplo n.º 6
0
void
accumulate_bins()
{
  mxtype bins[MAX_BIN+1];
  mxtype s;
  int b; /* bin number */
  int i; /* character number in line */
  int have_number; /* whether we are building a number */

#ifdef DEBUG
#define SHOW_S printf("%d ",s);
#else
#define SHOW_S 
#endif
#define ACCUMULATE do {				\
    SHOW_S have_number = 0;			\
    bins[b++] = s;				\
    total_counts += s;				\
    nnz += (s!=0);				\
  } while (0)

  for (b=0; b < MAX_BIN+1; b++) bins[b] = 0.;

  next_line(line,MAX_LINE);
  have_number = 0; s=0;
  b = i = 0;
  while (1) {
    const char c = line[i];
    // printf("<s=%d c='%c'>",s,c);
    if (isdigit(c)) {
      if (have_number) {
	s = s*10 + c - '0';
      } else {
	have_number = 1;
	s = c - '0';
      }
      // printf("<digit %c s=%d>",c,s);
      i++;
    } else if (c==',' || c==';') {
      assert(have_number == 1);
      ACCUMULATE;
      if (c == ';') {
	save_row(bins, b);
	while (b>0) bins[--b] = 0;
      }
      i++;
    } else if (c=='\n' || c=='\r') {
      next_line(line,MAX_LINE);
      if (have_number) { 
	/* End of frame if line ends in a number without punctuation */
	ACCUMULATE;
	save_row(bins, b);
	return;
      }
      if (gzeof(infile)) return;
      i = 0;
    } else if (c == '\0') {
      /* Maybe line was too long or maybe we are at the end of the file */
      next_line(line,MAX_LINE);
      if (gzeof(infile)) {
	/* If at the end of the file, finish off current frame */
	if (have_number) {
	  ACCUMULATE;
	  save_row(bins,b);
	}
	return;
      }
      i = 0;
    } else if (isspace(c)) {
      /* If at a space between numbers ... must in be a new point */
      /* Note that we don't save it, since the end of */
      /* the matrix was already saved by the '\n'.  The only */
      /* way we can get here is if we have an empty frame. */ 
      i++;
      if (have_number) {
#ifdef DEBUG
	printf("empty frame triggered by consecutive numbers with no separator\n");
#endif
	return;
      }
    } else {
      /* Some kind of floating point character ... must be a new point */
#ifdef DEBUG
      printf("empty frame triggered by character which is not digit, space or separator\n");
#endif
      return;
    }
  }
}
Ejemplo n.º 7
0
// Support for iteratively locating the offsets of history items
// Pass the address and length of a mapped region.
// Pass a pointer to a cursor size_t, initially 0
// If custoff_timestamp is nonzero, skip items created at or after that timestamp
// Returns (size_t)(-1) when done
static size_t offset_of_next_item_fish_2_0(const char *begin, size_t mmap_length, size_t *inout_cursor, time_t cutoff_timestamp)
{
    size_t cursor = *inout_cursor;
    size_t result = (size_t)(-1);
    while (cursor < mmap_length) {
        const char * const line_start = begin + cursor;
        
        /* Advance the cursor to the next line */
        const char *newline = (const char *)memchr(line_start, '\n', mmap_length - cursor);
        if (newline == NULL)
            break;
        
        /* Advance the cursor past this line. +1 is for the newline */
        size_t line_len = newline - line_start;
        cursor += line_len + 1;

        /* Skip lines with a leading space, since these are in the interior of one of our items */
        if (line_start[0] == ' ')
            continue;
        
        /* Skip very short lines to make one of the checks below easier */
        if (line_len < 3)
            continue;
        
        /* Try to be a little YAML compatible. Skip lines with leading %, ---, or ... */
        if (! memcmp(line_start, "%", 1) ||
            ! memcmp(line_start, "---", 3) ||
            ! memcmp(line_start, "...", 3))
            continue;

        /* At this point, we know line_start is at the beginning of an item. But maybe we want to skip this item because of timestamps. A 0 cutoff means we don't care; if we do care, then try parsing out a timestamp. */
        if (cutoff_timestamp != 0) {
            /* Hackish fast way to skip items created after our timestamp. This is the mechanism by which we avoid "seeing" commands from other sessions that started after we started. We try hard to ensure that our items are sorted by their timestamps, so in theory we could just break, but I don't think that works well if (for example) the clock changes. So we'll read all subsequent items.
             */
            const char * const end = begin + mmap_length;
            
            /* Walk over lines that we think are interior. These lines are not null terminated, but are guaranteed to contain a newline. */
            bool has_timestamp = false;
            time_t timestamp;
            const char *interior_line;
            for (interior_line = next_line(line_start, end - line_start);
                 interior_line != NULL && ! has_timestamp;
                 interior_line = next_line(interior_line, end - interior_line)) {
                 
                /* If the first character is not a space, it's not an interior line, so we're done */
                if (interior_line[0] != ' ')
                    break;
                    
                /* Hackish optimization: since we just stepped over some interior line, update the cursor so we don't have to look at these lines next time */
                cursor = interior_line - begin;
                
                /* Try parsing a timestamp from this line. If we succeed, the loop will break. */
                has_timestamp = parse_timestamp(interior_line, &timestamp);
            }
                 
            /* Skip this item if the timestamp is at or after our cutoff. */
            if (has_timestamp && timestamp >= cutoff_timestamp) {
                continue;
            }
        }

        /* We made it through the gauntlet. */
        result = line_start - begin;
        break;
    }
    *inout_cursor = cursor;
    return result;
}
Ejemplo n.º 8
0
std::string
POParser::get_string(unsigned int skip)
{
    std::ostringstream out;

    if (skip+1 >= static_cast<unsigned int>(current_line.size()))
        error("unexpected end of line");

    if (current_line[skip] == ' ' && current_line[skip+1] == '"')
    {
        get_string_line(out, skip+1);
    }
    else
    {
        if (pedantic)
            warning("keyword and string must be seperated by a single space");

        for(;;)
        {
            if (skip >= static_cast<unsigned int>(current_line.size()))
                error("unexpected end of line");
            else if (current_line[skip] == '\"')
            {
                get_string_line(out, skip);
                break;
            }
            else if (!isspace(current_line[skip]))
            {
                error("string must start with '\"'");
            }
            else
            {
                // skip space
            }

            skip += 1;
        }
    }

next:
    next_line();
    for(std::string::size_type i = 0; i < current_line.size(); ++i)
    {
        if (current_line[i] == '"')
        {
            if (i == 1)
                if (pedantic)
                    warning("leading whitespace before string");

            get_string_line(out, i);
            goto next;
        }
        else if (isspace(current_line[i]))
        {
            // skip
        }
        else
        {
            break;
        }
    }

    return out.str();
}
Ejemplo n.º 9
0
static void
parse_character(char c)
{
	switch (sScreen.state) {
		case CONSOLE_STATE_NORMAL:
			// just output the stuff
			switch (c) {
				case '\n':
					next_line();
					break;
				case 0x8:
					back_space();
					break;
				case '\t':
					// TODO: real tab...
					sScreen.x = (sScreen.x + 8) & ~7;
					if (sScreen.x >= sScreen.columns)
						next_line();
					break;

				case '\r':
				case '\0':
				case '\a': // beep
					break;

				case 0x1b:
					// escape character
					sScreen.arg_count = 0;
					sScreen.state = CONSOLE_STATE_GOT_ESCAPE;
					break;
				default:
					put_character(c);
			}
			break;
		case CONSOLE_STATE_GOT_ESCAPE:
			// look for either commands with no argument, or the '[' character
			switch (c) {
				case '[':
					sScreen.state = CONSOLE_STATE_SEEN_BRACKET;
					break;
				default:
					sScreen.args[0] = 0;
					process_vt100_command(c, false, sScreen.args, 0);
					sScreen.state = CONSOLE_STATE_NORMAL;
			}
			break;
		case CONSOLE_STATE_SEEN_BRACKET:
			switch (c) {
				case '0'...'9':
					sScreen.arg_count = 0;
					sScreen.args[0] = c - '0';
					sScreen.state = CONSOLE_STATE_PARSING_ARG;
					break;
				case '?':
					// private DEC mode parameter follows - we ignore those
					// anyway
					break;
				default:
					process_vt100_command(c, true, sScreen.args, 0);
					sScreen.state = CONSOLE_STATE_NORMAL;
					break;
			}
			break;
		case CONSOLE_STATE_NEW_ARG:
			switch (c) {
				case '0'...'9':
					if (++sScreen.arg_count == MAX_ARGS) {
						sScreen.state = CONSOLE_STATE_NORMAL;
						break;
					}
					sScreen.args[sScreen.arg_count] = c - '0';
					sScreen.state = CONSOLE_STATE_PARSING_ARG;
					break;
				default:
					process_vt100_command(c, true, sScreen.args,
						sScreen.arg_count + 1);
					sScreen.state = CONSOLE_STATE_NORMAL;
					break;
			}
			break;
		case CONSOLE_STATE_PARSING_ARG:
			// parse args
			switch (c) {
				case '0'...'9':
					sScreen.args[sScreen.arg_count] *= 10;
					sScreen.args[sScreen.arg_count] += c - '0';
					break;
				case ';':
					sScreen.state = CONSOLE_STATE_NEW_ARG;
					break;
				default:
					process_vt100_command(c, true, sScreen.args,
						sScreen.arg_count + 1);
					sScreen.state = CONSOLE_STATE_NORMAL;
					break;
			}
	}
}
Ejemplo n.º 10
0
static void parserobotstxt(char *robots_buffer, int buflen, httpserverinfo *server)
{
    char *buffer;
    char *bufend = robots_buffer + buflen -1;  // last char of string
    char *next_start = robots_buffer;
    
    enum {START, USERAGENT, DISALLOW} state = START;
    enum {SPECIFIC, GENERIC, SKIPPING} useragentstate = SKIPPING;
    char *p;
    int len;
    robotrules *entry;
    robotrules *entry2;
	
    server->useragent = 0;

    buffer = NULL;

    while ( (buffer = next_line( &next_start, bufend ) ) )
    {
        if ( strchr( buffer, '#' ) )
            *(strchr( buffer, '#' )) = '\0';

		if ((*buffer == '#') || (*buffer == '\0'))
			continue;

		
		if (strncasecmp(buffer, useragent, sizeof(useragent) - 1) == 0) {
			switch (state) {
			case DISALLOW:
			/* Since we found our specific user-agent, we can
			** skip the rest of the file.
				**/
				if (useragentstate == SPECIFIC) {
					return;
				}
				
				useragentstate = SKIPPING;
				
				/* explict fallthrough */
				
			case START:
			case USERAGENT:
				state = USERAGENT;
				
				if (useragentstate != SPECIFIC) {
					p = isolatevalue(buffer, useragent, &len);
					
					if ((len == (sizeof(swishspider) - 1)) &&
						(strncasecmp(p, swishspider, sizeof(swishspider) - 1) == 0) ) {
						useragentstate = SPECIFIC;
						
						/* We might have already parsed generic rules,
						** so clean them up if necessary.
						*/
						if (server->useragent) {
							efree(server->useragent);
						}
						for (entry = server->robotrules; entry; ) {
							entry2 = entry->next;
							efree(entry);
							entry = entry2;
						}
						server->robotrules = 0;
						
						server->useragent = (char *)emalloc(len + 1);
						strncpy(server->useragent, p, len);
						*(server->useragent + len) = '\0';
						
					}
					else if ((len == 1) && (*p == '*')) {
						useragentstate = GENERIC;
						server->useragent = (char *)emalloc(2);
						strcpy(server->useragent, "*"); /* emalloc'd 2 bytes, no safestrcpy */
					}
					
				}
				
				
				break;
				
			}
		}
		
		if (strncasecmp(buffer, disallow, sizeof(disallow) - 1) == 0) {
			state = DISALLOW;
			if (useragentstate != SKIPPING) {
				p = isolatevalue(buffer, disallow, &len);
				if (len) {
					entry = (robotrules *)emalloc(sizeof(robotrules));
					entry->next = server->robotrules;
					server->robotrules = entry;
					entry->disallow = (char *)emalloc(len + 1);
					strncpy(entry->disallow, p, len);
					*(entry->disallow + len) = '\0';
				}
			}
		}
    }
}
Ejemplo n.º 11
0
static Token next_token (void)
{
  Token token;
 restart:
  outbuffer_off();
  outbuffer_on();
  token.startindex = out.buffindex;
  {
    int c = next_char();
    switch (c) {
      case EOF:
        /* EOF */
        token.type = eof;
        goto done;
      case ' ': case '\v': case '\t': case '\n':
        /* whitespace, ignore */
        goto restart;
      case '\\':
        if (peek_char()=='\n') {
          /* backslash newline, ignore */
          next_char();
          goto restart;
        }
        goto separator;
      case '/':
        if (peek_char() == '*') {
          /* Comment */
          next_char();
          while (1) {
            c = next_char();
            if (c==EOF) {
              fprintf(stderr,"Unfinished comment\n");
              break;
            }
            if ((c=='*') && (peek_char()=='/')) {
              next_char();
              break;
            }
          }
          goto restart;
        }
        goto separator;
      case '*':
        if (peek_char() == '/')
          fprintf(stderr,"End of comment outside comment in line %lu\n",input_line);
        goto separator;
      case '#':
        /* preprocessor directive */
        {
          char* line = next_line();
          if (line) {
            char* old_line = line;
            line = concat2("#",line);
            xfree(old_line);
          } else
            line = concat1("#");
          while (line[strlen(line)-1] == '\\') {
            char* continuation_line = next_line();
            line[strlen(line)-1] = '\0';
            if (continuation_line) {
              char* old_line = line;
              line = concat2(line,continuation_line);
              xfree(old_line);
              xfree(continuation_line);
            }
          }
          {
            const char* condition;
            long line_directive;
            if ((condition = is_if(line)) != NULL) {
              do_if(condition);
            } else if (is_else(line)) {
              do_else();
              line_repeat_else();
            } else if ((condition = is_elif(line)) != NULL) {
              do_elif(condition);
              line_repeat_else();
            } else if (is_endif(line)) {
              do_endif();
              line_repeat_endif();
            } else if ((line_directive = decode_line_directive(line)) >= 0)
              input_line = line_directive;
#ifdef SPLIT_OBJECT_INITIALIZATIONS
            else {
              /* Replace "var object foo = ..." with "var object foo; foo = ..."
               in macros as well. */
              if (out.buffindex < MAXHEADERLEN) {
                uintB* p;
                out.buffer[out.buffindex] = '\0';
                for (p = &out.buffer[token.startindex]; ; p++) {
                  p = (uintB*) strstr((char*)p,"var ");
                  if (p == NULL)
                    break;
                  if ((strncmp((char*)p,"var object ",
                               strlen("var object "))==0
                       || strncmp((char*)p,"var chart ",
                                  strlen("var chart "))==0)
                      && (p[-1] == ' ' || p[-1] == '{')) {
                    if (strncmp((char*)p,"var object ",
                                strlen("var object "))==0)
                      p += strlen("var object ");
                    else if (strncmp((char*)p,"var chart ",
                                     strlen("var chart "))==0)
                      p += strlen("var chart ");
                    { uintB* q = p;
                      if ((*q >= 'A' && *q <= 'Z')
                          || (*q >= 'a' && *q <= 'z')
                          || *q == '_') {
                        do q++;
                        while ((*q >= 'A' && *q <= 'Z')
                               || (*q >= 'a' && *q <= 'z')
                               || (*q >= '0' && *q <= '9')
                               || *q == '_');
                        while (*q == ' ')
                          q++;
                        if (*q == '=') {
                          uintL insertlen = 2+(q-p);
                          if (out.buffindex + insertlen < MAXHEADERLEN) {
                            memmove(q+insertlen,q,
                                    &out.buffer[out.buffindex]-q+1);
                            q[0] = ';'; q[1] = ' ';
                            memcpy(q+2, p, q-p);
                            out.buffindex += insertlen;
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
#endif
          }
          xfree(line);
        }
        goto separator;
      case '.':
        c = peek_char();
        if (!(((c>='0') && (c<='9')) || (c=='.')))
          goto separator;
      case '0': case '1': case '2': case '3': case '4':
      case '5': case '6': case '7': case '8': case '9':
        /* Digit. Continue reading as long as alphanumeric or '.'. */
        while (1) {
          c = peek_char();
          if (((c>='0') && (c<='9')) || ((c>='A') && (c<='Z')) || ((c>='a') && (c<='z')) || (c=='.'))
            next_char();
          else
            break;
        }
        token.type = number;
        goto done;
      case '\'':
        /* Character constant */
        while (1) {
          c = next_char();
          if (c==EOF) {
            fprintf(stderr,"Unterminated character constant\n");
            break;
          }
          if (c=='\'')
            break;
          if (c=='\\')
            c = next_char();
        }
        token.type = charconst;
        goto done;
      case '\"':
        /* String constant */
        while (1) {
          c = next_char();
          if (c==EOF) {
            fprintf(stderr,"Unterminated string constant\n");
            break;
          }
          if (c=='\"')
            break;
          if (c=='\\')
            c = next_char();
        }
        token.type = stringconst;
        goto done;
      case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
      case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
      case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
      case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
      case 'Y': case 'Z':
      case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
      case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
      case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
      case 's': case 't': case 'u': case 'v': case 'w': case 'x':
      case 'y': case 'z':
      case '_':
        /* Identifier. */
        while (1) {
          c = peek_char();
          if (((c>='0') && (c<='9')) || ((c>='A') && (c<='Z')) || ((c>='a') && (c<='z')) || (c=='_'))
            next_char();
          else
            break;
        }
        token.type = ident;
        goto done;
      default:
      separator:
        token.type = sep;
        token.ch = c;
        goto done;
    }
  }
 done:
  token.endindex = out.buffindex;
  return token;
}
Ejemplo n.º 12
0
//////////////////////////////////////////////////////////////////////////////
///  private normal_input
///  Handles most of the input stuff for GTerm
///
///  @return void
///
///  @author Timothy Miller @date 04-22-2004
//////////////////////////////////////////////////////////////////////////////
void GTerm::normal_input()
{
    int n, n_taken, i, c, y;

#if 0

    char str[100];

#endif

    if (* input_data<32)
        return;

    if (cursor_x>=width)
    {
        if (mode_flags & NOEOLWRAP)
        {
            cursor_x = width - 1;
        }
        else
        {
            next_line();
        }
    }

    n = 0;

    if (mode_flags & NOEOLWRAP)
    {
        while (input_data[n]>31 && n<data_len)
            n++;

        n_taken = n;

        if (cursor_x + n>=width)
            n = width - cursor_x;
    }
    else
    {
        while (input_data[n]>31 && n<data_len && cursor_x + n<width)
            n++;

        n_taken = n;
    }

#if 0

    memcpy(str, input_data, n);
    str[n] = 0;
    //printf("Processing %d characters (%d): %s\n", n, str[0], str);

#endif

    if (mode_flags & INSERT)
    {
        changed_line(cursor_y, cursor_x, width - 1);
    }
    else
    {
        changed_line(cursor_y, cursor_x, cursor_x + n - 1);
    }

	// IMPORTANT Here's where the text pointer gets assigned.
    y = linenumbers[cursor_y] * MAXWIDTH;

	int altY = m_nextLineCounter * MAXWIDTH;

	// MPE: moves the text after the cursor to the right N spaces (inserting)
    if (mode_flags & INSERT)
        for (i = width - 1; i>=cursor_x + n; i--)
        {
            //text[y + i] = text[y + i - n];

			char c = tm.GetCharAdjusted(cursor_y, i - n);
			tm.SetCharAdjusted(cursor_y, i, c);

            //color[y + i] = color[y + i - n];

			unsigned short tempcolor = tm.GetColorAdjusted(cursor_y, i - n);
			tm.SetColorAdjusted(cursor_y, i, tempcolor);
        }

    c = calc_color(fg_color, bg_color, mode_flags);

	// MPE: inserts the new received text, overwriting what was there already
    for (i = 0; i<n; i++)
    {
        //text[y + cursor_x] = input_data[i];
		tm.SetCharAdjusted(cursor_y, cursor_x, input_data[i]);

        //color[y + cursor_x] = c;
		tm.SetColorAdjusted(cursor_y, cursor_x, c);
        cursor_x++;
    }

    input_data += n_taken - 1;
    data_len -= n_taken - 1;
}
Ejemplo n.º 13
0
int rl_bdffont_create_filter( rl_bdffont_t* bdffont, const char* path, rl_bdffont_filter_t filter, void* userdata )
{
  rl_bdffontchar_t* chr = NULL;
  size_t length;
  uint32_t hash;
  uint8_t* bits;
  int num_chars = 0, add = 0;
  int dwx0 = 0, dwy0 = 0;
  /*int dwx1, dwy1;*/
  int bbw = 0, bbh = 0, bbxoff0x = 0, bbyoff0y = 0;
  int i, j, chr_bbh = 0;
  char line[ MAXLEN ];

  PHYSFS_File* file = PHYSFS_openRead( path );

  if ( file == NULL )
  {
    return -1;
  }

  PHYSFS_sint64 bytes = PHYSFS_fileLength( file );

  if ( bytes == -1 )
  {
    PHYSFS_close( file );
    return -1;
  }

  int len = 0;
  const char* source = next_line( line, &len, file );

  for ( ;; )
  {
    /* Find end of keyword. */
    if ( strspn( source, ALPHA ) == 0 ) goto error;

    length = strspn( source, ALNUM );
    hash = djb2_length( source, length );
    source += length;

    switch ( hash )
    {
    /* Starts a font. */
    case STARTFONT:
      if ( readint( &source, &i ) != 0 ) goto error;
      if ( *source++ != '.' ) goto error;
      if ( readint( &source, &j ) != 0 ) goto error;

      /* Issue an error on versions higher than 2.2. */
      if ( i > 2 || ( i == 2 && j > 2 ) ) goto error;

      source = next_line( line, &len, file );
      break;

    /* The FONTBOUNDINGBOX values seems to be defaults for BBX values. */
    case FONTBOUNDINGBOX:
      if ( readint4( &source, &bbw, &bbh, &bbxoff0x, &bbyoff0y ) != 0 ) goto error;

      source = next_line( line, &len, file );
      break;

    case METRICSSET:
      if ( readint( &source, &bdffont->metrics_set) != 0 ) goto error;

      /* We only handle horizontal writing by now. */
      if ( bdffont->metrics_set != 0 ) goto error;

      source = next_line( line, &len, file );
      break;

    /* This is the character's width in pixels. */
    case DWIDTH:
      if ( readint2( &source, &i, &j ) != 0 ) goto error;

      if ( chr != NULL )
      {
        if ( add )
        {
          chr->dwx0 = i; chr->dwy0 = j;
        }
      }
      else
      {
        dwx0 = i; dwy0 = j;
      }

      source = next_line( line, &len, file );
      break;

    case CHARS:
      /* Read the number of chars in this font and malloc the required memory. */
      if ( readint( &source, &bdffont->num_chars) != 0 ) goto error;

      bdffont->chars = (rl_bdffontchar_t*)calloc( bdffont->num_chars, sizeof( rl_bdffontchar_t ) );

      if ( bdffont->chars == NULL ) goto error;

      source = next_line( line, &len, file );
      break;

    case STARTCHAR:
      /* If chr is not NULL the last character was not properly ended. */
      if ( chr != NULL ) goto error;

      /* Bounds check. */
      if ( num_chars == bdffont->num_chars ) goto error;

      chr = bdffont->chars + num_chars;

      /* Copy default values. */
      chr->code = -1;
      chr->dwx0 = dwx0;
      chr->dwy0 = dwy0;
      /*chr->dwx1 = dwx1;*/
      /*chr->dwy1 = dwy1;*/
      chr->bbw = bbw;
      chr->bbh = bbh;
      chr->bbxoff0x = bbxoff0x;
      chr->bbyoff0y = bbyoff0y;

      source = next_line( line, &len, file );
      break;

    case ENCODING:
      /* If chr is NULL the character was not properly started. */
      if ( chr == NULL ) goto error;

      /* Read character's code, it can be -1. */
      if ( readint( &source, &i ) != 0 ) goto error;

      /* If the encoding is -1, try to read another integer. */
      if ( i == -1 )
      {
        if ( readint( &source, &j ) != 0 )
        {
          j = -1;
        }
      }
      else
      {
        j = -1;
      }

      add = filter( i, j, userdata );

      if ( add != -1 )
      {
        chr->code = add;
        num_chars++;
        add = 1;
      }
      else
      {
        add = 0;
      }

      source = next_line( line, &len, file );
      break;

    /* The bounding box around the character's black pixels. */
    case BBX:
      /* If chr is NULL the character was not properly started. */
      if ( chr == NULL ) goto error;

      /* Only process the character if it was not filtered out. */
      if ( add )
      {
        if ( readint4( &source, &chr->bbw, &chr->bbh, &chr->bbxoff0x, &chr->bbyoff0y ) != 0 ) goto error;
      }
      else
      {
        /* Save the character's bbh so we can skip the BITMAP section later. */
        if ( readint4( &source, &i, &chr_bbh, &i, &i ) != 0 ) goto error;
      }

      source = next_line( line, &len, file );
      break;

    /* BITMAP signals the start of the hex data. */
    case BITMAP:
      /* If chr is NULL the character was not properly started. */
      if ( chr == NULL ) goto error;

      source = next_line( line, &len, file );

      /* Only process the character if it was not filtered out. */
      if ( add )
      {
        /* wbytes is the width of the char in bytes. */
        chr->wbytes = (chr->bbw + 7) / 8;

        /* Malloc the memory for the pixels. */
        chr->bits = bits = (uint8_t*)malloc( chr->wbytes * chr->bbh );

        if ( bits == NULL ) goto error;

        /* Read all pixels from file. */
        for ( i = chr->bbh; i != 0; i-- )
        {
          length = strspn( source, HEXDG );

          if ( length != chr->wbytes * 2 ) goto error;

          while ( length != 0 )
          {
            *bits++ = XVAL( source[ 0 ] ) * 16 + XVAL( source[ 1 ] );
            source += 2;
            length -= 2;
          }

          source = next_line( line, &len, file );
        }
      }
      else
      {
        /* Skip the bitmap. */
        for ( i = chr_bbh; i != 0; i-- )
        {
          source = next_line( line, &len, file );
        }
      }

      break;

    case ENDCHAR:
      /* If chr is NULL the character was not properly started. */
      if ( chr == NULL ) goto error;

      chr = NULL;
      source = next_line( line, &len, file );
      break;

    case ENDFONT:
      /* If chr is not NULL the last character was not properly ended. */
      if ( chr != NULL ) goto error;

      if ( num_chars < bdffont->num_chars )
      {
        bdffont->chars = realloc( bdffont->chars, num_chars * sizeof( rl_bdffontchar_t ) );
        bdffont->num_chars = num_chars;
      }

      /* Sort font by character codes (TODO: should be an hash table). */
      qsort( bdffont->chars, bdffont->num_chars, sizeof( rl_bdffontchar_t ), compare );
      PHYSFS_close( file );
      return 0;
    
    default:
      /* Unknown section, skip. */
      source = next_line( line, &len, file );
      break;
    }
  }

  error:
  /* Free everything. */
  rl_bdffont_destroy( bdffont );
  PHYSFS_close( file );
  return -1;
}
Ejemplo n.º 14
0
void create_network(NETWORK *network)
{
  int i;
  int length;
  char *ptr;
  char *start,*stop;
  char line[LINELENGTH];
  char label[LINELENGTH];

  // Determine whether the network is directed

  network->directed = is_directed();

  // Count the vertices

  network->nvertices = count_vertices();

  // Make space for the vertices

  network->vertex = calloc(network->nvertices,sizeof(VERTEX));

  // Go through the file reading the details of each vertex one by one

  reset_buffer();
  for (i=0; i<network->nvertices; i++) {

    // Skip to next "node" entry

    do {
      next_line(line);
    } while (strstr(line,"node")==NULL);

    // Read in the details of this vertex

    do {

      // Look for ID

      ptr = strstr(line,"id");
      if (ptr!=NULL) sscanf(ptr,"id %i",&network->vertex[i].id);

      // Look for label

      ptr = (strstr(line,"label"));
      if (ptr!=NULL) {
	start = strchr(line,'"');
	if (start==NULL) {
	  sscanf(ptr,"label %s",&label);
	} else {
	  stop = strchr(++start,'"');
	  if (stop==NULL) length = strlen(line) - (start-line);
	  else length = stop - start;
	  strncpy(label,start,length);
	  label[length] = '\0';
	  network->vertex[i].label = malloc((length+1)*sizeof(char));
	  strcpy(network->vertex[i].label,label);
	}
      }

      // If we see a closing square bracket we are done

      if (strstr(line,"]")!=NULL) break;

    } while (next_line(line)==0);

  }

  // Sort the vertices in increasing order of their IDs so we can find them
  // quickly later

  qsort(network->vertex,network->nvertices,sizeof(VERTEX),(void*)cmpid);
}
Ejemplo n.º 15
0
Archivo: io.c Proyecto: goshng/psi
void pass_lines (int n, FILE *fp) {
  next_line (n, fp);
}
Ejemplo n.º 16
0
void read_edges(NETWORK *network)
{
  int i;
  int s,t;
  int vs,vt;
  int *count;
  double w;
  char *ptr;
  char line[LINELENGTH];

  // Malloc space for the edges and temporary space for the edge counts
  // at each vertex

  for (i=0; i<network->nvertices; i++) {
    network->vertex[i].edge = malloc(network->vertex[i].degree*sizeof(EDGE));
  }
  count = calloc(network->nvertices,sizeof(int));

  // Read in the data

  reset_buffer();

  while (next_line(line)==0) {

    // Find the next edge entry

    ptr = strstr(line,"edge");
    if (ptr==NULL) continue;

    // Read the source and target of the edge and the edge weight

    s = t = -1;
    w = 1.0;

    do {

      ptr = strstr(line,"source");
      if (ptr!=NULL) sscanf(ptr,"source %i",&s);
      ptr = strstr(line,"target");
      if (ptr!=NULL) sscanf(ptr,"target %i",&t);
      ptr = strstr(line,"value");
      if (ptr!=NULL) sscanf(ptr,"value %lf",&w);

      // If we see a closing square bracket we are done

      if (strstr(line,"]")!=NULL) break;

    } while (next_line(line)==0);

    // Add these edges to the appropriate vertices

    if ((s>=0)&&(t>=0)) {
      vs = find_vertex(s,network);
      vt = find_vertex(t,network);
      network->vertex[vs].edge[count[vs]].target = vt;
      network->vertex[vs].edge[count[vs]].weight = w;
      count[vs]++;
      if (network->directed==0) {
	network->vertex[vt].edge[count[vt]].target = vs;
	network->vertex[vt].edge[count[vt]].weight = w;
	count[vt]++;
      }
    }

  }

  free(count);
  return;
}
Ejemplo n.º 17
0
Archivo: io.c Proyecto: goshng/psi
void locate_m1_block1 ( FILE *fp, int sample_size ) {
  int upto = (sample_size + 1) * 3 + 1;
  next_line (upto, fp);
}
Ejemplo n.º 18
0
void
POParser::parse()
{
    next_line();

    // skip UTF-8 intro that some text editors produce
    // see http://en.wikipedia.org/wiki/Byte-order_mark
    if (current_line.size() >= 3 &&
            current_line[0] == '\xef' &&
            current_line[1] == '\xbb' &&
            current_line[2] == '\xbf')
    {
        current_line = current_line.substr(3);
    }

    // Parser structure
    while(!eof)
    {
        try
        {
            bool fuzzy =  false;
            bool has_msgctxt = false;
            std::string msgctxt;
            std::string msgid;

            while(prefix("#"))
            {
                if (current_line.size() >= 2 && current_line[1] == ',')
                {
                    // FIXME: Rather simplistic hunt for fuzzy flag
                    if (current_line.find("fuzzy", 2) != std::string::npos)
                        fuzzy = true;
                }

                next_line();
            }

            if (!is_empty_line())
            {
                if (prefix("msgctxt"))
                {
                    has_msgctxt = true;
                    msgctxt = get_string(7);
                }

                if (prefix("msgid"))
                    msgid = get_string(5);
                else
                    error("expected 'msgid'");

                if (prefix("msgid_plural"))
                {
                    std::string msgid_plural = get_string(12);
                    std::vector<std::string> msgstr_num;
                    bool saw_nonempty_msgstr = false;

next:
                    if (is_empty_line())
                    {
                        if (msgstr_num.empty())
                            error("expected 'msgstr[N] (0 <= N <= 9)'");
                    }
                    else if (prefix("msgstr[") &&
                             current_line.size() > 8 &&
                             isdigit(current_line[7]) && current_line[8] == ']')
                    {
                        unsigned int number = static_cast<unsigned int>(current_line[7] - '0');
                        std::string msgstr = get_string(9);

                        if(!msgstr.empty())
                            saw_nonempty_msgstr = true;

                        if (number >= msgstr_num.size())
                            msgstr_num.resize(number+1);

                        msgstr_num[number] = conv.convert(msgstr);
                        goto next;
                    }
                    else
                    {
                        error("expected 'msgstr[N]'");
                    }

                    if (!is_empty_line())
                        error("expected 'msgstr[N]' or empty line");

                    if (saw_nonempty_msgstr)
                    {
                        if (use_fuzzy || !fuzzy)
                        {
                            if (!dict.get_plural_forms())
                            {
                                warning("msgstr[N] seen, but no Plural-Forms given");
                            }
                            else
                            {
                                if (msgstr_num.size() != dict.get_plural_forms().get_nplural())
                                {
                                    warning("msgstr[N] count doesn't match Plural-Forms.nplural");
                                }
                            }

                            if (has_msgctxt)
                                dict.add_translation(msgctxt, msgid, msgid_plural, msgstr_num);
                            else
                                dict.add_translation(msgid, msgid_plural, msgstr_num);
                        }

                        if (0)
                        {
                            std::cout << (fuzzy?"fuzzy":"not-fuzzy") << std::endl;
                            std::cout << "msgid \"" << msgid << "\"" << std::endl;
                            std::cout << "msgid_plural \"" << msgid_plural << "\"" << std::endl;
                            for(std::vector<std::string>::size_type i = 0; i < msgstr_num.size(); ++i)
                                std::cout << "msgstr[" << i << "] \"" << conv.convert(msgstr_num[i]) << "\"" << std::endl;
                            std::cout << std::endl;
                        }
                    }
                }
                else if (prefix("msgstr"))
                {
                    std::string msgstr = get_string(6);

                    if (msgid.empty())
                    {
                        parse_header(msgstr);
                    }
                    else if(!msgstr.empty())
                    {
                        if (use_fuzzy || !fuzzy)
                        {
                            if (has_msgctxt)
                                dict.add_translation(msgctxt, msgid, conv.convert(msgstr));
                            else
                                dict.add_translation(msgid, conv.convert(msgstr));
                        }

                        if (0)
                        {
                            std::cout << (fuzzy?"fuzzy":"not-fuzzy") << std::endl;
                            std::cout << "msgid \"" << msgid << "\"" << std::endl;
                            std::cout << "msgstr \"" << conv.convert(msgstr) << "\"" << std::endl;
                            std::cout << std::endl;
                        }
                    }
                }
                else
                {
                    error("expected 'msgstr' or 'msgid_plural'");
                }
            }

            if (!is_empty_line())
                error("expected empty line");

            next_line();
        }
        catch(POParserError&)
        {
        }
    }
}
Ejemplo n.º 19
0
Archivo: io.c Proyecto: goshng/psi
void locate_m4_block1_e2 ( FILE *fp, int sample_size ) {
  int upto = (sample_size + 1) * 1 + 1;
  next_line (upto, fp);
}
Ejemplo n.º 20
0
/***********************************************************************
 *            WriteConsoleW   (KERNEL32.@)
 */
BOOL WINAPI WriteConsoleW(HANDLE hConsoleOutput, LPCVOID lpBuffer, DWORD nNumberOfCharsToWrite,
			  LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved)
{
    DWORD			mode;
    DWORD			nw = 0;
    WCHAR*			psz = (WCHAR*)lpBuffer;
    CONSOLE_SCREEN_BUFFER_INFO	csbi;
    int				k, first = 0;

    TRACE("%d %s %ld %p %p\n",
	  hConsoleOutput, debugstr_wn(lpBuffer, nNumberOfCharsToWrite),
	  nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);

    if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = 0;

    if (!GetConsoleMode(hConsoleOutput, &mode) ||
	!GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
	return FALSE;

    if (mode & ENABLE_PROCESSED_OUTPUT)
    {
	int	i;

	for (i = 0; i < nNumberOfCharsToWrite; i++)
	{
	    switch (psz[i])
	    {
	    case '\b': case '\t': case '\n': case '\a': case '\r':
		/* don't handle here the i-th char... done below */
		if ((k = i - first) > 0)
		{
		    if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
			goto the_end;
		    nw += k;
		}
		first = i + 1;
		nw++;
	    }
	    switch (psz[i])
	    {
	    case '\b':
		if (csbi.dwCursorPosition.X > 0) csbi.dwCursorPosition.X--;
		break;
	    case '\t':
	        {
		    WCHAR tmp[8] = {' ',' ',' ',' ',' ',' ',' ',' '};

		    if (!write_block(hConsoleOutput, &csbi, mode, tmp,
				     ((csbi.dwCursorPosition.X + 8) & ~7) - csbi.dwCursorPosition.X))
			goto the_end;
		}
		break;
	    case '\n':
		next_line(hConsoleOutput, &csbi);
		break;
 	    case '\a':
		Beep(400, 300);
 		break;
	    case '\r':
		csbi.dwCursorPosition.X = 0;
		break;
	    default:
		break;
	    }
	}
    }

    /* write the remaining block (if any) if processed output is enabled, or the
     * entire buffer otherwise
     */
    if ((k = nNumberOfCharsToWrite - first) > 0)
    {
	if (!write_block(hConsoleOutput, &csbi, mode, &psz[first], k))
	    goto the_end;
	nw += k;
    }

 the_end:
    SetConsoleCursorPosition(hConsoleOutput, csbi.dwCursorPosition);
    if (lpNumberOfCharsWritten) *lpNumberOfCharsWritten = nw;
    return nw != 0;
}
Ejemplo n.º 21
0
void while_stm(FILE *fp) {
    int f, whilestack_num;
    long int while_begin, while_end, con_pos, sim_pos, e_con_pos;
    char str[B_SIZE + 1], st[B_SIZE + 1], con[B_SIZE + 1];

    if (while_num >= WHILE_LIMITED_NUM) {
        error_sxc(WHILE_LIMITED_ERROR, fp);
    }
    while_num += 1;

    con_pos = ftell(fp);
    f = value_stm(fp);
    while_begin = ftell(fp);

	fseek(fp, -1L, SEEK_CUR);
	e_con_pos = ftell(fp);
	fgets(con, B_SIZE, fp);
	if (!strcmp(con, "\n") == 0) {
		fseek(fp, e_con_pos, SEEK_SET);
		error_sxc(WHILE_CONDITION_ERROR, fp);
	}
	else
	{
		fseek(fp, while_begin, SEEK_SET);
	}

    fgets(str, B_SIZE, fp);
    if(strcmp(str, "{\n") == 0) {
        while_begin = ftell(fp);
    } else {
        fseek(fp, while_begin, SEEK_SET);
		error_sxc(WHILE_MISSING_1_ERROR, fp);
    }

    /*while_end = find_stm(fp);

    while(f) {
        exec_stm(while_begin, while_end, fp);
	fseek(fp, con_pos, SEEK_SET);
	f = value_stm(fp);
    }
	fseek(fp, while_end, SEEK_SET);
    while_num -= 1;*/
	
	if (f == 0){
		while_end = find_stm(fp);
	}
	while (f){
		fseek(fp, while_begin, SEEK_SET);
		whilestack_num = 1;
		while (whilestack_num){
			sim_pos = ftell(fp);
			fgets(st, B_SIZE, fp);
			if (strcmp(st, "}\n") == 0){
				whilestack_num -= 1;
			}
			else if (strcmp(st, "{\n") == 0){
				whilestack_num += 1;
			}
			else if (strcmp(st, "end\n") == 0){
				fseek(fp, sim_pos, SEEK_SET);
				error_sxc(MISSING_1_ERROR, fp);
			}
			else if (strcmp(st, "else\n") == 0){
				fseek(fp, sim_pos, SEEK_SET);
				error_sxc(MISSING_1_ERROR, fp);
			}
			else if (strcmp(st, "if\n") == 0){
				fseek(fp, sim_pos, SEEK_SET);
				next_line(fp);
				if_stm(fp);
			}
			else if (strcmp(st, "while\n") == 0){
				fseek(fp, sim_pos, SEEK_SET);
				next_line(fp);
				while_stm(fp);
			}
			else if (strcmp(st, "in\n") == 0){
				fseek(fp, sim_pos, SEEK_SET);
				next_line(fp);
				in_stm(fp);
			}
			else if (strcmp(st, "out\n") == 0){
				fseek(fp, sim_pos, SEEK_SET);
				next_line(fp);
				out_stm(fp);
			}
			else if (strcmp(st, "for\n") == 0){
				fseek(fp, sim_pos, SEEK_SET);
				next_line(fp);
				in_stm(fp);
			}
			else
			{
				fseek(fp, sim_pos, SEEK_SET);
				simple_stm(fp);
			}
			while_end = ftell(fp);
		}
		fseek(fp, con_pos, SEEK_SET);
		f = value_stm(fp);
	}

	fseek(fp, while_end, SEEK_SET);
	while_num -= 1;
}
Ejemplo n.º 22
0
Boolean parseRTSPResponseString(char const* reqStr,
                                unsigned reqStrSize,
                                char* resultCode,
                                unsigned resultCodeMaxSize,
                                char* resultStatus,
                                unsigned resultStatusMaxSize,
                                char* contentType,
                                unsigned contentTypeMaxSize,
                                char* challenge,
                                unsigned challengeMaxSize,
                                unsigned int* contentLength,
                                unsigned char** content) {
    char* p, *q, *u, *v;

    *contentLength = 0;

    // First line, parse the result code and result status
    p = eat_white((char*)reqStr);
    if (strncmp(p, "RTSP/1.0", 8) != 0)
        return False;
    q = next_white(p);
    p = eat_white(q);
    q = next_white(p);
    if (q - p >= (int)resultCodeMaxSize)
        return False;
    memcpy(resultCode, p, q-p);
    resultCode[q-p] = 0;

    p = eat_white(q);
    q = next_line(p);
    if (q - p >= (int)resultStatusMaxSize)
        return False;
    memcpy(resultStatus, p, q-p-2);
    resultStatus[q-p-2] = 0;

    while (1)
    {
        p = q;
        q = next_line(p);
        if (strncmp(p, "Content-type", strlen("Content-type")) == 0 ||
                strncmp(p, "Content-Type", strlen("Content-Type")) == 0)
        {
            // Parse content-type header
            u = eat_white(next_white(p));
            v = next_white(u);
            memcpy(contentType, u, v-u);
            contentType[v-u] = 0;
        }
        else if (strncmp(p, "Content-length", strlen("Content-length")) == 0 ||
                 strncmp(p, "Content-Length", strlen("Content-Length")) == 0)
        {
            // Parse content-length header
            u = eat_white(next_white(p));
            *contentLength = ::atoi(u);
        }
        else if (strncmp(p, "Challenge", strlen("Challenge")) == 0)
        {
            // Parse challenge header
            u = eat_white(next_white(p));
            v = next_white(u);
            memcpy(challenge, u, v-u);
            challenge[v-u] = 0;
        }
        if (*q == 0 || *q == '\r')
            break;
    }
    if (*q == '\r')
        q += 2;
    if (*contentLength > 0 && *q != 0)
    {
        unsigned char* temp = (unsigned char*)malloc(*contentLength);
        memcpy(temp, q, *contentLength);
        *content = temp;
    }
    return True;
}
Ejemplo n.º 23
0
void scan_space (void)
{	start: while (*next==' ' || *next==TAB) next++;
	if (!udfon && *next=='.' && *(next+1)=='.')
		{	next_line(); if (error) return; goto start; }
}
Ejemplo n.º 24
0
int
__get_nprocs (void)
{
  static int cached_result;
  static time_t timestamp;

  time_t now = time (NULL);
  time_t prev = timestamp;
  atomic_read_barrier ();
  if (now == prev)
    return cached_result;

  /* XXX Here will come a test for the new system call.  */

  const size_t buffer_size = __libc_use_alloca (8192) ? 8192 : 512;
  char *buffer = alloca (buffer_size);
  char *buffer_end = buffer + buffer_size;
  char *cp = buffer_end;
  char *re = buffer_end;

#ifdef O_CLOEXEC
  const int flags = O_RDONLY | O_CLOEXEC;
#else
  const int flags = O_RDONLY;
#endif
  int fd = open_not_cancel_2 ("/sys/devices/system/cpu/online", flags);
  char *l;
  int result = 0;
  if (fd != -1)
    {
      l = next_line (fd, buffer, &cp, &re, buffer_end);
      if (l != NULL)
	do
	  {
	    char *endp;
	    unsigned long int n = strtoul (l, &endp, 10);
	    if (l == endp)
	      {
		result = 0;
		break;
	      }

	    unsigned long int m = n;
	    if (*endp == '-')
	      {
		l = endp + 1;
		m = strtoul (l, &endp, 10);
		if (l == endp)
		  {
		    result = 0;
		    break;
		  }
	      }

	    result += m - n + 1;

	    l = endp;
	    while (l < re && isspace (*l))
	      ++l;
	  }
	while (l < re);

      close_not_cancel_no_status (fd);

      if (result > 0)
	goto out;
    }

  cp = buffer_end;
  re = buffer_end;
  result = 1;

  /* The /proc/stat format is more uniform, use it by default.  */
  fd = open_not_cancel_2 ("/proc/stat", flags);
  if (fd != -1)
    {
      result = 0;

      while ((l = next_line (fd, buffer, &cp, &re, buffer_end)) != NULL)
	/* The current format of /proc/stat has all the cpu* entries
	   at the front.  We assume here that stays this way.  */
	if (strncmp (l, "cpu", 3) != 0)
	  break;
	else if (isdigit (l[3]))
	  ++result;

      close_not_cancel_no_status (fd);
    }
  else
    {
      fd = open_not_cancel_2 ("/proc/cpuinfo", flags);
      if (fd != -1)
	{
	  GET_NPROCS_PARSER (fd, buffer, cp, re, buffer_end, result);
	  close_not_cancel_no_status (fd);
	}
    }

 out:
  cached_result = result;
  atomic_write_barrier ();
  timestamp = now;

  return result;
}
Ejemplo n.º 25
0
static int process_mtxp_file(PARIO_INFO_PTR pio_info,
  char *filebuf, int fsize,
  int nprocs, int myrank,
  int *nGlobalEdges, int *nGlobalVtxs, int *vtxWDim, int *edgeWDim,
  int *nMyPins, int **myPinI, int **myPinJ,
  int *nMyVtx, int **myVtxNum, float **myVtxWgts,
  int *nMyEdgeWgts, int **myEdgeNum, float **myEdgeWgts)
{
int nedges, nvtxs, npins, vdim, edim, numew, nFileProcs;
int countMyVtxs, countMyEdges, countMyPins;
int proc, mine, nextpin, rc;
int eid, vid, i, j;
int mineid = -1, minvid = 0, maxeid = -1, maxvid = -1, numeids, numvids;
int nexte, nextv, nDistProcs;
int myminPin, mymaxPin, myminVtx, mymaxVtx, myshare, share;
float pinVal;
int *myi, *myj, *myvno, *myeno;
char *line, *token, *linestr, *pinBuf, *vwgtBuf, *ewgtBuf;
float *myvwgt, *myewgt;
char cmesg[256];

  *nGlobalEdges = *nGlobalVtxs = *nMyPins = 0;
  *nMyVtx = *nMyEdgeWgts = *vtxWDim = *edgeWDim = 0;
  *myPinI = *myPinJ = *myVtxNum = *myEdgeNum = NULL;
  *myVtxWgts = *myEdgeWgts = NULL;

  linestr = (char *)malloc(MATRIX_MARKET_MAX_LINE+1);
  if (!linestr){
    sprintf(cmesg, "memory allocation\n");
    Gen_Error(0, cmesg);
    return 0;
  }

  line = first_char(filebuf, fsize);
  if (line && (*line == '%')){
    line = next_line(filebuf, fsize, linestr);  /* skip comments & blanks */
  }

  if (!line){
    sprintf(cmesg, "Truncated file\n");
    Gen_Error(0, cmesg);
    return 0;
  }

  rc = sscanf(linestr, "%d %d %d %d %d %d %d",
	    &nedges, &nvtxs, &npins, &nFileProcs,
	    &vdim, &numew, &edim);

  if (rc != 7){
    sprintf(cmesg, "%s\nFirst line should have 7 values in it\n",linestr);
    Gen_Error(0, cmesg);
    return 0;
  }

  myminPin = mymaxPin = -1;
  myminVtx = mymaxVtx = -1;
  if ((pio_info->init_dist_procs > 0) &&
      (pio_info->init_dist_procs < nprocs)){
    nDistProcs = pio_info->init_dist_procs;
  }
  else{
    nDistProcs = nprocs;
  }
  if (pio_info->init_dist_type == INITIAL_LINEAR){ /* vertex distribution */
    if (myrank < nDistProcs){
      share = nvtxs / nDistProcs;
      i = nvtxs - (nDistProcs * share);
      myshare = ((myrank < i) ? share+1 : share);
      myminVtx = myrank * myshare;
      if (myrank >= i) myminVtx += i;
      mymaxVtx = myminVtx + myshare - 1;
    }
  }
  if (pio_info->init_dist_pins == INITIAL_LINEAR){ /* pin distribution */
    share = npins / nprocs;
    i = npins - (nprocs * share);
    myshare = ((myrank < i) ? share+1 : share);
    myminPin = myrank * myshare;
    if (myrank >= i) myminPin += i;
    mymaxPin = myminPin + myshare - 1;
  }

  myvno = myeno = myi = myj = NULL;
  myewgt = myvwgt = NULL;
  pinBuf = vwgtBuf = ewgtBuf = NULL;

  /* Read through the pins, vertex weights and edge weights.
   * Accumulate all vertex and edge IDs, and map these to
   * consecutive global numbers beginning with zero.
   *
   * Also count my pins, my vertices, and the number of edges
   * for which I provide weights.
   */

  countMyPins = 0;
  countMyVtxs = 0;
  countMyEdges = 0;
  nexte = nextv = 0;

  for (i=0; i<npins; i++){           /* PINS */
    line = next_line(line, fsize, linestr);

    if (!line){
      if (myrank == 0) printf("File is truncated in pins\n");
      goto failure;
    }
    if (!i) pinBuf = line;

    rc = sscanf(linestr, "%d %d %f %d", &eid, &vid, &pinVal, &proc);
    if ((rc != 4) || (eid < 1) || (eid > nedges) ||
	(vid < 1) || (vid > nvtxs) || (proc < 0) || (proc >= nFileProcs)){
      sprintf(cmesg,"%s\nlooking for \"edge vertex pin process\"\n",linestr);
      Gen_Error(0, cmesg);
      goto failure;
    }

    eid -= 1;
    vid -= 1;

    mine = my_pin(eid, vid, proc, i, npins,
		  myminPin, mymaxPin, myrank, nprocs, pio_info);

    if (i){  /* should get rid of this, IDs are always 1 ... N */
      if (eid < mineid) mineid = eid;
      if (vid < minvid) minvid = vid;
      if (eid > maxeid) maxeid = eid;
      if (vid > maxvid) maxvid = vid;
    }
    else{
      mineid = maxeid = eid;
      minvid = maxvid = vid;
    }

    if (mine){
      countMyPins++;
    }
  }

  if (npins)
    numeids = maxeid - mineid + 1;
  else
    numeids = nedges;

  for (i=0; i<nvtxs; i++){        /* VERTICES and possibly WEIGHTS */
    line = next_line(line, fsize, linestr);

    if (!line){
      sprintf(cmesg,"File is truncated at vertex weights\n");
      Gen_Error(0, cmesg);
      goto failure;
    }
    if (!i) vwgtBuf = line;

    rc = sscanf(linestr, "%d", &vid);
    token = get_token(linestr, vdim + 1, strlen(linestr));
    if (token) proc = atoi(token);
    if ((rc != 1) || !token ||
	 (vid < 1) || (vid > nvtxs) || (proc < 0) || (proc >= nFileProcs)){
      sprintf(cmesg,
      "%s\nlooking for \"vertex {optional weights} process\"\n",linestr);
      Gen_Error(0, cmesg);
      goto failure;
    }

    vid -= 1;

    if (i) {
      if (vid < minvid) minvid = vid;
      if (vid > maxvid) maxvid = vid;
    }
    else
      minvid = maxvid = vid;

    mine = my_vtx(proc, i, myminVtx, mymaxVtx, myrank, nDistProcs, pio_info);

    if (mine){
      countMyVtxs++;
    }
  }

  numvids = maxvid - minvid + 1;

  if (numew > 0){                      /* HYPEREDGE WEIGHTS */
    for (i=0; i<numew; i++){
      line = next_line(line, fsize, linestr);

      if (!line){  /* error */
	sprintf(cmesg,"File is truncated at edge weights\n");
	Gen_Error(0, cmesg);
	goto failure;
      }

      if (!i) ewgtBuf = line;

      rc = sscanf(linestr, "%d", &eid);
      token = get_token(linestr, edim + 1, strlen(linestr));
      if (token) proc = atoi(token);
      if ((rc != 1) || !token ||
	  (eid < 1) || (eid > nedges) || (proc < 0) || (proc >= nFileProcs)){
	sprintf(cmesg,
	"%s\nlooking for \"edge {optional weights} process\"\n",linestr);
	Gen_Error(0, cmesg);
	goto failure;
      }
      proc = atoi(token);

      eid -= 1;

      if (eid < mineid) mineid = eid;
      if (eid > maxeid) maxeid = eid;

      if (rc < 0){
	sprintf(cmesg,"File has more than %d edge IDs\n",nedges);
	Gen_Error(0, cmesg);
	goto failure;
      }

      if ((proc % nprocs) == myrank){
	countMyEdges++;
      }
    }
  }

  if (numew)
    numeids = maxeid - mineid + 1;
  else
    numeids = nedges;

  rc = 1;

  if (numeids != nedges){
    sprintf(cmesg,"found range of %d edges (not %d expected) in file\n",
	    numeids,nedges);
    rc = 0;
  }
  else if (numvids != nvtxs){
    sprintf(cmesg,"found range of %d vertices (not %d expected) in file\n",
	    numvids,nvtxs);
    rc = 0;
  }
  if (!rc){
    Gen_Error(0, cmesg);
    goto failure;
  }

  /* Start over at beginning of file and save my pins, and weights */

  if (countMyPins > 0){
    myi = (int *)malloc(sizeof(int) * countMyPins);
    myj = (int *)malloc(sizeof(int) * countMyPins);
    if (!myi || !myj){
      sprintf(cmesg,"memory allocation\n");
      Gen_Error(0, cmesg);
      goto failure;
    }
    nextpin = 0;

    make_string(pinBuf, linestr);
    line = pinBuf;

    for (i=0; i<npins; i++){

      sscanf(linestr, "%d %d %f %d", &eid, &vid, &pinVal, &proc);

      eid -= 1;
      vid -= 1;
      mine = my_pin(eid, vid, proc, i, npins,
		  myminPin, mymaxPin, myrank, nprocs, pio_info);

      if (mine){
	myi[nextpin] = eid - mineid;
	myj[nextpin] = vid - minvid;
	nextpin++;
      }
      line = next_line(line, fsize, linestr);
    }
  }

  if (countMyVtxs){

    myvno = (int *)malloc(sizeof(int) * countMyVtxs);
    if (vdim > 0){
      myvwgt = (float *)malloc(sizeof(float) * countMyVtxs * vdim);
    }
    if (!myvno || (vdim && !myvwgt)){
      sprintf(cmesg,"memory allocation\n");
      Gen_Error(0, cmesg);
      goto failure;
    }
    nextv = 0;

    make_string(vwgtBuf, linestr);
    line = vwgtBuf;

    for (i=0; i<nvtxs; i++){
      sscanf(linestr, "%d", &vid);
      token = get_token(linestr, vdim + 1, strlen(linestr));
      proc = atoi(token);
      vid -= 1;
      mine = my_vtx(proc, i, myminVtx, mymaxVtx, myrank, nDistProcs, pio_info);
      if (mine){
	myvno[nextv] = vid - minvid;
	for (j=0; j<vdim; j++){
	  token = get_token(linestr, 1 + j, strlen(linestr));
	  if (!token){
	    sprintf(cmesg,"%s\nCan't find %d vertex weights\n",linestr,vdim);
	    Gen_Error(0, cmesg);
	    goto failure;
	  }
	  myvwgt[nextv*vdim + j] = (float)atof(token);
	}
	nextv++;
      }
      line = next_line(line, fsize, linestr);
    }
  }

  if (countMyEdges > 0){
    myeno = (int *)malloc(sizeof(int) * countMyEdges);
    myewgt = (float *)malloc(sizeof(float) * countMyEdges * edim);
    if (!myeno || !myewgt){
      sprintf(cmesg,"memory allocation\n");
      Gen_Error(0, cmesg);
      goto failure;
    }
    nexte = 0;

    make_string(ewgtBuf, linestr);
    line = ewgtBuf;

    for (i=0; i<numew; i++){
      sscanf(linestr, "%d", &eid);
      token = get_token(linestr, edim + 1, strlen(linestr));
      proc = atoi(token);
      eid -= 1;
      if ((proc % nprocs) == myrank){
	myeno[nexte] = eid - mineid;
	for (j=0; j<edim; j++){
	  token = get_token(linestr, 1 + j, strlen(linestr));
	  if (!token){
	    sprintf(cmesg,"%s\nCan't find %d edge weights\n",linestr,edim);
	    Gen_Error(0, cmesg);
	    goto failure;
	  }
	  myewgt[nexte*edim + j] = (float)atof(token);
	}
	nexte++;
      }
      line = next_line(line, fsize, linestr);
    }
  }

  rc = 1;   /* success */
  goto done;

failure:
  if (myvno) free(myvno);
  if (myvwgt) free(myvwgt);
  if (myeno) free(myeno);
  if (myewgt) free(myewgt);
  if (myi) free(myi);
  if (myj) free(myj);
  nedges = nvtxs = vdim = edim = 0;
  countMyPins = countMyVtxs = countMyEdges = 0;
  rc = 0;

done:
  free(linestr);

  *nGlobalEdges = nedges;
  *nGlobalVtxs = nvtxs;
  *vtxWDim = vdim;
  *edgeWDim = edim;

  *nMyPins = countMyPins;
  *myPinI  = myi;
  *myPinJ  = myj;

  *nMyVtx = countMyVtxs;
  *myVtxNum = myvno;
  *myVtxWgts = myvwgt;

  *nMyEdgeWgts = countMyEdges;
  *myEdgeNum = myeno;
  *myEdgeWgts = myewgt;

  return rc;
}
void initialize(void)
/* Read constants and initial conditions from br2dtask.dat */
{
  void readAfield();

  int i,j,k,l;
  double tanhval;
  double pi=3.141592653589793;
  int icewidthn, icbwidthn, iclengthactn, iclengthblockn, middlex, middley, b1, b2;
  FILE *fp;
  
  if((fp=fopen("brdr2dtask.dat","r"))==NULL) {
    printf("Cannot open task file: brdr2dtask.dat \n");
    exit(1);
  }
  else {
  
    // initialize constant array
    printf("Initializing constant array ... \n");   
//    constarr=(double *)malloc((unsigned int)(constnum*sizeof(double)));
    for (i=0;i<constnum;++i) constarr[i]=0;
  
    // initialize derivative array
    printf("Initializing derivative array ... \n"); 
    //derivarr=(double *)malloc((unsigned int)(derivnum*sizeof(double)));
    for (i=0;i<derivnum;++i) derivarr[i]=0;
        
    next_line(fp);
    next_line(fp);
    fscanf(fp,"%lf",&tfinal); next_line(fp);        /* tfinal (msec) */  
    fscanf(fp,"%lf",&dt); next_line(fp);            /* dt (mesc) */
    fscanf(fp,"%lf",&Lx); next_line(fp);            /* Lx (cm) */
    fscanf(fp,"%d",&Nx); next_line(fp);            /* Nx (unitless integer) */
    fscanf(fp,"%lf",&Ly); next_line(fp);            /* Ly (cm) */
    fscanf(fp,"%d",&Ny); next_line(fp);            /* Ny (unitless integer) */
    fscanf(fp,"%lf",&constarr[0]); next_line(fp);   /* gK1 */
    fscanf(fp,"%lf",&constarr[1]); next_line(fp);   /* gNa */
    fscanf(fp,"%lf",&constarr[2]); next_line(fp);   /* ENa */
    fscanf(fp,"%lf",&constarr[3]); next_line(fp);   /* gx1 */
    fscanf(fp,"%lf",&constarr[4]); next_line(fp);   /* gs */
    fscanf(fp,"%lf",&constarr[5]); next_line(fp);   /* Cm */
    fscanf(fp,"%lf",&constarr[6]); next_line(fp);   /* kCa */
    fscanf(fp,"%lf",&constarr[7]); next_line(fp);   /* gNaC */
    fscanf(fp,"%lf",&constarr[8]); next_line(fp);   /* Dpara   (cm^2/msec) */
    fscanf(fp,"%lf",&constarr[9]); next_line(fp);   /* Dperpen (cm^2/msec) */
    fscanf(fp,"%lf",&constarr[10]); next_line(fp);  /* theta   (degrees)   */
    fscanf(fp,"%lf",&constarr[11]); next_line(fp);  /* sigma   (unitless)   */
    fscanf(fp,"%lf",&constarr[12]); next_line(fp);  /* A       (unitless)   */
    
    Nsteps=ceil(tfinal/dt);      // total number of time steps
    dx=Lx/Nx;                    // (cm)
    dy=Ly/Ny;                    // (cm)
    middlex=(unsigned int)(floor(Nx/2));
    middley=(unsigned int)(floor(Ny/2));  /* changed to 1/3 on 9/9/05 */
    
    // Compute Diffusion Tensor  (cm^2/msec)
    D[0][0]=constarr[8]*pow(cos(constarr[10]*pi/180),2)+constarr[9]*pow(sin(constarr[10]*pi/180),2);
    D[1][0]=(constarr[8]-constarr[9])*cos(constarr[10]*pi/180)*sin(constarr[10]*pi/180);
    D[0][1]=D[1][0];
    D[1][1]=constarr[8]*pow(sin(constarr[10]*pi/180),2)+constarr[9]*pow(cos(constarr[10]*pi/180),2);
    
    // Compute Laplacian multipliers: Dp for Dprime
    Dp[0][0]=D[0][0]/(dx*dx);          /* msec^-1 */
    Dp[1][0]=D[1][0]/(2*dx*dy);        /* msec^-1 */
    Dp[0][1]=Dp[1][0];                 /* msec^-1 */
    Dp[1][1]=D[1][1]/(dy*dy);          /* msec^-1 */
        
    // Allocate memory and define datarr size
    // datarr[Nx+2][Ny+2][varnum][datarr4dim]: (rows)X(columns)X(depth)X(4dim)=(Nx+2)X(Ny+2)X(varnum)X(datarr4dim)
    // Nx+2,Ny+2 to provide a border of ghost points for fast application of boundary conditions (aka Barkley) 
    // Range: 0<=x<=Nx+1 and  0<=y<=Ny+1
    //printf("Allocating memory for data array ... \n");                                                    
    //datarr=(double ****)malloc((unsigned int)((Nx+2)*sizeof(double***)));   // Nx+2 rows, Ny+2 columns, depth of varnum, 4th dim of datarr4dim
    //for (i=0;i<Nx+2;++i){
      //datarr[i]=(double ***)malloc((unsigned int)((Ny+2)*sizeof(double**)));
      //for (j=0;j<Ny+2;++j){
        //datarr[i][j]=(double **)malloc((unsigned int)(varnum*sizeof(double*)));
        //for (k=0;k<varnum;++k){
          //datarr[i][j][k]=(double *)malloc((unsigned int)(datarr4dim*sizeof(double)));
	//}
      //}
   // }
       
    // initialize datarr
    printf("Initializing data array ... \n");   
    for (i=0;i<Nx+2;++i){  
      for (j=0;j<Ny+2;++j){
        for (k=0;k<varnum;++k){ 
	  for (l=0;l<datarr4dim;++l) datarr[l][k][i][j]=0.0;
	}
      }
    }
 
    printf("Initializing block matrix ... \n");
//    block=(int **)malloc((unsigned int)((Nx+2)*sizeof(int*)));         
//    for (i=0;i<Nx+2;++i) block[i]=(int *)malloc((unsigned int)((Ny+2)*sizeof(int)));
    for (i=0;i<Nx+2;++i){  
      for (j=0;j<Ny+2;++j){
        block[i][j]=1;
      }
    }
    
    next_line(fp);
    next_line(fp);
    next_line(fp);
    /* Fill first node with initial conditions: Read ics */
    fscanf(fp,"%lf",&datarr[0][0][1][1]); next_line(fp);    /* Vm (mV) */
    fscanf(fp,"%lf",&datarr[0][11][1][1]); next_line(fp);   /* Cai   (mole/L) */
    /* Get spiral stimulus options */
    fscanf(fp,"%d",&ictype); next_line(fp);          /* type of initial conditions (0, 1, or 2) */
    next_line(fp);
    next_line(fp);
    next_line(fp);
    /* Get block stuff */
    fscanf(fp,"%lf",&icewidth); next_line(fp);       /* width of excited ic bar (cm) */
    fscanf(fp,"%lf",&icbwidth); next_line(fp);       /* width of block ic bar (cm) */
    fscanf(fp,"%lf",&iclengthact); next_line(fp);   /* length of ic active bar (cm) */
    fscanf(fp,"%lf",&iclengthblock); next_line(fp); /* length of ic block bar (cm) */
    fscanf(fp,"%d",&blocktimenum); next_line(fp);  /* number of block times */
    
    if (blocktimenum<0){
      printf("Invalid number of block times: %d \n",blocktimenum);
      exit(1);}
    if ((blocktimenum==0)&&(ictype==1)){
      printf("Invalid blocktimenum %d for spiral ics! \n",blocktimenum);
      exit(1);} 
    else if (blocktimenum>0){
      /* Allocate memory for block time array. */
      //blocktimes=(double **)malloc((unsigned int)(blocktimenum*sizeof(double*)));
      //for (i=0;i<blocktimenum;++i) blocktimes[i]=(double *)malloc((unsigned int)(2*sizeof(double)));
      /* Initialize blocktimes  */
      for (i=0;i<blocktimenum;++i){  
        blocktimes[i][0]=0.0;
	blocktimes[i][1]=0.0;
      }
      for (i=0;i<blocktimenum;++i) fscanf(fp,"%lf",&blocktimes[i][0]);      // read block times from br2dtask.dat
    }
     
    /* Fill first node with initial conditions: Compute ics */
    /* Generate initial conditions for gate variables from infinity constants */
    datarr[0][4][1][1]=abfun_0(datarr[0][0][1][1])/(abfun_0(datarr[0][0][1][1])+abfun_1(datarr[0][0][1][1]));      // x1 initial condition
    datarr[0][6][1][1]=abfun_2(datarr[0][0][1][1])/(abfun_2(datarr[0][0][1][1])+abfun_3(datarr[0][0][1][1]));      // m initial condition
    datarr[0][7][1][1]=abfun_4(datarr[0][0][1][1])/(abfun_4(datarr[0][0][1][1])+abfun_5(datarr[0][0][1][1]));      // h initial condition
    datarr[0][9][1][1]=abfun_8(datarr[0][0][1][1])/(abfun_8(datarr[0][0][1][1])+abfun_9(datarr[0][0][1][1]));     // d initial condition
    datarr[0][10][1][1]=abfun_10(datarr[0][0][1][1])/(abfun_10(datarr[0][0][1][1])+abfun_11(datarr[0][0][1][1]));  // f initial condition

    // Propagate initial conditions to all other nodes
    for (i=1;i<Nx+1;++i){
      for (j=1;j<Ny+1;++j){
        if (i>1 | j>1) { for (k=0;k<varnum;++k) datarr[0][k][i][j]=datarr[0][k][1][1]; }
      }
    }
     
    next_line(fp);
    next_line(fp);
    next_line(fp);
    next_line(fp);
    fscanf(fp,"%d",&stimnum); next_line(fp);           /* num of stimuli */
    fscanf(fp,"%lf",&Istimamp); next_line(fp);         /* stimulus amplitude (uA/cm^2) */
    fscanf(fp,"%lf",&stimint); next_line(fp);          /* stimulus interval, duration (msec) */
    fscanf(fp,"%lf",&stimsize1); next_line(fp);        /* first stimulus size (cm) */
    fscanf(fp,"%lf",&stimsize2); next_line(fp);        /* second stimulus size (cm) */
    
    if (ictype==1) {
      printf("Establishing initial conditions for spiral wave ... \n");      
      icewidthn=(unsigned int)(round(icewidth/dy));
      icbwidthn=(unsigned int)(round(icbwidth/dy));
      iclengthactn=(unsigned int)(floor(iclengthact/dx));  
      iclengthblockn=(unsigned int)(floor(iclengthblock/dx));  
      b1=middley-icewidthn;
      if (b1<1) b1=1;
      b2=middley+icbwidthn+1;
      if (b2>Ny) b2=Ny;
      for (i=1;i<=iclengthactn;++i){
        for (j=b1;j<=middley;++j){
          datarr[0][0][i][j]=-20;     // Vm 
	  datarr[0][6][i][j]=1;       // m 
	}
      }
      for (i=1;i<=iclengthblockn;++i){
        for (j=middley+1;j<=b2;++j){
	  block[i][j]=0;  // set to zero to turn on block
        }
      }
      printf("b1: %d, b2: %d, middley: %d \n",b1,b2,middley);
    }
    else if (ictype==0) printf("Using normal initial conditions ... \n");
    else if (ictype==2) printf("Using final conditions of a previous run to establish initial conditions ... \n");
    else {
      printf("Invalid ic type value in brdr2dtask.dat: %d \n",ictype);
      exit(1);}
    
    if (stimnum<0){
      printf("Invalid stimulus number: %d \n",stimnum);
      exit(1);}
    else if (stimnum>0){
      /* Allocate memory for stimulus matrix. Stimarr is undefined at ghost nodes */
      /* Nx rows, Ny columns, depth of stimnum, 4th dim of 2 */
      printf("Initializing stimulus array for %d stimul[us/i] ... \n",stimnum);
//      stimarr=(double ****)malloc((unsigned int)((Nx)*sizeof(double***)));   
//      for (i=0;i<Nx;++i){
//        stimarr[i]=(double ***)malloc((unsigned int)((Ny)*sizeof(double**)));
//        for (j=0;j<Ny;++j){
//          stimarr[i][j]=(double **)malloc((unsigned int)(stimnum*sizeof(double*)));
//          for (k=0;k<stimnum;++k){
//            stimarr[i][j][k]=(double *)malloc((unsigned int)(2*sizeof(double)));
//	  }
//        }
//      } 
      /* Initialize stimarr  */
      for (i=0;i<Nx;++i){  
        for (j=0;j<Ny;++j){
          for (k=0;k<stimnum;++k){ 
	    for (l=0;l<2;++l) stimarr[i][j][k][l]=0.0;
	  }
        }
      }
      stimes=(double *)malloc((unsigned int)(stimnum*sizeof(double)));
      for (i=0;i<stimnum;++i) fscanf(fp,"%lf",&stimes[i]);      // read stimulus times from br2dtask.dat
    }

    next_line(fp);
    next_line(fp);
    next_line(fp);
    next_line(fp);
    fscanf(fp,"%lf",&msecW); next_line(fp);          /* msec per write to datafile */
    fscanf(fp,"%d",&wdN); next_line(fp);             /* spatial sampling for writes to datafiles */
    wN=(unsigned int)(floor(Nsteps*msecW/tfinal));   /* time steps per write to datafile */
    nodeWx=wdN*dx;                                   /* dx per write to datafile (cm) */
    nodeWy=wdN*dy;                                   /* dy per write to datafile (cm) */
    
    next_line(fp);
    next_line(fp);
    next_line(fp);
    fscanf(fp,"%lf",&msecRP); next_line(fp);          /* msec per user update (print time to screen) */  
    rpN=(unsigned int)(floor(Nsteps*msecRP/tfinal)); /* time steps per user update (print time to screen) */
    fscanf(fp,"%d",&mNx); next_line(fp);             /* x index of node to monitor */
    fscanf(fp,"%d",&mNy); next_line(fp);             /* y index of node to monitor */
    
    if (mNx==-1) mNx=Nx;
    else if (mNx==-2) mNx=middlex;
    else if (mNx>Nx) mNx=Nx;
    else if (mNx==0) mNx=1;
    else if (mNx<-2) mNx=1;
    
    if (mNy==-1) mNy=Ny;
    else if (mNy==-2) mNy=middley;
    else if (mNy>Ny) mNy=Ny;
    else if (mNy==0) mNy=1;
    else if (mNy<-2) mNy=1;
    
    next_line(fp);
    next_line(fp);
    next_line(fp);
    fscanf(fp,"%d",&BC); next_line(fp);     /* Boundary Conditions */
    
    next_line(fp);
    next_line(fp);
    next_line(fp);
    fscanf(fp,"%d",&Af); next_line(fp);     /* Field flag for reading "A.field" file */
    
    next_line(fp);
    next_line(fp);
    next_line(fp);                          /* Data to save to disk */
    fscanf(fp,"%d",&outfilef[0]); next_line(fp);
    fscanf(fp,"%d",&outfilef[1]); next_line(fp);
    fscanf(fp,"%d",&outfilef[2]); next_line(fp);
    fscanf(fp,"%d",&outfilef[3]); next_line(fp);
    fscanf(fp,"%d",&outfilef[4]); next_line(fp);
    fscanf(fp,"%d",&outfilef[5]); next_line(fp);
    fscanf(fp,"%d",&outfilef[6]); next_line(fp);
    fscanf(fp,"%d",&outfilef[7]); next_line(fp);
    fscanf(fp,"%d",&outfilef[8]); next_line(fp);
    fscanf(fp,"%d",&outfilef[9]); next_line(fp);
    fscanf(fp,"%d",&outfilef[10]); next_line(fp);
    fscanf(fp,"%d",&outfilef[11]); next_line(fp);
    fscanf(fp,"%d",&outfilef[12]); next_line(fp);
    fscanf(fp,"%d",&outfilef[13]); next_line(fp);
    outfilef[14]=1;  // always save the time data
    fclose(fp);
  
    /* Tell the user what data is to be used. */
    printf("**********************************************************\n\n");
    printf("Model parameters: \n");
    printf("                 tfinal (msec): %5.2f\n",tfinal);
    printf("                     dt (msec): %1.4f\n",dt);
    printf("                        Nsteps: %10.2f\n",Nsteps);
    printf("                       Lx (cm): %4.2f\n",Lx);
    printf("                       dx (cm): %3.4f\n",dx);
    printf("                            Nx: %d\n",Nx);
    printf("                       Ly (cm): %4.2f\n",Ly);
    printf("                       dy (cm): %3.4f\n",dy);
    printf("                            Ny: %d\n",Ny);
    printf("        dt/[dx*dy] (msec/cm^2): %1.4f\n",dt/(dx*dy));
    printf("\n");
    printf("                msec per write: %4.3f\n",wN*dt);
    printf("              Nsteps per write: %d\n",wN);
    printf("Spatial rate for write (nodes): %d\n",wdN);
    printf("              datafile dx (cm): %1.4f\n",nodeWx);
    printf("              datafile dy (cm): %1.4f\n",nodeWy);
    printf("         datafile Nx (columns): %d\n",(unsigned int)ceil((double)Nx/wdN));
    printf("            datafile Ny (rows): %d\n",(unsigned int)ceil((double)Ny/wdN));
    printf("\n");
    
    printf("        Nsteps per user update: %d\n",rpN);
    printf("              msec user update: %4.3f\n",rpN*dt);
    printf("   Monitor this node [mNx,mNy]: %d, %d\n",mNx,mNy);
    printf("\n");

    printf("\nBR Constants: \n");
    printf("    gK1 (mmho/cm^2): %3.3f\n",constarr[0]);
    printf("    gNa (mmho/cm^2): %3.3f\n",constarr[1]);
    printf("           ENa (mV): %3.3f\n",constarr[2]);
    printf("    gx1 (mmho/cm^2): %3.3f\n",constarr[3]);
    printf("     gs (mmho/cm^2): %3.3f\n",constarr[4]); 
    printf("       Cm (uF/cm^2): %3.3f\n",constarr[5]);
    printf("      kCa (msec^-1): %3.3f\n",constarr[6]);
    printf("   gNaC (mmho/cm^2): %3.3f\n",constarr[7]);
    printf("  Dpara (cm^2/msec): %3.6f\n",constarr[8]);
    printf("Dperpen (cm^2/msec): %3.6f\n",constarr[9]);
    printf("    theta (degrees): %3.3f\n",constarr[10]);
    printf("   sigma (unitless): %3.3f\n",constarr[11]);
    printf("       A (unitless): %3.3f\n",constarr[12]);
    printf("\n");
    
    /* See courtemanche for Euler mesh ratio requirement */
    printf("\nMesh Ratios: \n");
    printf("(dx*dy)/dt [%1.5f (cm^2/msec)] should be greater than 4*Dpara [%1.5f (cm^2/msec)].\n",(dx*dy)/dt,4*constarr[8]);
    printf("(dx*dy)/dt [%1.5f (cm^2/msec)] should be greater than 4*Dperpen [%1.5f (cm^2/msec)].\n",(dx*dy)/dt,4*constarr[9]);
    printf("\n");
    
    printf("\nDiffusion Tensor: \n");
    printf(" D11 (cm^2/msec): %3.6f\n",D[0][0]);
    printf(" D12 (cm^2/msec): %3.6f\n",D[0][1]);
    printf(" D21 (cm^2/msec): %3.6f\n",D[1][0]);
    printf(" D22 (cm^2/msec): %3.6f\n",D[1][1]);
    printf("\n");
    
    printf("\nLaplacian Multipliers: \n");
    printf(" Dp11 (msec^-1): %3.4f\n",Dp[0][0]);
    printf(" Dp12 (msec^-1): %3.4f\n",Dp[0][1]);
    printf(" Dp21 (msec^-1): %3.4f\n",Dp[1][0]);
    printf(" Dp22 (msec^-1): %3.4f\n",Dp[1][1]);
    printf("\n");
    
    printf(" Af=%d\n",Af);
    /* Allocate memory for Afield. */
//    Afield=(double **)malloc((unsigned int)(Nx*sizeof(double*)));
//    for (i=0;i<Nx;++i) Afield[i]=(double *)malloc((unsigned int)(Ny*sizeof(double)));
    if (Af) {
      readAfield();}
    else {
      printf(" Initializing the A field as a homogenous distribution, A=%3.3f \n",constarr[12]);
      /* Establish homogenous A field */
      for (i=0;i<Nx;++i){ 
        for (j=0;j<Ny;++j){ 
          Afield[i][j]=constarr[12];
        }
      }
    }
    if (ictype==1) {
      printf("\nInitial conditions set for spiral wave.\n");
    }
    if (blocktimenum>0){
      printf("\nBlock information: \n");
      printf("       icewidth (cm): %3.4f \n",icewidth);       // Spiral ics and block stuff are still integretated at this point: 3/28/03
      printf("       icbwidth (cm): %3.4f \n",icbwidth);       // Spiral ics and block stuff are still integretated at this point: 3/28/03
      printf("    iclengthact (cm): %3.4f \n",iclengthact);   // Spiral ics and block stuff are still integretated at this point: 3/28/03
      printf("  iclengthblock (cm): %3.4f \n",iclengthblock); // Spiral ics and block stuff are still integretated at this point: 3/28/03
      printf("          icewidthn : %d \n",icewidthn+1);
      printf("          icbwidthn : %d \n",icbwidthn+1);
      printf("       iclengthactn : %d \n",iclengthactn);
      printf("     iclengthblockn : %d \n",iclengthblockn);
      printf("       blocktimenum : %d \n",blocktimenum);
      printf("   blocktimes (msec): ");
      for (i=0;i<blocktimenum;++i) printf("%4.2f ",blocktimes[i][0]);
      printf("\n\n");
    }
    
    if (ictype!=2) {
      printf("\nInitial Conditions: \n"); 
      printf("        Vm (mV): %3.3f\n",datarr[0][0][middlex][middley]);
      printf("  IK1 (uA/cm^2): %3.3f\n",datarr[0][2][middlex][middley]);
      printf("  Ix1 (uA/cm^2): %3.3f\n",datarr[0][3][middlex][middley]);
      printf("  x1 (unitless): %3.3f\n",datarr[0][4][middlex][middley]);
      printf("  INa (uA/cm^2): %3.3f\n",datarr[0][5][middlex][middley]);
      printf("   m (unitless): %3.3f\n",datarr[0][6][middlex][middley]);
      printf("   h (unitless): %3.3f\n",datarr[0][7][middlex][middley]);
      printf("   Is (uA/cm^2): %3.3f\n",datarr[0][8][middlex][middley]);
      printf("   d (unitless): %3.3f\n",datarr[0][9][middlex][middley]);
      printf("   f (unitless): %3.3f\n",datarr[0][10][middlex][middley]);
      printf("   Cai (mole/L): %3.3e\n",datarr[0][11][middlex][middley]);  
      printf("\n");}
    
    if (stimnum>0) {
      printf("\nStimuli: \n");
      printf("           stimnum: %d\n",stimnum);
      printf("Istimamp (uA/cm^2): %4.3f\n",Istimamp);   // (uA/cm^2)
      printf("    stimint (msec): %2.3f\n",stimint);
      printf("    stimsize1 (cm): %2.3f\n",stimsize1);
      printf("    stimsize2 (cm): %2.3f\n",stimsize2);
      printf("      times (msec): ");
      for (i=0;i<stimnum;++i) printf("%4.2f ",stimes[i]);
      printf("\n\n");}
    if (BC==1) printf("End conditions: Slab\n\n");
    else printf("End conditions: Cylinder\n\n");
    
    printf("\nVariables to save to disk: \n");
    if (outfilef[0]==1) printf("    Vm\n");
    if (outfilef[1]==1) printf("    dVmdt\n");
    if (outfilef[2]==1) printf("    IK1\n");
    if (outfilef[3]==1) printf("    Ix1\n");
    if (outfilef[4]==1) printf("    x1\n");
    if (outfilef[5]==1) printf("    INa\n");
    if (outfilef[6]==1) printf("    m\n");
    if (outfilef[7]==1) printf("    h\n");
    if (outfilef[8]==1) printf("    Is\n");
    if (outfilef[9]==1) printf("    d\n");
    if (outfilef[10]==1) printf("    f\n");
    if (outfilef[11]==1) printf("    Cai\n");
    if (outfilef[12]==1) printf("    Isum\n");
    if (outfilef[13]==1) printf("    Diff\n"); 
    printf("**********************************************************\n");
  }
}
Ejemplo n.º 27
0
instruction_ptr Parser::parse_function_definition()
{
    int start_line = current_lexeme().line();
    if (!match_current_lexeme(kDefKeyword))
        return instruction_ptr();
    
    next_lexeme();
    
    if (!match_current_lexeme(kId))
    {
        report_current_syntax_error();
        return instruction_ptr();
    }
    
    string name = current_lexeme().value();
    
    next_lexeme();
    
    if (!match_current_lexeme(kLeftBracket))
    {
        report_current_syntax_error();
        return instruction_ptr();
    }
    
    next_lexeme();
    
    vector<string> parameters;
    
    if (!match_current_lexeme(kRightBracket))
    {
        while (true)
        {
            if (!match_current_lexeme(kId))
            {
                report_current_syntax_error();
                return instruction_ptr();
            }
            
            parameters.push_back(current_lexeme().value());
            
            next_lexeme();
            
            if (!match_current_lexeme(kComma))
                break;
            
            next_lexeme();
        }
    }
    
    if (!match_current_lexeme(kRightBracket))
    {
        report_current_syntax_error();
        return instruction_ptr();
    }
    
    next_lexeme();
    
    if (!match_current_lexeme(kColon))
    {
        report_current_syntax_error();
        return instruction_ptr();
    }
    
    next_lexeme();
    
    next_line();
    
    instructions function_body;
    
    while (!match_current_lexeme(kEndKeyword))
    {
        instruction_ptr instruction = parse_instruction();
        if (!instruction)
        {
            report_current_syntax_error();
            return instruction_ptr();
        }
        
        function_body.push_back(instruction);
    }
    
    next_lexeme();
    
    next_line();
    
    return instruction_ptr(new Function(start_line, function_body, name, parameters));
}
Ejemplo n.º 28
0
int main(void) {
  initialize();
int prog=0, bool_=1;
  led_on();
  delay_ms(200);
  led_off();
  delay_ms(200);
  led_on();
  delay_ms(200);
  led_off();
  delay_ms(200);
  print_string("Start Up");
  next_line();
  print_string("Select a Prog");
  delay_ms(1500);
  clear_screen();
  while(bool_){
	print_string("prog " );
	print_int(prog);
	delay_ms(500);
	if(get_sw1()==257)
	{
	    prog++;
		//if(prog>10);
		  // prog=0;
	}
	else
	   bool_=0;
	clear_screen();
  }
  clear_screen();
  print_string("Ready" );
  next_line();  
  print_string("Prog " );
  print_int(prog);
  print_string(" Selected");
  delay_ms(2000);
  clear_screen();
  if(prog==1)
  {
   
       orientate();
	
    /* print_string("Collection");
     one_row();
     deposite();
     clear_screen();
	 print_string("DONE");
	 forward(0);*/
	 
  }
  else if(prog==0)
  {
     print_string("sensor test");
     delay_ms(500);
     clear_screen();
     while(1)
     {
	    forward(100);
        if(digital(0)==1)
	    {  
		   break;
	    }  
	 }
	
     clear_screen();
     
	 print_string("DONE");
     reverse(0, 1000);
	 //stop();
	
  }
  else if(prog==2)
  {
     print_string("ATTACK");
	 forward(100);
	 //swing_left(100,250);
	 clear_screen();
	 print_string("DONE");
	 return 0;
	 //return code?
  }
  return 0;
}
Ejemplo n.º 29
0
int get_next_token(void) {

  int q;

  while (1) {
    if (i == size)
      break;
    if (buffer[i] == ' ') {
      i++;
      newline_beginning = OFF;
      continue;
    }
    if (buffer[i] == 0xA) {
      i++;
      next_line();
      continue;
    }
    break;
  }

  if (buffer[i] == '"') {
    for (ss = 0, i++; buffer[i] != 0xA && buffer[i] != '"'; ) {
      if (buffer[i] == '\\' && buffer[i + 1] == '"') {
				tmp[ss++] = '"';
				i += 2;
      }
      else
				tmp[ss++] = buffer[i++];
    }

    if (buffer[i] == 0xA) {
      print_error("GET_NEXT_TOKEN: String wasn't terminated properly.\n", ERROR_NONE);
      return FAILED;
    }
    tmp[ss] = 0;
    i++;

    /* expand eg. \1 and \@ */
    if (macro_active != 0) {
      q = 0;
      if (expand_macro_arguments(tmp, &q) == FAILED)
				return FAILED;
      if (q != 0) {
				strcpy(tmp, expanded_macro_string);
				ss = strlen(tmp);
      }
    }

    return GET_NEXT_TOKEN_STRING;
  }

  if (buffer[i] == '.') {
    tmp[0] = '.';
    i++;
    for (ss = 1; buffer[i] != 0x0A && buffer[i] != ' ' && ss <= MAX_NAME_LENGTH; ) {
      tmp[ss] = buffer[i];
      cp[ss - 1] = toupper((int)buffer[i]);
      i++;
      ss++;
    }
    cp[ss - 1] = 0;
  }
  else if (buffer[i] == '=' || buffer[i] == '>' || buffer[i] == '<' || buffer[i] == '!') {
    for (ss = 0; buffer[i] != 0xA && (buffer[i] == '=' || buffer[i] == '!' || buffer[i] == '<' || buffer[i] == '>')
					 && ss <= MAX_NAME_LENGTH; tmp[ss++] = buffer[i++]);
  }
  else {
    for (ss = 0; buffer[i] != 0xA && buffer[i] != ',' && buffer[i] != ' ' && ss <= MAX_NAME_LENGTH; ) {
      tmp[ss] = buffer[i];
      ss++;
      i++;
    }
    if (buffer[i] == ',')
      i++;
  }

  if (ss > MAX_NAME_LENGTH) {
    print_error("GET_NEXT_TOKEN: Too long for a token.\n", ERROR_NONE);
    return FAILED;
  }

  tmp[ss] = 0;

  /* expand eg. \1 and \@ */
  if (macro_active != 0) {
    q = 0;
    if (expand_macro_arguments(tmp, &q) == FAILED)
      return FAILED;
    if (q != 0) {
      strcpy(tmp, expanded_macro_string);
      ss = strlen(tmp);
    }
  }

  return SUCCEEDED;
}