Esempio n. 1
0
File: main.c Progetto: npc3/DumbLisp
void repl() {
    char line[100];
    char *s;
    printf("> ");
    while(fgets(line, 100, stdin) != NULL) {
        s = line;
        if(VERBOSE)
            printf("reading...\n"); fflush(stdout);
        LispObject *r = read(&s);
        if(VERBOSE) {
            obj_print(r);
            printf("\nevaluating...\n"); fflush(stdout);
        }
        LispObject *e = eval_sub(r);
        if(VERBOSE)
            printf("printing...\n"); fflush(stdout);
        obj_print(e);
        printf("\n");
        fflush(stdout);
        if(VERBOSE) {
            printf("symbol table:\n");
            print_symbol_table();
        }
        collect_garbage();
        if(VERBOSE)
            printf("amount of memory in in alloc table: %d\n",
                   memory_in_alloc_table());
        printf("> ");
    }
}
Esempio n. 2
0
/*
 *	clean-up and exit the software
 */
int	java2cpp_exit( void)
{
#ifdef	YYDEBUG
	if( IS_FLAGS_SYMBOL(data.flags))
	{
		print_symbol_table();
	}
#endif
	de_clips_list(data.symbol_table);


#ifdef YYDEBUG
	print_typedef_table();
#endif
de_clips_list(data.typedef_table);
/*
*	Check if memory leak
*/
if(data.memory)
{
	fprintf(stderr, "Error: memory deallocation error: %d\n",data.memory);
}

/** check if compiler warnings */
if(data.warnings)
	fprintf(stderr, "Warning: compiler warnings: %d\n", data.warnings);
/** check for errors */
if(data.errors)
	fprintf(stderr, "Error: compiler errors: %d\n", data.errors);
return (data.errors);
}
/*
 *	pop symbol table identifiers at this level
		symbol_right_bracket();
 */
void	symbol_right_bracket( void)
{
	TUPLE	*tuple;
/*
 *	print the complete symbol table before poping symbols off
 */
#ifdef	YYDEBUG
	if( IS_FLAGS_SYMBOL( data.flags))
	{
		printf( "pop symbol table level: %d\n", data.level);
		print_symbol_table();
	}
#endif
/*
 *	check and remove all tuple above level
 */
	for( tuple = data.symbol_table; tuple; tuple = data.symbol_table)
	{
		if( tuple->level < data.level)
			break;
		put_address( tuple->address, 1);
		data.symbol_table = tuple->next;
		tuple->next = data.symbol_table_free;
		data.symbol_table_free = tuple;
	}
/*
 *	decrement the symbol table level
 */
	data.level--;
	return;
}
Esempio n. 4
0
/*
 *	clean-up and exit the software
 */
int	main_exit( void)
{
/*
 *	print the symbol table 
 */
#ifdef	YYDEBUG
	if( IS_FLAGS_SYMBOL( data.flags))
	{
		print_symbol_table();
	}
#endif
/*
 *	deallocate the symbol table list
 */
	free_tuple_list( data.symbol_table);
	free_tuple_list( data.symbol_table_free);
/*
 *	check if memory leak
 */
	if( data.memory)
		fprintf( stderr, "Error: memory deallocation error: %d\n", data.memory);
/*
 *	check if compiler warnings
 */
	if( data.warnings)
		fprintf( stderr, "Warning: compiler warnings: %d\n", data.warnings);
/*
 *	check if compiler errors 
 */
	if( data.errors)
		fprintf( stderr, "Error: compiler errors: %d\n", data.errors);
	return( data.errors);
}
Esempio n. 5
0
/*
 *	pop symbol table identifiers at this level
		symbol_right_bracket();
 */
void	symbol_right_bracket( void)
{
	CLIPS	*clips;
/*
 *	print the complete symbol table before poping symbols off
 */
#ifdef	YYDEBUG
	if( IS_FLAGS_SYMBOL( data.flags))
	{
		printf( "pop symbol table level: %d\n", data.level);
		print_symbol_table();
	}
#endif
/*
 *	check and remove all clips above level
 */
	for( clips = data.symbol_table; clips; clips = data.symbol_table)
	{
		if( clips->level < data.level)
			break;
		put_address( clips->address);
		data.symbol_table = clips->next;
		de_clips( clips);
	}
/*
 *	decrement the symbol table level
 */
	data.level--;
	return;
}
/*
 *	clean-up and exit the software
 */
int	ifrelop_exit( void)
{
/*
 *	print the symbol table
 */
	print_symbol_table();
	return 0;
}
Esempio n. 7
0
bool print_topo_order(void) {
    // Now print the symbols in order
    symbol* current;
    while (symbols->size > 0) {
    #ifdef DEBUG
        print_symbol_table();
    #endif
        for (current = symbols->first; current != NULL; current = current->next) {
            if (current->inDegree == 0) {
                // Add to sorted list
                add_symbol_to_sorted(current);
            }
        }
        #ifdef DEBUG
            print_sorted_symbols();
        #endif
        if (sortedSyms->size == 0) {
            perror("This cannot be solved, there is a cycle");
            exit(EXIT_FAILURE);
        }
        else {
            // Now go thru sorted list, print, decrement the indegrees,  and free all the data
            sortedSymbol* currentSorted;
            for (currentSorted = sortedSyms->first; currentSorted != NULL; currentSorted = currentSorted->next) {
                printf("%s ", currentSorted->sym->symbolName);
                symbolsAfter* symA;
                for (symA = currentSorted->sym->curSymbolAfter; symA != NULL; symA = symA->nextSymAfter) {
                    /*Go thru the current symbol's "symbolsAfter" list and decrement
                     *their in-degree
                     */
                    symA->sym->inDegree--;
                }
    #ifdef DEBUG
        printf("printing new In Degrees after traversing sorted list\n");
        print_symbol_table();
    #endif
            }
            destroy_sorted_symbols();
        }
    }
    printf("\n");
}
Esempio n. 8
0
int main(void) {
	FILE* automaton_p;
	if((automaton_p = fopen("automaton.txt", "r")) == NULL)
		return EXIT_FAILURE;
	
	automaton* test = read_automaton(automaton_p);
	printf("Initial state: %d\n", test->initial_state);
	printf("Number of states: %d\n", test->states);
	printf("Number of final states: %d\n", test->final_state_c);
	printf("Final state: %d\n", test->final_states[0]);
	printf("Transitions of the initial state:\n");
	state initial = test->state_table[0];
	print_transitions(&initial);
	print_symbol_table(test);
	free_automaton(test);
	free(test);
}
Esempio n. 9
0
/*
 *	clean-up and exit the software
 */
int	main_exit( void)
{
/*
 *	print the symbol table
 */
	print_symbol_table();
/*
 *	check if memory leak
 */
	if( data.memory)
		fprintf( stderr, "Error: memory deallocation error: %d\n", data.memory);
/*
 *	check if compiler errors 
 */
	if( data.errors)
		fprintf( stderr, "Error: compiler errors: %d\n", data.errors);
	return( data.errors);
}
void test_var_def() {
	char tmp;
	FILE *inn = fopen("tests/test_var_def.txt", "r");
	while (!feof(inn)) {
		in = fopen("test.txt", "w+");
		while ((tmp = fgetc(inn)) != '}' && tmp != -1)
			fprintf(in, "%c", tmp);
		if (tmp == EOF) break;
		if (tmp <= 31) continue;
		fseek(in, 0, SEEK_SET);
		idx = 0;
		printf("******************\n");
		get_token_with_history();
		parse_var_def(2);
		print_symbol_table();
		fclose(in);
		remove("test.txt");
	}
}
Esempio n. 11
0
int main(int argc, char *argv[]) {
    parser_create();

    if (atexit(exit_hook) != 0) {
        fprintf(stderr, "could not register exit hook\n");
        exit(EXIT_FAILURE);
    }

    int ret = parser_run();

    if (ret == 0) {
        puts("{* input looks ok *}");
        puts("{* symbol table:");
        print_symbol_table();
        puts("*}");
        print_ast_as_prascal(parser_get_root_node());
    }

    return ret;
}
Esempio n. 12
0
/*
 *	clean-up and exit the software
 */
int	ansi_c_exit( void)
{
/*
 *	print the typedef table then deallocate it
 */
#ifdef	YYDEBUG
	print_typedef_table();
#endif
	de_clips_list( data.typedef_table);
/*
 *	print the symbol table 
 */
#ifdef	YYDEBUG
	if( IS_FLAGS_SYMBOL( data.flags))
	{
		print_symbol_table();
	}
#endif
/*
 *	deallocate the symbol table list
 */
	de_clips_list( data.symbol_table);
/*
 *	check if memory leak
 */
	if( data.memory)
		fprintf( stderr, "Error: memory deallocation error: %d\n", data.memory);
/*
 *	check if compiler warnings
 */
	if( data.warnings)
		fprintf( stderr, "Warning: compiler warnings: %d\n", data.warnings);
/*
 *	check if compiler errors 
 */
	if( data.errors)
		fprintf( stderr, "Error: compiler errors: %d\n", data.errors);
	return( data.errors);
}
Esempio n. 13
0
/*
 *	clean-up and exit the software
 */
int	main_exit( void)
{
/*
 *	print the symbol table 
 */
#ifdef	YYDEBUG
	if( IS_FLAGS_SYMBOL( data.flags))
	{
		print_symbol_table();
	}
#endif
/*
 *	check for a memory leak
 */
	if( data.memory)
		fprintf( stderr, "Error: memory leak: %d\n", data.memory);
    /*
     * check for compiler errors 
     */
  if( data.errors)
    fprintf( stderr, "Errors: %d\n", data.errors);
  return data.errors;
}
Esempio n. 14
0
void stackMachine(std::list<decoraded_nodes> instruction_list, std::list<sym_table> lst_of_identifiers) {
	int instruction_pointer = 0;

	std::stack<string> instruc_stack;
	std::list<sym_table>::iterator itt;
				
	int i_size = instruction_list.size();
	int l_i_size = lst_of_identifiers.size();

	for (std::list<decoraded_nodes>::iterator cur_instruc = instruction_list.begin(), end = instruction_list.end(); cur_instruc != end; ++cur_instruc) {
		// cout << "Current instruction: " << cur_instruc->instruction_ptr <<endl;
		if (cur_instruc->instruction == "op_push") {
			if (cur_instruc->token == TK_ID) {
			
				std::list<sym_table> copy_sym_tbl = lst_of_identifiers;									// copy of the original
				
				lst_of_identifiers.clear();

				itt = lst_of_identifiers.begin();

				for (int j = 0; j < l_i_size; j++) {
					sym_table a = copy_sym_tbl.front();
					copy_sym_tbl.pop_front();

					if (a.Name == cur_instruc->value) {
						instruc_stack.push(a.Value);
						lst_of_identifiers.insert(itt, a);
					} else {
						lst_of_identifiers.insert(itt, a);
					}
				}
			
			} else {
				instruc_stack.push(cur_instruc->value);
			}
		}else if (cur_instruc->instruction == "op_pop") {

			string poped = instruc_stack.top();
			instruc_stack.pop();

			std::list<sym_table> copy_sym_tbl = lst_of_identifiers;									// copy of the original
			lst_of_identifiers.clear();
			itt = lst_of_identifiers.begin();

			for (int j = 0; j < l_i_size; j++) {
				sym_table a = copy_sym_tbl.front();
				copy_sym_tbl.pop_front();
					
				if (a.Name == cur_instruc->value) {
					a.Value = poped;
					lst_of_identifiers.insert(itt, a);

				} else {
					lst_of_identifiers.insert(itt, a);
				}
			}
		} else if (cur_instruc->instruction == "op_add") {
			int op1 = std::stoi(instruc_stack.top());
			instruc_stack.pop();
			int op2 = std::stoi(instruc_stack.top());
			instruc_stack.pop();

			int sum = op1 + op2;

			instruc_stack.push(std::to_string(sum));
		} else if (cur_instruc->instruction == "op_sub") {
			int op1 = std::stoi(instruc_stack.top());
			instruc_stack.pop();
			int op2 = std::stoi(instruc_stack.top());
			instruc_stack.pop();

			int sub = op2 - op1;
	
			instruc_stack.push(std::to_string(sub));
		} else if (cur_instruc->instruction == "op_multi") {
			int op1 = std::stoi(instruc_stack.top());
			instruc_stack.pop();
			int op2 = std::stoi(instruc_stack.top());
			instruc_stack.pop();

			int sub = op2 * op1;
	
			instruc_stack.push(std::to_string(sub));
		} else if (cur_instruc->instruction == "op_greater") {

			int op1 = std::stoi(instruc_stack.top());
			instruc_stack.pop();

			int op2 = std::stoi(instruc_stack.top());
			instruc_stack.pop();

			int op_g = (op2 > op1);

			instruc_stack.push(std::to_string(op_g));

		} else if (cur_instruc->instruction == "op_less") {

			int op1 = std::stoi(instruc_stack.top());
			instruc_stack.pop();

			int op2 = std::stoi(instruc_stack.top());
			instruc_stack.pop();

			int op_g = (op2 < op1);

			instruc_stack.push(std::to_string(op_g));

		} else if (cur_instruc->instruction == "op_jfalse") {

			int flag = std::stoi(instruc_stack.top());

			cout << "FLAG : " << flag <<endl;
			instruc_stack.pop();
			
			if (!flag) {									 // if 0
				int go_to = std::stoi(cur_instruc->value);   // 9
				int at = cur_instruc->instruction_ptr;       // 5
				int diff = at - go_to + 1;                   // 5
				if (diff > 0) {
					while (diff > 0) {
						diff--;
						cur_instruc--;
					}
				} else if (diff < 0) {
					while (diff <= 0) {
						diff++;
						cur_instruc++;
					}
				}
			}

		} else if (cur_instruc->instruction == "op_jmp") {

			int go_to = std::stoi(cur_instruc->value);   // 13
			int at = cur_instruc->instruction_ptr;       // 9
			int diff = at - go_to + 1;                   // 5

			if (diff > 0) {
				while (diff > 0) {
					diff--;
					cur_instruc--;
				}
			} else if (diff < 0) {
				while (diff < 0) {
					diff++;
					cur_instruc++;
				}
			}

		} else if (cur_instruc->instruction == "op_writeln") {
			cout << "********************************************\n";
			cout << "writeln OUTPUT -- > " << instruc_stack.top() << endl;
			cout << "********************************************\n";
			instruc_stack.pop();

		}
	}

	print_symbol_table(lst_of_identifiers);
}
/*
 exe_commande
    Descr: Execute les différentes opérations demandés par l'utilisateur
    Param:
        - c: Commande (voir #define ci dessus)
        - nomfichier: Nom du fichier à lire
        - nm_index: Argument de l'option -x, NULL si l'option n'a pas été choisis
    Return:
        Etat de sortie de la fonction:
        - -1: Impossible d'ouvrir le fichier donné
        - 0: Ouverture du fichier réussi
 */
int exe_commande(unsigned char c, char *nomfichier,char* nm_index)
{
	if (nomfichier==NULL)
		return NOMFICHIERNULL;
    FILE *f;
    
    Elf32_Ehdr header;
    Elf32_Shdr *section_header_table;
    Elf32_Sym *symbol_tab;
    sectioncontent section;
    
    int nbSym = 0;
    int valid = 0;
    
    f = fopen(nomfichier,"r"); // Ouverture du fichier nomfichier

    if(f == NULL) { // Echec d'ouverture
        return FICHIERINEXISTANT;
    }
    else {
        /* Lecture Header */
        header = read_header(f,&valid);
        
        if(valid==1) { // Header valide
            
            /* Lecture Table de section header */
            section_header_table = read_section_header_table(f,header);
            
            /* Lecture Table des symboles */
            symbol_tab =
                read_symbol_table(f ,section_header_table, header, &nbSym);

            if(c&COMMANDE_HEAD) //COMMANDE_HEAD
            {
                printf("ELF Header:\n");
                print_header(header);
                printf("\n");
                 
            }
            if(c&COMMANDE_SECTIONTAB)//COMMANDE_SECTIONTAB
            {
                printf("Section Headers:\n");
                print_section_header_table(f,section_header_table,header);
                printf("\n");
            }
            
            if(c&COMMANDE_CONTENT)//COMMANDE_CONTENT
            {
                printf("Section %s content:\n", nm_index);
                
                section = read_section_content(f,nm_index, section_header_table, header);
                if(section.content==NULL) {
                    printf("Warning, section : %s,was not dumped because it does not exist \n",nm_index);
                }
                else {
                    print_section_content(section);
                }
            }
            if(c&COMMANDE_RELOC)//COMMANDE_RELOC
            {
                print_all_reloc_table(f, header, section_header_table, symbol_tab);
                printf("\n");
            }
            
           
            if(c&COMMANDE_SYM)//COMMANDE_SYM
            {
                printf("Symbol table\n");
                print_symbol_table(symbol_tab, nbSym, f, section_header_table, header);
                freeSymbolTable(symbol_tab);
            }
            }
        else // Header non valide
        {
            if(valid ==-1) { // Fichier non valid (vide ou autre)
                return FILEEMPTY;fprintf(stderr, "%s : Error while reading the file (possibly empty)\n",nomfichier);
            }
            else if(valid==0) { //Fichier pas au format elf32
                return NOTELF32;
            }
            else { // Cas normalement impossible
                fprintf(stderr, "Impossible error append\n");
            }
        }
            
        fclose(f); // Fermeture du fichier
    }
    return 0;
}
Esempio n. 16
0
int
main(void)
{
  // INITIALIZING
  struct queue cmd_queue;
  q_init (&cmd_queue);

  uint8_t *mem = calloc (__MEMORY_SIZE, sizeof(uint8_t));
  char *input = malloc (sizeof(char)*__INPUT_SIZE);
  char *cmd = malloc (sizeof(char)*__CMD_SIZE);
  char *filename = malloc (sizeof(char)*__FILENAME_SIZE);
  if (mem == NULL || input == NULL || filename == NULL
      || cmd == NULL)
    {
      puts("MEMORY INSUFFICIENT");
      goto memory_clear;
    }

  if (!init_oplist (__OPCODE_FILENAME))
    {
      puts("OPCODE LIST INITIALIZATION FAILED.");
      goto memory_clear;
    }

  // COMMAND PROCESSING
  while (true)
    {
      int i;
      struct q_elem *qe;
      uint8_t value;
      uint32_t start, end;
      DIR *dirp = NULL;
      struct dirent *dir = NULL;
      char check[2];
      bool is_valid_cmd = false;
      char *tok = NULL;

      printf("%s", __SHELL_FORM);
      if (!get_chars(input, __INPUT_SIZE))
        goto memory_clear;

      // Processing input string
      snprintf((char *) __CMD_FORMAT, __CMD_FORMAT_SIZE,
                   "%%%ds", __CMD_SIZE - 1);
      if (sscanf(input, (const char *) __CMD_FORMAT, cmd)!=1)
        cmd[0] = '\0';
      
      // Switching with commands
      switch(get_cmd_index(cmd))
        {
        case CMD_HELP:
          if(sscanf(input, "%*s %1s", check) == 1)
            {
              puts("WRONG INSTRUCTION");
              break;
            }
          puts(__HELP_FORM);
          is_valid_cmd = true;
          break;
        
        case CMD_DIR:
          if(sscanf(input, "%*s %1s", check) == 1)
            {
              puts("WRONG INSTRUCTION");
              break;
            }
          // open directory and read through all elem.
          i = 1;
          dirp = opendir(".");
          dir = readdir(dirp);
          for(; dir!=NULL; dir = readdir(dirp))
            {
              struct stat st;
              if(stat((const char*) dir->d_name, &st)!=0)
                {
                  puts("FILE NOT FOUND");
                  goto memory_clear;
                }
              // FIX: ignore . and ..
              if(_SAME_STR(dir->d_name, ".")
                 || _SAME_STR(dir->d_name, ".."))
                continue;
              printf("%20s", dir->d_name);
              if(S_ISDIR(st.st_mode)) // is Directory?
                putchar('/');
              else if( (st.st_mode & S_IXUSR) // is exe?
                 || (st.st_mode & S_IXGRP)
                 || (st.st_mode & S_IXOTH) )
                putchar('*');
              putchar('\t');
             
              // print newline after 3 elements
              if((i++)%3==0)
                putchar('\n');
            }
          if((i-1)%3!=0)
            putchar('\n');
          
          is_valid_cmd = true;
          break;
        
        case CMD_QUIT:
          if(sscanf(input, "%*s %1s", check) == 1)
            {
              puts("WRONG INSTRUCTION");
              break;
            }
          
          is_valid_cmd = true;
          goto memory_clear;
        
        case CMD_HISTORY:
          if(sscanf(input, "%*s %1s", check) == 1)
            {
              puts("WRONG INSTRUCTION");
              break;
            }
          qe = q_begin (&cmd_queue);
          i = 1;
          // print every formatted history
          for (; qe!=q_end(&cmd_queue); qe=q_next(qe))
            printf("%-4d %s\n", i++,
                   q_entry(qe, struct cmd_elem, elem)->cmd);
          printf("%-4d %s\n", i, input);
          
          is_valid_cmd = true;
          break;
        
        case CMD_DUMP:
          switch(sscanf(input, "%s %x , %x", cmd, &start, &end))
            {
            case 1:
              if(sscanf(input, "%*s %1s", check) == 1)
                {
                  puts("WRONG INSTRUCTION");
                  break;
                }
              start = get_location (0, false);
              end = start + 0x10 * 10 - 1;
              // if end is too large, point to end and go 0
              if ( end >= __MEMORY_SIZE )
                end = __MEMORY_SIZE - 1;
              hexdump (mem, start, end);
              if ( end == __MEMORY_SIZE - 1)
                get_location (0, true);
              else
                get_location (end + 1, true);
              
              is_valid_cmd = true;
              break;
            
            case 2:
              if(sscanf(input, "%*s %*x %1s", check) == 1)
                {
                  puts("WRONG INSTRUCTION");
                  break;
                }
              if (start >= __MEMORY_SIZE)
                {
                  puts("OUT OF MEMORY BOUNDS.");
                  break;
                }
              end = start + 0x10 * 10 - 1;
              // if end is too large, point to end and go 0
              if ( end >= __MEMORY_SIZE )
                end = __MEMORY_SIZE - 1;
              hexdump (mem, start, end);
              if ( end == __MEMORY_SIZE - 1)
                get_location (0, true);
              else
                get_location (end + 1, true);
              
              is_valid_cmd = true;
              break;
            
            case 3:
              if(sscanf(input, "%*s %*x , %*x %1s", check) == 1)
                {
                  puts("WRONG INSTRUCTION");
                  break;
                }
              if (!(start<=end && end<__MEMORY_SIZE))
                {
                  puts("OUT OF MEMORY BOUNDS.");
                  break;
                }
              hexdump (mem, start, end);
              // if end is too large, point to end and go 0
              if ( end == __MEMORY_SIZE - 1)
                get_location (0, true);
              else
                get_location (end + 1, true);
              
              is_valid_cmd = true;
              break;

            default:
              puts("WRONG INSTRUCTION");
              break;
            }
          break;
        
        case CMD_EDIT:
          switch(sscanf(input, "%s %x , %hhx",
                        cmd, &start, &value))
            {
            case 3:
              if(sscanf(input, "%*s %*x , %*x %1s", check) == 1)
                {
                  puts("WRONG INSTRUCTION");
                  break;
                }
              hexfill (mem, __MEMORY_SIZE, start, start, value);
              
              is_valid_cmd = true;
              break;
            
            default:
              puts("WRONG INSTRUCTION");
              break;
            }
          break;
        
        case CMD_FILL:
          switch(sscanf(input, "%s %x , %x , %hhx",
                        cmd, &start, &end, &value))
            {
            case 4:
              if(sscanf(input,
                        "%*s %*x , %*x , %*x %1s", check) == 1)
                {
                  puts("WRONG INSTRUCTION");
                  break;
                }
              hexfill (mem, __MEMORY_SIZE, start, end, value);
              
              is_valid_cmd = true;
              break;
            
            default:
              puts("WRONG INSTRUCTION");
              break;
            }
          break;

        case CMD_RESET:
          if(sscanf(input, "%*s %1s", check) == 1)
            {
              puts("WRONG INSTRUCTION");
              break;
            }
          // equivalent to fill 0, __MEMORY_SIZE-1
          hexfill (mem, __MEMORY_SIZE, 0, __MEMORY_SIZE - 1, 0);
              
          is_valid_cmd = true;
          break;

        case CMD_OPCODE:
          switch(sscanf(input, "%*s %s", cmd))
            {
            case 1:
              if(sscanf(input, "%*s %*s %1s", check) == 1)
                {
                  puts("WRONG INSTRUCTION");
                  break;
                }
              i = find_oplist (cmd);
              if (i != -1)
                printf("opcode is %02X\n", i);
              else
                {
                  printf("%s: NO SUCH OPCODE\n", cmd);
                  is_valid_cmd = false;
                }
              break;

            default:
              puts("WRONG INSTRUCTION");
              break;
            }
          break;

        case CMD_OPCODELIST:
          if(sscanf(input, "%*s %1s", check) == 1)
            {
              puts("WRONG INSTRUCTION");
              break;
            }
          print_oplist ();
          is_valid_cmd = true;
          break;

        case CMD_ASSEMBLE:
          // Processing input string
          snprintf((char *) __CMD_FORMAT,
                   __CMD_FORMAT_SIZE,
                   "%%%ds %%%ds %%1s",
                   __CMD_SIZE - 1,
                   __FILENAME_SIZE - 1);
          if (sscanf(input,
                     (const char *) __CMD_FORMAT,
                     cmd, filename, check)!=2)
            {
              puts("WRONG INSTRUCTION");
              break;
            }
          if (!is_file((const char*)filename))
            {
              puts("FILE NOT FOUND");
              break;
            }

          is_valid_cmd = assemble_file (filename);

          break;

        case CMD_TYPE:
          // Processing input string
          snprintf((char *) __CMD_FORMAT,
                   __CMD_FORMAT_SIZE,
                   "%%%ds %%%ds %%1s",
                   __CMD_SIZE - 1,
                   __FILENAME_SIZE - 1);
          if (sscanf(input,
                     (const char *) __CMD_FORMAT,
                     cmd, filename, check)!=2)
            {
              puts("WRONG INSTRUCTION");
              break;
            }
          if (!is_file((const char*)filename))
            {
              puts("FILE NOT FOUND");
              break;
            }
          else
            {
              print_file((const char*)filename);
              is_valid_cmd = true;
            }

          break;

        case CMD_SYMBOL:
          if(sscanf(input, "%*s %1s", check) == 1)
            {
              puts("WRONG INSTRUCTION");
              break;
            }

          print_symbol_table ();
          is_valid_cmd = true;

          break;

        case CMD_PROGADDR:
          if(sscanf(input, "%*s %*x %1s", check) == 1
             || sscanf(input, "%*s %x", &i) != 1)
            {
              puts("WRONG INSTRUCTION");
              break;
            }
          if (i < 0 || i >= __MEMORY_SIZE - 1)
            {
              puts("INVALID PROGRAM ADDRESS");
              break;
            }

          set_progaddr ((uint32_t) i);
          is_valid_cmd = true;

          break;

        case CMD_LOADER:
          init_loader ();
          tok = strtok (input, " ");
          while ( (tok = strtok (NULL, " ")) != NULL)
            {
              if (!is_file (tok))
                {
                  printf ("[%s]: INVALID FILE\n", tok);
                  free_loader ();
                  break;
                }
              if (!add_obj_loader (tok))
                {
                  printf ("[%s]: LOADER FAILED\n", tok);
                  free_loader ();
                  break;
                }
            }

          // if normally added
          if (tok == NULL)
            {
              // address __MEMORY_SIZE is reserved for boot
              if (get_proglen()+get_progaddr()>=__MEMORY_SIZE-1)
                {
                  puts ("PROGRAM IS TOO BIG: LOADER FAILED");
                  free_loader ();
                  break;
                }
              if (!run_loader (mem))
                {
                  puts ("LOADER FAILED");
                  free_loader ();
                  break;
                }
              print_load_map ();
            }
          free_loader ();
          is_valid_cmd = true;

          break;

        case CMD_RUN:
          if(sscanf(input, "%*s %1s", check) == 1)
            {
              puts("WRONG INSTRUCTION");
              break;
            }
          if (!init_run ())
            {
              puts ("RUN FAILED");
              free_run ();
              break;
            }
          run (mem);
          free_run ();
          is_valid_cmd = true;

          break;

        case CMD_BP:
          if(sscanf(input, "%*s %1s", check) != 1)
            {
              print_bp ();
              is_valid_cmd = true;
              break;
            }
          if(sscanf(input, "%*s %6s %1s", cmd, check) == 2
             || sscanf(input, "%*s %6s", cmd) != 1)
            {
              puts("WRONG INSTRUCTION");
              break;
            }
          if (_SAME_STR(cmd, "clear"))
            {
              puts ("\t[ok] clear all breakpoints");
              free_bp ();
              is_valid_cmd = true;
              break;
            }

          if(sscanf(input, "%*s %*x %1s", check) == 1
             || sscanf(input, "%*s %x", &start) != 1)
            {
              puts("WRONG INSTRUCTION");
              break;
            }
          if (start >= __MEMORY_SIZE - 1)
            {
              puts ("INVALID BREAKPOINT ADDRESS");
              break;
            }
          if (add_bp (start))
            printf ("\t[ok] create breakpoint %x\n", start);
          is_valid_cmd = true;

          break;

        default:
          if(sscanf(input, "%1s", check) == 1)
            {
              puts("WRONG INSTRUCTION");
              break;
            }
        }

      if (is_valid_cmd)
        {
          // Saving commands
          struct cmd_elem *e = malloc(sizeof(struct cmd_elem));
          if (e == NULL)
            {
              puts("MEMORY INSUFFICIENT.");
              goto memory_clear;
            }
          e->cmd = malloc(sizeof(char)*(strlen(input)+1));
          if (e->cmd == NULL)
            {
              puts("MEMORY INSUFFICIENT.");
              goto memory_clear;
            }
          strcpy(e->cmd, input);
          q_insert (&cmd_queue, &(e->elem));
        } 
    }


memory_clear:
  if (mem != NULL)
    free (mem);
  if (input != NULL)
    free (input);
  if (cmd != NULL)
    free (cmd);
  while (!q_empty(&cmd_queue))
    {
      struct q_elem *e = q_delete(&cmd_queue);
      struct cmd_elem *ce = q_entry(e, struct cmd_elem, elem);
      if (ce->cmd != NULL)
        free(ce->cmd);
      free(ce);
    }
  free_oplist ();
  free_loader ();
  free_bp ();
  free_run ();

  return 0;
}