Ejemplo n.º 1
0
void Volume::export_off()
{
  QFileDialog filedialog(mw, tr("Export surface to file"));
  filedialog.setFileMode(QFileDialog::AnyFile);
  
  filedialog.setNameFilter(tr("OFF files (*.off);;"
                              "All files (*)"));
  
  filedialog.setAcceptMode(QFileDialog::AcceptSave);
  filedialog.setDefaultSuffix("off");
  if(filedialog.exec())
  {
    const QString filename = filedialog.selectedFiles().front();
    std::cerr << "Saving to file \"" << filename.toLocal8Bit().data() << "\"...";
    std::ofstream out(filename.toUtf8());
    CGAL::output_surface_facets_to_off(out, c2t3);
    if(!out)
    {
      QMessageBox::warning(mw, mw->windowTitle(),
                           tr("Export to the OFF file <tt>%1</tt> failed!").arg(filename));
      status_message(tr("Export to the OFF file %1 failed!").arg(filename));
      std::cerr << " failed!\n";
    }
    else
    {
      std::cerr << " done.\n";
      status_message(tr("Successfull export to the OFF file %1.").arg(filename));
    }
  }
}
Ejemplo n.º 2
0
void Volume::save_image_to_inr()
{
  QFileDialog filedialog(mw, tr("Export image to Inrimage format"));
  filedialog.setFileMode(QFileDialog::AnyFile);
  
  filedialog.setNameFilter(tr("Inrimage files (*.inr);;"
                              "Compressed Inrimage files (*.inr.gz)"));


  filedialog.setAcceptMode(QFileDialog::AcceptSave);
  filedialog.setDefaultSuffix("inr.gz");
  if(filedialog.exec())
  {
    const QString filename = filedialog.selectedFiles().front();
    std::cerr << "Saving image to file \"" << filename.toLocal8Bit().data() << "\"...";
    const int result = ::_writeImage(m_image.image(), filename.toUtf8());
    if(result != ImageIO_NO_ERROR)
    {
      QMessageBox::warning(mw, mw->windowTitle(),
                           tr("Export to the Inrimage file <tt>%1</tt> failed!").arg(filename));
      status_message(tr("Export to the Inrimage file %1 failed!").arg(filename));
      std::cerr << " failed!\n";
    }
    else
    {
      std::cerr << " done.\n";
      status_message(tr("Successfull export to the Inrimage file %1.").arg(filename));
    }
  }
}
Ejemplo n.º 3
0
// Process one line of incoming serial data. Remove unneeded characters and capitalize.
void protocol_process()
{
  uint8_t c;
  while((c = serial_read()) != SERIAL_NO_DATA) {
    if ((c == '\n') || (c == '\r')) { // End of line reached

      // Runtime command check point before executing line. Prevent any furthur line executions.
      // NOTE: If there is no line, this function should quickly return to the main program when
      // the buffer empties of non-executable data.
      protocol_execute_runtime();
      if (sys.abort) { return; } // Bail to main program upon system abort

      if (char_counter > 0) {// Line is complete. Then execute!
        line[char_counter] = 0; // Terminate string
        status_message(protocol_execute_line(line));
      } else {
        // Empty or comment line. Skip block.
        status_message(STATUS_OK); // Send status message for syncing purposes.
      }
      char_counter = 0; // Reset line buffer index
      iscomment = false; // Reset comment flag

    } else {
      if (iscomment) {
        // Throw away all comment characters
        if (c == ')') {
          // End of comment. Resume line.
          iscomment = false;
        }
      } else {
        if (c <= ' ') {
          // Throw away whitepace and control characters
        } else if (c == '/') {
          // Disable block delete and throw away characters. Will ignore until EOL.
          #if BLOCK_DELETE_ENABLE
            iscomment = true;
          #endif
        } else if (c == '(') {
          // Enable comments flag and ignore all characters until ')' or EOL.
          iscomment = true;
        } else if (char_counter >= LINE_BUFFER_SIZE-1) {
          // Throw away any characters beyond the end of the line buffer
        } else if (c >= 'a' && c <= 'z') { // Upcase lowercase
          line[char_counter++] = c-'a'+'A';
        } else {
          line[char_counter++] = c;
        }
      }
    }
  }
}
Ejemplo n.º 4
0
bool Volume::opendir(const QString& dirname) 
{
  bool result = true;
  if(!fileinfo.isReadable())
  {
    QMessageBox::warning(mw, mw->windowTitle(),
                         tr("Cannot read directory <tt>%1</tt>!").arg(dirname));
    status_message(tr("Opening of directory %1 failed!").arg(dirname));
    result = false;
  }
  else
  {
    dicom_reader = vtkDICOMImageReader::New();
    dicom_reader->SetDirectoryName(dirname.toUtf8());

    executive =
      vtkDemandDrivenPipeline::SafeDownCast(dicom_reader->GetExecutive());
    if (executive)
    {
      executive->SetReleaseDataFlag(0, 0); // where 0 is the port index
    }

    smoother = vtkImageGaussianSmooth::New();
    smoother->SetStandardDeviations(1., 1., 1.);
    smoother->SetInputConnection(dicom_reader->GetOutputPort());
    smoother->Update();
    vtk_image = smoother->GetOutput();
    vtk_image->Print(std::cerr);
    m_image = CGAL::read_vtk_image_data(vtk_image);
    if(m_image.image() == 0)
    {
      QMessageBox::warning(mw, mw->windowTitle(),
                           tr("Error with file <tt>%1/</tt>:\nunknown file format!").arg(dirname));
      status_message(tr("Opening of file %1/ failed!").arg(dirname));
      result = false;
    }
    else
    {
      status_message(tr("File %1/ successfully opened.").arg(dirname));
      finish_open();
      result = true;
    }
    // if(executive) executive->Delete();
    // dicom_reader->Delete();
    // smoother->Delete();
  }
  return result;
}
Ejemplo n.º 5
0
int
main(int argc, char *argv[]) {

  if (argc != 2) {
    std::cerr << "Usage: " << argv[0] << " url" << std::endl;
    return 1;
  }

  try {
    http::client client;
    http::client::request request{network::uri{std::string{argv[1]}}};
    request.version("1.0");
    request.append_header("Connection", "close");
    request.append_header("User-Agent", "cpp-netlib read_headers example");
    auto future_response = client.head(request);
    auto response = future_response.get();

    std::cout << "HTTP version: " << response.version() << std::endl;
    std::cout << "HTTP status: " << static_cast<int>(response.status()) << std::endl;
    std::cout << "HTTP status message: " << response.status_message() << std::endl;
    std::cout << std::endl;
    for (auto header : response.headers()) {
      std::cout << header.first << ": " << header.second << std::endl;
    }
  }
  catch (std::exception& e) {
    std::cerr << e.what() << std::endl;
    return 1;
  }

  return 0;
}
Ejemplo n.º 6
0
void print_audio_devices_info(audio_device_t *d)
{
  ao_info *info;

  while (d != NULL) {
    info = ao_driver_info(d->driver_id);
    
    status_message(2, _("\nAudio Device:   %s"), info->name);
    status_message(3, _("Author:   %s"), info->author);
    status_message(3, _("Comments: %s"), info->comment);
    status_message(2, "");

    d = d->next_device;
  }

}
Ejemplo n.º 7
0
bool Volume::open_vtk(const QString& filename)
{
  only_in();

  fileinfo.setFile(filename);

  if(fileinfo.isDir())
  {
    return opendir(filename);
  }

  if(!fileinfo.isReadable())
  {
    QMessageBox::warning(mw, mw->windowTitle(),
                         tr("Cannot read file <tt>%1</tt>!").arg(filename));
    status_message(tr("Opening of file %1 failed!").arg(filename));
    return false;
  }
  else
  {
    vtk_reader = vtkImageReader::New();
    vtk_reader->SetFileName(filename.toUtf8());
    vtk_reader->SetDataScalarTypeToUnsignedChar();
    vtk_reader->SetDataExtent(0, 249, 0, 249, 0,  124);
    vtk_reader->SetDataSpacing(1., 1., 1.);
    vtk_reader->SetFileDimensionality(3);
    vtk_reader->Update();
    vtk_reader->Print(std::cerr);
    vtk_image = vtk_reader->GetOutput();
    vtk_image->Print(std::cerr);
    m_image = CGAL::read_vtk_image_data(vtk_image);
    if(m_image.image() == NULL)
    {
      QMessageBox::warning(mw, mw->windowTitle(),
                           tr("Error with file <tt>%1</tt>:\nunknown file format!").arg(filename));
      status_message(tr("Opening of file %1 failed!").arg(filename));
      return false;
    }
    else
    {
      status_message(tr("File %1 successfully opened.").arg(filename));
      finish_open();
      return true;
    }
  }
}
Ejemplo n.º 8
0
void
chat::_handle_global_ignore(::message *msg) {
    ACE_DEBUG((LM_DEBUG, "chat::_handle_global_ignore"));
    message_global_ignore *m = dynamic_ptr_cast<message_global_ignore>(msg);
    message_global_ignore::ip_list_type::const_iterator i = m->ip_begin();

    bool first = true;
    for (; i != m->ip_end(); i++) {
        if (first) {
            status_message(langstr("chat/global_ignore"));
            first = false;
        }
        status_message(
            langstr("chat/user_global_ignore",
                    i->userid.c_str(), i->reason.c_str())
        );
    }
}
Ejemplo n.º 9
0
// Process one line of incoming serial data. Remove unneeded characters and capitalize.
void protocol_process()
{
  char c;
  while((c = serial_read()) != SERIAL_NO_DATA) 
  {
    if ((c == '\n') || (c == '\r')) { // End of line reached
      if (char_counter > 0) {// Line is complete. Then execute!
        line[char_counter] = 0; // Terminate string
        status_message(protocol_execute_line(line));
      } else { 
        // Empty or comment line. Skip block.
        status_message(STATUS_OK); // Send status message for syncing purposes.
      }
      char_counter = 0; // Reset line buffer index
      iscomment = false; // Reset comment flag
    } else {
      if (iscomment) {
        // Throw away all comment characters
        if (c == ')') {
          // End of comment. Resume line.
          iscomment = false;
        }
      } else {
        if (c <= ' ') { 
          // Throw away whitepace and control characters
        } else if (c == '/') {
          // Disable block delete and throw away character
          // To enable block delete, uncomment following line. Will ignore until EOL.
          // iscomment = true;
        } else if (c == '(') {
          // Enable comments flag and ignore all characters until ')' or EOL.
          iscomment = true;
        } else if (char_counter >= LINE_BUFFER_SIZE-1) {
          // Throw away any characters beyond the end of the line buffer
        } else if (c >= 'a' && c <= 'z') { // Upcase lowercase
          line[char_counter++] = c-'a'+'A';
        } else {
          line[char_counter++] = c;
        }
      }
    }
  }
}
Ejemplo n.º 10
0
Archivo: volume.cpp Proyecto: FMX/CGAL
bool Volume::opendir(const QString& dirname) 
{
  bool result = true;
  if(!fileinfo.isReadable())
  {
    QMessageBox::warning(mw, mw->windowTitle(),
                         tr("Cannot read directory <tt>%1</tt>!").arg(dirname));
    status_message(tr("Opening of directory %1 failed!").arg(dirname));
    result = false;
  }
  else
  {
    vtkDICOMImageReader* dicom_reader = vtkDICOMImageReader::New();
    dicom_reader->SetDirectoryName(dirname.toUtf8());
    vtkImageGaussianSmooth* smoother = vtkImageGaussianSmooth::New();
    smoother->SetStandardDeviations(1., 1., 1.);
    smoother->SetInputConnection(dicom_reader->GetOutputPort());
    smoother->Update();
    vtkImageData* vtk_image = smoother->GetOutput();
    dicom_reader->SetReleaseDataFlag(false);
    vtk_image->SetReleaseDataFlag(false);
    vtk_image->Print(std::cerr);
    if(!m_image.read_vtk_image_data(vtk_image))
    {
      QMessageBox::warning(mw, mw->windowTitle(),
                           tr("Error with file <tt>%1/</tt>:\nunknown file format!").arg(dirname));
      status_message(tr("Opening of file %1/ failed!").arg(dirname));
      result = false;
    }
    else
    {
      status_message(tr("File %1/ successfully opened.").arg(dirname));
      finish_open();
      result = true;
    }
    dicom_reader->Delete();
    // smoother->Delete();
  }
  return result;
}
Ejemplo n.º 11
0
void sp_process()
{
    char c;
    while((c = serialRead()) != -1)
    {
        if((char_counter > 0) && ((c == '\n') || (c == '\r'))) {  // Line is complete. Then execute!
            line[char_counter] = 0; // treminate string
            status_message(gc_execute_line(line));
            char_counter = 0; // reset line buffer index
        } else if (c <= ' ') { // Throw away whitepace and control characters
        } else if (c >= 'a' && c <= 'z') { // Upcase lowercase
            line[char_counter++] = c-'a'+'A';
        } else {
            line[char_counter++] = c;
        }
    }
}
Ejemplo n.º 12
0
/*
 * FILEVIEW CALLBACKS
 */
static void
updir_click_cb(GtkWidget *widget, GdkEventButton *event, FileView *view)
{
  if (event->button == 1)
  {
    gchar path[PATH_MAX];
    g_snprintf(path, sizeof(path), "%s/..", view->dir);
    change_dir(view, path);
  }
  else if (event->button == 3)
  {
    gchar *home;
    if ((home = getenv("HOME")) != NULL)
      change_dir(view, home);
    else
      status_message(_("Environment variable 'HOME' not set."));
  }
  gtk_signal_emit_stop_by_name(GTK_OBJECT(widget), "button_press_event");
  focus_row(view, view->row, TRUE, TRUE, TRUE);
}
Ejemplo n.º 13
0
	QMSMMainWindow::QMSMMainWindow(QWidget* pParent, NData::CDataHandler& rDataHandler, QApplication* pApplication) :
		QMainWindow(pParent),
		MainWindow(),
		mpApplication(pApplication),
		mpFormInfo(0),
		mpFormSettings(0),
		mpFormSystemOverview(0),
		mrDataHandler(rDataHandler),
		mpFormPower(0),
		mpFormTemperature(0),
		mpFormClock(0),
		mpFormUtilization(0),
		mpFormMemory(0),
		mpFormHeatmapUtilization(0),
		mpFormHeatmapTemperature(0),
		mGuiMarker(this)
		{
		
		setupUi(this);
		
		QString windowTitleKey = "MSMonitor v";
		windowTitleKey += QString::number(MS_MAJOR_VERSION);
		windowTitleKey += ".";
		windowTitleKey += QString::number(MS_MINOR_VERSION);
		windowTitleKey += ".";
		windowTitleKey += QString::number(MS_REVISION_VERSION);
		
		setWindowTitle(QApplication::translate("MainWindow", qPrintable(windowTitleKey), 0, QApplication::UnicodeUTF8));
		
		mdiArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
		mdiArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
		
		pushButtonStop->setEnabled(false);
		
		createActions();
		createShortcuts();
		
		mpFormInfo					= QMSMFormInfo::construct(this);
		mpFormSettings				= QMSMFormSettings::construct(this, mrDataHandler.getSettings());
		mpFormSystemOverview		= QMSMFormSystemOverview::construct(this, &mrDataHandler);
		mpFormPower					= QMSMFormPower::construct(this, &mrDataHandler);
		mpFormTemperature			= QMSMFormTemperature::construct(this, &mrDataHandler);
		mpFormClock					= QMSMFormClock::construct(this, &mrDataHandler);
		mpFormUtilization			= QMSMFormUtilization::construct(this, &mrDataHandler);
		mpFormMemory				= QMSMFormMemory::construct(this, &mrDataHandler);
		mpFormHeatmapUtilization	= QMSMFormHeatmapUtilization::construct(this, &mrDataHandler);
		mpFormHeatmapTemperature	= QMSMFormHeatmapTemperature::construct(this, &mrDataHandler);
		
		mdiArea->addSubWindow(mpFormInfo);
		mdiArea->addSubWindow(mpFormSettings);
		mdiArea->addSubWindow(mpFormSystemOverview);
		mdiArea->addSubWindow(mpFormPower);
		mdiArea->addSubWindow(mpFormTemperature);
		mdiArea->addSubWindow(mpFormClock);
		mdiArea->addSubWindow(mpFormUtilization);
		mdiArea->addSubWindow(mpFormMemory);
		mdiArea->addSubWindow(mpFormHeatmapUtilization);
		mdiArea->addSubWindow(mpFormHeatmapTemperature);
		
		mpFormInfo->hide();
		mpFormSettings->hide();
		mpFormSystemOverview->hide();
		mpFormPower->hide();
		mpFormTemperature->hide();
		mpFormClock->hide();
		mpFormUtilization->hide();
		mpFormMemory->hide();
		mpFormHeatmapUtilization->hide();
		mpFormHeatmapTemperature->hide();
		
		QString status_message("Listening on socket \"");
		status_message += mGuiMarker.getSocketName();
		status_message += "\".";
		QLabel status_label(status_message);
		statusBar()->addPermanentWidget(&status_label);
		
		show();
		
		statusbar->showMessage(status_message);
	}
Ejemplo n.º 14
0
//********************************************************************
void find_anagrams(HWND hwnd)
{
   char msgstr[81] ;
   //  read data out of hwnd:IDC_PHRASE
   char input_bfr[MAX_PKT_CHARS+1] ;
   uint input_bfr_len = GetWindowTextA (GetDlgItem(hwnd,IDC_PHRASE) , input_bfr, MAX_PKT_CHARS);
   if (input_bfr_len > MAX_PKT_CHARS) 
       input_bfr_len = MAX_PKT_CHARS ;
   input_bfr[MAX_PKT_CHARS] = 0 ;
   if (vflag)  //lint !e506 !e774
      syslog("find_anagrams: [%u] [%s]\n", input_bfr_len, input_bfr) ;

   //  scan for separator char
   excl_idx = 0 ; //  reset exclusions list
   char *hd ;
   char *tl = strchr(input_bfr, '!');
   if (tl != NULL) {
      *tl++ = 0 ; //  NULL-term word list, point to exclusions list
      while (LOOP_FOREVER) {
         tl = strip_leading_spaces(tl);
         if (*tl != 0) {
            hd = tl ;
            tl = strchr(hd, ' ');
            if (tl != NULL) {
               *tl++ = 0 ;
               //  hd points to one exclusion arg
            }
            add_to_excl_list(hd);
            if (tl == NULL) {
               break;
            }
         }
      }
   }

   status_message("Begin new anagram search") ;

   // clear_message_area(&this_term);
   clear_message_area();
   if (excl_idx == 0) {
      status_message("excl: <none>", 1);
   }
   else
   {
      uint slen = sprintf(msgstr, "excl: ");
      for (uint idx=0; idx<excl_idx; idx++) {
         slen += (uint) sprintf(msgstr+slen, "%s ", excl_list[idx]);
      }
      status_message(msgstr, 1);
   }
   delete_wordlist() ;

   ZeroMemory((char *) &freq[0], sizeof(freq)) ;
   nletters = 0 ;
   for (char *p = input_bfr; *p != 0; p++) {
      if (*p != ' ') {
         freq[(uint) (u8) *p]++ ;
         nletters++;
      }
   }
   if (maxgen == 0)
       maxgen = nletters;
   
   wordlist = buildwordlist ();
   if (wordlist == NULL) {
      syslog("Empty dictionary or no suitable words.\n");
      return ;
   }

   wordlist = sort (wordlist);
   initfind (wordlist);

   solutions_found = 0 ;
   findanags (0, forgelinks (wordlist), nletters);
   if (solutions_found == 0) {
      status_message("no anagrams found for input string !") ;
   } else {
      // reverse_list_entries() ;
      // InsertListViewItems(solutions_found);  //  This triggers drawing of listview
      myTerminal->reverse_list_entries() ;
      update_listview();

      wsprintf(msgstr, "%u anagrams found", solutions_found) ;
      status_message(msgstr) ;
   }
}
Ejemplo n.º 15
0
void Volume::display_surface_mesher_result()
{
  if(m_surface.empty() || // Either the surface is not computed.
     m_view_surface) // Or it is computed and displayed, and one want
                     // to recompute it.
  {
    QTime total_time;
    total_time.start();

    values_list->save_values(fileinfo.absoluteFilePath());

    std::size_t nx = m_image.xdim();
    std::size_t ny = m_image.ydim();
    std::size_t nz = m_image.zdim();
    if(nx * ny * nz == 0)
    {
      status_message("No volume loaded.");
      return;
    }

    m_surface.clear();
    sm_timer.reset();
    busy();

    status_message("Surface meshing...");

    sm_timer.start();

    c2t3.clear();
    del.clear();
    Sphere bounding_sphere(m_image.center(),m_image.radius()*m_image.radius());

    Classify_from_isovalue_list classify(values_list);
    Generate_surface_identifiers generate_ids(values_list);

    m_image.set_interpolation(mw->interpolationCheckBox->isChecked());
    if(mw->labellizedRadioButton->isChecked()) {
      std::cerr << "Labellized image\n";
    }
    m_image.set_labellized(mw->labellizedRadioButton->isChecked());
    classify.set_identity(mw->labellizedRadioButton->isChecked());
    generate_ids.set_labellized_image(mw->labellizedRadioButton->isChecked());

    // definition of the surface
    Surface_3 surface(m_image, bounding_sphere, m_relative_precision);
//     Threshold threshold(m_image.isovalue());

    // surface mesh traits class
    typedef CGAL::Surface_mesher::Implicit_surface_oracle_3<Kernel,
      //     typedef CGAL::Surface_mesher::Image_surface_oracle_3<Kernel,
      Surface_3, 
      Classify_from_isovalue_list,
      Generate_surface_identifiers> Oracle;
    Oracle oracle(classify, generate_ids);

    if(mw->searchSeedsCheckBox->isChecked())
    {
      typedef std::vector<std::pair<Point, double> > Seeds;
      Seeds seeds;
      {
	std::cerr << "Search seeds...\n";
	std::set<unsigned char> domains;
	search_for_connected_components(std::back_inserter(seeds),
					CGAL::inserter(domains),
					classify);
	std::cerr << "Found " << seeds.size() << " seed(s).\n";

	if(mw->labellizedRadioButton->isChecked() && 
	   values_list->numberOfValues() == 0) 
	{
	  Q_FOREACH(unsigned char label, domains) {
	    if(label != 0) {
	      values_list->addValue(label);
	    }
	  }
	}
      }
      std::ofstream seeds_out("seeds.off");
      std::ofstream segments_out("segments.txt");
      seeds_out.precision(18);
      seeds_out << "OFF\n" << seeds.size() << " 0 0\n";
      segments_out.precision(18);
      for(Seeds::const_iterator it = seeds.begin(), end = seeds.end();
	  it != end; ++it)
      {
        seeds_out << it->first << std::endl;
	CGAL::Random_points_on_sphere_3<Point> random_points_on_sphere_3(it->second);
	Oracle::Intersect_3 intersect = oracle.intersect_3_object();
	for(int i = 0; i < 20; ++i)
	{
	  const Point test = it->first + (*random_points_on_sphere_3++ - CGAL::ORIGIN);
	  CGAL::Object o = intersect(surface, Segment_3(it->first, test));
	  if (const Point* intersection = CGAL::object_cast<Point>(&o)) {
            segments_out << "2 " << it->first << " " << *intersection << std::endl;
	    del.insert(*intersection);
          }
	  else 
	  {
	    std::cerr << 
	      boost::format("Error. Segment (%1%, %2%) does not intersect the surface! values=(%3%, %4%)\n")
	      % it->first % test
	      % surface(it->first) % surface(test);
	  }
	}
      }
    }
Ejemplo n.º 16
0
static
VALUE rhe_write_response(VALUE self, VALUE filenov, VALUE timeoutv, VALUE status_codev, VALUE headers, VALUE body) {
  ssize_t hlen;
  ssize_t blen;

  ssize_t len;
  ssize_t rv = 0;
  ssize_t iovcnt;
  ssize_t vec_offset;
  ssize_t written;
  int count;
  int i;
  char status_line[512];
  char date_line[512];
  int date_pushed = 0;
  VALUE arr;
  VALUE key_obj;
  VALUE val_obj;
  char * key;

  int fileno = NUM2INT(filenov);
  double timeout = NUM2DBL(timeoutv);
  int status_code = NUM2INT(status_codev);

  arr = rb_ary_new();
  rb_hash_foreach(headers, my_hash_keys, arr);
  hlen = RARRAY_LEN(arr);
  blen = RARRAY_LEN(body);
  iovcnt = 10 + (hlen * 2) + blen;

  {
    struct iovec v[iovcnt]; // Needs C99 compiler
    /* status line */
    iovcnt = 0;
    i=0;
    status_line[i++] = 'H';
    status_line[i++] = 'T';
    status_line[i++] = 'T';
    status_line[i++] = 'P';
    status_line[i++] = '/';
    status_line[i++] = '1';
    status_line[i++] = '.';
    status_line[i++] = '0';
    status_line[i++] = ' ';
    str_i(status_line,&i,status_code,3);
    status_line[i++] = ' ';
    const char * message = status_message(status_code);
    str_s(status_line, &i, message, strlen(message));
    status_line[i++] = 13;
    status_line[i++] = 10;
    v[iovcnt].iov_base = status_line;
    v[iovcnt].iov_len = i;
    iovcnt++;

    v[iovcnt].iov_base = "Connection: close\r\nServer: Rhebok\r\n";
    v[iovcnt].iov_len = sizeof("Connection: close\r\nServer: Rhebok\r\n")-1;
    iovcnt++;

    date_pushed = 0;
    for ( i = 0; i < hlen; i++ ) {
      key_obj = rb_ary_entry(arr, i);
      key = StringValuePtr(key_obj);
      len = RSTRING_LEN(key_obj);
      if ( strncasecmp(key,"Connection",len) == 0 ) {
        continue;
      }
      if ( strncasecmp(key,"Server",len) == 0 ) {
        v[1].iov_len -= (sizeof("Server: Rhebok\r\n") - 1);
      }
      if ( strncasecmp(key,"Date",len) == 0 ) {
        date_pushed = 1;
      }
      v[iovcnt].iov_base = key;
      v[iovcnt].iov_len = len;
      iovcnt++;
      v[iovcnt].iov_base = ": ";
      v[iovcnt].iov_len = sizeof(": ") - 1;
      iovcnt++;
      /* value */
      val_obj = rb_hash_aref(headers, key_obj);
      v[iovcnt].iov_base = StringValuePtr(val_obj);
      v[iovcnt].iov_len = RSTRING_LEN(val_obj);
      iovcnt++;
      v[iovcnt].iov_base = "\r\n";
      v[iovcnt].iov_len = sizeof("\r\n") - 1;
      iovcnt++;
    }

    if ( date_pushed == 0 ) {
      v[iovcnt].iov_len = _date_line(date_line);
      v[iovcnt].iov_base = date_line;
      iovcnt++;
    }

    v[iovcnt].iov_base = "\r\n";
    v[iovcnt].iov_len = sizeof("\r\n") - 1;
    iovcnt++;

    for (i=0; i < blen; i++ ) {
      val_obj = rb_ary_entry(body, i);
      v[iovcnt].iov_base = StringValuePtr(val_obj);
      v[iovcnt].iov_len = RSTRING_LEN(val_obj);
      iovcnt++;
    }

    vec_offset = 0;
    written = 0;
    while ( iovcnt - vec_offset > 0 ) {
      count = (iovcnt > IOV_MAX) ? IOV_MAX : iovcnt;
      rv = _writev_timeout(fileno, timeout,  &v[vec_offset], count - vec_offset, (vec_offset == 0) ? 0 : 1);
      if ( rv <= 0 ) {
        // error or disconnected
        break;
      }
      written += rv;
      while ( rv > 0 ) {
        if ( (int)rv >= v[vec_offset].iov_len ) {
        rv -= v[vec_offset].iov_len;
          vec_offset++;
        }
        else {
          v[vec_offset].iov_base = (char*)v[vec_offset].iov_base + rv;
          v[vec_offset].iov_len -= rv;
          rv = 0;
        }
      }
    }
  }
  if ( rv < 0 ) {
    return Qnil;
  }
  return rb_int_new(written);
}
Ejemplo n.º 17
0
void
chat::handle_message(::message *msg) {
    switch (msg->id()) {
    case ::message::send:
    case ::message::send_private:
    {
        message_channel *m = dynamic_ptr_cast<message_channel>(msg);
        ACE_DEBUG((LM_DEBUG, "chat::handle message _channel/channel %s/%s\n",
                  _channel.c_str(), m->channel().c_str()));

        if (_channel == m->channel()) {
            // Public message
            public_message(m->sender_id(), m->str(), m->group_base());
        }
    }
        break;
    case ::message::private_refused:
    {
        message_channel *m = dynamic_ptr_cast<message_channel>(msg);
        ACE_DEBUG((LM_DEBUG, "chat::handle message _channel/channel %s/%s\n",
                  _channel.c_str(), m->channel().c_str()));

        if (_channel == m->channel()) {
            // Status message of refused
            status_message(
                langstr("chat/private_msg_refused", m->str().c_str())
            );
        }
    }
        break;
    case ::message::send_notification:
    {
        message_channel *m = dynamic_ptr_cast<message_channel>(msg);
        ACE_DEBUG((LM_DEBUG, "chat::handle message _channel/channel %s/%s\n",
                  _channel.c_str(), m->channel().c_str()));

        if (_channel == m->channel()) {
            notification_message(
                m->sender_id(), m->str(), m->group_base()
            );
        }
    }
        break;
    case ::message::block_users:
    {
        message_block_users *m = dynamic_ptr_cast<message_block_users>(msg);
        if (m->global_ignore() == false) {
            ACE_DEBUG((LM_DEBUG, "chat::handle message block_users\n"));
            status_message(
                langstr("chat/user_ignores", m->user().display_id().c_str())
            );
        }
    }
        break;
    case ::message::global_ignore_list:
        _handle_global_ignore(msg);
        break;
    case ::message::room:
    {
        message_room *m = dynamic_ptr_cast<message_room>(msg);
        const chat_gaming::room &r = m->room();

    if (app_opts.debug()) {
        std::string msgstr =
            "Room update id " + (const std::string)r.id() +
            " topic "         + r.topic() +
            " owner id "      + (const std::string)(r.owner_id());
        status_message(msgstr);
    }

    }
        break;
    case ::message::user:
    {
        message_user *m = dynamic_ptr_cast<message_user>(msg);
        const chat_gaming::user &u = m->user();

    if (app_opts.debug()) {
        std::string msgstr =
            "User update id " + (std::string)u.id() +
            " in room id "    + (std::string)u.room_id();
        status_message(msgstr);
    }


    }
        break;

    }
}
Ejemplo n.º 18
0
void Volume::display_marchin_cube()
{
#ifdef CGAL_SURFACE_MESH_DEMO_USE_MARCHING_CUBE
  if(m_surface_mc.empty())
  {
    QTime total_time;
    total_time.start();

    values_list->save_values(fileinfo.absoluteFilePath());

    unsigned int nx = m_image.xdim();
    unsigned int ny = m_image.ydim();
    unsigned int nz = m_image.zdim();
    if(nx * ny * nz == 0)
    {
      status_message("No volume loaded.");
      return;
    }

    mc_timer.reset();
    busy();
    status_message("Marching cubes...");

    mc_timer.start();
    m_surface_mc.clear();

    if(mc.ntrigs()!=0)
      mc.clean_all();
    mc.set_resolution(nx,ny,nz);
    mc.init_all();
    mc.set_ext_data(static_cast<unsigned char*>(m_image.image()->data));

    nbs_of_mc_triangles.resize(values_list->numberOfValues());

    for(int value_id = 0; 
        value_id < values_list->numberOfValues();
        ++value_id)
    {
      status_message(tr("Marching cubes, isovalue #%1...").arg(value_id));

      // set data
//       for(unsigned int i=0;i<nx;i++)
//         for(unsigned int j=0;j<ny;j++)
//           for(unsigned int k=0;k<nz;k++)
//           {
//             const float& value = m_image.value(i,j,k);
//             mc.set_data(value,i,j,k);
//           }
      // compute scaling ratio
      if(value_id > 0)
        mc.init_temps();
      mc.run(values_list->value(value_id),
             m_image.vx(),
             m_image.vy(),
             m_image.vz());
      mc.clean_temps();

      std::vector<double> facets;
      mc.get_facets(facets);

      mc_timer.stop();
      const unsigned int begin = value_id == 0 ? 0 : nbs_of_mc_triangles[value_id-1];
      const unsigned int nbt = facets.size() / 9;
      for(unsigned int i=begin;i<nbt;i++)
      {
        const Point a(facets[9*i],   facets[9*i+1], facets[9*i+2]);
        const Point b(facets[9*i+3], facets[9*i+4], facets[9*i+5]);
        const Point c(facets[9*i+6], facets[9*i+7], facets[9*i+8]);
        const Triangle_3 t(a,b,c);
        const Vector u = t[1] - t[0];
        const Vector v = t[2] - t[0];
        Vector n = CGAL::cross_product(u,v);
        n = n / std::sqrt(n*n);
        m_surface_mc.push_back(Facet(t,n,values_list->item(value_id)));
      }
      nbs_of_mc_triangles[value_id]=m_surface_mc.size();
      mc_timer.start();
    }
    mc_timer.stop();
    not_busy();
    mc_total_time = total_time.elapsed();

    // invalidate the display list
    lists_draw_surface_mc_is_valid = false;
    list_draw_marching_cube_is_valid = false;
  }
  CGAL::Bbox_3 bbox(0,0,0,0,0,0);
  for(std::vector<Facet>::const_iterator
        it = m_surface_mc.begin(), end = m_surface_mc.end();
      it != end; ++it)
  {
    bbox = bbox + it->get<0>().bbox();
  }

  m_view_mc = true;
  m_view_surface = false;
  Q_EMIT changed();
  if(!m_surface_mc.empty())
  {
    Q_EMIT new_bounding_box(bbox.xmin(),
                          bbox.ymin(),
                          bbox.zmin(),
                          bbox.xmax(),
                          bbox.ymax(),
                          bbox.zmax());
  }
  status_message(tr("Marching cubes done. %2 facets in %1s (CPU time), total time is %3s.")
                 .arg(mc_timer.time())
                 .arg(m_surface_mc.size())
                 .arg(mc_total_time/1000.));

  save_image_settings(fileinfo.absoluteFilePath());
#endif // CGAL_SURFACE_MESH_DEMO_USE_MARCHING_CUBE
}
Ejemplo n.º 19
0
void play (char *source_string)
{
  transport_t *transport;
  format_t *format;
  data_source_t *source;
  decoder_t *decoder;

  decoder_callbacks_t decoder_callbacks;
  void *decoder_callbacks_arg;

  /* Preserve between calls so we only open the audio device when we 
     have to */
  static audio_format_t old_audio_fmt = { 0, 0, 0, 0, 0 };
  audio_format_t new_audio_fmt;
  audio_reopen_arg_t *reopen_arg;

  /* Flags and counters galore */
  int eof = 0, eos = 0, ret;
  int nthc = 0, ntimesc = 0;
  int next_status = 0;
  static int status_interval = 0;

  /* Reset all of the signal flags */
  sig_request.cancel   = 0;
  sig_request.skipfile = 0;
  sig_request.exit     = 0;
  sig_request.pause    = 0;

  /* Set preferred audio format (used by decoder) */
  new_audio_fmt.big_endian = ao_is_big_endian();
  new_audio_fmt.signed_sample = 1;
  new_audio_fmt.word_size = 2;

  /* Select appropriate callbacks */
  if (audio_buffer != NULL) {
    decoder_callbacks.printf_error = &decoder_buffered_error_callback;
    decoder_callbacks.printf_metadata = &decoder_buffered_metadata_callback;
    decoder_callbacks_arg = audio_buffer;
  } else {
    decoder_callbacks.printf_error = &decoder_error_callback;
    decoder_callbacks.printf_metadata = &decoder_metadata_callback;
    decoder_callbacks_arg = NULL;
  }

  /* Locate and use transport for this data source */  
  if ( (transport = select_transport(source_string)) == NULL ) {
    status_error(_("No module could be found to read from %s.\n"), source_string);
    return;
  }
  
  if ( (source = transport->open(source_string, &options)) == NULL ) {
    status_error(_("Cannot open %s.\n"), source_string);
    return;
  }

  /* Detect the file format and initialize a decoder */
  if ( (format = select_format(source)) == NULL ) {
    status_error(_("The file format of %s is not supported.\n"), source_string);
    return;
  }
  
  if ( (decoder = format->init(source, &options, &new_audio_fmt, 
			       &decoder_callbacks,
			       decoder_callbacks_arg)) == NULL ) {

    /* We may have failed because of user command */
    if (!sig_request.cancel)
      status_error(_("Error opening %s using the %s module."
		     "  The file may be corrupted.\n"), source_string,
		   format->name);
    return;
  }

  /* Decide which statistics are valid */
  select_stats(stat_format, &options, source, decoder, audio_buffer);

  /* Start the audio playback thread before we begin sending data */    
  if (audio_buffer != NULL) {
    
    /* First reset mutexes and other synchronization variables */
    buffer_reset (audio_buffer);
    buffer_thread_start (audio_buffer);
  }

  /* Show which file we are playing */
  decoder_callbacks.printf_metadata(decoder_callbacks_arg, 1,
				    _("Playing: %s"), source_string);

  /* Skip over audio */
  if (options.seekpos > 0.0) {
    if (!format->seek(decoder, options.seekpos, DECODER_SEEK_START)) {
      status_error(_("Could not skip %f seconds of audio."), options.seekpos);
      if (audio_buffer != NULL)
	buffer_thread_kill(audio_buffer);
      return;
    }
  }

  /* Main loop:  Iterates over all of the logical bitstreams in the file */
  while (!eof && !sig_request.exit) {
    
    /* Loop through data within a logical bitstream */
    eos = 0;    
    while (!eos && !sig_request.exit) {
      
      /* Check signals */
      if (sig_request.skipfile) {
	eof = eos = 1;
	break;
      }

      if (sig_request.pause) {
	if (audio_buffer)
	  buffer_thread_pause (audio_buffer);

	kill (getpid(), SIGSTOP); /* We block here until we unpause */
	
	/* Done pausing */
	if (audio_buffer)
	  buffer_thread_unpause (audio_buffer);

	sig_request.pause = 0;
      }


      /* Read another block of audio data */
      ret = format->read(decoder, convbuffer, convsize, &eos, &new_audio_fmt);

      /* Bail if we need to */
      if (ret == 0) {
	eof = eos = 1;
	break;
      } else if (ret < 0) {
	status_error(_("Error: Decoding failure.\n"));
	break;
      }

      
      /* Check to see if the audio format has changed */
      if (!audio_format_equal(&new_audio_fmt, &old_audio_fmt)) {
	old_audio_fmt = new_audio_fmt;
	
	/* Update our status printing interval */
	status_interval = new_audio_fmt.word_size * new_audio_fmt.channels * 
	  new_audio_fmt.rate / options.status_freq;
	next_status = 0;

	reopen_arg = new_audio_reopen_arg(options.devices, &new_audio_fmt);

	if (audio_buffer)	  
	  buffer_insert_action_at_end(audio_buffer, &audio_reopen_action,
				      reopen_arg);
	else
	  audio_reopen_action(NULL, reopen_arg);
      }
      

      /* Update statistics display if needed */
      if (next_status <= 0) {
	display_statistics(stat_format, audio_buffer, source, decoder); 
	next_status = status_interval;
      } else
	next_status -= ret;

      if (options.endpos > 0.0 && options.endpos <= current_time(decoder)) {
	eof = eos = 1;
	break;
      }


      /* Write audio data block to output, skipping or repeating chunks
	 as needed */
      do {
	
	if (nthc-- == 0) {
	  if (audio_buffer)
	    buffer_submit_data(audio_buffer, convbuffer, ret);
	  else
	    audio_play_callback(convbuffer, ret, eos, &audio_play_arg);
	  
	  nthc = options.nth - 1;
	}
	
      } while (!sig_request.exit && !sig_request.skipfile &&
	       ++ntimesc < options.ntimes);

      ntimesc = 0;
            
    } /* End of data loop */
    
  } /* End of logical bitstream loop */
  
  /* Done playing this logical bitstream.  Clean up house. */

  if (audio_buffer) {
    
    if (!sig_request.exit && !sig_request.skipfile) {
      buffer_mark_eos(audio_buffer);
      buffer_wait_for_empty(audio_buffer);
    }

    buffer_thread_kill(audio_buffer);
  }

  /* Print final stats */
  display_statistics_quick(stat_format, audio_buffer, source, decoder); 
   
  
  format->cleanup(decoder);
  transport->close(source);
  status_reset_output_lock();  /* In case we were killed mid-output */

  status_message(1, _("Done."));
  
  if (sig_request.exit)
    exit (0);
}
Ejemplo n.º 20
0
bool Volume::open(const QString& filename)
{
  only_in();

  fileinfo.setFile(filename);

  if(fileinfo.isDir())
  {
    return opendir(filename);
  }

  if(!fileinfo.isReadable())
  {
    QMessageBox::warning(mw, mw->windowTitle(),
                         tr("Cannot read file <tt>%1</tt>!").arg(filename));
  }
  else
  {
    if(m_image.read(filename.toStdString().c_str()))
    {
      status_message(tr("File %1 successfully opened.").arg(filename));
      finish_open();
      return true;
    }
    else if(open_xt(filename)) {
      return true;
    }
    else 
    {
      QSettings settings;
      settings.beginGroup(QUrl::toPercentEncoding(fileinfo.absoluteFilePath()));
      if( settings.value("is_raw").toBool() &&
	  m_image.read_raw(filename.toStdString().c_str(),
			   settings.value("dim_x").toInt(),
			   settings.value("dim_y").toInt(),
			   settings.value("dim_z").toInt(),
			   settings.value("spacing_x").toDouble(),
			   settings.value("spacing_y").toDouble(),
			   settings.value("spacing_z").toDouble(),
			   settings.value("offset").toInt()) )
      {
	status_message(tr("File %1 successfully opened.").arg(filename));
	finish_open();
	return true;
      }
      else if(QMessageBox::warning(mw, mw->windowTitle(),
				   tr("Error with file <tt>%1</tt>:\n"
				      "unknown file format!\n"
				      "\n"
				      "Open it as a raw image?").arg(filename),
				   QMessageBox::Yes|QMessageBox::No) == QMessageBox::Yes) 
      {
	Raw_image_dialog raw_dialog;
	raw_dialog.label_file_size->setText(QString("%1 B").arg(fileinfo.size()));
	if( raw_dialog.exec() && 
	    m_image.read_raw(filename.toStdString().c_str(),
			     raw_dialog.dim_x->value(),
			     raw_dialog.dim_y->value(),
			     raw_dialog.dim_z->value(),
			     raw_dialog.spacing_x->value(),
			     raw_dialog.spacing_y->value(),
			     raw_dialog.spacing_z->value(),
			     raw_dialog.offset->value()) )
	{
	  status_message(tr("File %1 successfully opened.").arg(filename));
	  QSettings settings;
	  settings.beginGroup(QUrl::toPercentEncoding(fileinfo.absoluteFilePath()));
	  settings.setValue("is_raw", true);
	  settings.setValue("dim_x", raw_dialog.dim_x->value());
	  settings.setValue("dim_y", raw_dialog.dim_y->value());
	  settings.setValue("dim_z", raw_dialog.dim_z->value());
	  settings.setValue("spacing_x", raw_dialog.spacing_x->value());
	  settings.setValue("spacing_y", raw_dialog.spacing_y->value());
	  settings.setValue("spacing_z", raw_dialog.spacing_z->value());
	  settings.setValue("offset", raw_dialog.offset->value());
	  settings.endGroup();
	  finish_open();
	  return true;
	}
      }
    }
  }
  status_message(tr("Opening of file %1 failed!").arg(filename));
  return false;
}
Ejemplo n.º 21
0
// Total 3D images (XT format, that is the old Inrimage format, 1994.
bool Volume::open_xt(const QString& filename)
{
  only_in();

  fileinfo.setFile(filename);

  if(fileinfo.isDir())
  {
    return false;
  }

  if(!fileinfo.isReadable())
  {
    QMessageBox::warning(mw, mw->windowTitle(),
                         tr("Cannot read file <tt>%1</tt>!").arg(filename));
    status_message(tr("Opening of file %1 failed!").arg(filename));
    return false;
  }
  else
  {
    long dimx, dimy, dimz;
    long word_dim;
    long header_size;
    const char* filename_stl = qPrintable(filename);
    CGAL::Total::lire_longueur_entete(filename_stl, &header_size);
    CGAL::Total::lire_nb_octet(filename_stl, &word_dim);
    CGAL::Total::lire_longueur_trace(filename_stl, &dimx);
    CGAL::Total::lire_nb_trace(filename_stl, &dimy);
    CGAL::Total::lire_nb_plan(filename_stl, &dimz);

    vtkImageReader* vtk_reader = vtkImageReader::New();
    vtk_reader->SetFileName(filename_stl);
    switch(word_dim) {
    case 8:
      vtk_reader->SetDataScalarTypeToUnsignedChar();
      break;
    case 16:
      vtk_reader->SetDataScalarTypeToUnsignedShort();
      break;
    default:
      return false;
    }
    vtk_reader->SetHeaderSize(header_size);
    vtk_reader->SetDataExtent(1, dimx, 1, dimy, 1,  dimz);
    vtk_reader->SetDataSpacing(1., 1., 1.);
    vtk_reader->SetFileDimensionality(3);
    vtk_reader->Update();
    vtk_reader->Print(std::cerr);
    vtkImageData* vtk_image = vtk_reader->GetOutput();
    vtk_image->Print(std::cerr);
    m_image = CGAL::read_vtk_image_data(vtk_image);
    if(m_image.image() != NULL)
    {
      QMessageBox::warning(mw, mw->windowTitle(),
                           tr("Error with file <tt>%1</tt>:\nunknown file format!").arg(filename));
      status_message(tr("Opening of file %1 failed!").arg(filename));
      return false;
    }
    else
    {
      status_message(tr("File %1 successfully opened.").arg(filename));
      finish_open();
    }
    return true;
  }
}
Ejemplo n.º 22
0
void MainWindow::simulationStateChanged()
{
    MainController::state_t new_state = mController.getSimulationState();
    QString status_message("");
    switch(new_state) {
        case MainController::RUNNING:
            /* Control buttons */
            ui->playButton->setText("Pause");
            ui->playButton->setEnabled(true);
            ui->stopButton->setEnabled(true);

            /* Menubar actions */
            ui->actionStart->setEnabled(false);
            ui->actionStop->setEnabled(true);

            /* Update status bar */
            status_message = tr("Running: ");
            status_message += mController.getSimulationFilePath();
            mStatusLabel->setText(status_message);
        break;
        case MainController::ON_HOLD:
            /* Control buttons */
            ui->playButton->setText("Play");
            ui->playButton->setEnabled(true);
            ui->stopButton->setEnabled(true);

            /* Menubar actions */
            ui->actionStart->setEnabled(true);
            ui->actionStop->setEnabled(true);

            /* Update status bar */
            status_message = tr("On hold: ");
            status_message += mController.getSimulationFilePath();
            mStatusLabel->setText(status_message);
        break;
        case MainController::WAITING_FOR_THREAD:
            /* Control buttons */
            ui->playButton->setText("Play");
            ui->playButton->setEnabled(false);
            ui->stopButton->setEnabled(false);

            /* Menubar actions */
            ui->actionStart->setEnabled(false);
            ui->actionStop->setEnabled(false);

            /* Update status bar */
            status_message = tr("Waiting for simulation thread: ");
            status_message += mController.getSimulationFilePath();
            mStatusLabel->setText(status_message);
        break;
        case MainController::UNINITIALIZED:
            ui->playButton->setText("Play");
            ui->playButton->setEnabled(false);
            ui->stopButton->setEnabled(false);

            /* Menubar actions */
            ui->actionStop->setEnabled(false);
            ui->actionStart->setEnabled(false);

            ui->objectList->clear();
            /* Update status bar */
            status_message = tr("Uninitialized");
            mStatusLabel->setText(status_message);

            if(mIsTerminated) {
                close();
            }
        break;
        case MainController::INITIALIZED:
            load_simulation_objects();

            ui->playButton->setText("Play");
            ui->playButton->setEnabled(true);
            ui->stopButton->setEnabled(true);

            /* Menubar actions */
            ui->actionStop->setEnabled(true);
            ui->actionStart->setEnabled(true);

            /* Update status bar */
            status_message = tr("Initialized: ");
            status_message += mController.getSimulationFilePath();
            mStatusLabel->setText(status_message);
        break;
        default:
        break;
    }
}
Ejemplo n.º 23
0
// Main deals with checking all the devices and arguments.
// It will call another function to do the actual work.
int main(int argc,char *argv[]){
	//variables
	int device_num = 0;
	int error = Pa_Initialize();
	int i = 0;
	int arg_data_count = 0;
	bool audio_get_list = false;
	bool input_wanted = false;
	int device_chosen = 0;
	const PaDeviceInfo *device_info;
	char user_select_device[8];
	PaStreamParameters input_stream_param;

	// Parse arguments
	if(argc >= 1){
		for(i = 0;i < argc;i++){
			if(arg_data_count == 0){
				// Prints a list of all audio devices.
				if(strcmp(argv[i],"-list") == 0){
					audio_get_list = true;
				}
				// Same as -list, but lets you select which one you use.
				if(strcmp(argv[i],"-input") == 0){
					audio_get_list = true;
					input_wanted = true;
				}
			} else {
				arg_data_count = arg_data_count-1;
			}
		}
	}


	/// Init
	status_message(stat_general,"SoundScale");
	status_message(stat_general,"Using PortAudio Version:");
	status_message(stat_general,(char *) Pa_GetVersionText());
	// Checks for PA and audio devices.
	if(error != paNoError){
		status_message(stat_critical,"PA DID NOT INITIALISE");
		return PA_INIT_FAIL;
	} else {
		status_message(stat_general,"PA INITIALIZED");
	}
	device_num = Pa_GetDeviceCount();
	if(device_num < 0){
		status_message(stat_critical,"ERROR - NO AUDIO DEVICES");
		return NO_AUDIO_DEVICES;
	} 

	// Audio Device selection. This can be cleaned up.
	if(audio_get_list == true){
		printf("[*] Discovered %i Audio devices\n",device_num);
		for(i = 0; i < device_num;i++){
			device_info = Pa_GetDeviceInfo(i);
			printf("[*] [%i] %s \n",i,device_info->name);
		}
		if(input_wanted == true){
			printf("[*] Please select input: ");
			scanf("%s",user_select_device);
			if(atoi(user_select_device) < device_num && atoi(user_select_device) >= 0){
				device_chosen = atoi(user_select_device);
				input_stream_param.device = device_chosen;
			} else {
				// Maybe ask user?
				input_stream_param.device = device_chosen  = Pa_GetDefaultInputDevice();
			}
		} else if(input_wanted == false){
			return SUCCESS;
		}
	} else {
		if(device_chosen > 0 && device_chosen <= device_num){
			input_stream_param.device = device_chosen;
			
		} else {
			input_stream_param.device = Pa_GetDefaultInputDevice();
			if(input_stream_param.device == paNoDevice){
				status_message(stat_critical,"NO DEFAULT INPUT DEVICE, EXITING");
				return FAILURE;
			}
		}
	}
	status_message(stat_general,"Using device:");
	device_info = Pa_GetDeviceInfo(input_stream_param.device);
	status_message(stat_general,(char *)device_info->name);
	return SUCCESS;
}