Пример #1
0
        void Main()
        {
			vector<ListNode*> input = { NULL, createList({ 91, 71 }), createList({ 2 }), NULL, createList({ 34 }), createList({ 45 }), createList({ 96 }), createList({ 27, 37 }), NULL, createList({ 19 })};
			rehashing(input);
        }
Пример #2
0
/**
 * Create a new (empty) linked list, with default paramaters.
 *
 * @return          Ptr to the newly created list.
 */
LinkList *List_New(void)
{
    return createList(0, compareAddress);
}
Пример #3
0
//--------------------------------
// WAVファイルを読む
//--------------------------------
BOOL Sound::open(LPCSTR pName,LPCSTR pType)
{
	getWaveData()->open(pName,pType);
	createList(3);
	return TRUE;
}
Пример #4
0
Linked_list* createCircularList(char* value) {
    Linked_list* list = createList(value, NULL);
    list->next = list;
    return list;
}
Пример #5
0
Файл: main.c Проект: jbl5088/psu
int main(int argc, char *const argv[])
{
	puts("");
	argF = 0;				// -f argument: file - use file as a makefile
	argK = 0;				// -k argument: keep going - Continue as much as possible after error
	argN = 0;				// -n argument: Just print - print the commands that would be executed, don't execute
	argQ = 0;				// -q argument: question - don't run commands
	hasChanged = 0;
	bool hasTarget = 0;		// whether or not a target is specified from command line	

	char *makeFile;			// filename for the makefile being used.
	char *target;			// target to be used

	FILE *myFile;			// file to be used for reading

	int c;					// used for getopt loop

	while((c = getopt(argc, argv, "f:knq")) != -1)			// Collect command arguments
	{
		if(c == 'k') argK = 1;								// set K
		
		if(c == 'f' && argF == 0)							// set F (only if it has not been set before)
		{
			argF = 1;				
			makeFile = (char*)calloc(1, strlen(optarg) + 1);	// extract filename
			strcpy(makeFile, optarg);
		}

		if(c == 'n') argN = 1;								// set N
		if(c == 'q') argQ = 1;								// set Q

	}
	
	if(!argF)
	{
		struct stat fileBuf;
	
		if(stat("GNUmakefile", &fileBuf) == 0)
			makeFile = "GNUmakefile";
		else if(stat("makefile", &fileBuf) == 0)
			makeFile = "makefile";
		else if(stat("Makefile", &fileBuf) == 0)
			makeFile = "Makefile";
		else
		{
			printf("Could not find a default makefile.  Program terminating...\n");
			exit(0);
		}
	}
												

	if(argc > optind)										// if there are still arguments after the command options,
	{														// extract the target command from the argument list
		hasTarget = 1;									
		target = calloc(1, strlen(argv[optind]) + 1);
		strcpy(target, argv[optind]);
		originalTarget = target;
	}
	
	myFile = fopen(makeFile, "r");
	
	char line[MACROSIZE];
	char *makeString[MACROSIZE];
	int counter = 0;

	if( myFile != NULL)
	{

		while(fgets (line, sizeof line, myFile) != NULL)
		{
			makeString[counter] = calloc(1, strlen(line) + 1);
			strcpy(makeString[counter], line);
//			puts(makeString[counter]);
			counter ++;
		}
		
		fclose(myFile);
	}
	


	macI *firstMacro = calloc(1, sizeof(macI));
	firstMacro = createList(firstMacro, makeString, counter);

	for(int i = 0; i < counter; i++)
	{
		char *temp = subMacros(makeString[i], firstMacro);
		makeString[i] = realloc(makeString[i], strlen(temp) + 1);
		strcpy(makeString[i], temp);
		RemoveNewLines(makeString[i]);
		makeString[i] = RemoveStartSpaces(makeString[i]);

	}




	
	tItem *firstTarget = calloc(1, sizeof(tItem));
	firstTarget = insertTarget(firstTarget, FIRSTTARGET);
	

	switch(evaluateTarget(makeString, target, counter, hasTarget, firstTarget))
	{
		case 3:
//			puts("1");
			return 1;
			break;
		case 4:
//			puts("0");
			return 0;
			break;
		default:
			break;
	}
	

// ****************************************** FREE MEMORY *************************************
// ****************************************** FREE MEMORY *************************************
// ****************************************** FREE MEMORY *************************************

	if(hasChanged == 0) printf("mymake: `%s' is up to date.\n", originalTarget);

	if(argF) free(makeFile);


	if(hasTarget) free(target);


	for(int i = 0; i < counter; i ++)
		free(makeString[counter]);

	
	freeTargets(firstTarget);


	freeMacros(firstMacro);


}
Пример #6
0
int main(int argc, char** argv){

	//Error checks number of arguments;
	if (argc != 2){
		printf("Incorrect number of arguments! Must include file in input\n");
		return 1;
	}

	//Scans file and error checks existence of input file
	FILE* input = fopen(argv[1], "r");
	if(input == NULL){
		printf("File not found\n");
		return 1;
	}
	
	//Scans first line of file to find the number of vertices
	int vertices;
	fscanf(input, "%d", &vertices);
		
	//creates array of linked lists
	List* list[vertices];
	int i;
	for(i=0; i<vertices; i++){
		list[i] = NULL;
	}
	
	//scans file and places information into linked lists
	char buffer[MAX_LINE_SIZE];
    char* token;
    while(fgets(buffer, MAX_LINE_SIZE, input))
    {
		//Error checking
		if(buffer[strlen(buffer)-1] == '\n')
			buffer[strlen(buffer)-1] = '\0';

		//Skips tabs, new lines, and spaces
		token = strtok(buffer, " \n\r\t");

		//Places destinations into correct vertexes
		int vertex, destination;
		while(token != NULL)
		{
			sscanf(token, "(%d,%d)", &vertex, &destination);			
			list[vertex-1] = createList(list[vertex-1], destination-1);
			token = strtok(NULL, " \n\r\t");
		}
	}
	
	// Prints adjacency list
	printList(list, vertices);
	
	//Stores the distances of each node from 1
	printf("\nDistances:\n");
	int* distances = BFS(vertices, list);
	
	//Prints the distances from 1
	for(i=0; i<vertices; i++){
		if(distances[i] == -1)
			printf("The distance from %d to 1 is infinity\n", i+1);
		else
			printf("The distance from %d to 1 is %d\n", i+1, distances[i]);
	}
	
	//Gives start and end times
	int* start = malloc(sizeof(int)*vertices);
	Times* end = malloc(sizeof(Times)*vertices);
	DFS(list, vertices, 0, &start, &end);
	
	/*printf("\nStart and end times:\n");
	for(i=0; i<vertices; i++){
		printf("start time of %d is %d\n", i+1, start[i]);
		printf("end time of %d is %d\n", i+1, end[i].end);
	}
	
	
	int begin;
	SCC(list, vertices, start, end);
	*/
	close(input);
	
	return 0;
}
Пример #7
0
//Exact k-NN search with the RBC
void searchExactK(matrix q, matrix x, matrix r, rep *ri, unint **NNs, real **dNNs, unint K){
  unint i, j, k;
  unint *repID = (unint*)calloc(q.pr, sizeof(*repID));
  real **dToReps = (real**)calloc(q.pr, sizeof(*dToReps));
  for(i=0; i<q.pr; i++)
    dToReps[i] = (real*)calloc(K, sizeof(**dToReps));
  intList *toSearch = (intList*)calloc(r.pr, sizeof(*toSearch));
  for(i=0;i<r.pr;i++)
    createList(&toSearch[i]);
  int nt = omp_get_max_threads();

  float ***d;  //d is indexed by: thread, cache line #, rep #
  d = (float***)calloc(nt, sizeof(*d));
  for(i=0; i<nt; i++){
    d[i] = (float**)calloc(CL, sizeof(**d));
    for(j=0; j<CL; j++){
      d[i][j] = (float*)calloc(r.pr, sizeof(***d));
    }
  }
  
  heap **hp;
  hp = (heap**)calloc(nt, sizeof(*hp));
  for(i=0; i<nt; i++){
    hp[i] = (heap*)calloc(CL, sizeof(**hp));
    for(j=0; j<CL; j++)
      createHeap(&hp[i][j],K);
  }
  
#pragma omp parallel for private(j,k)
  for(i=0; i<q.pr/CL; i++){
    unint row = i*CL;
    unint tn = omp_get_thread_num();
    heapEl newEl; 

    for( j=0; j<r.r; j++ ){
      for(k=0; k<CL; k++){
	d[tn][k][j] = distVec(q, r, row+k, j);
	if( d[tn][k][j] < hp[tn][k].h[0].val ){
	  newEl.id = j;
	  newEl.val = d[tn][k][j];
	  replaceMax( &hp[tn][k], newEl );
	}
      }
    }
    for(j=0; j<r.r; j++ ){
      for(k=0; k<CL; k++ ){
	real minDist = hp[tn][k].h[0].val;
	real temp = d[tn][k][j];
	if( row + k<q.r && minDist >= temp - ri[j].radius && 3.0*minDist >= temp ){
#pragma omp critical
	  {
	    addToList(&toSearch[j], row+k);
	  }
	}
      }
    }
    for(j=0; j<CL; j++)
      reInitHeap(&hp[tn][j]);
  }

  for(i=0; i<r.r; i++){
    while(toSearch[i].len % CL != 0)
      addToList(&toSearch[i],DUMMY_IDX);
  }

  bruteListK(x,q,ri,toSearch,r.r,NNs,dNNs,K);

  
  //clean-up
  for(i=0; i<nt; i++){
    for(j=0; j<CL; j++)
      destroyHeap(&hp[i][j]);
    free(hp[i]);
  }
  free(hp);
  for(i=0;i<r.pr;i++)
    destroyList(&toSearch[i]);
  free(toSearch);
  free(repID);
  for(i=0;i<q.pr; i++)
    free(dToReps[i]);
  free(dToReps);
  for(i=0; i<nt; i++){
    for(j=0; j<CL; j++)
      free(d[i][j]); 
    free(d[i]);
  }
  free(d);
}
Пример #8
0
int main()
{
	LIST *list1;
	list1=createList(10);
	insertAtHead(list1,1);
	insertAtHead(list1,2);
	printList(list1);

	insertAtTail(list1,2);
	insertAtTail(list1,3);
	insertAtTail(list1,4);
	insertAtTail(list1,5);
	insertAtTail(list1,6);
	insertAtTail(list1,7);
	insertAtTail(list1,8);
	insertAtTail(list1,9);
	insertAtTail(list1,10);
	insertAtTail(list1,11);
	printList(list1);

	int res, j;
	for(j=0; j<12; j++)
	{
		res=deleteFromHead(list1);
		if(res>0)
			printf("\nDeleted:\t%d",res);
	}
	printList(list1);

	for(j=0; j<12; j++)
	{
		insertAtHead(list1,j+1);
	}
	printList(list1);

	for(j=0; j<12; j++)
	{
		insertAtTail(list1,j+1);
	}
	printList(list1);

	printf("\nDeleted:\t%d",deleteFromHead(list1));
	printf("\nDeleted:\t%d",deleteFromHead(list1));
	printf("\nDeleted:\t%d",deleteFromHead(list1));
	printList(list1);
	printf("\nDeleted:\t%d",deleteFromTail(list1));
	printf("\nDeleted:\t%d",deleteFromTail(list1));
	printf("\nDeleted:\t%d",deleteFromTail(list1));
	printList(list1);

	for(j=0; j<12; j++)
	{
		res=deleteFromTail(list1);
		if(res>0)
			printf("\nDeleted:\t%d",res);
	}
	printList(list1);

	for(j=0; j<12; j++)
	{
		insertAtTail(list1,j+1);
	}
	printList(list1);

	printf("\n");
	return 0;
}
Пример #9
0
void list_test()
{
	int comps, mergecomps;
	list_t *list_a, *list_b, *list_c;
	test_t *ptr_a, *ptr_b, *ptr_c, *ptr_d, *ptr_e, *ptr_f;
	
	/* createList () Test */
	fprintf(stdout, "TEST: createList () \t\t... \t");
	list_a = createList(5);
	(list_a != NULL && list_a->size == 5) ?
		fprintf(stdout, "OK\n") :
		fprintf(stdout, "ERROR\n");
		
	/* destroyList () Test */	
	fprintf(stdout, "TEST: destroyList () \t\t... \t");	
	destroyList(list_a);
	(list_a == NULL) ?
		fprintf(stdout, "OK\n") :
		fprintf(stdout, "ERROR: List of size %d still exists\n", list_a->size);
	
	/* insert() Test */
	
	list_b = createList(3);
	fprintf(stdout, "LIST: size : %d, items : %d, lock : %d\n", list_b->size, list_b->items, list_b->lock);
	ptr_a = (test_t*)safe_malloc(sizeof(test_t));
	ptr_a->value = 8;
	strcpy(ptr_a->name, "Tester1");
	ptr_b = (test_t*)safe_malloc(sizeof(test_t));
	ptr_b->value = 2;
	strcpy(ptr_b->name, "Tester2");
	insertItem(list_b, ptr_a);
	insertItem(list_b, ptr_b);
	fprintf(stdout, "LIST: size : %d, items : %d, lock : %d\n", list_b->size, list_b->items, list_b->lock);
	fprintf(stdout, "TEST: insertItem () \t\t... \t");
	(list_b->items == 2) ?
		fprintf(stdout, "OK\n") :
		fprintf(stdout, "ERROR\n");
	fprintf(stdout, "STATUS: struct from list \n"
					"Struct 1 : %d, %s\n"
					"Struct 2 : %d, %s\n",
					((test_t*)list_b->data[0])->value, ((test_t*)list_b->data[0])->name,
					((test_t*)list_b->data[1])->value, ((test_t*)list_b->data[1])->name);
	
	/* removeItem () Test */
	fprintf(stdout, "TEST: removeItem () \t\t... \t");
	removeItem(list_b, 1);
	(list_b->items == 1) ?
		fprintf(stdout, "OK\n") :
		fprintf(stdout, "ERROR\n");
	
	/* sortList () Test */
	fprintf(stdout, "TEST: sortList () \t\t... \t");
	ptr_b = (test_t*)safe_malloc(sizeof(test_t));
	ptr_b->value = 2;
	strcpy(ptr_b->name, "Tester2");
	ptr_c = (test_t*)safe_malloc(sizeof(test_t));
	ptr_c->value = 1;
	strcpy(ptr_c->name, "Tester3");
	insertItem(list_b, ptr_b);
	insertItem(list_b, ptr_c);
	comps = sortList(list_b, &compareTest);
	(comps > 0) ?
		fprintf(stdout, "OK Comparisons : %d\n", comps) :
		fprintf(stdout, "ERROR\n");
	fprintf(stdout, "STATUS: struct from list \n"
				"Struct 1 : %d, %s\n"
				"Struct 2 : %d, %s\n"
				"Struct 3 : %d, %s\n",
				((test_t*)list_b->data[0])->value, ((test_t*)list_b->data[0])->name,
				((test_t*)list_b->data[1])->value, ((test_t*)list_b->data[1])->name,
				((test_t*)list_b->data[2])->value, ((test_t*)list_b->data[2])->name);
				
	/* mergeLists () Test */
	fprintf(stdout, "TEST: mergeLists () \t\t... \t");
	list_a = createList(3);
	list_c = createList(3);
	ptr_d = (test_t*)safe_malloc(sizeof(test_t));
	ptr_d->value = 9;
	strcpy(ptr_d->name, "Tester4");
	ptr_e = (test_t*)safe_malloc(sizeof(test_t));
	ptr_e->value = 3;
	strcpy(ptr_e->name, "Tester5");
	ptr_f = (test_t*)safe_malloc(sizeof(test_t));
	ptr_f->value = 1;
	strcpy(ptr_f->name, "Tester6");
	insertItem(list_a, ptr_d);
	insertItem(list_a, ptr_e);
	insertItem(list_a, ptr_f);
	comps = sortList(list_a, &compareTest);
	mergecomps = mergeLists(list_a, list_b, list_c, &compareTest);
	(list_a->items < 3 && list_b->items < 3) ?
		fprintf(stdout, "OK Sort Comparisons : %d, Merge Comparisons: %d\n", comps, mergecomps) :
		fprintf(stdout, "ERROR\n");
	fprintf(stdout, "STATUS: Output from merge \n"
				"Struct 1 : %d, %s\n"
				"Struct 2 : %d, %s\n"
				"Struct 3 : %d, %s\n",
				((test_t*)list_c->data[0])->value, ((test_t*)list_c->data[0])->name,
				((test_t*)list_c->data[1])->value, ((test_t*)list_c->data[1])->name,
				((test_t*)list_c->data[2])->value, ((test_t*)list_c->data[2])->name);
	destroyList(list_c);
	list_c = createList(3);
	fprintf(stdout, "LIST: size : %d, items : %d, lock : %d\n", list_c->size, list_c->items, list_c->lock);
	mergecomps = mergeLists(list_a, list_b, list_c, &compareTest);
	fprintf(stdout, "LIST: size : %d, items : %d, lock : %d\n", list_c->size, list_c->items, list_c->lock);
	fprintf(stdout, "STATUS: Output from merge \n"
				"Struct 1 : %d, %s\n"
				"Struct 2 : %d, %s\n"
				"Struct 3 : %d, %s\n",
				((test_t*)list_c->data[0])->value, ((test_t*)list_c->data[0])->name,
				((test_t*)list_c->data[1])->value, ((test_t*)list_c->data[1])->name,
				((test_t*)list_c->data[2])->value, ((test_t*)list_c->data[2])->name);
}
Пример #10
0
int main(int argc, char *argv[]) {
   char line,c;
   int i,j,e1, e2;
   edge e;
   createList(&edgeList, sizeof(edge), NULL);
   pthread_t thread_satcnf, thread_approx_1, thread_approx_2;
      
   loop:while(scanf(" %c", &line) != EOF) {
      switch(line) {
         case 'V':
            scanf(" %d", &numNodes);

            if(numNodes <= 0) {
               fprintf(stderr,"Error: Invalid number of vertices: %d!\n", numNodes);
               goto loop;
            }

            if(edgeList.length != 0) {
               destroy(&edgeList);             
            }

            break;
         case 'E':
            scanf(" %c", &c);

            while(c != '}') {
               if(!scanf(" <%d,%d>", &e1,&e2)) goto loop;

               if( (e1 >= numNodes || e1 < 0) || (e2 >= numNodes || e2 < 0)) {
                  fprintf(stderr,"Error: Invalid edge <%d,%d>!\n", e1, e2);
                  destroy(&edgeList);
                  goto loop;
               }

               e.p1 = e1;
               e.p2 = e2;
               append(&edgeList,&e);
               scanf("%c", &c); //scan ',' or '}'
            }

            thread_function_args thread_args[N];

            /*initialize parameters for each thread function*/
            for(i=0; i<N; i++) {
               thread_args[i].numNodes = numNodes;
               thread_args[i].edgeList = &edgeList;
               thread_args[i].vc = NULL;
            }

            int iter = 1;

            #ifdef DEBUG
               iter = 10;
               double ratio1,ratio2;
               double *runTimeSatCnf = (double *)malloc(iter*sizeof(double));
               double *runTimeApprox1 = (double *)malloc(iter*sizeof(double));
               double *runTimeApprox2 = (double *)malloc(iter*sizeof(double));
            #endif

            for(j=0; j<iter; j++) {
               pthread_create(&thread_satcnf, NULL, &sat_cnf, &thread_args[0]);
               pthread_create(&thread_approx_1, NULL, &approx1, &thread_args[1]);
               pthread_create(&thread_approx_2, NULL, &approx2, &thread_args[2]);

               pthread_join(thread_satcnf, NULL);
               pthread_join(thread_approx_1, NULL);
               pthread_join(thread_approx_2, NULL);   

               #ifdef DEBUG
                  runTimeSatCnf[j] = thread_args[0].cputime;
                  runTimeApprox1[j] = thread_args[1].cputime;
                  runTimeApprox2[j] = thread_args[2].cputime;
               #endif
            }

            #ifdef DEBUG
               ratio1 = thread_args[1].vcSize / (double) thread_args[0].vcSize;
               ratio2 = thread_args[2].vcSize / (double) thread_args[0].vcSize; 

               for(j=0; j<iter; j++) {
                  //printf("%f,%f\n", runTimeApprox1[j],runTimeApprox2[j]);
                  printf("%f,%f,%f\n", runTimeSatCnf[j],runTimeApprox1[j],runTimeApprox2[j]);
                  fflush(stdout);
               }
               printf("%f,%f\n", ratio1,ratio2);
               fflush(stdout);

               for(i=0; i<N; i++) {
                  free(thread_args[i].vc);
               }
               free(runTimeSatCnf);
               free(runTimeApprox1);
               free(runTimeApprox2);
            #else
               const char *name[N] = {"CNF-SAT-VC", "APPROX-VC-1", "APPROX-VC-2"};
                  
               for(i=0; i<N; i++) {
                  printVC(thread_args[i].vcSize, thread_args[i].vc, name[i]);
                  free(thread_args[i].vc);
               }
            #endif

            break;   
      }
   }
   destroy(&edgeList);
}
Пример #11
0
// Method that stores the individual lines from questions_file 
//	to be stored in a Linked_List via createList()	
void Process_Questions()
{
	char c;
	
	int lineBufferSize = 100;
	int numLinesBufferSize = 20;
	char* buffer = (char*)(malloc(lineBufferSize * sizeof(char)));
	allLines = (char**)(malloc(numLinesBufferSize * sizeof(char*)));
		// Assuming there will be enough memory for initalization.

	int numLines = 0;	
	int i = 0;

	while((c = getc(questions_file)) != EOF)	
	{
		if(c == '\n')
		{

			numLines++;
			if(numLines == numLinesBufferSize - 1)
			{
				numLinesBufferSize = numLinesBufferSize * 2;

				allLines = (char**)(realloc(allLines, (numLinesBufferSize * sizeof(char*))));
				if(allLines == NULL)
				{
					fprintf(stderr, "ERROR: Out of Memory\n");
					exit(1);
				}
			}

			// ??? Instead of lineBufferSize
			(* (allLines + numLines-1)) = (char*)(malloc(lineBufferSize * sizeof(char))); 
			memcpy((* (allLines + (numLines-1))), buffer, lineBufferSize);

			// Reset Buffer in order to eliminate overlap of facts	
			memset(buffer, 0, lineBufferSize);

			// Reset Index for char placement
			i = 0;
		}
		else
		{
			// Realloc Memory if more space to store the line is needed
			if(i == lineBufferSize - 1)
			{
				lineBufferSize = lineBufferSize * 2;
				
				buffer = (char*)(realloc(buffer, (lineBufferSize * sizeof(char))));	
				if(buffer == NULL)
				{
					fprintf(stderr, "ERROR: Out of Memory\n");
					exit(1);
				}
			}

			buffer[i] = c;
			i++;
		}
	}	

	createList(lineBufferSize, numLines);
	getFacts();

	free(buffer);
	free(allLines);
}
Пример #12
0
int main(int argc, char *argv[]) 
{
	
		char *line;
		char *prompt = "myshell>";
		char *envPrompt = "DASH_PROMPT";
		char *args[2048];
		char *str;
		char *multiCmd[2048];
				
		int i=0;
		int flag;
	        int jobid;
		int code;
		int fd1,fd2;	
					
		tcpid = getpgrp();
		
		ObjectPtr myObj;
		NodePtr node;

		lst = createList(getKey,toString,freeObject);  // Creating a List
			
		prompt = getenv(envPrompt);

		if(prompt == NULL)
			prompt = "myshell>";
		
		using_history();

		if(signal(SIGINT,signalHandling) == SIG_ERR){}
		
		if(signal(SIGTSTP,signalHandling) == SIG_ERR){}

		if(signal(SIGTTOU,SIG_IGN)==SIG_ERR){}
		if(signal(SIGCHLD,SIG_DFL)==SIG_ERR){}

		if((argc == 2) && (strcmp(argv[1],"-v")==0))
		{
			printf("%s\n",svn_version());
			exit(0);
		}
			
		code = sigsetjmp(env,TRUE);
				
		while ((line=readline(prompt))) 		// Reading Input
		{
			if(line==NULL)
			{	
				printf("\n read line failed \n");
				continue;
			}
			
		      	add_history(line);
 
			str = (char *)mymalloc(sizeof(char)*(strlen(line)+1));
			strcpy(str,line);
											
			if(str[0] == '&' || str[0] == ';')
			{
				printf("dash: syntax error near unexpected token %c \n",str[0]);
				freeVar(line,str,args);
				continue;
			}
			
			while((pid = waitpid(-1,NULL,WNOHANG)) > 0)
			{
				node = search(lst,pid);
				((ObjectPtr)(node->obj))->jobStatus = 0;
				printf("%s\n",(*toString)(node->obj));
				removeNode(lst,node);
			}
			
						
			if(checkMultiCmd(str, multiCmd)== -1)
				continue;
			
			while(multiCmd[i])			
			{
				flag = searchAmp(multiCmd[i]);	// Function to check if there is an '&' in the Command
				struct IORedirect *ior = tokenize(multiCmd[i],args);
				if((int)ior == -1)
				break;		       // Parsing the Command that needs to be executed
				
				if(exitLogout(multiCmd[i]))	// Function to check Exit and Logout Commands
				{
					if(checkStoppedJobs())
					{
						//memset(multiCmd,0,sizeof(multiCmd));
						break;
					}
					else
					{
						freeVar(line,str,args);
						freeList(lst);
						memset(multiCmd,'\0',sizeof(multiCmd));
						myfree(ior);
						exit(0);
					}
				}
				if(checkEOF(multiCmd[i]))			// Function to check EOF
				{
					freeVar(line,str,args);
					memset(multiCmd,'\0',sizeof(multiCmd));	
					freeList(lst);
					myfree(ior);
					exit(0);
				}
				if(checkEmptyCmd(multiCmd[i]))		// Function to Check if Enter Key is pressed
				break;
			
			
				if((strcmp(args[0],"cd")==0) && (flag == FALSE))  // Function to check if 'cd' command is used
				{
					chgDir(args);
					break;
				}
			
				if((strcmp(args[0],"jobs")==0) && (flag == FALSE)) // Function to check if 'jobs' command is used
				{
					jobsCmd();
					break;
				}
			
				if(strcmp(args[0],"history")==0)
        		        {
                     	        	printHistory(args, str, flag);
	                                break;
       			        }
	
				if((strcmp(args[0],"bg") == 0) && (flag == FALSE))
				{
					bgCmd(args);
					break;
				}
					
				if((strcmp(args[0],"fg")==0) && (flag == FALSE))
				{
					fgCmd(args);
					break;
				}
			
				if(ampCount(multiCmd[i]))
				{
					printf(" dash: syntax error near unexpected token '&' \n");
					break;
				}
				if ( (pid = fork()) < 0)		// Forking a Process
				err_sys("fork error");
					
				else if (pid == 0) 
				{		
					struct stat buf;
					/* child */
    				     	if(flag == TRUE)
					{
						if(setpgid(0,0)!=0)
						perror("setpid() error");
					
						if(tcsetpgrp(0,tcpid)!=0)
						perror("tcsetpgrp() error");
					}
				
					if(ior->input != NULL)
					{
					
						if((fd1 = stat(ior->input,&buf))==-1){
                	                        printf("dash: %s file does not exist\n",ior->input);
                       			        break;
                                        	}

                                        	if((fd1= access(ior->input,R_OK))==-1){
                                   	        printf("dash: %s permission denied\n",ior->input);
                                        	break;
                                        	}
		                                if((fd1 = open(ior->input,O_RDONLY))==-1){
                		                printf("dash: %s inpRedirect opening failed\n",ior->input);
                                	        break;
                               		        }
                                      		else {
							close(0);
					 		dup(fd1);
						}
					}
	
					if(ior->output != NULL)				
					{
						/*if((fd1= access(ior->output,W_OK))==-1){
                        	                printf("dash: %s permission denied",ior->output);
                                	        break;}*/
                                        	if((fd2=open(ior->output,O_WRONLY|O_TRUNC|O_CREAT,S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH ))==-1){
                                        	printf("dash: %s outRedirect opening failed\n",ior->output);
                                       		break;}
                                       		else{
							close(1);
							dup(fd2);
						}
					}
					if (setpgid(0,0) != 0)
       		         		perror("setpgid() error");

			                if (tcsetpgrp(0, getpid()) != 0)
                			perror("tcsetpgrp() error");
					
					execvp(args[0],args);
					err_ret("couldn't execute: %s", line);
					exit(127);
				}
				if(flag == TRUE && (*args[0] !='\0'))
				{
					jobid = assignJobId();
					myObj = createObject(pid,multiCmd[i],jobid,1); 
					node = createNode(myObj);
					addAtRear(lst,node);
				
					printf("[%d] %d %s &\n",((ObjectPtr)(node->obj))->jobId, ((ObjectPtr)(node->obj))->key, ((ObjectPtr)(node->obj))->data);
					
					if ( (pid = waitpid(pid, &status, WNOHANG)) < 0)
					err_sys("waitpid error");
					if((tcsetpgrp(0,tcpid))!=0)
					perror("tcsetgroup error");
				
				}
				else
				{
				
					if ( (pid = waitpid(pid, &status, 0|WUNTRACED)) < 0)
					err_sys("waitpid error");
					if((tcsetpgrp(0,tcpid))!=0)
					perror("tcsetgroup error");
					if(WIFSTOPPED(status))
					{
						jobid = assignJobId();
                				myObj = createObject(pid,line,jobid,2);
                				node = createNode(myObj);
                				addAtRear(lst,node);
                				printf("%s\n",(*toString)(node->obj));
					}
			
				}
			i++;
			}
			freeVar(line,str,args);
			memset(multiCmd,'\0',sizeof(multiCmd));
			i=0;
		}
		freeList(lst);
		exit(0);
	}
Пример #13
0
void processLine(char* line){
    int index;
    index = 0;
    char holder[30];
    
    int i;
    for (i = 0; i < 30; i++){ holder[i] = '\0';}
    
    removeSpaces(line);
    if(line[0] == '{'){
        index++;
        
        while(line[index] != ',')
        {
            holder[index-1] = line[index];
            index++;
        }
    
        if(head == NULL){
            createList(holder);
        }
        else{
            addToList(holder);
        }
        
        //printf("%s", curr->name);
    }
    
    while(line[index] != '\0'){
        //skip comma
        if(line[index] == ','){
            index++;
        }
        //skip
        else if(line[index] == '['){
            index++;
        }
        else if(line[index] == '('){
            index++;
            char xBuffer[100];
            
            for (i=0; i<100;++i) {xBuffer[i]='\0';}
            
            int size;
            size = 0;

            //x value
            while(line[index] != ','){
                xBuffer[size] = line[index];
                index++;
                size++;
            }
            double xPoint=(atof(xBuffer));
            curr->p.points[curr->p.size].x= xPoint;
            
            index++;
            
            char yBuffer[100];
            
            for (i=0; i<100;++i) {yBuffer[i]='\0';}

            size = 0;

            //y value
            while(line[index] != ')'){
                yBuffer[size] = line[index];
                index++;
                size++;
            }
            double yPoint=(atof(yBuffer));
            curr->p.points[curr->p.size].y= yPoint;
            curr->p.size++;
            
            //printf("%s\n", curr->name);
            //printf("(%lf, %lf)\n", curr->p.points[0].x, curr->p.points[0].y);
        }
        else{
            index++;
        }
        
    }
    
   // printf("%s", line);
}
Пример #14
0
void init(void) {

  texturesList = createList();
  musicList = createList();
  fontList = createList();
  black.r = 0; black.g = 0; black.b = 0;
  white.r = 255; white.g = 255; white.b = 255;

 // Initialize SDL2
  if( SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) {
    fprintf(stderr, "Unable to initialize SDL: %s \n", SDL_GetError());
    quit(1);
  }

  // Display available audio device
  int count = SDL_GetNumAudioDevices(0), i;
  for (i = 0; i < count; ++i ) {
    fprintf(stderr, "Audio device %d: %s\n", i, SDL_GetAudioDeviceName(i, 0));
  }

  // init sound
  int audio_rate = 22050;
  Uint16 audio_format = AUDIO_S16SYS;
  int nb_audio_channels = 4;
  int audio_buffers = 4096;

  if(Mix_OpenAudio(audio_rate, audio_format, nb_audio_channels, audio_buffers) != 0) {
    fprintf(stderr, "Unable to initialize audio: %s\n", Mix_GetError());
    quit(1);
  }

  // Get desktop information
  if (SDL_GetDesktopDisplayMode(0, &displaymode) < 0) {
    fprintf(stderr, "Could not get display mode: %s\n", SDL_GetError());
    quit(1);
  }

  viewport.x = 0;
  viewport.y = 0;
  viewport.w = MIN(displaymode.w, 800);
  viewport.h = MIN(displaymode.h, 600);

  // Create an application window with the following settings:
  window = SDL_CreateWindow(
      "Game example",                    //    window title
      SDL_WINDOWPOS_UNDEFINED,           //    initial x destination
      SDL_WINDOWPOS_UNDEFINED,           //    initial y destination
      viewport.w,                        //    width, in pixels
      viewport.h,                        //    height, in pixels
      SDL_WINDOW_SHOWN                   //    flags
  );

  // Check that the window was successfully made
  if(window==NULL){   
      // In the event that the window could not be made...
      fprintf(stderr, "Could not create window: %s\n", SDL_GetError());
      quit(1);
  }
  
  renderer = SDL_CreateRenderer(window, -1, 0); // SDL_RENDERER_PRESENTVSYNC
  if (renderer < 0) {
      fprintf(stderr, "Could not create renderer: %s\n", SDL_GetError());
      quit(1);
  }

  SDL_RenderGetViewport(renderer, &viewport);

  if (TTF_Init() == -1) {
      fprintf(stderr, "Unable to initialize SDL_ttf: %s \n", TTF_GetError());
      quit(1);
  }

}
Пример #15
0
void test_add_to_list_string() {
  LinkedList list = createList();
  char value[] = "saran";
  assert(add_to_list(&list, &value) == 1);
  assert(add_to_list(&list, &value) != 0);
};
Пример #16
0
NodeL *getListFromTree(NodeT *root)
{
    NodeL *head=NULL;
    createList(root,&head);
    return head;
}
Пример #17
0
void test_empty_create_list() {
  LinkedList list = createList();
  assert(list.length == 0);
  assert(list.head == NULL);
  assert(list.tail == NULL);
};
Пример #18
0
void test_createList(){
	LinkedList list = createList();
	assert(0==list.length);
}
Пример #19
0
//Exact 1-NN search with the RBC.
void searchExact(matrix q, matrix x, matrix r, rep *ri, unint *NNs, real *dToNNs){
  unint i, j, k;
  unint *repID = (unint*)calloc(q.pr, sizeof(*repID));
  real *dToReps = (real*)calloc(q.pr, sizeof(*dToReps));
  intList *toSearch = (intList*)calloc(r.pr, sizeof(*toSearch));
  for(i=0;i<r.pr;i++)
    createList(&toSearch[i]);
  int nt = omp_get_max_threads();
  
  float ***d;  //d is indexed by: thread, cache line #, rep #
  d = (float***)calloc(nt, sizeof(*d));
  for(i=0; i<nt; i++){
    d[i] = (float**)calloc(CL, sizeof(**d));
    for(j=0; j<CL; j++){
      d[i][j] = (float*)calloc(r.pr, sizeof(***d));
    }
  }
  
#pragma omp parallel for private(j,k) //schedule(dynamic)
  for(i=0; i<q.pr/CL; i++){
    unint row = i*CL;
    unint tn = omp_get_thread_num();
    
    unint minID[CL];
    real minDist[CL];
    for(j=0;j<CL;j++)
      minDist[j] = MAX_REAL;
    
    for( j=0; j<r.r; j++ ){
      for(k=0; k<CL; k++){
	d[tn][k][j] = distVec(q, r, row+k, j);
	if(d[tn][k][j] < minDist[k]){
	  minDist[k] = d[tn][k][j]; //gamma
	  minID[k] = j;
	}
      }
    }

    for( j=0; j<CL; j++ )
      dToReps[row+j] = minDist[j];

    for(j=0; j<r.r; j++ ){
      for(k=0; k<CL; k++ ){
	real temp = d[tn][k][j];
	if( row + k<q.r && minDist[k] >= temp - ri[j].radius && 3.0*minDist[k] >= temp ){
#pragma omp critical
	  {
	    addToList(&toSearch[j], row+k);
	  }
	}
      }
    }
  }
  for(i=0; i<r.r; i++){
    while(toSearch[i].len % CL != 0)
      addToList(&toSearch[i],DUMMY_IDX);
  }

  bruteList(x,q,ri,toSearch,r.r,NNs,dToReps);
  
  for(i=0; i<q.r; i++)
    dToNNs[i] = dToReps[i];
  
  for(i=0;i<r.pr;i++)
    destroyList(&toSearch[i]);
  free(toSearch);
  free(repID);
  free(dToReps);
  for(i=0; i<nt; i++){
    for(j=0; j<CL; j++)
      free(d[i][j]); 
    free(d[i]);
  }
  free(d);
}
Пример #20
0
GLvoid DrawScene() { // Desenhar cena
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Limpa a tela e o Depth Buffer

    glMatrixMode(GL_PROJECTION); //define que matriz é de projeção
    glLoadIdentity();
    gluPerspective(50, 1.0, 0.1, width*3); //define projeção perspectiva

    if (!idList) createList();
        glCallList(idList); //desenha paredes

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(obsX, obsY, obsZ, //posição da câmera
              centerX, centerY, centerZ, //para onde câmera aponta
              0.0, 10.0, 0.0); //vetor view-up

    //desenha objetos
    glPushMatrix();
        glTranslatef(place->objetos[0].vertice.x, place->objetos[0].vertice.y, place->objetos[0].vertice.z);
        DesenhaObjeto(place->objetos[0].objeto);
    glPopMatrix();

    if (showEspada){ //só desenha espada quando flag estiver ativa
        glPushMatrix();
            glTranslatef(place->objetos[1].vertice.x+tx, place->objetos[1].vertice.y, place->objetos[1].vertice.z);
            glRotatef(thetaE+5, 0.0, 0.0, 1.0);
            glRotatef(thetaE, 1.0, 0.0, 0.0);
            glScalef(130.0f, 130.0f, 130.0f);
            DesenhaObjeto(place->objetos[1].objeto);
        glPopMatrix();
    }

    glEnable(GL_BLEND); //habilita transparência
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //define os fatores de blending para RGBA

    glMaterialfv(GL_FRONT, GL_EMISSION, emission); //ativa emissão de luz simulada
    glColor4f(1,1,1,0.9); //Transparência com luz branca e fator de 0.9
    glPushMatrix(); //desenha luzes simuladas
        glBegin(GL_POLYGON);
            glVertex3f(width-10, height-100, -width+250);
            glVertex3f(width-10, height-250, -width+250);
            glVertex3f(width-10, height-250, -width/2);
            glVertex3f(width-10, height-100, -width/2);
        glEnd();
        glBegin(GL_POLYGON);
            glVertex3f(10, height-100, -width+250);
            glVertex3f(10, height-250, -width+250);
            glVertex3f(10, height-250, -width/2);
            glVertex3f(10, height-100, -width/2);
        glEnd();
    glPopMatrix();

    glColor4f(1,1,1,0.5); //define luz branca e transparência de 0.5
    glMaterialfv(GL_FRONT, GL_EMISSION, no_emission); //desativa a emissão para os cubos
    glPushMatrix(); //desenha cubos sobre a mesa
        glTranslated(width/2,220,-250);
        glScalef(2.5f, 0.8f, 1.0f);
        glutSolidCube(50);
    glPopMatrix();
    glPushMatrix(); //cubo de cima
        glTranslated(width/2,260+ty,-250+tz);
        glRotatef(thetaC, 1.0, 0.0, 0.0);
        glScalef(2.5f, 0.8f, 1.0f);
        glutSolidCube(50);
    glPopMatrix();
    glDisable(GL_BLEND); //desabilita transparência

    glFlush(); // Processa as rotinas do OpenGL o quanto antes
}
Пример #21
0
Linked_list* insertAfter(void* value, Linked_list* list) {
    Linked_list* node = createList(value, list->next);
    list->next = node;
    return node;
}
Пример #22
0
void test_add_to_list_int() {
  LinkedList list = createList();
  int value = 3;
  assert(add_to_list(&list, &value) == 1);
  assert(add_to_list(&list, &value) != 0);
};
Пример #23
0
////////////////////////////////////////////////////////////
// ---------------------------------------------------------
WI_StringList::WI_StringList ( WI_Int size )
{
	createList ( size );
}
Пример #24
0
void test_add_to_list_float() {
  LinkedList list = createList();
  float value = 1.023;
  assert(add_to_list(&list, &value) == 1);
  assert(add_to_list(&list, &value) != 0);
};
Пример #25
0
void initWorkerProcess(struct workerProcess *worker, char *worker_name)
{
    struct configuration *conf;
    int i;
    struct app *app;
    struct moduleAttr *module;

    if (Server.stat_fd != 0)
        close(Server.stat_fd);
    setProctitle(worker_name);
    worker->pid = getpid();
    worker->ppid = getppid();
    worker->alive = 1;
    worker->start_time = Server.cron_time;
    worker->worker = spotWorker(worker_name);
    worker->master_stat_fd = 0;
    ASSERT(worker->worker);
    worker->stats = NULL;
    initWorkerSignals();
    worker->center = eventcenterInit(WHEAT_CLIENT_MAX);
    if (!worker->center) {
        wheatLog(WHEAT_WARNING, "eventcenter_init failed");
        halt(1);
    }
    if (createEvent(worker->center, Server.ipfd, EVENT_READABLE, acceptClient,  NULL) == WHEAT_WRONG)
    {
        wheatLog(WHEAT_WARNING, "createEvent failed");
        halt(1);
    }

    // It may nonblock after fork???
    if (wheatNonBlock(Server.neterr, Server.ipfd) == NET_WRONG) {
        wheatLog(WHEAT_WARNING, "Set nonblock %d failed: %s", Server.ipfd, Server.neterr);
        halt(1);
    }

    module = NULL;
    conf = getConfiguration("protocol");
    if (conf->target.ptr) {
        module = getModule(PROTOCOL, conf->target.ptr);
        if (module && getProtocol(module)->initProtocol() == WHEAT_WRONG) {
            wheatLog(WHEAT_WARNING, "init protocol failed");
            halt(1);
        }
    }
    if (!module) {
        wheatLog(WHEAT_WARNING, "find protocol %s failed", conf->target.ptr);
        halt(1);
    }
    worker->protocol = getProtocol(module);

    StatTotalClient = getStatItemByName("Total client");
    gettimeofday(&Server.cron_time, NULL);
    if (worker->worker->setup)
        worker->worker->setup();
    WorkerProcess->refresh_time = Server.cron_time.tv_sec;

    FreeClients = createAndFillPool();
    Clients = createList();
    StatBufferSize = getStatItemByName("Max buffer size");
    StatTotalRequest = getStatItemByName("Total request");
    StatFailedRequest = getStatItemByName("Total failed request");
    StatRunTime = getStatItemByName("Worker run time");

    worker->apps = arrayCreate(sizeof(struct app*), 3);
    if (!worker->apps) {
        wheatLog(WHEAT_WARNING, "array create failed");
        halt(1);
    }

    getAppsByProtocol(worker->apps, worker->protocol);
    for (i = 0; i < narray(worker->apps); i++) {
        app = *(struct app**)arrayIndex(worker->apps, i);
        if (app->initApp(worker->protocol) == WHEAT_WRONG) {
            wheatLog(WHEAT_WARNING, "init app failed %s", getModuleName(APP, app));
            halt(1);
        }
    }

    sendStatPacket(WorkerProcess);
}
Пример #26
0
void test_add_to_list_double() {
  LinkedList list = createList();
  double value = 1.03;
  assert(add_to_list(&list, &value) == 1);
  assert(add_to_list(&list, &value) != 0);
};
Пример #27
0
/**
 * Create a new (empty) linked list, with paramaters.
 *
 * @param flags     Creation flags specify list behavior:
 *                  LCF_CIRCULAR:
 *                  The list forms a ring of items, as opposed to the
 *                  default linear list.
 * @param cFunc     If @c NULL, the default compare function (compare by
 *                  address) will be set.
 * @return          Ptr to the newly created list.
 */
LinkList *List_NewWithCompareFunc(int flags, comparefunc cFunc)
{
    return createList(flags, (!cFunc? compareAddress : cFunc));
}
Пример #28
0
void test_add_to_list_char() {
  LinkedList list = createList();
  char value = 's';
  assert(add_to_list(&list, &value) == 1);
  assert(add_to_list(&list, &value) != 0);
};
Пример #29
0
/* but do change this! */
List initList(int nums[], int n) {
    List l = createList();
    
    return l;
}
// main crawler function
int main(int argc, char* argv[]) {

    // local variables
    FILE *fp; // file pointer for html files
    char *nextURL; // pointer to the next URL found on the seed page
    char *newURL; // pointer to the next URL in the while loop

    // check command line arguments
    if (argc != 4) {
        printf("Incorrect number of arguments provided.");
        exit(1);
    }
    // check that the second argument is a directory
    stat(argv[2],&statbuffer);
    if S_ISDIR(statbuffer.st_mode) { }
    else {
        printf("Error, you did not supply a valid directory");
        exit(1);
    }

    // get arguments
    char *seedURL = argv[1];
    int filename_len = strlen(argv[2])+21;

    // get the directory
    char*filename = calloc(filename_len,sizeof(char));

    // check the maxDepth
    int value = is_numeric(argv[3]);
    if (value != 0) {
        sscanf(argv[3],"%i",&maxDepth);
    }
    else {
        printf("Error! maxDepth must be a number");
        exit(1);
    }

    // init curl
    curl_global_init(CURL_GLOBAL_ALL);

    // initialize data structures/variables

    // initialize hashtable
    HashTable *table = malloc(sizeof(HashTable));
    memset(table,0,MAX_HASH_SLOT);

    // initialize linked list
    List *WebPageList;
    WebPageList = createList();

    // setup seed page

    // get seed webpage
    // if it fails, report and exit
    if (NormalizeURL(seedURL) == 0) {
        printf("Error, bad URL");
        exit(1);
    }
    // write seed file

    // create WebPage object by allocating memory
    WebPage *seedPage = malloc(sizeof(WebPage));

    // assign values to each part of the struct
    seedPage->url = seedURL;
    seedPage->html = NULL;
    seedPage->html_len = 0;
    seedPage->depth = 0;

    // try to get the webpage up to MAX_TRY times
    if (!GetWebPage(seedPage)) {
        for (tries = 0; tries < MAX_TRY; tries++) {
            if (GetWebPage(seedPage)) {
                break;
            }
        }
    }

    // write html contents to a file "1" in the given directory
    sprintf(filename,"%s/%d",argv[2],1);
    fp = fopen(filename,"w");
    fputs(seedURL,fp);
    fputs("\n",fp);
    fprintf(fp,"%d\n",seedPage->depth);
    fputs(seedPage->html,fp);

    // close the file and wipe the filename
    fclose(fp);
    memset(filename,'\0',filename_len);

    // add seed page to hashtable
    add(table,seedURL);

    // extract urls from seed page

    // while there are still URLs in the seed page's html
    while ((pos = GetNextURL(seedPage->html,pos,seedPage->url,&nextURL)) > 0) {

        // only visiting them if it wouldn't exceed maxDepth
        if ((seedPage->depth+1) > maxDepth) {
            free(seedPage);
            exit(1);
        }

        // ensure it's a valid url
        if (NormalizeURL(nextURL) != 0) {

            // also check if its in the right domain
            if (strncmp(URL_PREFIX,nextURL,strlen(URL_PREFIX)) == 0) {

                // if it is added to the hashtable it is a unique URL that
                // hasn't been visited before, add it to the linked list
                // of URLs to visit
                if (add(table,nextURL)) {
                    // create a new webpage object
                    WebPage *pages = malloc(sizeof(WebPage));
                    pages->url = nextURL;
                    pages->html = NULL;
                    pages->html_len = 0;
                    pages->depth = 1;

                    // try to get the webpage up until the MAX_TRY
                    tries = 0;
                    if (!GetWebPage(pages)) {
                        for (tries = 0; tries < MAX_TRY; tries++) {
                            if (GetWebPage(pages)) {
                                break;
                            }
                        }
                    }

                    // add it to the linked list
                    addToEnd(WebPageList,pages);
                }
            }
        }
    }

    // while there are urls to crawl
    while (WebPageList->head != NULL) {
        // get next url from list
        WebPage *nextPage = malloc(sizeof(WebPage));
        nextPage = removeFromFront(WebPageList);

        // try to get the webpage up until the MAX_TRY
        tries = 0;
        if (!GetWebPage(nextPage)) {
            for (tries = 0; tries < MAX_TRY; tries++) {
                if (GetWebPage(nextPage)) {
                    break;
                }
            }
        }

        // write page file
        sprintf(filename,"%s/%d",argv[2],docNum);
        fp = fopen(filename,"w");
        fputs(nextPage->url,fp);
        fputs("\n",fp);
        fprintf(fp,"%d\n",nextPage->depth);
        fputs(nextPage->html,fp);

        // close the file and wipe the filename (to be used next time)
        fclose(fp);
        memset(filename,'\0',filename_len);

        // increment the doc num
        docNum++;

        // check if visiting the URLs on this page will exceed maxDepth
        if ((nextPage->depth+1) > maxDepth) {
            free(nextPage);
            continue;
        }
        pos = 0;
        // iterate through all the URLs on the page
        while ((pos = GetNextURL(nextPage->html,pos,nextPage->url,&newURL))>0) {
            // check to ensure that the URLs are the proper format
            if (NormalizeURL(newURL) != 0 ) {
                // check to ensure that they are in the right domain
                if (strncmp(URL_PREFIX,newURL,strlen(URL_PREFIX)) == 0) {
                    // making sure to only add new ones to the list
                    if (add(table,newURL) != 0) {
                        // create a new WebPage object
                        WebPage *page = malloc(sizeof(WebPage));
                        page->url = newURL;
                        page->html = NULL;
                        page->html_len = 0;
                        page->depth = nextPage->depth + 1;
                        GetWebPage(page);

                        // try to get the webpage up until the MAX_TRY
                        tries = 0;
                        if (!GetWebPage(page)) {
                            for (tries = 0; tries < MAX_TRY; tries++) {
                                if (GetWebPage(page)) {
                                    break;
                                }
                            }
                        }

                        // add the page to the linked list
                        addToEnd(WebPageList,page);
                    }
                }
            }
        }
        // Sleep for a bit to avoid annoying the target
        sleep(INTERVAL_PER_FETCH);

        // Free resources
        free(nextPage);

    }

    // cleanup curl
    curl_global_cleanup();

    // free resources
    // free hashtable
    hash = JenkinsHash(seedURL,MAX_HASH_SLOT);
    HashTableNode *freer = table->table[hash];
    HashTableNode *tempHash = NULL;
    while (freer != NULL) {
        tempHash = freer;
        freer = freer->next;
        free(tempHash);
    }
    free(table);

    // free linked list
    free(WebPageList);

    // free WebPage and filename pointer
    free(seedPage);
    free(filename);
    return 0;
}