Example #1
0
int create_thread(ref_t start_operation)
{
#ifdef THREADS
  pthread_t new_thread;
  int index;
  start_info_t *info_p = (start_info_t *)malloc(sizeof(start_info_t));
  index = get_next_index();
  if (index == -1) {
    fprintf (stderr,
	     "Max thread count of %d has been exceeded.  No thread created\n",
	     MAX_THREAD_COUNT);
    return 0;
  }
  gc_ready[index] = 0;
  info_p->start_operation = start_operation;
  info_p->parent_index = *((int *)pthread_getspecific(index_key));
  info_p->my_index = index;
  if (pthread_create(&new_thread, NULL,
		     (void *)init_thread, (void *)info_p))
    // Error creating --- need to add some clean up code here !!!
    return 0;
  else
    return 1;
#else
  return 0;
#endif
}
Example #2
0
static int add_field_to_array(HTable table, char *token, char *buf, long int *pos)
{
    int idx = get_next_index(table);
    char b[100];
    sprintf(b, "%i", idx);
    return add_field(table, b, token, buf, pos);
}
Example #3
0
/**
 * Borrows and sets "result" as any number from "pool". Returns error status.
 */
int poolnum_get_any(struct poolnum *pool, u16 *result)
{
	if (poolnum_is_empty(pool))
		return -ESRCH; /* We ran out of values. */

	*result = pool->array[pool->next];
	pool->next = get_next_index(pool->next, pool->count);
	pool->next_is_ahead = true;
	return 0;
}
Example #4
0
/**
 * Borrows "value" from "pool".
 * This function is slow; avoid it during packet processing.
 */
int poolnum_get(struct poolnum *pool, u16 value)
{
	u32 current_index;

	if (poolnum_is_empty(pool))
		return -ESRCH;

	current_index = pool->next;
	do {
		if (pool->array[current_index] == value) {
			pool->array[current_index] = pool->array[pool->next];
			pool->next = get_next_index(pool->next, pool->count);
			pool->next_is_ahead = true;
			return 0;
		}
		current_index = get_next_index(current_index, pool->count);
	} while (current_index != pool->returned);

	return -ESRCH;
}
void sa_free_list_backend::init()
{
	get_next_index() = 0;
	
	// This makes it so that the values initially stored in the array are
	// decrementing in value, starting with the highest value of
	// ( get_size() - 1 ) and ending with 0. 
	for ( int i=get_size()-1; i>= 0; --i )
	{
		push(i);
	}
}
Example #6
0
/**
 * Returns "value" to "pool".
 */
int poolnum_return(struct poolnum *pool, u16 value)
{
	if (WARN_IF_REAL(poolnum_is_full(pool), "Something's trying to return values that were "
			"originally not part of the pool."))
		return -EINVAL;

	pool->array[pool->returned] = value;
	pool->returned = get_next_index(pool->returned, pool->count);
	if (pool->next == pool->returned)
		pool->next_is_ahead = false;

	return 0;
}
Example #7
0
int table_append_table(HTable table, HTable val)
{
    int idx;
    char b[100];

    if ((! table) || (! val))
        return -1;

    idx = get_next_index(table);
    sprintf(b, "%i", idx);
    table_set_table(table, b, val);
    return 0;
}
u32 get_next_u32(struct xos_trace_ring_buffer *buffer_mngt, u32 *idx)
{
    u32 index,val;
    char *buffer;
    u8 i;
    u8 buff[4];
    u32 *ptr_u32;

    index= *idx;
    buffer=buffer_mngt->va_buffer;
    for (i=0; i<sizeof(u32); i++)
    {
        buff[i] = buffer[index];
        index = get_next_index(buffer_mngt, index);
    }
    ptr_u32 = (u32 *) buff;

    val = *ptr_u32;
    *idx = index;
    return val;
}
u64 get_next_u64(struct xos_trace_ring_buffer *buffer_mngt, u32 *idx)
{
    u32 index;
    char *buffer;
    u8 i;
    u8 buff[8];
    u64 *ptr_u64;
    u64 val;

    index= *idx;
    buffer=buffer_mngt->va_buffer;
    for (i=0; i<sizeof(u64); i++)
    {
        buff[i] = buffer[index];
        index = get_next_index(buffer_mngt, index);
    }
    ptr_u64 = (u64 *) buff;
    val = *ptr_u64;
    *idx = index;
    return val;
}
Example #10
0
//--------------------------------------------------------------
string Autocorrect::find_similars(string word){
    
    string similars_f = "";
    int ld_min = 3;
    int ld_thresh = 2;
    
    char c = word.at(0);
    
    int it_begin = alpha_indices[get_index(c)];
    int it_end = alpha_indices[get_next_index(c)];
    
    for (int it = it_begin; it < it_end; ++it){
        
        // get next word in dictionary
        string line = dictionary[it];
        // calculate Levenshtein distance
        int ld = levenshtein(word, line);
        
        if (ld == 0){
            // if similar word found, matching 100%
            similars_f = line;
            break;
        }else if (ld < ld_min && ld <= ld_thresh){
            // if word is found with a smaller LD than found before
            similars_f = line;
            ld_min = ld;
        }else if (ld == ld_min && similars_f.empty() && ld <= ld_thresh){
            // if word with similar LD distance is found
            similars_f = line;
            ld_min = ld;
        }else if (ld == ld_min && !similars_f.empty() && ld <= ld_thresh){
            // if equal LDs and already words in similar: append word to string
            // ! separate words with comma --> word_in_string checks amount of commas + 1 !
            similars_f.append(",");
            similars_f.append(ofToString(line));
        }
    }
    return similars_f;
}
Example #11
0
int main(int argc, char **argv)
{
	int ret;
	int session_id;

	plan_tests(NUM_TESTS);

	diag("Live unit tests");

	ret = connect_viewer("localhost");
	ok(ret == 0, "Connect viewer to relayd");

	ret = establish_connection();
	ok(ret == 0, "Established connection and version check with %d.%d",
			VERSION_MAJOR, VERSION_MINOR);

	ret = list_sessions(&session_id);
	ok(ret > 0, "List sessions : %d session(s)", ret);

	ret = attach_session(session_id);
	ok(ret > 0, "Attach to session, %d streams received", ret);

	ret = get_metadata();
	ok(ret > 0, "Get metadata, received %d bytes", ret);

	ret = get_next_index();
	ok(ret == 0, "Get one index per stream");

	ret = get_data_packet(first_packet_stream_id, first_packet_offset,
			first_packet_len);
	ok(ret == first_packet_len,
			"Get one data packet for stream %d, offset %d, len %d",
			first_packet_stream_id, first_packet_offset,
			first_packet_len);

	return exit_status();
}
Example #12
0
/* pointerreversed_handle_reference marks the given object as
   well as any objects pointed to by it using pointer-reversal. */
void pointerreversed_handle_reference(jobject_unwrapped *ref)
{
  jobject_unwrapped prev = NULL;
  jobject_unwrapped curr = *ref;
  jobject_unwrapped next;
  int done = 0;

  // in pointer-reversal, the mark has 3 possible states.
  // when an object has not yet been visited, it is
  // unmarked. after an object has been visited and all
  // its roots traced, it is marked as reachable. after
  // an object has been visited and before all its roots
  // have been traced, its mark encodes the field or
  // array element that is currently being examined.
  while (!done)
    {
      // follow pointers down
      while (curr != NULL)
	{
	  jobject_unwrapped obj = PTRMASK(curr);
	  struct block *bl = (void *)obj - BLOCK_HEADER_SIZE;

	  if (!IN_MARKSWEEP_HEAP(obj, heap))
	    {
	      error_gc("%p not allocated by marksweep.\n", obj);
	      if (prev == NULL)
		done = 1;
	      break;
	    }
	  
	  debug_verify_object(obj);

	  // these objects are untouched
	  if (NOT_MARKED(bl))
	    {
	      ptroff_t next_index;
	      jobject_unwrapped *elements_and_fields;

	      error_gc("%p is unmarked.\n", obj);

	      elements_and_fields = (jobject_unwrapped *)obj;

	      // we know the header does not contain heap pointers
	      next_index = get_next_index(obj, OBJ_HEADER_SIZE/SIZEOF_VOID_P);

	      if (next_index == NO_POINTERS)
		{
		  // does not contain pointers, mark as done
		  error_gc("%p does not contain pointers.\n", obj);
		  
		  MARK_AS_REACHABLE(bl);

		  if (prev == NULL)
		    done = 1;
		  break;
		}
	      else
		{
		  // the indices returned by next_index 
		  // is off by one; do fix up
		  next_index -= INDEX_OFFSET;
		  assert(next_index >= 0);

		  error_gc("next_index = %d\n", next_index); 

		  // look at the next index
		  SET_INDEX(bl, next_index);

		  next = elements_and_fields[next_index];
		  elements_and_fields[next_index] = prev;
		  prev = curr;
		  error_gc("Setting prev = %p.\n", prev);
		  curr = next;
		}
	    }
	  else
	    {
	      // these are references we're done with or that
	      // we are already looking at somewhere in the chain
	      if (prev == NULL)
		done = 1;
	      break;
	    }
	}
      
      // retreat! curr should point to the last thing we looked at, and prev to its parent
      while (prev != NULL)
	{
	  // these objects are in the middle of being examined
	  jobject_unwrapped obj = PTRMASK(prev);
	  struct block *bl = (void *)obj - BLOCK_HEADER_SIZE;
	  ptroff_t last_index;
	  ptroff_t next_index;
	  jobject_unwrapped *elements_and_fields;

	  error_gc("Starting prev loop with prev = %p.\n", prev);

	  last_index = GET_INDEX(bl);

	  elements_and_fields = (jobject_unwrapped *)obj;

	  next_index = get_next_index(obj, last_index+1);

	  if (next_index == NO_POINTERS)
	    {
	      // does not contain any more pointers, mark as done
	      error_gc("None of the rest of the fields/elements in this object contains a ptr.\n", "");
	      MARK_AS_REACHABLE(bl);

	      // restore pointers
	      next = prev;
	      prev = elements_and_fields[last_index];
	      error_gc("Setting prev = %p.\n", prev);
	      elements_and_fields[last_index] = curr;
	      curr = next;

	      if (prev == NULL)
		done = 1;
	    }
	  else
	    {
	      // the indices returned by next_array_index 
	      // and next_field_index are off by one; do fix up
	      next_index -= INDEX_OFFSET;
	      assert(next_index > 0);

	      error_gc("last_index = %d\n", last_index); 
	      error_gc("next_index = %d\n", next_index); 
	      
	      SET_INDEX(bl, next_index);

	      next = elements_and_fields[next_index];
	      elements_and_fields[next_index] = elements_and_fields[last_index];
	      elements_and_fields[last_index] = curr;
	      curr = next;

	      break;
	    }
	}
    }
}
float Automation::AutomationData::get_tick_val(Tick p_tick) {
	
	int stream_size=get_stream_size();
	
	if (stream_size==0)
		return -1;
	
	int prev = get_prev_index( p_tick );
	int next = get_next_index( p_tick );
	
	
	
	
	if (prev==-1) 
		return -1;
	
	float val=0;
	float lfo_val=0;
	
	if (next==stream_size) {
		val=get_index_value( stream_size -1 ).value; //just send the last one, nothing else can be done
		lfo_val=get_index_value( stream_size -1 ).lfo_depth;
	} else if (prev==next) { //we got an exact index, just return it, no interp. needed
		val=get_index_value(prev).value;
		lfo_val=get_index_value(prev).lfo_depth;
	} else {
	
		switch (interpolation) {
			
			case Automation::INTERP_NONE: {
				
				val=get_index_value(prev).value;
				lfo_val=get_index_value(prev).lfo_depth;
				
			} break;
			case Automation::INTERP_LINEAR: {
				
				Tick prev_tick=get_index_pos( prev);
				float prev_val=get_index_value( prev).value;
				float prev_lfo_depth_val=get_index_value( prev ).lfo_depth;
				
				Tick next_tick=get_index_pos( next);
				float next_val=get_index_value( next).value;
				float next_lfo_depth_val=get_index_value( next ).lfo_depth;
				
				val=prev_val+((double)(p_tick-prev_tick)*(next_val-prev_val))/(double)(next_tick-prev_tick); //linear interpolation
				lfo_val=prev_lfo_depth_val+((double)(p_tick-prev_tick)*(next_lfo_depth_val-prev_lfo_depth_val))/(double)(next_tick-prev_tick); //linear interpolation
			} break;
			case Automation::INTERP_CUBIC: {
				
				
				
				Tick prev_tick=get_index_pos( prev);
				float prev_val=get_index_value( prev).value;
				float prev_lfo=get_index_value( prev ).lfo_depth;
				
				float pre_prev_val=(prev>0)?get_index_value( prev-1).value:prev_val;
				float pre_prev_lfo=(prev>0)?get_index_value( prev-1).lfo_depth:prev_lfo;
				
				Tick next_tick=get_index_pos( next);
				float next_val=get_index_value( next).value;
				float next_lfo=get_index_value( next ).lfo_depth;
				
				float post_next_val=((next+1)<get_stream_size())?get_index_value( next+1).value:next_val;
				float post_next_lfo=((next+1)<get_stream_size())?get_index_value( next+1).lfo_depth:next_lfo;
				
				
				float coeff=(double)(p_tick-prev_tick)/(double)(next_tick-prev_tick);
				
				val = cubic_interpolate_points(pre_prev_val,prev_val,next_val,post_next_val,coeff);
				lfo_val = cubic_interpolate_points(pre_prev_lfo,prev_lfo,next_lfo,post_next_lfo,coeff);
				

				
			} break;
		}
	
	}
	
	val+=lfo_val*lfo.get_value( p_tick );
	
	if (val<0)
		val=0;
	if (val>1)
		val=1;
	return val;
	
}
void sa_pod_stack_backend::pop()
{
	--get_next_index();
}
Example #15
0
int
main(int argc, char **argv)
{
#ifdef THREADS
    int my_index;
    int *my_index_p;
    pthread_key_create (&index_key, (void*)free_registers);
#endif

#ifdef THREADS
    my_index_p = (int *)malloc (sizeof (int));
    *my_index_p = get_next_index();
    pthread_setspecific (index_key, (void*)my_index_p);
    my_index_p = pthread_getspecific(index_key);
    my_index = *my_index_p;
    gc_ready[my_index] = 0;
    /* inc_next_index();*/
    value_stack_array[my_index] = (oakstack*)malloc (sizeof (oakstack));
    cntxt_stack_array[my_index] = (oakstack*)malloc(sizeof (oakstack));
    value_stack.size = 1024;
    value_stack.filltarget = 1024/2;
    context_stack.size = 512;
    context_stack.filltarget = 512/2;
    gc_examine_ptr = gc_examine_buffer;
#endif

    parse_cmd_line(argc, argv);

    init_weakpointer_tables();

    init_stacks();

    read_world(world_file_name);

    new_space.size = e_next_newspace_size = original_newspace_size;
    alloc_space(&new_space, new_space.size);
    free_point = new_space.start;

#ifdef THREADS
    register_array[my_index] = (register_set_t*)malloc(sizeof(register_set_t));
#else
    reg_set = (register_set_t*)malloc(sizeof(register_set_t));
#endif

    /* Set the registers to the boot code */

    e_current_method = e_boot_code;
    e_env = REF_TO_PTR(REF_SLOT(e_current_method, METHOD_ENV_OFF));
    e_code_segment = REF_SLOT(e_current_method, METHOD_CODE_OFF);
    e_pc = CODE_SEG_FIRST_INSTR(e_code_segment);

    /* Put a reasonable thing in e_bp to avoid confusing GC */
    e_bp = e_env;

    /* Tell the boot function the truth */
    e_nargs = 0;

    /* Big virtual machine interpreter loop */
    loop(INT_TO_REF(54321));

    return 0;
}
Example #16
0
int main (int argc, char ** argv)
{
	std::string filename;
	std::ifstream trace_file;

	uint64_t memory_size = 8*1024*1024; // default is 8GB
	// Check if all arguments are given in command line
	if (argc != 3)
	{
		std::cout << "Please supply two arguements: <trace file> <physical memory size (B)>." << std::endl;
		return -1;
	}

	// Get the filename
	filename.assign(argv[1]);
	// Assign the memory size
	memory_size = std::stol(argv[2], nullptr, 10);

	// allocate array
	uint64_t array_size = memory_size / page_size;
	array_size--; // assume 1st level page table ALWAYS in memory
	MEME * in_memory = new MEME[array_size];
//	in_memory [array_size];
	uint64_t array_index = 0;

	//std::cout << argv[2] << " " << memory_size << " " << array_size << std::endl;


	// Open the file
	trace_file.open(filename);
	char operation;
	std::string virtual_address;
	std::string this_key;
	int byte_size;
	std::string file_line;
	std::vector<std::string> line_input;
	std::string token;

	while (std::getline(trace_file, file_line))
	{
		// tokenize string
		std::istringstream ss(file_line);
		while(std::getline(ss, token, ' '))
		{
			line_input.push_back(token);
			//std::cout << token << std::endl;
		}

		if (line_input.size() != 3)
		{
			line_input.clear();
			continue;
		}
		
		operation = line_input[0].at(0);
		if (operation != 'R' && operation != 'W')
		{
			line_input.clear();
			continue;
		}

		line_input[1] = line_input[1].substr(0, line_input[1].size() - 3);
		if (!valid_address(line_input[1]))
		{
			line_input.clear();
			continue;
		}
		virtual_address = line_input[1];
		this_key = line_input[1];//virtual_address;//get_VPN(virtual_address);

		if (!valid_size(line_input[2]))
		{
			line_input.clear();
			continue;
		}
		byte_size = std::stoi(line_input[2]);

		if (operation == 'R')
			total_bytes_read += byte_size;
		else
			total_bytes_write += byte_size;

		auto search = vpn_tracker.find(this_key);
		if (search != vpn_tracker.end())
		{
			// check if 2nd level not in memory
			if (!vpn_tracker[this_key].lvl_2_mem)
			{
				// find page to eject
				array_index = get_next_index(in_memory, array_size, array_index);
				eject_from_memory (in_memory[array_index].vpn, in_memory[array_index].level);

				// insert new page
				insert_into_memory (in_memory, array_index, this_key, 2);
			}
			else if (vpn_tracker[this_key].lvl_2_mem)
			{
				total_accessed++;
				vpn_tracker[this_key].lvl_2_clock = 1;
			}

			// check if 3rd level not in memory
			if (!vpn_tracker[this_key].lvl_3_mem)
			{
				// find page to eject
				array_index = get_next_index(in_memory, array_size, array_index);
				eject_from_memory (in_memory[array_index].vpn, in_memory[array_index].level);

				// insert new page
				insert_into_memory (in_memory, array_index, this_key, 3);
			}
			else if (vpn_tracker[this_key].lvl_3_mem)
			{
				total_accessed++;
				vpn_tracker[this_key].lvl_3_clock = 1;
			}

			// check if 4th level not in memory
			if (!vpn_tracker[this_key].lvl_4_mem)
			{
				// find page to eject
				array_index = get_next_index(in_memory, array_size, array_index);
				eject_from_memory (in_memory[array_index].vpn, in_memory[array_index].level);

				// insert new page
				insert_into_memory (in_memory, array_index, this_key, 4);
			}
			else if (vpn_tracker[this_key].lvl_4_mem)
			{
				total_accessed++;
				vpn_tracker[this_key].lvl_4_clock = 1;
			}

			vpn_tracker[this_key].num_accessed += 1;
		}
		else
		{
			PTE new_elem = {this_key, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0};
			vpn_tracker.insert(std::pair<std::string, PTE>(this_key, new_elem));
			for (int i = 2; i < 5; ++i)
			{
				array_index = get_next_index(in_memory, array_size, array_index);
				eject_from_memory (in_memory[array_index].vpn, in_memory[array_index].level);
				insert_into_memory (in_memory, array_index, this_key, i);
			}
		}
		// std::cout << "num tokens: " << line_input.size() << std::endl;
		// {
		// 	virtual_address 
		// }
		//std::cout << operation << " " << std::hex << virtual_address << " " << std::hex << get_VPN(virtual_address) << std::endl;

		line_input.clear();
	}

	std::string most_accessed_vpn = "";
	uint64_t num_access_vpn = 0;
	for (auto& x: vpn_tracker)
	{
		if (x.second.num_accessed > num_access_vpn)
		{
			num_access_vpn = x.second.num_accessed;
			most_accessed_vpn = x.first;
		}
	}

	long double page_fault_rate = (long double) total_faults / (long double) total_accessed;

	std::cout << "Number of pages accessed: " << vpn_tracker.size() << std::endl;
	//std::cout << "faults " << total_faults << " accessed " << total_accessed << std::endl;
	std::cout << "Page fault rate: " << page_fault_rate << std::endl;
	std::cout << "Most accessed VPN: " << most_accessed_vpn << std::endl;
	std::cout << "Number of bytes read: " << total_bytes_read << std::endl;
	std::cout << "Number of bytes written: " << total_bytes_write << std::endl;
	std::cout << "Memory footprint: " << (page_size * (1 + vpn_tracker.size())) << std::endl;

	delete [] in_memory;

	// uint64_t hex_value = 0;
	// std::cin >> std::hex >> hex_value;

	// std::cout << std::hex << get_VPN(hex_value) << std::endl;

	return 0;
}
Example #17
0
float Shape::get_value(float p_at) {

    int stream_size=get_stream_size();
    int prev = get_prev_index( p_at );
    int next = get_next_index( p_at );

    if (prev==-1)
        return 0;

    float val=0;
    float lfo_val=0;

    if (next==stream_size) {
        val=get_index_value( stream_size -1 );

    } else if (prev==next) { //we got an exact index, just return it, no interp. needed
        val=get_index_value(prev);

    } else {

        switch (interpolation) {

        case INTERP_NONE: {

            val=get_index_value(prev);

        }
        break;
        case INTERP_LINEAR: {

            float prev_pos=get_index_pos( prev);
            float prev_val=get_index_value( prev);


            float next_pos=get_index_pos( next);
            float next_val=get_index_value( next);

            val=prev_val+((p_at-prev_pos)*(next_val-prev_val))/(next_pos-prev_pos); //linear interpolation
        }
        break;
        case INTERP_CUBIC: {



            float prev_pos=get_index_pos( prev);
            float prev_val=get_index_value( prev);


            float pre_prev_val=(prev>0)?get_index_value( prev-1):prev_val;


            float next_pos=get_index_pos( next);
            float next_val=get_index_value( next);


            float post_next_val=((next+1)<get_stream_size())?get_index_value( next+1):next_val;

            float coeff=(p_at-prev_pos)/(next_pos-prev_pos);

            val = cubic_interpolate_points(pre_prev_val,prev_val,next_val,post_next_val,coeff);



        }
        break;
        }
    }

    return val;
}
Example #18
0
int
main( int argc, char **argv )
{
    /* these could also be declared as "void *" */
    simple_reader *srd, *sri;
    int index = -1;

    int nindex = 0, nindex_used = 0;
    int ndata = 0, nkeep = 0;

    if( argc < 3 ) {
        fprintf( stderr, "Usage: %s  FILE  INDEX  >  TRIMMED_FILE\n", argv[0] );
        fprintf( stderr, "  **NOTE: assumes sorted INDEX (monotonically increasing)\n" );
        return EXIT_FAILURE;
    }

    srd = sr_init( argv[1] );   /* input DATA file */
    sri = sr_init( argv[2] );   /* input INDEX file */
    fprintf( stderr, "TRIMMING:   %s\n", sr_filename( srd ) );
    fprintf( stderr, "FROM INDEX: %s\n", sr_filename( sri ) );

    /* loop over input data file */
    while( sr_readline( srd ) ) {
        char *line;

        line = sr_line( srd );

        if( sr_line_isempty( srd ) )
            continue;
        if( '#' == line[0] )
            continue;

        ndata += 1;
        /* ndata is the appropriate 1-based input index, comments and blank lines skipped */

        while( index < ndata ) {
            index = get_next_index( sri, index );
            if( index < 1 )
                break;
            nindex += 1;
        }

        if( ndata == index ) {
            nkeep += 1;
            fprintf( stdout, "%s\n", line );
        }

        if( sr_eof( sri ) )
            break;
    }

    nindex_used = nindex;

    /* check to see how much longer index is */
    while( !sr_eof( sri ) ) {
        index = get_next_index( sri, index );
        if( index < 1 )
            break;
        nindex += 1;
    }
    fprintf( stderr, "INDEX: used %d of %d entries\n", nindex_used, nindex );

    srd = sr_kill( srd );
    sri = sr_kill( sri );

    fprintf( stderr, "INPUT: kept %d of %d read (could be truncated due to short INDEX)\n",
             nkeep, ndata );

    return EXIT_SUCCESS;
}
Example #19
0
int
getopt (int argc, char *argv[], char *optstring)
{
  int fd, i;
  char *ptr = NULL;

  optarg = NULL;
  if (!optind) {                /* If not set to 1, set it to 1  */
    index = (char *) NULL;
    optind++;
  }

  fd = fileno (stderr);
  while (argv[optind]) {        /* Used for the write() function */
    if (!index) {               /* If no index string yet   */
      index = argv[optind];
      if (!index || *index != '-') {  /*no index and  */
        index = NULL;           /* no dash: done */
        return (EOF);
      }
      if (*(++index) == '-') {  /* Double dash? */
        get_next_index ();      /* Don't parse any more */
        return EOF;
      }
      if (!*(index))            /* Ready for next iteration */
        get_next_index ();

      continue;
    }

    i = (int) *index++;         /* Look at next character */
    if (i != ':') {             /* No command-line argument */
      ptr = strchr (optstring, i);  /* Is i in options list? */
      if (ptr && *(ptr + 1) == ':') {  /* Yes, plus argument  */
        if (*index)             /* If non-NULL index...  */
          optarg = index;       /* set optarg to pt to it */
        else                    /* else get the next argv */
          optarg = argv[++optind];

        get_next_index ();

        if (!optarg) {          /* Colon but no argument */
          i = EOF;
          if (opterr) {
            write (fd, argv[0], strlen (argv[0]));
            write (fd, ": option requires argument ", 27);
            write (fd, &i, sizeof (char));
            write (fd, "\r\n", 2);
            exit (1);
          }
        }
        return (i);             /* Must be an error */
      }
    }

    if (!(*index))              /* If a null character */
      get_next_index ();

    if (ptr)                    /* Return the command option */
      return (i);

    else {
      if (opterr) {             /* Not in the list */
        write (fd, argv[0], strlen (argv[0]));
        write (fd, ": illegal option ", 17);
        write (fd, &i, sizeof (char));
        write (fd, "\r\n", 2);
        exit (1);
      }
      return ('?');
    }
  }
  return EOF;                   /* None left */
}