void Connection::onReadyRead() {

    while (bytesAvailable()) {
        if (!mOpLength) {
            // calculate length, read first byte
            qint32 readed = readIn(&mOpLength, 1);
            if (mOpLength == 0x7f) {
                readed = readIn(&mOpLength, 3);
            }
            Q_UNUSED(readed)
            mOpLength *= 4;
        }

        QByteArray buffer = readIn(mOpLength - mBuffer.length());

        qint32 opReaded = buffer.length() + mBuffer.length();

        if (opReaded == mOpLength) {
            //process request
            mBuffer.append(buffer);
            QMetaObject::invokeMethod(this, "processRpcAnswer", Qt::QueuedConnection, Q_ARG(QByteArray, mBuffer));
            mOpLength = 0;
            mBuffer.clear();
        } else if (opReaded < mOpLength) {
            mBuffer.append(buffer);
        }
    }
}
Esempio n. 2
0
int readGraph(){
    int startVertex = 0 ;
    int n = 0 ;
    scanf("%d",&startVertex);
    scanf("%d",&n);

    int ** matrix = readIn(n);
    printMatrix(matrix,n);

    struct queue* q = (struct queue*)malloc(sizeof(struct queue));
    init(q);
    struct stack stk;
    initialize(&stk);
    int * visited = (int *) malloc(sizeof(int)*n);
    int i = 0 ;
    for ( i = 0 ; i < n ; i++ ) visited[i] = 0 ;

    printf("\nBreadth First: ");
    breadthFirst(matrix,startVertex,n,q);


    printf("\nDepth First: ");
    depthFirst(matrix,startVertex,n,stk);
    printf("\nDepth First: ");
    depthCaller(matrix,n);
    printf("\n");

    free(q);
    free(visited);
    free(matrix);

    return 0 ;
}
Esempio n. 3
0
//This method creates a readIn process by forking the current process.
void createReadIn(){
	//Instantiating a variable to check pid.
	pid_t childPID;
	//Creates a child process by forking.
	switch(childPID = fork()){
		//Checks if forked successfully
		case -1:
			perror("fork failed");
			exit(EXIT_FAILURE);
		//If it is a child process, close the appropriate pipes and call readIn with the appropriate open pipes
		case 0:
			close(pipe1[0]);
			close(pipe2[0]);
			close(pipe2[1]);
			close(pipe3[0]);
			close(pipe3[1]);
			readIn(pipe1[1]);
			break;
		//Default is run by the parent process which continues to fork more processes by calling a
		//function to create process1. It then waits for child process before completing.
		default:
			createProcess1();
			wait();
	}
}
Esempio n. 4
0
void onStart() {
    readIn();
    initAllGPU("matrixmul.cl", clCallFunc);
    executeGPU(clCallFunc);
    writeOut();
    destroyGPU(clCallFunc);
}
Esempio n. 5
0
int main(int argc, char** argv)
{  
  size_t from_len = arrlen(argv[1]);

  /* Return error if 'from' & 'to' don't have the same size */
  if(from_len != arrlen(argv[2])) 
    goto ERROR_LEN_EXIT;

  /* Return error if 'from' contains duplicates */
  if(containsDuplicates(argv[1],from_len))
    goto ERROR_DUP_EXIT;

  int buffer;
  size_t i;
  while (readIn(buffer) != EOF) 
  {    
    /* If read byte belongs to 'from', then translate it */
    for(i=0;i<from_len;i++)
      if(buffer == argv[1][i])
	buffer = argv[2][i];

    writeOut(buffer);
  } 

  exit(0);

 ERROR_LEN_EXIT:
    fprintf(stdout,"'from' and 'to' are not the same length\n");
    exit(1);
 ERROR_DUP_EXIT:
    fprintf(stdout,"'from' contains duplicates \n");
    exit(1);
}
Esempio n. 6
0
int		main(int ac, char **av)
{
  bool		help = false;
  bool		verbose = check_op(ac, av, help);

  if (!help)
    {
      if (!(optind < ac))
	readIn(verbose);
      else
	{
	  for (; optind < ac; optind += 1)
	    {
	      std::cout << "---     ---     ---     ---" << std::endl
			<< "  Debut du fichier " << av[optind] << ": "
			<< std::endl
			<< "---     ---     ---     ---" << std::endl;
	      readOut(av[optind], verbose);
	      std::cout << "---     ---     ---     ---" << std::endl
			<< "  Fin du fichier " << av[optind] << "."
			<< std::endl
			<< "---     ---     ---     ---" << std::endl;
	    }
	}
    }
  return (0);
}
Esempio n. 7
0
int main(){
  int op;
  std::list<student> studentlist;
  readIn(studentlist);
  cout<<"Main menu start\n\n\n";
    do{
      op=mainMenu();
      switch(op){
	 case 1:printMenu(studentlist);
         break;
	 case 2: findStudents(studentlist);
	 break;
	 case 3: addStudent(studentlist);
	 break;
	 case 4: modifyStudentMenu(studentlist);
	 break;
	 case 5: deleteStudentMenu(studentlist);
	 break;
	 case 6:writeToFile(studentlist);
       }
  }while(op!=6);
 return 0;
    

}
Esempio n. 8
0
/* loadPresetFile: private function that loads a specific preset denoted
   by the given pathname */
int Preset::loadPresetFile(const std::string & pathname)
{
  /* Open the file corresponding to pathname */
  FILE* f = fopen(pathname.c_str(), "r");
  if (!f) {
    if (PRESET_DEBUG)
    	std::cerr << "loadPresetFile: loading of file \"" << pathname << "\" failed!\n";
    return PROJECTM_ERROR;
  }

  fseek(f, 0, SEEK_END);
  long fsize = ftell(f);
  rewind(f);
  std::vector<char> buffer(fsize);

  int err = fread(&buffer[0], 1, fsize, f);
  if (!err)
  {
    printf("read failed\n");
    fclose(f);
    return PROJECTM_ERROR;
  }

  fclose(f);
  std::stringstream stream;
  stream.rdbuf()->pubsetbuf(&buffer[0],buffer.size());
  return readIn(stream);
}
Esempio n. 9
0
int main()
{
	chainingTable hash(250'003);

	readIn("dictionary.txt", hash);

	string word1, word2, word3;
	word1 = "notaword";
	word2 = "hello";
	word3 = "sulfamethoxazole";

	if (hash.contains(word1))
		cout << "The word " << word1 << " is a real word" << endl;
	else
		cout << "The word " << word1 << " is not real word" << endl;

	if (hash.contains(word2))
		cout << "The word " << word2 << " is a real word" << endl;
	else
		cout << "The word " << word2 << " is not real word" << endl;
	
	if (hash.contains(word3))
		cout << "The word " << word3 << " is a real word" << endl;
	else
		cout << "The word " << word3 << " is not real word" << endl;

	cout << "My program's average search cost is: " << hash.averageSearchCost() << endl;

	spell_check_file("raven.txt", hash);

	return 0;
}
Esempio n. 10
0
int main() {

    int i;
    int vals[10];
    struct heapStruct *h;
    h = initHeap();

    // Insert from input stream.
    h = readIn(h);
    // print it
    printHeap(h);

    // Delete some and print delete and new heap
    for (i=0; i<9; i++) {
        printf("Delete %d\n",removeMin(h));
        printHeap(h);
    }
    freeHeap(h);

    // Test out array initialization.
    vals[0] = 12, vals[1] = 3, vals[2] = 18, vals[3] = 14, vals[4] = 5;
    vals[5] = 9, vals[6] = 1, vals[7] = 7; vals[8] = 2, vals[9] = 13;

    sort(vals, 10);

    for (i=0; i<10; i++)
        printf("%d ", vals[i]);
    printf("\n");

    system("echo \"done\"");
    return 0;
}
Esempio n. 11
0
void onStart() {
    initAllGPU("vecdot.cl", clCallFunc);
    while (readIn()) {
        executeGPU(clCallFunc);
        writeOut();
    }
    destroyGPU(clCallFunc);
}
Esempio n. 12
0
int main( int argc, char * argv[] ){

    readIn( argc, argv );
    printf( "Done reading.\n" );
    

    return 0;
}
Esempio n. 13
0
void onStart() {
	char kernelName[][32] = {"vecdot", "reduction"};
	initAllGPU("vecdot.cl", kernelName, clCallFunc);
	int N;
	uint32_t keyA, keyB;
	while (readIn(&N, &keyA, &keyB))
		executeGPU(clCallFunc, N, keyA, keyB);
	destroyGPU(clCallFunc);
}
Esempio n. 14
0
int main(int argc, char** argv){
  char* k11File = NULL;
  bool MEASURETIME = false;
  for (int i = 1; i < argc; i++){
    char* rg = argv[i];
    D_(1, "%s\n", rg);
    if (rg[0] == 0x2d){
      if (EQ(rg, "-v")) DEBUG = 1;
      if (EQ(rg, "-vv")) DEBUG = 2;
      if (EQ(rg, "-t")) MEASURETIME = true;
    }
    else{
      k11File = rg;
    }
  }
  if (!k11File){
    fprintf(stderr, "Use: %s k11_index_file [-v]\n", argv[0]);
    return 1;
  }
  printf("Reading %s...\n", k11File);
  kmerHolder* kh = readIn(k11File);
  printf("Done\n");
  printf("Please enter one sequence at a time\n");
  char* seq = (char*) calloc(0xFFFF, sizeof(char));
  while (scanf("%s", seq) > 0){
    uint32_t times = 1;
    time_t ts = 0;
    time_t te = 0;
    bool done = false;
    if (MEASURETIME){
      times = REPS;
      ts = time(NULL);
    }
    for (uint32_t i = 0; i < times; i++){
      seqCollection* result = searchSeq(&kh, seq);
      if (!done){
        printSeqCollection(&kh, &result);
        printf("\n");
      }
      destroySeqCollection(&result);
      done = true;
    }
    if (MEASURETIME){
      te = time(NULL);
      printf("Done %" PRIu32 " times in %"PRIu32"\n", times, (uint32_t)((te - ts)));
    }
  }
  printf("Cleaning...\n");
  free(seq);
  destroyKh(&kh);
  return 0;
}
Esempio n. 15
0
/* loadPresetFile: private function that loads a specific preset denoted
   by the given pathname */
int MilkdropPreset::loadPresetFile(const std::string & pathname)
{


  /* Open the file corresponding to pathname */
  std::ifstream fs(pathname.c_str());
  if (!fs || fs.eof()) {
    if (MILKDROP_PRESET_DEBUG)
    	std::cerr << "loadPresetFile: loading of file \"" << pathname << "\" failed!\n";
    return PROJECTM_ERROR;
  }

 return readIn(fs);

}
Esempio n. 16
0
void Preset::initialize(std::istream & in)
{
  int retval;

  preloadInitialize();

  if ((retval = readIn(in)) < 0)
  {

	if (PRESET_DEBUG)
     std::cerr << "[Preset] failed to load from stream " << std::endl; 

    /// @bug how should we handle this problem? a well define exception?
    throw retval;
  }

  postloadInitialize();
}
Esempio n. 17
0
int sumTrees(int &no_of_lines){
    std::vector<int> runningTotal(no_of_lines, 0);
    for(int i = 1; i <= no_of_lines; ++i)
    {
        std::vector<int> next_line(i, 0);
        readIn(next_line); // scan in next line from console to the vector
        std::vector<int> clone = runningTotal;
        for(int j = 0; j < i; ++j)
        {
            if(j != 0)
            {
                clone[j] =
                max(runningTotal[j] + next_line[j], runningTotal[j - 1] + next_line[j]);
            }
            else
            {
                clone[j] =
                runningTotal[j] + next_line[j];
            }
        }
        runningTotal = clone;
    }
    return max(runningTotal);
}
Esempio n. 18
0
Lexicon::Lexicon(string lexFile)
{
	lexicon_.resize(LETTERS_IN_ALPHABET);//initialize lexicon to size of
	readIn(lexFile);		     //all letters in alphabet
}
Esempio n. 19
0
int main(int argc, char **argv)
{
	bool printUsageAndExit = true;
	bool showDebug = false;
	bool showInfo = false;

	EPath prog(argv[0]);
	EStringArray files;
	const char *lang = "C";
	const char *style = "DocBook";
	const char *options = NULL;
	files.AddItem(NULL);

	const char *tmp_env = getenv("LC_ALL");
	if(tmp_env == NULL) tmp_env = getenv("LANG");
	if(tmp_env != NULL) lang = tmp_env;

	do {
		if(argc < 2) break;

		for(int n = 1; n < argc; n++)
		{
			if(strcmp(argv[n], "-s") == 0)
			{
				if(argc - n < 2) break;
				n++;
				style = argv[n];
			}
			else if(strcmp(argv[n], "-t") == 0)
			{
				if(argc - n < 2) break;
				n++;
				options = argv[n];
			}
			else if(strcmp(argv[n], "-o") == 0)
			{
				if(argc - n < 2) break;
				n++;
				if(files.ReplaceItem(0, argv[n]) == false) break;
			}
			else if(strcmp(argv[n], "-l") == 0)
			{
				if(argc - n < 2) break;
				n++;
				lang = argv[n];
			}
			else if(strcmp(argv[n], "--debug") == 0)
			{
				showDebug = true;
			}
			else if(strcmp(argv[n], "--showinfo") == 0)
			{
				showInfo = true;
			}
			else
			{
				files.AddItem(argv[n]);
			}
		}

		if(files.CountItems() < 2) break;

		printUsageAndExit = false;
	} while(false);

	if(printUsageAndExit)
	{
		print_usage(prog.Leaf());
		exit(1);
	}

	EString xml_buffer;
	EString strDocStart = "<document ";
	EString strDocEnd = "</document>";

	for(eint32 i = 1; i < files.CountItems(); i++)
	{
		if(files.ItemAt(i) == NULL) continue;
		EPath readInPath(files.ItemAt(i)->String(), NULL, true);
		EFile readIn(readInPath.Path(), E_READ_ONLY);
		if(readIn.InitCheck() != E_OK)
		{
			ETK_DEBUG("[%s] --- Unable to read \"%s\".", prog.Leaf(), files.ItemAt(i)->String());
			continue;
		}

		eint32 old_length = xml_buffer.Length();

		char buffer[BUFFER_SIZE];
		bool foundDocEnd = true;
		size_t nLeave = 0;
		xml_buffer.AppendFormat("<!-- convert from \"%s\" -->\n", readInPath.Leaf());
		while(true)
		{
			ssize_t len = readIn.Read(buffer + nLeave, BUFFER_SIZE - nLeave);
			if(len <= 0) break;
			EString str;
			str.SetTo(buffer, len + nLeave);
			str.RemoveAll("\r");
			eint32 offset = 0;
			while(offset >= 0 && offset < str.Length())
			{
				nLeave = 0;
				if(foundDocEnd)
				{
					offset = str.FindFirst("/*", offset);
					if(offset < 0)
					{
						if(str.Length() < 2) break;
						if(str[str.Length() - 1] == '/' && str[str.Length() - 2] != '*') nLeave = 1; break;
					}

					nLeave = str.Length() - offset;
					offset = str.FindFirst("\n", offset);
					if(offset < 0)
					{
						if(nLeave > 80) nLeave = 0;
						break;
					}
					nLeave = 0;

					offset++;
					if(offset >= str.Length()) break;

					if(strDocStart.Compare(str.String() + offset, strDocStart.Length()) != 0)
					{
						eint32 tmp = str.FindLast("<");
						if(tmp >= 0 && str.Length() - tmp < strDocStart.Length())
						{
							nLeave = str.Length() - tmp;
						}
						else
						{
							nLeave = 0;
						}
						continue;
					}

					foundDocEnd = false;
				}

				eint32 endOffset = str.FindFirst(strDocEnd, offset);
				if(endOffset >= 0)
				{
					endOffset += strDocEnd.Length();
					foundDocEnd = true;
					nLeave = 0;
				}
				else
				{
					eint32 tmp = str.FindLast("<");
					if(tmp >= 0 && str.Length() - tmp < strDocEnd.Length())
					{
						nLeave = str.Length() - tmp;
					}
					else
					{
						nLeave = 0;
					}
				}

				xml_buffer.Append(str.String() + offset, (endOffset >= 0 ? endOffset : str.Length()) - offset - nLeave);
				if(foundDocEnd) xml_buffer.Append("\n");
				offset = endOffset;
			}
			if(nLeave > 0) str.CopyInto(buffer, BUFFER_SIZE, str.Length() - nLeave, nLeave);
		}

		if(foundDocEnd == false)
		{
			xml_buffer.Remove(old_length, -1);
			ETK_DEBUG("[%s] --- Invalid document \"%s\".", prog.Leaf(), readInPath.Path());
		}
	}

	EString output_buffer;

	if(strcmp(style, "None") == 0)
	{
		output_buffer.Adopt(xml_buffer);
	}
	else if(strcmp(style, "DocBook") == 0)
	{
		xml_buffer.ReplaceAll("&", "&amp;");
		xml_buffer.ReplaceAll("&amp;lt;", "&lt;");
		xml_buffer.ReplaceAll("&amp;gt;", "&gt;");
		xml_buffer.ReplaceAll("&amp;nbsp;", "&nbsp;");
		xml_buffer.ReplaceAll("©", "&copy;");
		xml_buffer.ReplaceAll("®", "&reg;");
		xml_buffer.ReplaceAll("\n", "&br;");

		eint32 offset = 0;
		while(offset >= 0 && offset < xml_buffer.Length())
		{
			if((offset = xml_buffer.FindFirst(">", offset)) < 0) break;
			eint32 tmp = xml_buffer.FindFirst("<", offset);
			if(tmp < 0 || tmp - offset <= 1) {offset = tmp; continue;}
			EString str;
			xml_buffer.MoveInto(str, offset + 1, tmp - offset);
			str.ReplaceAll(" ", "&nbsp;");
			xml_buffer.Insert(str, offset + 1);
			offset += str.Length() + 1;
		}

		ESimpleXmlNode node(NULL, NULL);
		if(etk_parse_simple_xml(xml_buffer.String(), &node) != E_OK)
		{
			ETK_OUTPUT("[%s] --- Unable to parse.\n", prog.Leaf());
			exit(1);
		}

		ESimpleXmlNode *aNode = NULL;
		offset = 0;
		while(offset >= 0 && offset < node.CountNodes())
		{
			if((offset = node.FindNode("document", offset)) < 0) break;
			if((aNode = node.NodeAt(offset)) == NULL) break;

			eint32 index = aNode->FindAttribute("lang");
			const char *tmp = NULL;
			if(index < 0 || aNode->AttributeAt(index, &tmp) == NULL || tmp == NULL || strcmp(tmp, lang) != 0)
			{
				aNode->RemoveSelf();
				delete aNode;
				continue;
			}

			offset++;
		}

		aNode = find_xml_node_deep(&node, "documentinfo");
		if(aNode != NULL)
		{
			if(!showInfo)
			{
				ESimpleXmlNode *cNode = aNode->NodeAt(aNode->FindNode("title"));
				if(cNode) cNode->RemoveSelf();
				ESimpleXmlNode *nNode;
				while((nNode = aNode->NodeAt(0)) != NULL) {nNode->RemoveSelf(); delete nNode;}
				if(cNode) aNode->AddNode(cNode);
			}
			aNode->RemoveSelf();
			if(node.AddNode(aNode) == false) delete aNode;
		}

		foreach_xml_node(&node, NULL, docbook_foreach, NULL);

		if(showDebug) node.PrintToStream();

		if(convert_to_docbook(&node, &output_buffer, options, lang) != E_OK)
		{
			ETK_OUTPUT("[%s] --- Unable to convert to \"DocBook\" style.\n", prog.Leaf());
			exit(1);
		}
	}
	else
	{
		ETK_OUTPUT("[%s] --- style \"%s\" unsupport yet.\n", prog.Leaf(), style);
		exit(1);
	}

	if(files.ItemAt(0) == NULL || files.ItemAt(0)->String() == NULL)
	{
		for(eint32 offset = 0; offset < output_buffer.Length(); offset += BUFFER_SIZE)
		{
			EString str(output_buffer.String() + offset, BUFFER_SIZE);
			fprintf(stdout, "%s", str.String());
		}
	}
	else
	{
		EFile writeOut(files.ItemAt(0)->String(), E_WRITE_ONLY | E_CREATE_FILE | E_ERASE_FILE);
		if(writeOut.InitCheck() != E_OK)
		{
			ETK_OUTPUT("[%s] --- Unable to write \"%s\".\n", prog.Leaf(), files.ItemAt(0)->String());
			exit(1);
		}
		else
		{
			for(eint32 offset = 0; offset < output_buffer.Length(); offset += BUFFER_SIZE)
				writeOut.Write(output_buffer.String() + offset, min_c(BUFFER_SIZE, output_buffer.Length() - offset));
		}
	}

	return 0;
}
Esempio n. 20
0
int main(int argc, char **argv)
{
  int            r;
  int            handle;
  struct termios attr;
  char *         name   = argv[0];
  char *         device = 0;
  struct stat    statbuf;
  int            pid = 0;
  int            speed;

  setProgName(argv[0]);
  while (argc > 1)
  {
    if (strcasecmp(argv[1], "-version") == 0)
    {
      printf("%s\n", VERSION);
      exit(0);
    }
    else if (strcasecmp(argv[1], "-w") == 0)
    {
      writeonly = 1;
    }
    else if (strcasecmp(argv[1], "-p") == 0)
    {
      passthru = 1;
    }
    else if (strcasecmp(argv[1], "-r") == 0)
    {
      readonly = 1;
    }
    else if (strcasecmp(argv[1], "-v") == 0)
    {
      verbose = 1;
    }
    else if (strcasecmp(argv[1], "-t") == 0 && argc > 2)
    {
      argc--;
      argv++;
      timeout = strtol(argv[1], 0, 10);
      logDebug("timeout set to %ld seconds\n", timeout);
    }
    else if (strcasecmp(argv[1], "-s") == 0 && argc > 2)
    {
      argc--;
      argv++;
      speed = strtol(argv[1], 0, 10);
      switch (speed)
      {
        case 38400:
          baudRate = B38400;
          break;
        case 57600:
          baudRate = B57600;
          break;
        case 115200:
          baudRate = B115200;
          break;
        case 230400:
          baudRate = B230400;
          break;
#ifdef B460800
        case 460800:
          baudRate = B460800;
          break;
#endif
#ifdef B921600
        case 921600:
          baudRate = B921600;
          break;
#endif
        default:
          baudRate = speed;
          break;
      }
      logDebug("speed set to %d (%d) baud\n", speed, baudRate);
    }
    else if (strcasecmp(argv[1], "-d") == 0)
    {
      setLogLevel(LOGLEVEL_DEBUG);
    }
    else if (strcasecmp(argv[1], "-o") == 0)
    {
      outputCommands = 1;
    }
    else if (!device)
    {
      device = argv[1];
    }
    else
    {
      device = 0;
      break;
    }
    argc--;
    argv++;
  }

  if (!device)
  {
    fprintf(stderr,
            "Usage: %s [-w] -[-p] [-r] [-v] [-d] [-s <n>] [-t <n>] device\n"
            "\n"
            "Options:\n"
            "  -w      writeonly mode, no data is read from device\n"
            "  -r      readonly mode, no data is sent to device\n"
            "  -p      passthru mode, data on stdin is sent to stdout but not to device\n"
            "  -v      verbose\n"
            "  -d      debug\n"
            "  -s <n>  set baudrate to 38400, 57600, 115200, 230400"
#ifdef B460800
            ", 460800"
#endif
#ifdef B921600
            ", 921600"
#endif
            "\n"
            "  -t <n>  timeout, if no message is received after <n> seconds the program quits\n"
            "  -o      output commands sent to stdin to the stdout \n"
            "  <device> can be a serial device, a normal file containing a raw log,\n"
            "  or the address of a TCP server in the format tcp://<host>[:<port>]\n"
            "\n"
            "  Examples: %s /dev/ttyUSB0\n"
            "            %s tcp://192.168.1.1:10001\n"
            "\n" COPYRIGHT,
            name,
            name,
            name);
    exit(1);
  }

retry:
  logDebug("Opening %s\n", device);
  if (strncmp(device, "tcp:", STRSIZE("tcp:")) == 0)
  {
    handle = open_socket_stream(device);
    logDebug("socket = %d\n", handle);
    isFile = true;
    if (handle < 0)
    {
      fprintf(stderr, "Cannot open NGT-1-A TCP stream %s\n", device);
      exit(1);
    }
  }
  else
  {
    handle = open(device, O_RDWR | O_NOCTTY | O_NONBLOCK);
    logDebug("fd = %d\n", handle);
    if (handle < 0)
    {
      logAbort("Cannot open NGT-1-A device %s\n", device);
    }
    if (fstat(handle, &statbuf) < 0)
    {
      logAbort("Cannot determine device %s\n", device);
    }
    isFile = S_ISREG(statbuf.st_mode);
  }

  if (isFile)
  {
    logInfo("Device is a normal file, do not set the attributes.\n");
  }
  else
  {
    logDebug("Device is a serial port, set the attributes.\n");

    memset(&attr, 0, sizeof(attr));
    if (cfsetspeed(&attr, baudRate) < 0)
    {
      logAbort("Could not set baudrate %d\n", speed);
    }
    attr.c_cflag |= CS8 | CLOCAL | CREAD;

    attr.c_iflag |= IGNPAR;
    attr.c_cc[VMIN]  = 1;
    attr.c_cc[VTIME] = 0;
    tcflush(handle, TCIFLUSH);
    tcsetattr(handle, TCSANOW, &attr);

    logDebug("Device is a serial port, send the startup sequence.\n");

    writeMessage(handle, NGT_MSG_SEND, NGT_STARTUP_SEQ, sizeof(NGT_STARTUP_SEQ));
    sleep(2);
  }

  for (;;)
  {
    unsigned char msg[BUFFER_SIZE];
    size_t        msgLen;
    int           r = isReady(writeonly ? INVALID_SOCKET : handle, readonly ? INVALID_SOCKET : 0, INVALID_SOCKET, timeout);

    if ((r & FD1_ReadReady) > 0)
    {
      if (!readNGT1(handle))
      {
        break;
      }
    }
    if ((r & FD2_ReadReady) > 0)
    {
      if (!readIn(msg, sizeof(msg)))
      {
        break;
      }
      if (!passthru)
      {
        parseAndWriteIn(handle, msg);
      }
      if (outputCommands)
      {
        fprintf(stdout, "%s", msg);
        fflush(stdout);
      }
    }
    else if (writeonly)
    {
      break;
    }
  }

  close(handle);
  return 0;
}
Esempio n. 21
0
int main(void)
{
	FILE *fin;
	FILE *fout,*sourceout;
	char in[132],out[132],in2[132],line[132];
	float lon,lat,lonc,latc,x,y;
	double junk1,junk2,junk3,junk4,junk5,junk6;
	int nt,npoi,ncol,i,j,ndo;
	int j1,j2;
	int nFile,n;
	globalIn inp;
	float rot;
//new v2
//parameter for Rob's code
	double g0, b0;
	double amat[9], ainv[9];
	int xy2ll = 0;
	int ll2xy = 1;
	float erad = ERAD;
//end new v2

	readIn(&inp,"faultGlobal.in");
	ncol=6;
	
	sourceout=fopen("source_model.list","w");
	if(sourceout==NULL)
	{
		printf("can't open source_model.list\n");
		exit(0);
	}

	fprintf(sourceout,"1 0.0\n");

	sprintf(in,"%s.srf",inp.name);
//.if for internal format
	sprintf(out,"%s.001.srf",inp.name);
	fin=fopen(in,"r");
	fout=fopen(out,"w");
	fprintf(sourceout,"%s\n",out);
	if(fin==NULL)
	{
		sprintf(in,"%s",inp.name);
		fin=fopen(in,"r");
		if(fin==NULL)
		{
			printf("can't find %s.srf or %s\n",inp.name,in);
			exit(0);
		}
	}
	if(fout==NULL)
	{
		printf("can't open %s\n",out);
		exit(0);
	}

	fgets(line,132,fin);
	fputs(line,fout);
	fgets(line,132,fin);
	fputs(line,fout);
	fgets(line,132,fin);
	sscanf(line,"%f %f %d %d %lf %lf",&lonc,&latc,&j1,&j2,&junk1,&junk2);
	//as top center is origin of local cosy
	fprintf(fout,"0. 0.  %d %d %lf %lf\n",j1,j2,junk1,junk2);
	fgets(line,132,fin);
	fputs(line,fout);
	fgets(line,132,fin);
	fputs(line,fout);

//set origin
//exchanged v2
	rot=0-90; //no rotation of COSY
   	gen_matrices(amat,ainv,&rot,&lonc,&latc);
	g0=0.0;
	b0=0.0;
//end exchanged v2

	sscanf(line,"%*s %d",&npoi);

	fgets(line,132,fin);
	for(i=0;i<npoi;i++)
	{
		sscanf(line,"%f %f %lf %lf %lf %lf %lf %lf",&lon,&lat,&junk1,&junk2,&junk3,&junk4,&junk5,&junk6);
		//printf("%f %f %f %f\n",lon,lat,lonc,latc);
//exchanged v2
      		gcproj(&x,&y,&lon,&lat,&erad,&g0,&b0,amat,ainv,ll2xy);
//end exchanged v2
		fprintf(fout,"%lf %lf %lf %lf %lf %lf %lf %lf\n",x*1000.,y*1000.,junk1*1000.,junk2,junk3,junk4,junk5,junk6);
		fgets(line,132,fin);
		sscanf(line,"%*s %*s %d",&nt);
		fputs(line,fout);
		//printf("%d\n",nt);
		ndo=floor((double)nt/((double)ncol))+1;
		if((ndo-1)*ncol==nt) ndo--;
		for(j=0;j<ndo;j++)
		{
			fgets(line,132,fin);
			fputs(line,fout);
		}
		fgets(line,132,fin);
	}

	fclose(fin);
	fclose(fout);
	fclose(sourceout);

	return 0;
}
Esempio n. 22
0
void Codebook::unittest()
{
    ofstream file;
    file.open ("tmp.dat435", ios::out);

    file << 3 << endl;
    file << 3 << endl;

    file << 1 << endl;
    file << 0 << endl;
    file << 0 << endl;

    file << 0 << endl;
    file << 1 << endl;
    file << 0 << endl;

    file << 0 << endl;
    file << 0 << endl;
    file << 1 << endl;

    file.close();
    readIn("tmp.dat435");
    save("tmp.dat435");
    codebook.clear();
    inverseDocFreq.clear();
    readIn("tmp.dat435");


    vector<float> term = {.5,0,.1};
    vector< tuple<int,float> > quan = quantizeSoft(term,1);
    assert(get<0>(quan[0])==0 && get<1>(quan[0])==1);

    vector<float> term2 = {.3,0,.3};
    quan = quantizeSoft(term2,2);
    assert(get<1>(quan[0])==.5 && get<1>(quan[1])==.5);

    file.open ("tmp.dat435", ios::out);

    file << 4 << endl;
    file << 4 << endl;

    file << 1 << endl;
    file << 0 << endl;
    file << 0 << endl;
    file << 0 << endl;

    file << 0 << endl;
    file << 1 << endl;
    file << 0 << endl;
    file << 0 << endl;

    file << 0 << endl;
    file << 0 << endl;
    file << 1 << endl;
    file << 0 << endl;

    file << 0 << endl;
    file << 0 << endl;
    file << 0 << endl;
    file << 1 << endl;

    file.close();
    codebook.clear();
    inverseDocFreq.clear();
    readIn("tmp.dat435");

    vector<float> term3 = {.3,0,.2,.1};
    quan = quantizeSoft(term3,3);
    double score0=0;
    double score1=0;
    double score2=0;
    double score3=0;
    for (auto p : quan)
    {
        if (get<0>(p) == 0)
            score0 = get<1>(p);
        else if (get<0>(p) == 1)
            score1 = get<1>(p);
        else if (get<0>(p) == 2)
            score2 = get<1>(p);
        else if (get<0>(p) == 3)
            score3 = get<1>(p);
    }
    assert(score0>score2);
    assert(score2>score3);
    assert(score3>score1);
    assert(score0+score1+score2+score3>=.9999 && score0+score1+score2+score3<=1.0001);
    double sumtest=0;
    for (const auto &v : quan)
    {
        sumtest+=get<1>(v);
    }
    assert(sumtest<1.0001 && sumtest>.9999);

    vector<float> term4 = {.1,.05,.3,.2};
    quan = quantizeSoft(term4,4);
    score0=0;
    score1=0;
    score2=0;
    score3=0;
    for (auto p : quan)
    {
        if (get<0>(p) == 0)
            score0 = get<1>(p);
        else if (get<0>(p) == 1)
            score1 = get<1>(p);
        else if (get<0>(p) == 2)
            score2 = get<1>(p);
        else if (get<0>(p) == 3)
            score3 = get<1>(p);
    }
    assert(score2>score3);
    assert(score3>score0);
    assert(score0>score1);
    assert(score0+score1+score2+score3>=.9999 && score0+score1+score2+score3<=1.0001);
    sumtest=0;
    for (const auto &v : quan)
    {
        sumtest+=get<1>(v);
    }
    assert(sumtest<1.0001 && sumtest>.9999);

    vector<float> term5 = {.1,.05,.3,.1};
    quan = quantizeSoft(term5,3);
    score0=0;
    score1=0;
    score2=0;
    score3=0;
    for (auto p : quan)
    {
        if (get<0>(p) == 0)
            score0 = get<1>(p);
        else if (get<0>(p) == 1)
            score1 = get<1>(p);
        else if (get<0>(p) == 2)
            score2 = get<1>(p);
        else if (get<0>(p) == 3)
            score3 = get<1>(p);
    }
    assert(score2>score3);
    assert(score3==score0);
    assert(score0>score1);
    assert(score0+score1+score2+score3>=.9999 && score0+score1+score2+score3<=1.0001);
    sumtest=0;
    for (const auto &v : quan)
    {
        sumtest+=get<1>(v);
    }
    assert(sumtest<1.0001 && sumtest>.9999);

    vector<float> term6 = {.05,.1,.2,.3};
    quan = quantizeSoft(term6,4);
    score0=0;
    score1=0;
    score2=0;
    score3=0;
    for (auto p : quan)
    {
        if (get<0>(p) == 0)
            score0 = get<1>(p);
        else if (get<0>(p) == 1)
            score1 = get<1>(p);
        else if (get<0>(p) == 2)
            score2 = get<1>(p);
        else if (get<0>(p) == 3)
            score3 = get<1>(p);
    }
    assert(score3>score2);
    assert(score2>score1);
    assert(score1>score0);
    assert(score0+score1+score2+score3>=.9999 && score0+score1+score2+score3<=1.0001);
    sumtest=0;
    for (const auto &v : quan)
    {
        sumtest+=get<1>(v);
    }
    assert(sumtest<1.0001 && sumtest>.9999);

    vector<float> term7 = {.05,1,100,5000};
    quan = quantizeSoft(term7,4);
    score0=0;
    score1=0;
    score2=0;
    score3=0;
    for (auto p : quan)
    {
        if (get<0>(p) == 0)
            score0 = get<1>(p);
        else if (get<0>(p) == 1)
            score1 = get<1>(p);
        else if (get<0>(p) == 2)
            score2 = get<1>(p);
        else if (get<0>(p) == 3)
            score3 = get<1>(p);
    }
    assert(score3>score2);
    assert(score2>=score1);
    //assert(score1>=score0);
    assert(score0+score1+score2+score3>=.9999 && score0+score1+score2+score3<=1.0001);
    sumtest=0;
    for (const auto &v : quan)
    {
        sumtest+=get<1>(v);
    }
    assert(sumtest<1.0001 && sumtest>.9999);

    vector<float> term8 = {.05,1,1000,5000};
    quan = quantizeSoft(term8,4);
    score0=0;
    score1=0;
    score2=0;
    score3=0;
    for (auto p : quan)
    {
        if (get<0>(p) == 0)
            score0 = get<1>(p);
        else if (get<0>(p) == 1)
            score1 = get<1>(p);
        else if (get<0>(p) == 2)
            score2 = get<1>(p);
        else if (get<0>(p) == 3)
            score3 = get<1>(p);
    }
    assert(score3>score2);
    assert(score2>score1);
    //assert(score1>score0);
    assert(score0+score1+score2+score3>=.9999 && score0+score1+score2+score3<=1.0001);
    sumtest=0;
    for (const auto &v : quan)
    {
        sumtest+=get<1>(v);
    }
    assert(sumtest<1.0001 && sumtest>.9999);


    ////Test training of codebook////////
    codebook.clear();
    vector< vector<double> >accum(1000);
    default_random_engine generator;
    normal_distribution<double> distributionP(5.0,.10);
    normal_distribution<double> distributionN(2.0,.10);
    normal_distribution<double> distributionR(3.0,.10);
    for (int i=0; i<accum.size(); i++)
    {
        for (int j=0; j<5*2+2; j++)
        {
            if (i%5 == j%5 && j<10)
                accum[i].push_back(fabs(distributionP(generator)));
            else if (j<10)
                accum[i].push_back(fabs(distributionN(generator)));
            else
                accum[i].push_back(fabs(distributionR(generator)));
        }

    }
    for (int i=0; i<accum.size(); i++)
    {
        for (int j=0; j<accum[i].size(); j++)
        {
            assert(accum[i][j] != 0);
        }
    }

    trainFromExamples(5,accum);

    vector<bool> found(5);
    for (int i=0; i<size(); i++)
    {
        double hi=0;
        int index;
        double hi2=0;
        int index2;
        for (int j=0; j<codebook[i].size(); j++)
        {
            if (codebook[i][j] > hi)
            {
                hi2=hi;
                index2=index;
                hi=codebook[i][j];
                index=j;
            }
            else if (codebook[i][j] > hi2)
            {
                hi2=codebook[i][j];
                index2=j;
            }
        }
        assert (index%5 == index2%5);
        assert(!found[index%5]);
        found[index%5]=true;
    }
    for (int i=0; i<size(); i++)
        assert(found[i]);

    vector<float> term9 = {7,3,3.3,2,2,3,1.5,1.7,.6,1.5,.1,10};
    quan = quantizeSoft(term9,1);
    assert(quan.size()==1 && get<1>(quan[0])==1 && get<0>(quan[0])==cw_0);

    vector<float> term10 = {7,3,3.3,2,10,7.1,2,2,2,12,.1,10};
    quan = quantizeSoft(term10,3);
    score0=0;
    double score4=0;
    double scoreOther=0;
    for (auto p : quan)
    {
        if (get<0>(p) == cw_0)
            score0 = get<1>(p);
        else if (get<0>(p) == cw_4)
            score4 = get<1>(p);
        else
            scoreOther = get<1>(p);
    }
    assert(quan.size()==3 && score0!=0 && score4!=0 && scoreOther!=0);
    assert(score0>scoreOther);
    assert(score4>scoreOther);
    sumtest=0;
    for (const auto &v : quan)
    {
        sumtest+=get<1>(v);
    }
    assert(sumtest<1.0001 && sumtest>.9999);

    vector< vector<double> > copy(codebook.size());
    for (int i=0; i<codebook.size(); i++)
    {
        for (int j=0; j<depth();   j++)
            copy[i].push_back(codebook[i][j]);
    }
    save("tmp.dat435");
    codebook.clear();
    inverseDocFreq.clear();
    readIn("tmp.dat435");
    for (int i=0; i<codebook.size(); i++)
    {
        for (int j=0; j<depth();   j++)
            assert(fabs(copy[i][j] - codebook[i][j])<.00001);
    }
    //double check
    vector<bool> found_doublecheck(5);
    for (int i=0; i<size(); i++)
    {
        double hi=0;
        int index;
        double hi2=0;
        int index2;
        for (int j=0; j<codebook[i].size(); j++)
        {
            if (codebook[i][j] > hi)
            {
                hi2=hi;
                index2=index;
                hi=codebook[i][j];
                index=j;
            }
            else if (codebook[i][j] > hi2)
            {
                hi2=codebook[i][j];
                index2=j;
            }
        }
        assert (index%5 == index2%5);
        assert(!found_doublecheck[index%5]);
        found_doublecheck[index%5]=true;
    }
    for (int i=0; i<size(); i++)
        assert(found_doublecheck[i]);


//    codebook.clear();
//    for (double y=0.1; y<6; y+=2+.05*(int)y)
//        for (double x=0.1; x<5; x+=2+1.33*(int)y)
//            for (double z=0.1; z<5; z+=2)
//        {
//            vector<double> v= {x,y,z};
//            push_back(v);
//        }
//    vector<double> t1= {0.1,.4,.2};
//    int t1q=quantize(t1);
////    assert(t1q==0);

//    vector<double> t2= {1,2,1};
//    vector< tuple<int,float> > t2q = quantizeSoft(t2,2);
////    assert(fabs(get<1>(t2q[0])-.5)<.001 && fabs(get<1>(t2q[1])-.5)<.001);

//    vector<double> t3= {1,3,4};
//    vector< tuple<int,float> > t3q = quantizeSoft(t3,4);
////    assert(fabs(get<1>(t3q[0])-.333)<.001 && fabs(get<1>(t3q[1])-.333)<.001 && fabs(get<1>(t3q[2])-.333)<.001);
    cout << "Codebook passed its tests!" << endl;
}
Esempio n. 23
0
int main(int argc, char ** argv)
{
  int r;
  int handle;
  struct termios attr;
  char * name = argv[0];
  char * device = 0;
  struct stat statbuf;
  int pid = 0;

  setProgName(argv[0]);
  while (argc > 1)
  {
    if (strcasecmp(argv[1], "-w") == 0)
    {
      writeonly = 1;
    }
    else if (strcasecmp(argv[1], "-p") == 0)
    {
      passthru = 1;
    }
    else if (strcasecmp(argv[1], "-r") == 0)
    {
      readonly = 1;
    }
    else if (strcasecmp(argv[1], "-v") == 0)
    {
      verbose = 1;
    }
    else if (strcasecmp(argv[1], "-t") == 0 && argc > 2)
    {
      argc--;
      argv++;
      timeout = strtol(argv[1], 0, 10);
      logDebug("timeout set to %ld seconds\n", timeout);
    }
    else if (strcasecmp(argv[1], "-d") == 0)
    {
      debug = 1;
      setLogLevel(LOGLEVEL_DEBUG);
    }
    else if (!device)
    {
      device = argv[1];
    }
    else
    {
      device = 0;
      break;
    }
    argc--;
    argv++;
  }

  if (!device)
  {
    fprintf(stderr, 
    "Usage: %s [-w] -[-p] [-r] [-v] [-d] [-t <n>] device\n"
    "\n"
    "Options:\n"
    "  -w      writeonly mode, no data is read from device\n"
    "  -r      readonly mode, no data is sent to device\n"
    "  -p      passthru mode, data on stdin is sent to stdout but not to device\n"
    "  -v      verbose\n"
    "  -d      debug\n"
    "  -t <n>  timeout, if no message is received after <n> seconds the program quits\n"
    "  <device> can be a serial device, a normal file containing a raw log,\n"
    "  or the address of a TCP server in the format tcp://<host>[:<port>]\n"
    "\n" 
    "  Examples: %s /dev/ttyUSB0\n"
    "            %s tcp://192.168.1.1:10001\n"
    "\n" 
    COPYRIGHT, name, name, name);
    exit(1);
  }

retry:
  if (debug) fprintf(stderr, "Opening %s\n", device);
  if (strncmp(device, "tcp:", STRSIZE("tcp:")) == 0)
  {
    handle = open_socket_stream(device);
    if (debug) fprintf(stderr, "socket = %d\n", handle);
    isFile = true;
    if (handle < 0)
    {
      fprintf(stderr, "Cannot open NGT-1-A TCP stream %s\n", device);
      exit(1);
    }
  }
  else
  {
    handle = open(device, O_RDWR | O_NOCTTY | O_NONBLOCK);
    if (debug) fprintf(stderr, "fd = %d\n", handle);
    if (handle < 0)
    {
      fprintf(stderr, "Cannot open NGT-1-A device %s\n", device);
      exit(1);
    }
    if (fstat(handle, &statbuf) < 0)
    {
      fprintf(stderr, "Cannot determine device %s\n", device);
      exit(1);
    }
    isFile = S_ISREG(statbuf.st_mode);
  }

  if (isFile)
  {
    if (debug) fprintf(stderr, "Device is a normal file, do not set the attributes.\n");
  }
  else
  {
    if (debug) fprintf(stderr, "Device is a serial port, set the attributes.\n");

    memset(&attr, 0, sizeof(attr));
    cfsetispeed(&attr, B115200);
    cfsetospeed(&attr, B115200);
    attr.c_cflag |= CS8 | CLOCAL | CREAD;

    attr.c_iflag |= IGNPAR;
    attr.c_cc[VMIN] = 1;
    attr.c_cc[VTIME] = 0;
    tcflush(handle, TCIFLUSH);
    tcsetattr(handle, TCSANOW, &attr);

    if (debug) fprintf(stderr, "Device is a serial port, send the startup sequence.\n");

    writeMessage(handle, NGT_MSG_SEND, NGT_STARTUP_SEQ, sizeof(NGT_STARTUP_SEQ));
    sleep(2);
  }

  for (;;)
  {
    unsigned char msg[BUFFER_SIZE];
    size_t msgLen;
    enum ReadyDescriptor r;

    r = isready(writeonly ? -1 : handle, readonly ? -1 : 0);

    if ((r & FD1_Ready) > 0)
    {
      if (!readNGT1(handle))
      {
        break;
      }
    }
    if ((r & FD2_Ready) > 0)
    {
      if (!readIn(msg, sizeof(msg)))
      {
        break;
      }
      if (!passthru)
      {
        parseAndWriteIn(handle, msg);
      }
      fprintf(stdout, "%s", msg);
      fflush(stdout);
    }
    else if (writeonly)
    {
      break;
    }
  }

  close(handle);
  return 0;
}
Esempio n. 24
0
void Hla::run(){
	readIn();
	connect();
	publish();
	delete ;
}
Esempio n. 25
0
int main(int argc , char *argv[])
{	
	long double error = .00000000001;
	long double error1 = 1.0;
	long double error2 = 0.0001;
	int debug = 0;
	char *NOT = "not a triangle\n";
	if(argc != 7)
	{
		printf(NOT);
		return 0;	
	}

	long double x1 = readIn(1 , argv);
	long double y1 = readIn(2 , argv);
	long double x2 = readIn(3 , argv);
	long double y2 = readIn(4 , argv);
	long double x3 = readIn(5 , argv);
	long double y3 = readIn(6 , argv);

	long double s1 = findSide(x1 , y1 , x2 , y2 , debug);
	long double s2 = findSide(x2 , y2 , x3 , y3 , debug);
	long double s3 = findSide(x3 , y3 , x1 , y1 , debug);

	double angleS1 = acos(((s2 * s2) + (s3 * s3) - (s1 * s1))/(2 * s2 * s3));
    	double angleS2 = acos(((s3 * s3) + (s1 * s1) - (s2 * s2))/(2 * s3 * s1));    
    	double angleS3 = M_PI - angleS1 - angleS2;
	
	if(debug)
	{
		printf("angles = %f , %f , %f, %f\n" , angleS1 , angleS2 , angleS3 , (M_PI/2));
	}
		
	char *toPrint1 = "";
	char *toPrint2 = "";
	
	if(debug)
        {
                printf("side lengths: %Lf, %Lf , %Lf\n", s1 , s2 , s3);
        }	

	if(s1 == 0 || s2 == 0 || s3 == 0)
	{
		printf(NOT);
		return 0;
	}
	else if(eq(s1 + s2 , s3, error) || eq(s1 + s3 , s2 , error) || eq(s2 + s3 , s1 , error))
	{
		printf(NOT);
		return 0;
	}
	else if(s1 == s2 && s2 == s3)
	{
		toPrint1 = "equilateral";
	}
	else if(eq(s1 , s2 , error) || eq(s2 , s3 , error)|| eq(s3 , s1 , error))
	{
		toPrint1 = "isosceles";
	}
	else
	{
		toPrint1 = "scalene";
	}

	if(eq((M_PI / 2) , angleS1 , error) || eq((M_PI / 2) , angleS2 , error) || eq((M_PI / 2) , angleS3 , error))
	{
		toPrint2 = "right";
	}
	else if((angleS1 < ((M_PI / 2) + error2)) && (angleS2 < ((M_PI / 2) + error2)) && (angleS3 < ((M_PI / 2) + error2)))
	{
		toPrint2 = "acute";
	}
	else if((angleS1 > (M_PI / 2)) || (angleS2 > (M_PI / 2)) || (angleS3 > (M_PI / 2)))
	{
		toPrint2 = "obtuse";
	}
	
	printf("%s %s\n" , toPrint1 , toPrint2);
	return 0;
}
Esempio n. 26
0
void CommandHandler::checkSerial(){
	while (Serial.available()){
		char inChar = Serial.read();
		readIn(inChar);
	}
}
Esempio n. 27
0
int main(int argc, char *argv[])
{
	int argCounter = 1;
	FILE *fp;
	int length;
	fp = fopen(file, "r");
	
	if(fp == NULL)
	{
		printf("Datei konnte nicht geoeffnet werden.\n");
		return 1;
	}
	fscanf(fp, "%d\n", &length);
	struct alarm alarms[length];

	for(int i=0; i< length; i++) 
	{
		fscanf(fp, formart, &alarms[i].ringTime, &alarms[i].weekdays, &alarms[i].on);
	}	
	fclose(fp);
	
	printAlarms(alarms,length);

	int mode = 0;
	if(argc > argCounter)
		mode=atoi(argv[argCounter++]);
	else
	{
		printf("\n1\tnew\n2\tremove\n3\tset on\nmode\t: ");
		scanf("%i",&mode);
	}
	switch(mode) {
		case 1: // New
			{
				int lengthNew = length + 1;
				struct alarm alarmsNew[lengthNew];
				for (int i = 0; i < length; ++i)
				{
					alarmsNew[i] = alarms[i];
				}
				struct alarm alarmNew = readIn();

				int h, min, sec;

				if(argc > argCounter)
					h=atoi(argv[argCounter++]);
				else
				{
					printf("h \t: ");
					scanf("%i",&h);
				}

				if(argc > argCounter)
					min=atoi(argv[argCounter++]);
				else
				{
					printf("min \t: ");
					scanf("%i",&min);
				}

				if(argc > argCounter)
					sec=atoi(argv[argCounter++]);
				else
				{
					printf("sec \t: ");
					scanf("%i",&sec);
				}

				alarmNew.ringTime = makeTime(h,min,sec);
				alarmNew.weekdays = 0;
				int answer = 0;
				for (int i = 0; i < 7; ++i)
				{
					if(argc > argCounter)
						answer=atoi(argv[argCounter++]);
					else
					{
						printf("%s \t: ", dayNames[i]);
						scanf("%i",&answer);
					}
					if(answer)
					{
						alarmNew.weekdays |= 1 << i;
					}
				}

				if(argc > argCounter)
					alarmNew.on=atoi(argv[argCounter++]);
				else
				{
					printf("on \t: ");
					scanf("%i",&alarmNew.on);
				}

				alarmsNew[lengthNew -1] = alarmNew;

				printAlarms(alarmsNew,lengthNew);
				save(alarmsNew,lengthNew);
			}
			break;
		case 2: // rm 
			{
				int index = 0;
				if(argc > argCounter)
					index=atoi(argv[argCounter++]);
				else
				{
					printf("index\t: ");
					scanf("%i",&index);
				}
				

				int lengthNew = length - 1;
				struct alarm alarmsNew[lengthNew];
				for (int i = 0; i < length; ++i)
				{
					alarmsNew[i] = alarms[i + (i >= index ? 1 : 0)];
				}

				printAlarms(alarmsNew,lengthNew);
				save(alarmsNew,lengthNew);
			}
			break;
		case 3: // set state 
			{
				int index = 0;
				if(argc > argCounter)
					index=atoi(argv[argCounter++]);
				else
				{
					printf("index\t: ");
					scanf("%i",&index);
				}

				if(argc > argCounter)
					alarms[index].on=atoi(argv[argCounter++]);
				else
				{
					printf("on \t: ");
					scanf("%i",&alarms[index].on);
				}

				printAlarms(alarms,length);
				save(alarms,length);
			}
			break;
	}
	return 0;
}