Esempio n. 1
0
/*
  This method carries out the execution of the binary code in the file specified
  by the arguments at run time. The file is loaded into the memory of the
  structure processor and then the execution is carried out in the while loop.
  The execution of terminates when an instruction with opcode HALT is reached.
  @param argv : this specifies the arguements which were given through the
                terminal when the program was run.
  @param argc : this specifes the number of arguments provided
  @return     : the method returns 0 when the method executes without any errors
*/
int main(int argc, char **argv) {
  assert("There are wrong number of arguents given" && argc==3);
  struct Processor *processor = malloc(sizeof(struct Processor));
  char *filepath = argv[1];

  memset(processor, 0, sizeof(struct Processor));

  int lineNumber = 0 ;
  
  binaryFileLoader(filepath, processor);
  printWelcomeMessage();
  char **tokens = malloc(sizeof(char) *BUFFER_SIZE);
    
  do {
    tokens = getUserCommand();    
    executeUserCommand(argv[2] , argv[1], processor, tokens);
    printf("token -> %s\n",tokens[0]); 
  }while (strcmp(tokens[0],"q")==0);
  
  printf("Thanks for using JVG debugger\n");
  
  fflush(stdout);

  return EXIT_SUCCESS;
}
Esempio n. 2
0
int main(void) {
  uint8_t opt = 0;

  /* Reset of all peripherals, Initializes the Flash interface and the SysTick. */
  HAL_Init();

  /* Configure the system clock */
  SystemClock_Config();

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USART2_UART_Init();

  /* Enable USART2 interrupt */
  HAL_NVIC_SetPriority(USART2_IRQn, 0, 0);
  HAL_NVIC_EnableIRQ(USART2_IRQn);

printMessage:

  printWelcomeMessage();

  while (1)  {
    opt = readUserInput();
    if(opt > 0) {
      processUserInput(opt);
      if(opt == 3)
        goto printMessage;
    }
    performCriticalTasks();
  }
}
Esempio n. 3
0
    /**
     * The Constructor.
     * Prints the welcome message (process rank 0 only).
     *
     * @param i_processRank rank of the constructing process.
     * @param i_programName definition of the program name.
     * @param i_welcomeMessage definition of the welcome message.
     * @param i_startMessage definition of the start message.
     * @param i_simulationTimeMessage definition of the simulation time message.
     * @param i_executionTimeMessage definition of the execution time message.
     * @param i_cpuTimeMessage definition of the CPU time message.
     * @param i_finishMessage definition of the finish message.
     * @param i_midDelimiter definition of the mid-size delimiter.
     * @param i_largeDelimiter definition of the large delimiter.
     * @param i_indentation definition of the indentation (used in all messages, except welcome, start and finish).
     */
    Logger( const int i_processRank = 0,
            const std::string i_programName = "SWE",
            const std::string i_welcomeMessage = "Welcome to",
            const std::string i_copyRights =  "\n\nSWE Copyright (C) 2012\n"
                                              "  Technische Universitaet Muenchen\n"
                                              "  Department of Informatics\n"
                                              "  Chair of Scientific Computing\n"
                                              "  http://www5.in.tum.de/SWE\n"
                                              "\n"
                                              "SWE comes with ABSOLUTELY NO WARRANTY.\n"
                                              "SWE is free software, and you are welcome to redistribute it\n"
                                              "under certain conditions.\n"
                                              "Details can be found in the file \'gpl.txt\'.",
            const std::string i_finishMessage = "finished successfully.",
            const std::string i_midDelimiter = "\n------------------------------------------------------------------\n",
            const std::string i_largeDelimiter = "\n*************************************************************\n",
            const std::string i_indentation = "\t" ):
            processRank(i_processRank),
            programName(i_programName),
            welcomeMessage(i_welcomeMessage),
            copyRights(i_copyRights),
            finishMessage(i_finishMessage),
            midDelimiter(i_midDelimiter),
            largeDelimiter(i_largeDelimiter),
            indentation(i_indentation) {
      //set time to zero
      cpuTime = cpuCommTime = wallClockTime = 0.;

      #ifndef USEMPI
        printWelcomeMessage();
      #endif
    }
Esempio n. 4
0
int main(int argc, char **argv) {
  struct Processor *proc = malloc(sizeof(struct Processor));
  assert("There are wrong number of arguents given" && argc==3);
  char *fBin = argv[2];
  char *fAssembly = argv[1];
  memset(proc,0,sizeof(struct Processor));
  binaryFileLoader(fBin,proc);
  system("clear");
  int *breakPoints = malloc(sizeof(int) *BREAKPOINTS_ARRAY_SIZE);
  memset(breakPoints,-1,sizeof(int) *BREAKPOINTS_ARRAY_SIZE);
  printWelcomeMessage();
  char **tokens = malloc(sizeof(char) *BUFFER_SIZE);
  int returnVal = 0; 
  do {
    tokens = getUserCommand();
    returnVal = executeUserCommand(fAssembly,fBin,proc,tokens,breakPoints);
    free(tokens);
  } while (!returnVal);
  printf("Thanks for using JVG debugger\n");
  system("clear");
  free(proc);
  free(breakPoints);
  return EXIT_SUCCESS;
}
Esempio n. 5
0
int main(void) {
	uint8_t opt = 0;

	/* Reset of all peripherals, Initializes the Flash interface and the SysTick. */
	HAL_Init();

	/* Configure the system clock */
	SystemClock_Config();

	/* Initialize all configured peripherals */
	MX_GPIO_Init();
	MX_USART2_UART_Init();

printMessage:

	printWelcomeMessage();

	while (1)  {
		opt = readUserInput();
		processUserInput(opt);
		if(opt == 3)
			goto printMessage;
	}
}
Esempio n. 6
0
int main(){
    int opt=0;
	int num,i,option;
	Pila *pila= loadHeaders();
	while(opt==0){
	//imprimir_pila(pila);
	printWelcomeMessage();
	headerInput(pila);
	num = inputNumOfStudents();
	for(i =0; i<num;i++){
		inputScores();
	}
	printf("\n\n");
	system("cls");
	printStadistics();
		
	option = printOptionMenu();
	
	switch(option){
       case 1:
            searchHeader(pila);
            break;
       case 2:
            printf("\n\nHeaders: \n\n");
            imprimir_pila(pila);
            system("PAUSE");
            break;
       case 3:
            eliminateHeader(pila);
            break;
             
             }
       }
	system("PAUSE");
	return 0;
}
Esempio n. 7
0
int mrsWatsonMain(ErrorReporter errorReporter, int argc, char** argv) {
  ReturnCodes result;
  // Input/Output sources, plugin chain, and other required objects
  SampleSource inputSource = NULL;
  SampleSource outputSource = NULL;
  AudioClock audioClock;
  PluginChain pluginChain;
  CharString pluginSearchRoot = newCharString();
  boolByte shouldDisplayPluginInfo = false;
  MidiSequence midiSequence = NULL;
  MidiSource midiSource = NULL;
  unsigned long maxTimeInMs = 0;
  unsigned long maxTimeInFrames = 0;
  unsigned long tailTimeInMs = 0;
  unsigned long tailTimeInFrames = 0;
  unsigned long processingDelayInFrames;
  ProgramOptions programOptions;
  ProgramOption option;
  Plugin headPlugin;
  SampleBuffer inputSampleBuffer = NULL;
  SampleBuffer outputSampleBuffer = NULL;
  TaskTimer initTimer, totalTimer, inputTimer, outputTimer = NULL;
  LinkedList taskTimerList = NULL;
  CharString totalTimeString = NULL;
  boolByte finishedReading = false;
  SampleSource silentSampleInput;
  SampleSource silentSampleOutput;
  unsigned int i;

  initTimer = newTaskTimerWithCString(PROGRAM_NAME, "Initialization");
  totalTimer = newTaskTimerWithCString(PROGRAM_NAME, "Total Time");
  taskTimerStart(initTimer);
  taskTimerStart(totalTimer);

  initEventLogger();
  initAudioSettings();
  initAudioClock();
  audioClock = getAudioClock();
  initPluginChain();
  pluginChain = getPluginChain();
  programOptions = newMrsWatsonOptions();
  inputSource = sampleSourceFactory(NULL);

  if(!programOptionsParseArgs(programOptions, argc, argv)) {
    printf("Run with '--help' to see possible options\n");
    printf("Or run with '--help full' to see extended help for all options\n");
    return RETURN_CODE_INVALID_ARGUMENT;
  }

  // These options conflict with standard processing (more or less), so check to see if the user wanted one
  // of these and then exit right away.
  if(argc == 1) {
    printf("%s needs at least a plugin, input source, and output source to run.\n\n", PROGRAM_NAME);
    printMrsWatsonQuickstart(argv[0]);
    return RETURN_CODE_NOT_RUN;
  }
  else if(programOptions->options[OPTION_HELP]->enabled) {
    printMrsWatsonQuickstart(argv[0]);
    if(charStringIsEmpty(programOptionsGetString(programOptions, OPTION_HELP))) {
      printf("All options, where <argument> is required and [argument] is optional:\n");
      programOptionsPrintHelp(programOptions, false, DEFAULT_INDENT_SIZE);
    }
    else {
      if(charStringIsEqualToCString(programOptionsGetString(programOptions, OPTION_HELP), "full", true)) {
        programOptionsPrintHelp(programOptions, true, DEFAULT_INDENT_SIZE);
      }
      // Yeah this is a bit silly, but the performance obviously doesn't matter
      // here and I don't feel like cluttering up this already huge function
      // with more variables.
      else if(programOptionsFind(programOptions, programOptionsGetString(programOptions, OPTION_HELP))) {
        programOptionPrintHelp(programOptionsFind(programOptions, programOptionsGetString(programOptions, OPTION_HELP)),
          true, DEFAULT_INDENT_SIZE, 0);
      }
      else {
        printf("Invalid option '%s', try running --help full to see help for all options\n",
          programOptionsGetString(programOptions, OPTION_HELP)->data);
      }
    }
    return RETURN_CODE_NOT_RUN;
  }
  else if(programOptions->options[OPTION_VERSION]->enabled) {
    printVersion();
    return RETURN_CODE_NOT_RUN;
  }
  else if(programOptions->options[OPTION_COLOR_TEST]->enabled) {
    printTestPattern();
    return RETURN_CODE_NOT_RUN;
  }
  // See if we are to make an error report and make necessary changes to the
  // options for good diagnostics. Note that error reports cannot be generated
  // for any of the above options which return with RETURN_CODE_NOT_RUN.
  else if(programOptions->options[OPTION_ERROR_REPORT]->enabled) {
    errorReporterInitialize(errorReporter);
    programOptions->options[OPTION_VERBOSE]->enabled = true;
    programOptions->options[OPTION_LOG_FILE]->enabled = true;
    programOptions->options[OPTION_DISPLAY_INFO]->enabled = true;
    // Shell script with original command line arguments
    errorReporterCreateLauncher(errorReporter, argc, argv);
    // Rewrite some paths before any input or output sources have been opened.
    _remapFileToErrorReport(errorReporter, programOptions->options[OPTION_INPUT_SOURCE], true);
    _remapFileToErrorReport(errorReporter, programOptions->options[OPTION_OUTPUT_SOURCE], false);
    _remapFileToErrorReport(errorReporter, programOptions->options[OPTION_MIDI_SOURCE], true);
    _remapFileToErrorReport(errorReporter, programOptions->options[OPTION_LOG_FILE], false);
  }

  // Read in options from a configuration file, if given
  if(programOptions->options[OPTION_CONFIG_FILE]->enabled) {
    if(!programOptionsParseConfigFile(programOptions, programOptionsGetString(programOptions, OPTION_CONFIG_FILE))) {
      return RETURN_CODE_INVALID_ARGUMENT;
    }
  }

  // Parse these options first so that log messages displayed in the below
  // loop are properly displayed
  if(programOptions->options[OPTION_VERBOSE]->enabled) {
    setLogLevel(LOG_DEBUG);
  }
  else if(programOptions->options[OPTION_QUIET]->enabled) {
    setLogLevel(LOG_ERROR);
  }
  else if(programOptions->options[OPTION_LOG_LEVEL]->enabled) {
    setLogLevelFromString(programOptionsGetString(programOptions, OPTION_LOG_LEVEL));
  }
  if(programOptions->options[OPTION_COLOR_LOGGING]->enabled) {
    // If --color was given but with no string argument, then force color. Otherwise
    // colors will be provided automatically anyways.
    if(charStringIsEmpty(programOptionsGetString(programOptions, OPTION_COLOR_LOGGING))) {
      programOptionsSetCString(programOptions, OPTION_COLOR_LOGGING, "force");
    }
    setLoggingColorEnabledWithString(programOptionsGetString(programOptions, OPTION_COLOR_LOGGING));
  }
  if(programOptions->options[OPTION_LOG_FILE]->enabled) {
    setLogFile(programOptionsGetString(programOptions, OPTION_LOG_FILE));
  }

  // Parse other options and set up necessary objects
  for(i = 0; i < programOptions->numOptions; i++) {
    option = programOptions->options[i];
    if(option->enabled) {
      switch(option->index) {
        case OPTION_BLOCKSIZE:
          setBlocksize((const unsigned long)programOptionsGetNumber(programOptions, OPTION_BLOCKSIZE));
          break;
        case OPTION_CHANNELS:
          setNumChannels((const unsigned long)programOptionsGetNumber(programOptions, OPTION_CHANNELS));
          break;
        case OPTION_DISPLAY_INFO:
          shouldDisplayPluginInfo = true;
          break;
        case OPTION_INPUT_SOURCE:
          freeSampleSource(inputSource);
          inputSource = sampleSourceFactory(programOptionsGetString(programOptions, OPTION_INPUT_SOURCE));
          break;
        case OPTION_MAX_TIME:
          maxTimeInMs = (const unsigned long)programOptionsGetNumber(programOptions, OPTION_MAX_TIME);
          break;
        case OPTION_MIDI_SOURCE:
          midiSource = newMidiSource(guessMidiSourceType(programOptionsGetString(
            programOptions, OPTION_MIDI_SOURCE)),
            programOptionsGetString(programOptions, OPTION_MIDI_SOURCE));
          break;
        case OPTION_OUTPUT_SOURCE:
          outputSource = sampleSourceFactory(programOptionsGetString(programOptions, OPTION_OUTPUT_SOURCE));
          break;
        case OPTION_PLUGIN_ROOT:
          charStringCopy(pluginSearchRoot, programOptionsGetString(programOptions, OPTION_PLUGIN_ROOT));
          break;
        case OPTION_SAMPLE_RATE:
          setSampleRate(programOptionsGetNumber(programOptions, OPTION_SAMPLE_RATE));
          break;
        case OPTION_TAIL_TIME:
          tailTimeInMs = (long)programOptionsGetNumber(programOptions, OPTION_TAIL_TIME);
          break;
        case OPTION_TEMPO:
          setTempo(programOptionsGetNumber(programOptions, OPTION_TEMPO));
          break;
        case OPTION_TIME_SIGNATURE:
          if(!setTimeSignatureFromString(programOptionsGetString(programOptions, OPTION_TIME_SIGNATURE))) {
            return RETURN_CODE_INVALID_ARGUMENT;
          }
          break;
        case OPTION_ZEBRA_SIZE:
          setLoggingZebraSize((int)programOptionsGetNumber(programOptions, OPTION_ZEBRA_SIZE));
          break;
        default:
          // Ignore -- no special handling needs to be performed here
          break;
      }
    }
  }

  if(programOptions->options[OPTION_LIST_PLUGINS]->enabled) {
    listAvailablePlugins(pluginSearchRoot);
    return RETURN_CODE_NOT_RUN;
  }
  if(programOptions->options[OPTION_LIST_FILE_TYPES]->enabled) {
    sampleSourcePrintSupportedTypes();
    return RETURN_CODE_NOT_RUN;
  }

  printWelcomeMessage(argc, argv);
  if((result = setupInputSource(inputSource)) != RETURN_CODE_SUCCESS) {
    logError("Input source could not be opened, exiting");
    return result;
  }
  if((result = buildPluginChain(pluginChain, programOptionsGetString(programOptions, OPTION_PLUGIN),
    pluginSearchRoot)) != RETURN_CODE_SUCCESS) {
    logError("Plugin chain could not be constructed, exiting");
    return result;
  }
  if(midiSource != NULL) {
    result = setupMidiSource(midiSource, &midiSequence);
    if(result != RETURN_CODE_SUCCESS) {
      logError("MIDI source could not be opened, exiting");
      return result;
    }
  }

  // Copy plugins before they have been opened
  if(programOptions->options[OPTION_ERROR_REPORT]->enabled) {
    if(errorReporterShouldCopyPlugins()) {
      if(!errorReporterCopyPlugins(errorReporter, pluginChain)) {
        logWarn("Failed copying plugins to error report directory");
      }
    }
  }

  // Initialize the plugin chain after the global sample rate has been set
  result = pluginChainInitialize(pluginChain);
  if(result != RETURN_CODE_SUCCESS) {
    logError("Could not initialize plugin chain");
    return result;
  }

  // Display info for plugins in the chain before checking for valid input/output sources
  if(shouldDisplayPluginInfo) {
    pluginChainInspect(pluginChain);
  }

  // Execute any parameter changes
  if(programOptions->options[OPTION_PARAMETER]->enabled) {
    if(!pluginChainSetParameters(pluginChain, programOptionsGetList(programOptions, OPTION_PARAMETER))) {
      return RETURN_CODE_INVALID_ARGUMENT;
    }
  }

  // Setup output source here. Having an invalid output source should not cause the program
  // to exit if the user only wants to list plugins or query info about a chain.
  if((result = setupOutputSource(outputSource)) != RETURN_CODE_SUCCESS) {
    logError("Output source could not be opened, exiting");
    return result;
  }

  // Verify input/output sources. This must be done after the plugin chain is initialized
  // otherwise the head plugin type is not known, which influences whether we must abort
  // processing.
  if(programOptions->options[OPTION_ERROR_REPORT]->enabled) {
    if(charStringIsEqualToCString(inputSource->sourceName, "-", false) ||
       charStringIsEqualToCString(outputSource->sourceName, "-", false)) {
      printf("ERROR: Using stdin/stdout is incompatible with --error-report\n");
      return RETURN_CODE_NOT_RUN;
    }
    if(midiSource != NULL && charStringIsEqualToCString(midiSource->sourceName, "-", false)) {
      printf("ERROR: MIDI source from stdin is incompatible with --error-report\n");
      return RETURN_CODE_NOT_RUN;
    }
  }
  if(outputSource == NULL) {
    logInternalError("Default output sample source was null");
    return RETURN_CODE_INTERNAL_ERROR;
  }
  if(inputSource == NULL || inputSource->sampleSourceType == SAMPLE_SOURCE_TYPE_SILENCE) {
    // If the first plugin in the chain is an instrument, use the silent source as our input and
    // make sure that there is a corresponding MIDI file
    headPlugin = pluginChain->plugins[0];
    if(headPlugin->pluginType == PLUGIN_TYPE_INSTRUMENT) {
      if(midiSource == NULL) {
        // I guess some instruments (like white noise generators etc.) don't necessarily
        // need MIDI, actually this is most useful for our internal plugins and generators.
        // Anyways, this should only be a soft warning for those who know what they're doing.
        logWarn("Plugin chain contains an instrument, but no MIDI source was supplied");
        if(maxTimeInMs == 0) {
          // However, if --max-time wasn't given, then there is effectively no input source
          // and thus processing would continue forever. That won't work.
          logError("No valid input source or maximum time, don't know when to stop processing");
          return RETURN_CODE_MISSING_REQUIRED_OPTION;
        }
        else {
          // If maximum time was given and there is no other input source, then use silence
          inputSource = newSampleSourceSilence();
        }
      }
    }
    else {
      logError("Plugin chain contains only effects, but no input source was supplied");
      return RETURN_CODE_MISSING_REQUIRED_OPTION;
    }
  }

  inputSampleBuffer = newSampleBuffer(getNumChannels(), getBlocksize());
  inputTimer = newTaskTimerWithCString(PROGRAM_NAME, "Input Source");
  outputSampleBuffer = newSampleBuffer(getNumChannels(), getBlocksize());
  outputTimer = newTaskTimerWithCString(PROGRAM_NAME, "Output Source");

  // Initialization is finished, we should be able to free this memory now
  freeProgramOptions(programOptions);

  // If a maximum time was given, figure it out here
  if(maxTimeInMs > 0) {
    maxTimeInFrames = (unsigned long)(maxTimeInMs * getSampleRate()) / 1000l;
  }

  processingDelayInFrames = pluginChainGetProcessingDelay(pluginChain);
  // Get largest tail time requested by any plugin in the chain
  tailTimeInMs += pluginChainGetMaximumTailTimeInMs(pluginChain);
  tailTimeInFrames = (unsigned long)(tailTimeInMs * getSampleRate()) / 1000l + processingDelayInFrames;
  pluginChainPrepareForProcessing(pluginChain);

  // Update sample rate on the event logger
  setLoggingZebraSize((long)getSampleRate());
  logInfo("Starting processing input source");
  logDebug("Sample rate: %.0f", getSampleRate());
  logDebug("Blocksize: %d", getBlocksize());
  logDebug("Channels: %d", getNumChannels());
  logDebug("Tempo: %.2f", getTempo());
  logDebug("Processing delay frames: %lu", processingDelayInFrames);
  logDebug("Time signature: %d/%d", getTimeSignatureBeatsPerMeasure(), getTimeSignatureNoteValue());
  taskTimerStop(initTimer);

  silentSampleInput = sampleSourceFactory(NULL);
  silentSampleOutput = sampleSourceFactory(NULL);
  // Main processing loop
  while(!finishedReading) {
    taskTimerStart(inputTimer);
    finishedReading = !readInput(inputSource, silentSampleInput, inputSampleBuffer, tailTimeInFrames);

    // TODO: For streaming MIDI, we would need to read in events from source here
    if(midiSequence != NULL) {
      LinkedList midiEventsForBlock = newLinkedList();
      // MIDI source overrides the value set to finishedReading by the input source
      finishedReading = !fillMidiEventsFromRange(midiSequence, audioClock->currentFrame, getBlocksize(), midiEventsForBlock);
      linkedListForeach(midiEventsForBlock, _processMidiMetaEvent, &finishedReading);
      pluginChainProcessMidi(pluginChain, midiEventsForBlock);
      freeLinkedList(midiEventsForBlock);
    }
    taskTimerStop(inputTimer);

    if(maxTimeInFrames > 0 && audioClock->currentFrame >= maxTimeInFrames) {
      logInfo("Maximum time reached, stopping processing after this block");
      finishedReading = true;
    }

    pluginChainProcessAudio(pluginChain, inputSampleBuffer, outputSampleBuffer);

    taskTimerStart(outputTimer);
    if(finishedReading) {
      outputSampleBuffer->blocksize = inputSampleBuffer->blocksize;//The input buffer size has been adjusted.
      logDebug("Using buffer size of %d for final block", outputSampleBuffer->blocksize);
    }
    writeOutput(outputSource, silentSampleOutput, outputSampleBuffer, processingDelayInFrames);
    taskTimerStop(outputTimer);
    advanceAudioClock(audioClock, outputSampleBuffer->blocksize);
  }

  // Close file handles for input/output sources
  silentSampleInput->closeSampleSource(silentSampleInput);
  silentSampleOutput->closeSampleSource(silentSampleOutput);
  inputSource->closeSampleSource(inputSource);
  outputSource->closeSampleSource(outputSource);

  // Print out statistics about each plugin's time usage
  // TODO: On windows, the total processing time is stored in clocks and not milliseconds
  // These values must be converted using the QueryPerformanceFrequency() function
  audioClockStop(audioClock);
  taskTimerStop(totalTimer);

  if(totalTimer->totalTaskTime > 0) {
    taskTimerList = newLinkedList();
    linkedListAppend(taskTimerList, initTimer);
    linkedListAppend(taskTimerList, inputTimer);
    linkedListAppend(taskTimerList, outputTimer);
    for(i = 0; i < pluginChain->numPlugins; i++) {
      linkedListAppend(taskTimerList, pluginChain->audioTimers[i]);
      linkedListAppend(taskTimerList, pluginChain->midiTimers[i]);
    }

    totalTimeString = taskTimerHumanReadbleString(totalTimer);
    logInfo("Total processing time %s, approximate breakdown:", totalTimeString->data);
    linkedListForeach(taskTimerList, _printTaskTime, totalTimer);
  }
  else {
    // Woo-hoo!
    logInfo("Total processing time <1ms. Either something went wrong, or your computer is smokin' fast!");
  }
  freeTaskTimer(initTimer);
  freeTaskTimer(inputTimer);
  freeTaskTimer(outputTimer);
  freeTaskTimer(totalTimer);
  freeLinkedList(taskTimerList);
  freeCharString(totalTimeString);

  if(midiSequence != NULL) {
    logInfo("Read %ld MIDI events from %s",
      midiSequence->numMidiEventsProcessed,
      midiSource->sourceName->data);
  }
  else {
    logInfo("Read %ld frames from %s",
      inputSource->numSamplesProcessed / getNumChannels(),
      inputSource->sourceName->data);
  }
  logInfo("Wrote %ld frames to %s",
    outputSource->numSamplesProcessed / getNumChannels(),
    outputSource->sourceName->data);

  // Shut down and free data (will also close open files, plugins, etc)
  logInfo("Shutting down");
  freeSampleSource(inputSource);
  freeSampleSource(outputSource);
  freeSampleBuffer(inputSampleBuffer);
  freeSampleBuffer(outputSampleBuffer);
  pluginChainShutdown(pluginChain);
  freePluginChain(pluginChain);

  if(midiSource != NULL) {
    freeMidiSource(midiSource);
  }
  if(midiSequence != NULL) {
    freeMidiSequence(midiSequence);
  }

  freeAudioSettings();
  logInfo("Goodbye!");
  freeEventLogger();
  freeAudioClock(getAudioClock());

  if(errorReporter->started) {
    errorReporterClose(errorReporter);
  }
  freeErrorReporter(errorReporter);

  return RETURN_CODE_SUCCESS;
}
/*******************************************************************************
*   @fn         main
*
*   @brief      Runs the main routine
*
*   @param      none
*
*   @return     none
*/
void main(void) {

    uint8 writeByte;

    // Initialize MCU and peripherals
    initMCU();

    // Write radio registers (preferred settings from SmartRF Studio)
    registerConfig();

    // Application specific registers
    // FIFO_THR = 120
    // GPIO0 = RXFIFO_THR
    // GPIO2 = PKT_SYNC_RXTX
    // GPIO3 = PKT_SYNC_RXTX
    writeByte = INFINITE_PACKET_LENGTH_MODE;
    cc112xSpiWriteReg(CC112X_PKT_CFG0, &writeByte, 1);
    writeByte = 0x78; cc112xSpiWriteReg(CC112X_FIFO_CFG, &writeByte, 1);
    writeByte = 0x00; cc112xSpiWriteReg(CC112X_IOCFG0,   &writeByte, 1);
    writeByte = 0x06; cc112xSpiWriteReg(CC112X_IOCFG2,   &writeByte, 1);
    writeByte = 0x06; cc112xSpiWriteReg(CC112X_IOCFG3,   &writeByte, 1);

    bspLedSet(BSP_LED_ALL);
    
    // Calibrate the radio according to the errata note
    manualCalibration();

    // Connect ISR function to GPIO0
    ioPinIntRegister(IO_PIN_PORT_1, GPIO0, &rxFifoAboveThresholdISR);

    // Interrupt on falling edge
    ioPinIntTypeSet(IO_PIN_PORT_1, GPIO0, IO_PIN_RISING_EDGE);

    // Clear interrupt
    ioPinIntClear(IO_PIN_PORT_1, GPIO0);

    // Enable interrupt
    ioPinIntEnable(IO_PIN_PORT_1, GPIO0);

    // Connect ISR function to GPIO2
    ioPinIntRegister(IO_PIN_PORT_1, GPIO2, &syncReceivedISR);

    // Interrupt on falling edge
    ioPinIntTypeSet(IO_PIN_PORT_1, GPIO2, IO_PIN_RISING_EDGE);

    // Clear interrupt
    ioPinIntClear(IO_PIN_PORT_1, GPIO2);

    // Enable interrupt
    ioPinIntEnable(IO_PIN_PORT_1, GPIO2);

    // Set up interrupt on GPIO3 (PKT_SYNC_RXTX)
    ioPinIntRegister(IO_PIN_PORT_1, GPIO3, &packetReceivedISR);

    // Interrupt on falling edge
    ioPinIntTypeSet(IO_PIN_PORT_1, GPIO3, IO_PIN_FALLING_EDGE);

    printWelcomeMessage();

    while (TRUE) {
        switch (state) {

            //------------------------------------------------------------------
            case RX_START:
            //------------------------------------------------------------------
            trxSpiCmdStrobe(CC112X_SRX);
            pBufferIndex = rxBuffer;

            // Disable interrupt on GPIO3
            ioPinIntDisable(IO_PIN_PORT_1, GPIO3);

            state = RX_WAIT;

            //------------------------------------------------------------------
            case RX_WAIT:
            //------------------------------------------------------------------
            if (packetReceived) {
                packetReceived = FALSE;

                // Check CRC and update LCD if CRC OK
                if ((rxBuffer[packetLength + 3]) & CRC_OK)
                    updateLcd();

                // Change to infinite packet length mode
                pktFormat = INFINITE;
                writeByte = INFINITE_PACKET_LENGTH_MODE;
                cc112xSpiWriteReg(CC112X_PKT_CFG0, &writeByte, 1);

                state = RX_START;
            }
            break;

            //------------------------------------------------------------------
            default:
            //------------------------------------------------------------------

            break;
        }
    }
}
task main()
{

	/*
	*	INITIALIZATION AND SETUP
	*	This first section gets the robot ready to start the match. It sets all the motor and servo
	*	starting positions, and prints some diagnostic information to the NXT and the debug stream.
	*/

	// Print a copyright notice to the debug stream
	string programName = "Autonomous";
	printWelcomeMessage(programName, programVersion);

	writeDebugStreamLine("Getting autonomous settings...");
	PlaySound(soundBeepBeep);
	runMenu();			// Get gameplay decisions from the operators

	initializeRobot();	// Set the robot to its starting positions

	// Notify the users that the program is ready and running
	writeDebugStreamLine("Waiting for start of match...");
	nxtDisplayTextLine(0, "2015 Powerstackers");
	nxtDisplayCenteredBigTextLine(1, "AUTO");
	nxtDisplayCenteredBigTextLine(3, "READY");
	PlaySound(soundFastUpwardTones);
	wait10Msec(200);

	/*
	*	DEBUG MODE
	*	If debug mode is activated, bypass the waitForStart function.
	*	Display a 3 second audio and visual countdown, and then execute.
	*/
	if(debugMode)
	{
		ClearSounds();
		for(int i = 3; i>0; --i)
		{
			nxtDisplayCenteredBigTextLine(3, "IN %d", i);
			PlaySound(soundException);
			wait10Msec(100);
		}
	}
	else
	{
		// Wait for the "starting gun" from the field control system
		waitForStart();
	}

	// Notify the users that the program is running
	nxtDisplayCenteredBigTextLine(3, "RUNNING");
	PlaySound(soundUpwardTones);
	//StartTask(watchMotors);

	/*
	*	GAMEPLAY
	*	From this point on, the program is split into different sections based on the options chosen in
	*	menu earlier. The two main options are the starting position and the game mode (offense or defense).
	*/

	if(startingPosition==STARTING_RAMP)
	{
		/*
		*	RAMP POSITION
		*	Starting from this position means that you can only access the rolling goals and the kickstand.
		*	In this position, offensive is mostly the only available game mode.
		*/

		// OFFENSIVE MODE
		if(offenseOrDefense==OFFENSIVE_MODE)
		{
			// Go straight down the ramp
			goTicks(inchesToTicks(-25), 30);
			turnDegrees(5, 50);
			goTicks(inchesToTicks(-40), 50);
			//this will make the robot drop the balls into the rolling goal
			grabTube();
			//this will make the robot turn to move twards the parking zone
			turnDegrees (-8,preferredTurnSpeed);
			goTicks(inchesToTicks(12), 75);
			turnDegrees(-20, preferredTurnSpeed);
			//this will make the robot move twards the parking zone
			goTicks (inchesToTicks(78), 75);
			//this will make the robot turn so it can be in place so it will move in the parking zone
			turnDegrees (-80,preferredTurnSpeed);
			goTicks(inchesToTicks(10), 50);
			dropBall(liftTargetMed);

		}	// END OFFENSE

		// DEFENSIVE MODE
		else if(offenseOrDefense==DEFENSIVE_MODE)
		{
			// Just go in a straight line down the ramp
			goTicks(inchesToTicks(80), 50);
		}	// END DEFENSE

	}	// END RAMP START
	else if(startingPosition==STARTING_FLOOR)
	{
		/*
		*	FLOOR POSITION
		*	In this position, you are available to block the other team, or to score in the high goal. You
		*	also have easy access to the kickstand. It is easiest to determine the orientation of the
		*	center tower from this position.
		*/

		// Detect and store the center goal position
		goTicks(inchesToTicks(-30), 100);
		char goalFacing = findGoalOrientation();

		// OFFENSIVE MODE
		if(offenseOrDefense==OFFENSIVE_MODE)
		{
			// Move slightly forwards to get into a better detecting position
			//goTicks(inchesToTicks(-20), 50);

			// Make a movement based on the position of the center goal
			switch (goalFacing)
			{
				// GOOD
				case CENTGOAL_POSITION_A :
				{
					// In this position, simply go in a straight line
					goTicks(inchesToTicks(-10),50);
					break;
				}
				// BAD
				case CENTGOAL_POSITION_B :
				{
					// Turn 45 degrees, tangent to the center structure
					turnDegrees (45,preferredTurnSpeed);

					// Move into position in front of the goal
					goTicks(inchesToTicks(-30),75);

					// Turn to face the goal
					turnDegrees (-90,preferredTurnSpeed); writeDebugStreamLine("Done");
					break;
				}
				// GOOD
				case CENTGOAL_POSITION_C :
				{
					// Turn 90 degrees, parallel to the center structure
					turnDegrees (-90,preferredTurnSpeed);

					// Move along the center structure until we're past the end
					goTicks(inchesToTicks(-38),50);

					// Turn 90 degrees, tangent to the center structure
					turnDegrees (90,preferredTurnSpeed);

					// Move into position in front of the center structure
					goTicks(inchesToTicks(-62),65);

					//  Turn to face the goal
					turnDegrees(90,preferredTurnSpeed);
					break;
				}

				default:
				{
					// In an ambiguous situtation, assume the goal is in A position
					goTicks(inchesToTicks(-20),75); writeDebugStreamLine("Done");
					break;
				}
			}

			// Print that the alignment is done
			writeDebugStreamLine("Aligned with center structure");


			// Position the robot to drop the ball in the center goal
			nMotorEncoder[mLift] = 0;
			moveMotorTo(mLift, liftTargetCent, 75);

			// Drop the ball in the center goal
			servo[rTrapDoor]=trapDoorOpenPosition;
			wait10Msec (500);
			servo[rTrapDoor]=trapDoorClosedPosition;

			// Drop down the lift
			moveMotorTo(mLift, liftTargetBase, 75);
			// Position the robot correctly to kick the kickstand
			turnDegrees (90, preferredTurnSpeed);
			goTicks(inchesToTicks(-15), 75);
			turnDegrees (90, preferredTurnSpeed);
			goTicks(inchesToTicks(35), 100);
			// Go to the robot's ending position


		}	// END OFFENSE

		// DEFENSIVE MODE
		else if(offenseOrDefense==DEFENSIVE_MODE)
		{
			/*
			*	Move from the starting position to block the opponent's rolling goals
			*/
			// Move 2 feet backwards at full power, to get out of the parking zone
			//goTicks(inchesToTicks(-24), 100);

			// Turn towards the opponent rolling goals
			turnDegrees(90, preferredTurnSpeed);

			// Drive forward and backward to disrupt the opponent 60cm goal
			goTicks(inchesToTicks(60), 100);
			goTicks(inchesToTicks(-12), 100);

			// turn slightly to get the 90cm goals
			turnDegrees(-45, preferredTurnSpeed);

			// Move forward and backwards to disrupt the 90cm goal
			goTicks(inchesToTicks(36), 75);
			goTicks(inchesToTicks(-36), 100);
return;
			// Turn slightly to face the 30cm goal
			turnDegrees(-45, preferredTurnSpeed);

			// Move foward and backward to disrupt the 30cm goal
			goTicks(inchesToTicks(36), 75);
			goTicks(inchesToTicks(-4), 100);

			// Move into position to align on the wall of the ramp
			turnDegrees(-90, preferredTurnSpeed);
			//goTicks(inchesToTicks(12), 100);
			//turnDegrees(90, preferredTurnSpeed);
return;
			// Align ourselves with this wall
			//wallAlign(ALIGN_FORWARD);

			/*
			*	BLOCK CETNER GOAL
			*	Move the robot in front of the opponent's center goal
			*/

			// Move into position for use to block the center goal
			goTicks(inchesToTicks(-6), 100);	// Move away from the wall
			turnDegrees(90, preferredTurnSpeed);				// Turn to face OUR ramp
			goTicks(inchesToTicks(-36), 100);		// Move foward, past the center goal
			//turnDegrees(90, preferredTurnSpeed);				// Turn parallel to the cetner structure

			// Move to block the center goal, in one of three positions
			switch(goalFacing)
			{
				// Farthest position
				case CENTGOAL_POSITION_A:
				{
					writeDebugStreamLine("-- BLOCKING GOAL POSITION A --");
					goTicks(inchesToTicks(-80), 100);	// Move alongside the goal
					turnDegrees(90, preferredTurnSpeed);				// Turn tangent to the center structure
					goTicks(inchesToTicks(20), 100);	// Move in front of the goal
					break;
				}
				// Middle position
				case CENTGOAL_POSITION_B:
				{
					writeDebugStreamLine("-- BLOCKING GOAL POSITION B --");
					goTicks(inchesToTicks(-40), 100);	// Move alongside the goal
					turnDegrees(45, preferredTurnSpeed);				// Turn tangent to the center structure
					goTicks(inchesToTicks(20), 100);	// Move in front of the goal
					break;
				}
				// Closest position
				case CENTGOAL_POSITION_C:
				{
					writeDebugStreamLine("-- BLOCKING GOAL POSITION C --");
					goTicks(inchesToTicks(-20), 100);	// Move in front of the goal
					break;
				}
				default:
				{
					break;
				}
			}

		}	// END DEFENSE

	}	// END FLOOR START

	// After the program has been carried out, play a cute "done" sound
	nxtDisplayCenteredBigTextLine(3, "DONE");
	PlaySound(soundBeepBeep);
	wait10Msec(200);
} // END