Exemple #1
0
int main(int argc, const char *argv[])
{
        int i;
        int soma = 0;
        int tamanho = argc - 1;

        List list;
        initializeList(&list);

        for (i = 1; i < argc; i++)
        {
                list.head = addToList(&list, atoi(argv[i]), true);
                soma += atoi(argv[i]);
        }
        
        printf("Conjunto: ");
        print(&list);

        if (soma%2 == 0)
        {
                int metade = soma / 2;
                if (max(&list) <= metade)
                {
                        List partition1;
                        initializeList(&partition1);
                        int val = getVal(&list, 0);
                        partition1.head = addToList(&partition1,  val, true);
                        List partition2;
                        partition2 = copy(&list);
                        del(&partition2, val);
                        algoritmo(0 + val, metade, tamanho, &partition1, &partition2, &list, 1);
                        destroy(&list);
                        destroy(&partition1);
                        destroy(&partition2);
                        printf("Quantidade de resultados: %d\n", qtdResult);
                }
                else
                {
                        printf("Não foi encontrado\n");
                        destroy(&list);
                }

        }
        else
        {
                printf("Não foi encontrado\n");
                destroy(&list);
        }
        return 0;
}
Exemple #2
0
int insertItem(int newitem)
{
	if(listMaxSize == 0){
        initializeList();
	}
	int * tempList ;
	if (length == listMaxSize)
	{
		//allocate new memory space for tempList
		listMaxSize = 2 * listMaxSize ;
		tempList = (int*) malloc (listMaxSize*sizeof(int)) ;
		int i;
        for( i = 0; i < length ; i++ )
        {
            tempList[i] = list[i] ; //copy all items from list to tempList
        }
        free(list) ; //free the memory allocated before
        list = tempList ; //make list to point to new memory
	};

	list[length] = newitem ; //store new item
	length++ ;

	return SUCCESS_VALUE ;
}
Exemple #3
0
int setDataInTableByString(HashTable *table, char *str, u_int64_t value, Error *error) {
  void **arrayCell = _getPtrListFromTableByString(table,str);
  LinkedList *list = *arrayCell;
  Data *data = NULL;
  if (NULL == list) {
    *arrayCell = initializeList(error);
    list = *arrayCell;
    if (NULL == list) {
      return 1; }
  }

  data = getDataFromTableByString(table,str);

  if (NULL == data) {
    data = initializeData(str,value,error);
    if (NULL == data) {
      return 1; }
    insertDataIntoList(list,data,error);
    if (0 != error->error) {
      return 1; }
  } else {
      data->value = value;
  }

#ifdef DEBUG
  printf(BOLD_GREEN"In "HEADER "HashTable"STANDART" (%p) set data (%p) by '%s' (hash=%"PRIu64"): %"PRIu64"\n",table,data,str,data->hash,data->value);
#endif

  return 0;
}
Exemple #4
0
int main(int argc, char const *argv[]) {
  List tegut;

  initializeList(&tegut);
  std::cout << "Ausgabe first: " << tegut.first << std::endl;
  std::cout << "Ausgabe last: " << tegut.last << std::endl;

  for (int i = 0; i < 3; i++) {
    insert0(&tegut, insertArtikel());

    // std::cout << "Ausgabe first: " << tegut.first << std::endl;
    // std::cout << "Ausgabe last: " << tegut.last << std::endl;
  }

  insertLast(&tegut, insertArtikel());
  insertPos(&tegut, insertArtikel(), 2);
  outputList(&tegut);

  std::cout << "Nach remove0:" << std::endl;
  remove0(&tegut);
  outputList(&tegut);

  std::cout << "Nach removePos:" << std::endl;
  removePos(&tegut, 1);
  outputList(&tegut);

  return 0;
}
List *createList()
{
		List* l;
		l = (List*) malloc(sizeof(List));
		initializeList(l);
		return (l);
}
int main(int argc, char **argv)
{
    struct Node *head = initializeList();
    head = reverseLinkedList(head);
    printLinkedList(head);
    return 0;
}
Exemple #7
0
int loadFromFile(FILE *file, Environment *env) {
  List *tokens, *parseTree, *leftoverTokens = NULL;
  leftoverTokens = initializeList();
  int depth = 0;
  char *expression = (char *)malloc(256 * sizeof(char));
  Value* temp;
  while (fgets(expression, 256, file)) {
    
     tokens = append(leftoverTokens, tokenize(expression)); 
     
     if (!tokens) {
       leftoverTokens->head = NULL;
       continue;
     }
    
     parseTree = parse(tokens,&depth);   
     
     if (depth < 0) {
       printf("syntax error. Too many close parentheses.\n");   // Too many close parentheses. 
       cleanup(tokens->head);
       //free(parseTree);
       free(leftoverTokens);
       free(tokens);
       return SYNTAX_ERROR_TOO_MANY_CLOSE_PARENS;
     } else if (depth > 0) {
       // There are more open parens than close parens, so these tokens are saved as leftovers. We partially generate a parse tree now.
       leftoverTokens->head = tokens->head;
       
      } else {
       if (parseTree && parseTree->head){
	 //printf("going to print parse tree: ");
	 //printValue(parseTree->head);
	 //printf("\n");
	 //printf("going to print parse tree again: ");
	 //printValue(deepCopyList(parseTree->head));
	 //printf("\n");
	 temp = eval(parseTree->head,env);
	 if (temp){
	   printValue(temp);
	   printf("\n");
	 }
	 
	 //leftoverTokens->head = tokens->head;
	 free(parseTree);
	 // cleanup(leftoverTokens->head);
       }
     }
  }
  if (leftoverTokens->head) {
    printf("syntax error. Too few close parentheses\n");   // Too few close parens at end of input. 
    destroy(leftoverTokens);   
    free(tokens);
    return SYNTAX_ERROR_UNTERMINATED_INPUT;
  }
  // clean up memory 
  destroy(leftoverTokens);
  free(tokens);
  free(expression); 
}
Exemple #8
0
Closure *initializeClosure(Environment* env){
  Closure *closure = (Closure *)malloc(sizeof(Closure));
  closure->parent = env;
  closure->identifier = NULL;
  closure->args = initializeList();
  //closure->body = (Value *)malloc(sizeof(Value));
  //closure->body->type = cellType;
  return closure;
}
int main(void)
{
    initializeList();
    while(1)
    {
        printf("1. Insert new item. 2. Delete item. 3. Search item. \n");
        printf("4. Insert Last. 5. Delete Last. 6. Print forward. \n");
        printf("7. Print backward. 8. exit.\n");

        int ch;
        scanf("%d",&ch);
        if(ch==1)
        {
            int item;
            scanf("%d", &item);
            insertFirst(item);
        }
        else if(ch==2)
        {
            int item = deleteLast();
            if(item!=NULL_VALUE) printf("Deleted: %d\n", item);
        }
        else if(ch==3)
        {
            int item;
            scanf("%d", &item);
            struct listNode * res = searchItem(item);
            if(res!=0) printf("Found.\n");
            else printf("Not found.\n");
        }
        else if(ch==4)
        {
            int item;
            scanf("%d",&item);
            insertLast(item);
        }
        else if(ch==5)
        {
            deleteLast();
        }
        else if(ch==6)
        {
            printListForward();
        }
        else if(ch==7)
        {
            printListBackward();
        }
        else if(ch==8)
        {
            freeall(list);
            break;
        }
    }

}
Exemple #10
0
// deep copy as a linked list.
List* deepCopyLinkedList(List* list){
  if (list){
 
    List *returnList = initializeList();
    Value *head = deepCopyList(list->head);
    returnList->head = head;
    return returnList;
  }
  return NULL;
}
ManageGlobalAlertsDialog::ManageGlobalAlertsDialog( int typeId ) : ManageAlertsDialog( 0 ),
    m_typeId( typeId )
{
    TypeEntity type = TypeEntity::find( typeId );
    setPrompt( tr( "Edit alert settings for type <b>%1</b>:" ).arg( type.name() ) );

    AlertsModel* model = new AlertsModel( this );
    model->initializeGlobalList( typeId );

    initializeList( model );
}
ManageFolderAlertsDialog::ManageFolderAlertsDialog( int folderId ) : ManageAlertsDialog( folderId ),
    m_folderId( folderId )
{
    FolderEntity folder = FolderEntity::find( folderId );
    setPrompt( tr( "Edit alert settings for folder <b>%1</b>:" ).arg( folder.name() ) );

    AlertsModel* model = new AlertsModel( this );
    model->initializeFolder( folderId );

    initializeList( model );
}
Exemple #13
0
void stealList(list_t *src, list_t *dest)
{
	// copy over the pointer info
	dest->head = src->head;
	dest->tail = src->tail;
	dest->numNodes = src->numNodes;
	dest->curNode = src->curNode;
	dest->currentNode = src->currentNode;

	// init src
	initializeList(src);
}
TObjectsPool<T, NumOfElementsInChunk, IsThreadSafe, CHUNK_ALLOCATOR>::TObjectsPool()
: __first_free_cell( FREE_CELL_NONE ), __num_of_objects(0), __num_of_chunks(0)
{
# if 0
	// allocate the first block
	t_list_element<T> *pBlock = __allocator.allocate();
	if( NULL != pBlock ) {
		initializeList( pBlock );
		__num_of_chunks ++;
	}
#endif
}
Exemple #15
0
List copy(List* list)
{
        List lst;
        initializeList(&lst);
        int i = 0;
        while (i < list->size)
        {
                lst.head = addToList(&lst, getVal(list, i), true);
                i++;
        }
        return lst;
}
Exemple #16
0
void ListView::initialUpdate()
{
    cleanUp();

    m_model = new FolderModel( this );

    connect( m_model, SIGNAL( layoutChanged() ), this, SLOT( updateActions() ) );
    connect( m_model, SIGNAL( layoutChanged() ), this, SLOT( updateSummary() ) );
    connect( m_model, SIGNAL( modelReset() ), this, SLOT( updateActions() ) );
    connect( m_model, SIGNAL( modelReset() ), this, SLOT( updateSummary() ) );

    initializeList();
}
Exemple #17
0
void emptyList(list_t *list)
{
	while (list->head != NULL)
	{
		// get the node
		listNode_t *node = list->head;
		list->head = node->next;

		// free it up
		Z_FREE(node);
	}
	initializeList(list);
}
int main(void)
{
    initializeList();
    while(1)
    {
        printf("1. Insert new item. 2. Delete item. 3. Search item.  \n");
        printf("4. Insert last.     5. Print.       6.exit. \n");

        int ch;
        scanf("%d",&ch);
        if(ch==1)
        {
            int item;
            scanf("%d", &item);
            insertItem(item);
        }
        else if(ch==2)
        {
            int item;
            scanf("%d", &item);
            deleteItem(item);
        }
        else if(ch==3)
        {
            int item;
            scanf("%d", &item);
            struct listNode * res = searchItem(item);
            if(res!=0) printf("Found.\n");
            else printf("Not found.\n");
        }
        else if(ch==4)
        {
            int item;
            scanf("%d", &item);
            insertLast(item);
        }
        else if(ch==5)
        {
            printList();
        }

        else if(ch==6)
        {
            break;
        }

    }

}
int main()
{
    initializeList();
    int i,j,k;
    int c;
    char sr[100];
    i=0;
    k=0;

    scanf("%s",&sr);

    while(sr[i]!='\0')
    {
        if(sr[i]=='(' || sr[i]=='{' || sr[i]=='[')
        {
            insertItem(sr[i]);
        }
        else
        {
            if(length==0)
            {
                k=1;
                break;
            }
            c=list[length-1];
            deleteLast();
            if(sr[i]==')' && c!='(')
            {
                k=1;
                break;
            }
            else if(sr[i]=='}' && c!='{')
            {
                k=1;
                break;
            }
            else if(sr[i]==']' && c!='[')
            {
                k=1;
                break;
            }
        }
        i++;
    }
    j=getlength();
    if(!j && !k)printf("Balanced");
    else printf("Not Balanced");
    clear();
}
void run(int *board,int h,int w)
{
    int i,j;
    statusList=initializeList(&statusList);

    for(i=0;i<h;i++)
    {
        for(j=0;j<w;j++)
        {
            rule1(board,i,j,h,w);
            rule2(board,i,j,h,w);
        }
    }
    applyChanges(board,w);
}
Exemple #21
0
int main(int argc, char** argv) {
    requestBuffer = createList();
    initializeList(requestBuffer);  
    
    sem_init(&full, 0, 0);
    pthread_mutex_init(&mutexAddLista, NULL);
    //Socket usado para aguardar a conexão
    int* listenSock;


    //Porta a ser usada pelo servidor... (use portas altas (10000+) para evitar conflitos com serviços já sendo executados)
    char* port;
    int nThreads = 1;

    //Verficar se a porta foi passada como argumento
    if (argc < 2) {
        fprintf(stderr, "uso: %s porta\n", argv[0]);
        return EXIT_FAILURE;
    }

    //porta é o primeiro argumento
    port = argv[1];
//    nThreads = atoi(argv[2]);

    int i;
    pthread_t* thread;
    for (i = 0; i < nThreads; i++) {
        thread = malloc(sizeof(pthread_t));
        pthread_create(thread, NULL, wakeThread, NULL);
    }

    listenSock = malloc(sizeof (int));
    *listenSock = 0;

    //Abrir socket para arguardar conexões
    *listenSock = CONN_listenTo((char*) port);

    while (!dispatcher(listenSock, port));

    //fechar o socket
    close(*listenSock);
    sem_destroy(&full);
    pthread_mutex_destroy(&mutexAddLista);

    return EXIT_SUCCESS;

}
Exemple #22
0
int main(int argc, char *argv[]) {

  List *tokens, *parseTree, *leftoverTokens = NULL;
  leftoverTokens = initializeList();
  int depth = 0;
  char *expression = (char *)malloc(256 * sizeof(char));
 
  while (fgets(expression, 256, stdin)) {
    
     tokens = append(leftoverTokens, tokenize(expression)); 
     
     if (!tokens) {
       leftoverTokens->head = NULL;
       continue;
       }
    
     parseTree = parse(tokens,&depth);   
     
     if (depth < 0) {
       printf("syntax error. Too many close parentheses.\n");   // Too many close parentheses. 
       return SYNTAX_ERROR_TOO_MANY_CLOSE_PARENS;
     } else if (depth > 0) {
       // There are more open parens than close parens, so these tokens are saved as leftovers. We partially generate a parse tree now.
       leftoverTokens->head = tokens->head;
       
      } else {
       if (parseTree && parseTree->head){
	 printValue(parseTree->head);
	 printf("\n");
	 cleanup(leftoverTokens->head);
       }
      }
  }
  if (leftoverTokens->head) {
    printf("syntax error. Too few close parentheses\n");   // Too few close parens at end of input. 
    destroy(leftoverTokens);   
    free(tokens);
    return SYNTAX_ERROR_UNTERMINATED_INPUT;
  }
  // clean up memory 
  destroy(leftoverTokens);
  free(tokens);
  free(expression);
  
  return -1;
}
void * TObjectsPool<T, NumOfElementsInChunk, IsThreadSafe, CHUNK_ALLOCATOR>::allocate_unlocked()
{
	if( FREE_CELL_NONE == __first_free_cell )
	{
		// try to allocate additional block
		t_list_element<T> *pNewBlock = __allocator.allocate();
		if( NULL != pNewBlock ) {
			initializeList( pNewBlock );
			__num_of_chunks ++;
		}

		if( FREE_CELL_NONE == __first_free_cell )
			return NULL;
	}

	void* retVal = static_cast<void*>( &(__first_free_cell->data) );
	__first_free_cell = __first_free_cell->next_free_cell;
	__num_of_objects ++;
	return retVal;
}
Exemple #24
0
main(int argc, void *argv)
{
  int n;

  if (argv != 1) {
    printf("usage: %s <n>\n", argv[0]);
    exit(-1);
  }
  n = atoi(argv[1]);
  if (n < 0) {
    printf("invalid value for n (%d)\n", n);
    exit(-1);
  }

  List = malloc(sizeof(int) * n);
  if (List == NULL) return -1;	/* not the best feedback */
  initializeList(n, List);	/* put some random values in the array */

  MyThreadInit(mergesort, (void*)n);
}
Exemple #25
0
SemList *createAndInitializeList() {
	SemList *list = (SemList *)malloc(sizeof(SemList));
	initializeList(list);
	return list;
}	
int main(int argc , char *argv[]){
	int i;
	struct timeval tv;
	char nameOfAlgo[20];
	unsigned int timeBeforeAlgo, timeAfterAlgo, timeBeforeOptimal, timeAfterOptimal, timeTakenByOptimal, timeTakenByAlgo;
	for (i=1; i < argc; i++){
		if (strcmp(argv[i],"-h") == 0){
			showHelp();
		}else
		if (strcmp(argv[i],"-f") == 0){
			availableFrames = framesLeft = atoi(argv[++i]);
		}else
		if (strcmp(argv[i],"-r") == 0){
			strcpy(replacementPolicy,argv[++i]);
		}else
		if (strcmp(argv[i],"-i") == 0){
			strcpy(fileName,argv[++i]);
		}else
			printf("%s is a wrong option. Please enter the correct option",argv[i]);
	}
	FILE *fp;
	if ((fp = fopen(fileName,"r")) != NULL){
		int c;
		i = 0;
		while ((c = getc(fp)) != EOF){
			if (isspace(c) == 0)
				inputSeq[i++] = c;
		}
		inputSeq[i] = '\0';
		fclose(fp);
	}
	else{
		printf("Enter the sequence!!\n");
		fgets(inputSeq,sizeof inputSeq, stdin);
	}
	if (strcmp(replacementPolicy,"LFU") == 0){
		strcpy(nameOfAlgo,"LFU");
		gettimeofday(&tv, NULL);
		timeBeforeAlgo = (uint)tv.tv_usec;
		LFUPageReplacement();
		gettimeofday(&tv, NULL);
		timeAfterAlgo = (uint)tv.tv_usec;
		timeTakenByAlgo = (uint) (timeAfterAlgo - timeBeforeAlgo);
	}
	else if (strcmp(replacementPolicy,"LRU-STACK") == 0){
		strcpy(nameOfAlgo,"LRU-STACK");
		gettimeofday(&tv, NULL);
		timeBeforeAlgo = (uint)tv.tv_usec;
		LRUStackPageReplacement();
		gettimeofday(&tv, NULL);
		timeAfterAlgo = (uint)tv.tv_usec;
		timeTakenByAlgo = (uint) (timeAfterAlgo - timeBeforeAlgo);
	}
	else if (strcmp(replacementPolicy,"LRU-CLOCK") == 0){
		strcpy(nameOfAlgo,"LRU-CLOCK");
		gettimeofday(&tv, NULL);
		timeBeforeAlgo = (uint)tv.tv_usec;
		LRUClockPageReplacement();
		gettimeofday(&tv, NULL);
		timeAfterAlgo = (uint)tv.tv_usec;
		timeTakenByAlgo = (uint) (timeAfterAlgo - timeBeforeAlgo);
	}
	else if (strcmp(replacementPolicy,"LRU-REF8") == 0){
		strcpy(nameOfAlgo,"LRU-REF8");
		gettimeofday(&tv, NULL);
		timeBeforeAlgo = (uint)tv.tv_usec;
		LRURefPageReplacement();
		gettimeofday(&tv, NULL);
		timeAfterAlgo = (uint)tv.tv_usec;
		timeTakenByAlgo = (uint) (timeAfterAlgo - timeBeforeAlgo);
	}
	else{
		strcpy(nameOfAlgo,"FIFO");
		gettimeofday(&tv, NULL);
		timeBeforeAlgo = (uint)tv.tv_usec;
		initializeList();
		initializeFrame();
		FIFOPageReplacement();	
		gettimeofday(&tv, NULL);
		timeAfterAlgo = (uint)tv.tv_usec;
		timeTakenByAlgo = (uint) (timeAfterAlgo - timeBeforeAlgo);
	}
	timeBeforeOptimal = (uint)tv.tv_usec;
	initializeList();
	initializeFrame();
	OptimalPageReplacement();
	timeAfterOptimal = (uint)tv.tv_usec;
	timeTakenByOptimal = (uint) (timeAfterOptimal - timeBeforeOptimal);
	float percentPage = ((nbOfPageReplacementByAlgo-nbOfPageReplacementByOptimal*1.00)/nbOfPageReplacementByOptimal)*100;
	float percentTime = ((timeAfterOptimal-timeTakenByAlgo*1.00)/timeAfterOptimal)*100;
	printf("Percentage page replacement penalty using %s \t: %2.2f percent\n\n",nameOfAlgo,percentPage);
	printf("Total time to run %s algorithm \t: %u microseconds\nTotal time to run Optimal algorithm  \t: %u microseconds\n",nameOfAlgo,timeTakenByAlgo,timeAfterOptimal);
	printf("%s is %2.2f percent faster than Optimal algorithm.\n\n",nameOfAlgo,percentTime);
	if(nbOfPageReplacementByOptimal < 0)
		printf("!! Any negative value should be considered as 0.\n\n");
	return 0;
}
int main(void)
{
    initializeList();
    while(1)
    {
        printf("1. Insert new item. 2. Delete item. 3. Search item. \n");
        printf("4. Insert new item at last of list. 5. Insert new item after old item in list.\n");
        printf("6. Delete first item in list 7. Delete last item in list.\n");
        printf("8. Print. 9. exit.\n");



        int ch;
        scanf("%d",&ch);
        if(ch==1)
        {
            int item;
            scanf("%d", &item);
            insertItem(item);
        }
        else if(ch==2)
        {
            int item;
            scanf("%d", &item);
            deleteItem(item);
        }
        else if(ch==3)
        {
            int item;
            scanf("%d", &item);
            struct listNode * res = searchItem(item);
            if(res!=0) printf("Found.\n");
            else printf("Not found.\n");
        }
        else if(ch==4)
        {
            int item;
            scanf("%d",&item);
            insertLast(item);
        }
        else if(ch==5)
        {
            int oldItem,newItem;
            printf("Old item: ");
            scanf("%d",&oldItem);
            printf("New item: ");
            scanf("%d",&newItem);
            insertAfter(oldItem,newItem);
        }
        else if(ch==6)
        {
            deleteFirst();
        }
        else if(ch==7)
        {
            deleteLast();
        }
        else if(ch==8)
        {
            printList();
        }
        else if(ch==9)
        {
            break;
        }
    }

}
void drawGameScreen() {
    clear();
    //draw exterior of game
    drawBox(10, 3, 44, 34, 0);
    
    //draw path walls
    drawBox(10, 7, 11, 3, 0);
    drawBox(18, 7, 4, 14, 0);
    drawBox(18, 18, 16, 3, 0);
    drawBox(31, 7, 4, 14, 0);
    drawBox(31, 7, 18, 3, 0);
    drawBox(46, 7, 4, 24, 0);
    drawBox(19, 28, 30, 3, 0);
    drawBox(19, 28, 4, 9, 0);

    //fix up the corners
    clearPath();
    fixCorners();

    //add beginning and ending chars
    mvaddch(8, 8, '>');
    mvaddch(37, 21, ACS_DARROW);

    //draw and fill the purchase portion of the screen
    attron(COLOR_PAIR(0));
    drawPurchaseArea();
    basicSetupScreen(1);
    updateScore(0);
    attroff(COLOR_PAIR(0));
    drawTowerExplain();

    //load arrays for drawing
    TowerArray* theTowerList = getTowerArray("assets/towersLevel1.txt");
    Path* thePath = getPathArray("assets/path.txt");
    UnitListHeader * unitList = malloc(sizeof(UnitListHeader));
    int moneyAmount = STARTINGMONEY;
    initializeList(unitList);
    drawUnitTypes(unitList);
    int theScore = 0;

    drawTowers(theTowerList);

    //go to entering unit purchases (gives control back to user)
    selectUnitsInterface(thePath,unitList,&moneyAmount,theTowerList,&theScore);

    //get lowest score of highscores
    ScoreHead scores;
    scores.size = 0;
    scores.first = NULL;
    ScoreNode * currScore = NULL;
    readScores(&scores);
    currScore = scores.first;
    int numScores = 1;
    int highestScore = 0;

    while ((currScore->next != NULL) && (numScores < 9)) { 
        numScores += 1;
        currScore = currScore->next;
    }

    highestScore = -1;
    if (numScores > 8 && currScore != NULL) {
        highestScore = currScore->score;
    }

    char * enterName;
    if (theScore > highestScore) {
        enterName = drawScore(theScore,1);
        if (enterName != NULL) {
            addScore(&scores, enterName, theScore);
            writeScores(&scores);
        }
    } else {
        drawScore(theScore,0);
    }

    if (scores.size > 0) destroyScores(&scores);

}
Exemple #29
0
void initSoundList()
{
	soundList = gi.TagMalloc (sizeof(list_t), TAG_LEVEL);
	initializeList(soundList);
	soundNumRejected = 0;
}
Exemple #30
0
int main(int argc, char* argv[])
{
    
    //Check for the number of arguments
    if(argc != 4){
	    printf("Invalid Input Argument\n");
	    printHelp();
        exit(1);
    } 
   
    //direcotry file path
    int dirSize = strlen(argv[2]);
    char dir[dirSize + 1];
    dir[0] = '\0';
    strcat(dir, argv[2]);

    int urlSize = strlen(argv[1]);
    char inputURL[urlSize + 1];
    inputURL[0] = '\0';
    strcat(inputURL, argv[1]);

    //Get the max depth number.
    int inputDepth = atoi(argv[3]);

    //Check if correct depth is provided.
    if(inputDepth > 4 || inputDepth < 0){
        printf("Invalid [depth]\n");
        printHelp();
        exit(1);
    }
    //Check for URL validity 
    if(!strstr(inputURL,URL_PREFIX)){
 	    printf("Invalid input [seed url]\n");
        printHelp();
	    exit(1);
    }
    //checkf for directory location validity
    DIR* directory = opendir(dir);
    if(directory){
	    closedir(directory);
    }
    else if(ENOENT == errno){
	    printf("Directory does not exist\n");
	    printHelp();
        exit(1);
    }
    else{
	    printf("Directory can't be opened\n");
        printHelp();
	    exit(1);
    }

    // init curl
    curl_global_init(CURL_GLOBAL_ALL);

    // setup seed page
    WebPage* seedWebPage = calloc(1, sizeof(WebPage));//Memory allocation for seed webpage
    seedWebPage->url = calloc((strlen(inputURL) + 1), sizeof(char));//Memory allocation to the seedURL
    seedWebPage->url[0] = '\0';
    strcat(seedWebPage->url, inputURL);
    seedWebPage->depth = 0;
    seedWebPage->html = NULL;
    
    //Initialize data structures
    HashTable* visitedURLHash = initHashTable();
    List* webPageList = initializeList();
    webPageList->head->page = seedWebPage;  
 
    //get seed webpage.
    if(GetWebPage(seedWebPage)){	
        // write seed file
        FILE *fPointer;
        char* pathVar1 = pathToDirectory(dir, fileNumber);
        fPointer = fopen(pathVar1, "w");
        free(pathVar1);	
        writeHTMLtoFile(fPointer, seedWebPage);
        //free(fPointer);
        
        if(inputDepth == 0){
            curl_global_cleanup();
            free(seedWebPage->html);
            free(seedWebPage->url);
            free(seedWebPage);

            //free webPageList and hashtable
            free(webPageList);
            for(int i = 0; i < MAX_HASH_SLOT; i++){
                free(visitedURLHash->table[i]->url);
                free(visitedURLHash->table[i]);
            }
            free(visitedURLHash);
            return 0;
        }   
        fileNumber += 1;
        depth += 1;
        HashTableInsert(visitedURLHash, seedWebPage->url); //mark as visited
        
        // extract urls from seed page
        char * result;
        int pos = 0;
        while((pos = GetNextURL(seedWebPage->html, pos, seedWebPage->url, &result))>0){

            if(NormalizeURL(result) && strstr(result,URL_PREFIX)){
                strtok(result, "#");
                //If not in hashtable, add it to the hashtable and add it to the webPageList.
                if(HashTableLookup(visitedURLHash, result) == 0){
                    HashTableInsert(visitedURLHash, result);
                    AppendList(webPageList, webPageInit(result, depth));
                    free(result);
                }
            }
        }
        if(webPageList->head->next->next == NULL){  //seed redirect case
            webPageList->head->next->page->depth = 0;
            fileNumber = 1;		
        }
        tempWebPage = PopList(webPageList); // Get rid of visited seedPage
    }
    else{	
        curl_global_cleanup();
        tempWebPage = PopList(webPageList);
        free(seedWebPage->html);
        free(seedWebPage->url);
        free(seedWebPage);
        //free(tempWebPage);
        free(webPageList);
        for(int i = 0; i < MAX_HASH_SLOT; i++){
            free(visitedURLHash->table[i]->url);
            free(visitedURLHash->table[i]);
        }
        free(visitedURLHash);
        exit(1);
    }

    
    //while there are urls to crawl
    while(webPageList->head != NULL && webPageList->tail != NULL){
        // get webpage for url
        tempWebPage = PopList(webPageList);
        if(GetWebPage(tempWebPage)){ 
            // write page file
            char* pathVar = pathToDirectory(dir, fileNumber);
            FILE *fPointer = fopen(pathVar, "w");
            free(pathVar);
            printf("Found link: %s\n",tempWebPage->url);
            writeHTMLtoFile(fPointer, tempWebPage);
            fileNumber += 1;
                
            if((tempWebPage->depth + 1) <= inputDepth ){
                char * resultTemp;
                int posTemp = 0;
                while((posTemp = GetNextURL(tempWebPage->html, posTemp, tempWebPage->url, &resultTemp))>0){
                    
                    if( NormalizeURL(resultTemp) && strstr(resultTemp,URL_PREFIX) ){
                        strtok(resultTemp, "#");
                        //insert to the hashtable and the webPageList if not already present
                        if(HashTableLookup(visitedURLHash, resultTemp) == 0){
                            HashTableInsert(visitedURLHash, resultTemp);
                            AppendList(webPageList, webPageInit(resultTemp, tempWebPage->depth+1));
                        }
                    }
                        free(resultTemp);
                }
            }
        
            free(tempWebPage->url);
            free(tempWebPage->html);
            free(tempWebPage);
        }
        else{
            free(tempWebPage->url);
            free(tempWebPage->html);
            free(tempWebPage);
        }
        sleep(INTERVAL_PER_FETCH);
    }
    // cleanup curl
    curl_global_cleanup();
    free(seedWebPage->url);
    free(seedWebPage->html);
    free(seedWebPage);
    free(webPageList);

    //free the hashtable
    for(int i = 0; i < MAX_HASH_SLOT; i++){
        if(visitedURLHash->table[i]->url != NULL){
            HashTableNode* currNode = visitedURLHash->table[i];
            while(currNode->next != NULL){
                HashTableNode* tempNode = currNode;
                currNode = currNode->next;
                free(tempNode->url);
                free(tempNode);
            }
            free(currNode->url);
            free(currNode);		
        }
        else{	
            free(visitedURLHash->table[i]);
        }
    }
    free(visitedURLHash);
    return 0;
}