Exemple #1
0
int main(int argc, char** argv)
{ 
	if (2 > argc) {
        printf ("Syntax: %s [conf_file_path]\n", argv[0]);
        return 1;
    }

	if( access( argv[1], F_OK ) == -1 ) {
		log_err("Specify correct path");
		return 1;
	}

	if (populate_blacklist(get_filename_from_path(argv[1])) == -1) {
		log_err("Failed to read %s", get_filename_from_path(argv[1]));
		return 1;
	}
	
	if (pthread_mutex_init(&lock, NULL) || pthread_mutex_init(&udev_lock, NULL)) {
		log_err("\n mutex init failed\n");
		return 1;
	}
	create_thread(&config_file_watcher, watcher, argv[1]);
    create_thread(&udev_sniffer_thread, do_udev_sniff, NULL);

	/* Meat */
    serve("Echo");
    /* End Meat*/

    thread_run = 0;
    join_thread(config_file_watcher);
    join_thread(udev_sniffer_thread);
    
	pthread_mutex_destroy(&lock);

    return 0;
}
Exemple #2
0
char *get_vcf_stats_filename_prefix(char *vcf_filename, char *out_filename, char *outdir) {
    char *stats_filename;

    if (out_filename == NULL || strlen(out_filename) == 0) {
        char suffix_filename[strlen(vcf_filename) + 1];
        get_filename_from_path(vcf_filename, suffix_filename);

        stats_filename = (char*) calloc ((strlen(outdir) + strlen(suffix_filename) + 2), sizeof(char));
        sprintf(stats_filename, "%s/%s", outdir, suffix_filename);
    } else {
        stats_filename = (char*) calloc ((strlen(outdir) + strlen(out_filename) + 2), sizeof(char));
        sprintf(stats_filename, "%s/%s", outdir, out_filename);
    }

    return stats_filename;
}
Exemple #3
0
void upload_file(AMDeviceRef device) {
    service_conn_t houseFd = start_house_arrest_service(device);

    afc_file_ref file_ref;

    afc_connection afc_conn;
    afc_connection* afc_conn_p = &afc_conn;
    AFCConnectionOpen(houseFd, 0, &afc_conn_p);

    //        read_dir(houseFd, NULL, "/");

    if (!target_filename)
    {
        target_filename = get_filename_from_path(doc_file_path);
    }
    char *target_path = malloc(sizeof("/Documents/") + strlen(target_filename) + 1);
    strcat(target_path, "/Documents/");
    strcat(target_path, target_filename);

    size_t file_size;
    void* file_content = read_file_to_memory(doc_file_path, &file_size);

    if (!file_content)
    {
        PRINT("Could not open file: %s\n", doc_file_path);
        exit(-1);
    }

    assert(AFCFileRefOpen(afc_conn_p, target_path, 3, &file_ref) == 0);
    assert(AFCFileRefWrite(afc_conn_p, file_ref, file_content, file_size) == 0);
    assert(AFCFileRefClose(afc_conn_p, file_ref) == 0);
    assert(AFCConnectionClose(afc_conn_p) == 0);

    free(target_path);
    free(file_content);
}
void print_screen_to_edf(UI_Mainwindow *mainwindow)
{
  int i, j, k, p,
      n=0,
      records,
      records_written,
      signalcomps,
      duration_factor[MAXFILES],
      temp=0,
      edfplus=0,
      tallen,
      annotationlist_nr=0,
      annotations_left=1,
      add_one_sec=0,
      annot_smp_per_record=16,
      type,
      len;

  long long duration,
            smpls_written[MAXSIGNALS],
            s2,
            preamble=0LL,
            smpls_preamble[MAXSIGNALS],
            taltime=0LL,
            l_temp,
            referencetime,
            annot_difftime=0LL;

  char path[MAX_PATH_LENGTH],
       scratchpad[512],
       datrecduration[8],
       *viewbuf;

  double frequency,
         frequency2,
         dig_value;

  FILE *outputfile;


  struct signalcompblock **signalcomp;

  union {
          signed int one_signed;
          signed short two_signed[2];
          unsigned char four[4];
        } wr_var;

  union {
          signed short one_signed;
          unsigned char two[2];
        } null_bytes[MAXSIGNALS];

struct annotationblock *annotations_pntr;

struct date_time_struct date_time;

/////////////////////////////////////////////////////////////////////////

  signalcomps = mainwindow->signalcomps;
  signalcomp = mainwindow->signalcomp;
  viewbuf = mainwindow->viewbuf;

  annotations_pntr = mainwindow->annotationlist[0];

  if((!mainwindow->files_open)||(!signalcomps))
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Print to EDF", "Put a signal on the screen and try again.");
    messagewindow.exec();
    return;
  }

  for(i=0; i<mainwindow->files_open; i++)
  {
    if(mainwindow->edfheaderlist[i]->bdf)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Print to EDF", "BDF files can not be printed to EDF.");
      messagewindow.exec();
      return;
    }

    if(mainwindow->edfheaderlist[i]->discontinuous)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Print to EDF", "Sorry, discontinues EDF files can not be printed to EDF.");
      messagewindow.exec();
      return;
    }

    if(mainwindow->edfheaderlist[i]->edfplus)
    {
      edfplus = 1;

      for(j=0; j<mainwindow->edfheaderlist[i]->nr_annot_chns; j++)
      {
        if(mainwindow->edfheaderlist[i]->edfparam[mainwindow->edfheaderlist[i]->annot_ch[j]].smp_per_record>annot_smp_per_record)
        {
          annot_smp_per_record = mainwindow->edfheaderlist[i]->edfparam[mainwindow->edfheaderlist[i]->annot_ch[j]].smp_per_record;
        }
      }
    }
  }

  annot_smp_per_record += 16;

  taltime = mainwindow->edfheaderlist[mainwindow->sel_viewtime]->starttime_offset;

  duration = 0;

  for(i=0; i<signalcomps; i++)
  {
    if(signalcomp[i]->edfhdr->long_data_record_duration>duration)
    {
      duration = signalcomp[i]->edfhdr->long_data_record_duration;
      n = i;
    }
  }

  fseeko(signalcomp[n]->edfhdr->file_hdl, 244LL, SEEK_SET);
  if(fread(datrecduration, 8, 1, signalcomp[n]->edfhdr->file_hdl)!=1)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while reading from inputfile.");
    messagewindow.exec();
    return;
  }

  temp = 0;

  for(i=0; i<signalcomps; i++)
  {
    if(duration % signalcomp[i]->edfhdr->long_data_record_duration)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "This combination of files can not be printed to EDF\n"
                                                                "because the quotient of the datarecordblock durations is not an integer.");
      messagewindow.exec();
      return;
    }

    duration_factor[signalcomp[i]->filenum] = duration / signalcomp[i]->edfhdr->long_data_record_duration;

    temp += signalcomp[i]->edfhdr->edfparam[signalcomp[i]->edfsignal[0]].smp_per_record;
  }

  path[0] = 0;
  if(mainwindow->recent_savedir[0]!=0)
  {
    strcpy(path, mainwindow->recent_savedir);
    strcat(path, "/");
  }
  len = strlen(path);
  get_filename_from_path(path + len, mainwindow->edfheaderlist[mainwindow->sel_viewtime]->filename, MAX_PATH_LENGTH - len);
  remove_extension_from_filename(path);
  strcat(path, "_screenprint.edf");

  strcpy(path, QFileDialog::getSaveFileName(0, "Print to EDF", QString::fromLocal8Bit(path), "EDF files (*.edf *.EDF)").toLocal8Bit().data());

  if(!strcmp(path, ""))
  {
    return;
  }

  get_directory_from_path(mainwindow->recent_savedir, path, MAX_PATH_LENGTH);

  if(mainwindow->file_is_opened(path))
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Error, selected file is in use.");
    messagewindow.exec();
    return;
  }

  outputfile = fopeno(path, "wb");
  if(outputfile==NULL)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Can not create a file for writing.");
    messagewindow.exec();
    return;
  }

  referencetime = mainwindow->edfheaderlist[mainwindow->sel_viewtime]->utc_starttime;

  if(mainwindow->edfheaderlist[mainwindow->sel_viewtime]->viewtime<0)
  {
    if((-mainwindow->edfheaderlist[mainwindow->sel_viewtime]->viewtime) % TIME_DIMENSION)
    {
      preamble = TIME_DIMENSION - ((-mainwindow->edfheaderlist[mainwindow->sel_viewtime]->viewtime) % TIME_DIMENSION);

      referencetime--;

      add_one_sec = 1;
    }
  }
  else
  {
    preamble = mainwindow->edfheaderlist[mainwindow->sel_viewtime]->viewtime % TIME_DIMENSION;

    if(preamble)  add_one_sec = 1;
  }

  for(i=0; i<signalcomps; i++)
  {
    smpls_preamble[i] = preamble / (signalcomp[i]->edfhdr->long_data_record_duration / signalcomp[i]->edfhdr->edfparam[signalcomp[i]->edfsignal[0]].smp_per_record);
  }

  referencetime += (mainwindow->edfheaderlist[mainwindow->sel_viewtime]->viewtime / TIME_DIMENSION);

  utc_to_date_time(referencetime, &date_time);

/************************* write EDF-header ***************************************/

  rewind(mainwindow->edfheaderlist[mainwindow->sel_viewtime]->file_hdl);

  rewind(outputfile);

  if(edfplus)
  {
    if(mainwindow->edfheaderlist[mainwindow->sel_viewtime]->edfplus)
    {
      if(fread(scratchpad, 88, 1, mainwindow->edfheaderlist[mainwindow->sel_viewtime]->file_hdl)!=1)
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while reading from inputfile.");
        messagewindow.exec();
        fclose(outputfile);
        return;
      }

      if(fwrite(scratchpad, 88, 1, outputfile)!=1)
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while writing to outputfile.");
        messagewindow.exec();
        fclose(outputfile);
        return;
      }
    }
    else
    {
      fprintf(outputfile, "0       X X X X ");

      if(fread(scratchpad, 88, 1, mainwindow->edfheaderlist[mainwindow->sel_viewtime]->file_hdl)!=1)
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while reading from inputfile.");
        messagewindow.exec();
        fclose(outputfile);
        return;
      }

      if(fwrite(scratchpad + 8, 72, 1, outputfile)!=1)
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while writing to outputfile.");
        messagewindow.exec();
        fclose(outputfile);
        return;
      }
    }

    fprintf(outputfile, "Startdate %02i-", date_time.day);

    switch(date_time.month)
    {
      case  1 : fprintf(outputfile, "JAN");
                break;
      case  2 : fprintf(outputfile, "FEB");
                break;
      case  3 : fprintf(outputfile, "MAR");
                break;
      case  4 : fprintf(outputfile, "APR");
                break;
      case  5 : fprintf(outputfile, "MAY");
                break;
      case  6 : fprintf(outputfile, "JUN");
                break;
      case  7 : fprintf(outputfile, "JUL");
                break;
      case  8 : fprintf(outputfile, "AUG");
                break;
      case  9 : fprintf(outputfile, "SEP");
                break;
      case 10 : fprintf(outputfile, "OCT");
                break;
      case 11 : fprintf(outputfile, "NOV");
                break;
      case 12 : fprintf(outputfile, "DEC");
                break;
      default : fprintf(outputfile, "ERR");
                break;
    }

    fprintf(outputfile, "-%04i ", date_time.year);

    if(mainwindow->edfheaderlist[mainwindow->sel_viewtime]->edfplus)
    {
      if(fread(scratchpad, 80, 1, mainwindow->edfheaderlist[mainwindow->sel_viewtime]->file_hdl)!=1)
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while reading from inputfile.");
        messagewindow.exec();
        fclose(outputfile);
        return;
      }

      if(scratchpad[10]=='X')
      {
        if(fwrite(scratchpad + 12, 58, 1, outputfile)!=1)
        {
          QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while writing to outputfile.");
          messagewindow.exec();
          fclose(outputfile);
          return;
        }
      }
      else
      {
        if(fwrite(scratchpad + 22, 58, 1, outputfile)!=1)
        {
          QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while writing to outputfile.");
          messagewindow.exec();
          fclose(outputfile);
          return;
        }
      }
    }
    else
    {
      fprintf(outputfile, "X X X ");

      if(fread(scratchpad, 80, 1, mainwindow->edfheaderlist[mainwindow->sel_viewtime]->file_hdl)!=1)
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while reading from inputfile.");
        messagewindow.exec();
        fclose(outputfile);
        return;
      }

      if(fwrite(scratchpad + 28, 52, 1, outputfile)!=1)
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while writing to outputfile.");
        messagewindow.exec();
        fclose(outputfile);
        return;
      }
    }
  }
  else
  {
    if(fread(scratchpad, 168, 1, mainwindow->edfheaderlist[mainwindow->sel_viewtime]->file_hdl)!=1)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while reading from inputfile.");
      messagewindow.exec();
      fclose(outputfile);
      return;
    }

    if(fwrite(scratchpad, 168, 1, outputfile)!=1)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while writing to outputfile.");
      messagewindow.exec();
      fclose(outputfile);
      return;
    }
  }

  fprintf(outputfile,
          "%02i.%02i.%02i%02i.%02i.%02i",
          date_time.day,
          date_time.month,
          date_time.year % 100,
          date_time.hour,
          date_time.minute,
          date_time.second);

  fprintf(outputfile, "%-8i", (signalcomps + edfplus) * 256 + 256);

  if(edfplus)
  {
    fprintf(outputfile, "EDF+C");

    for(i=0; i<39; i++)  fputc(' ', outputfile);
  }
  else  for(i=0; i<44; i++)  fputc(' ', outputfile);

  records = (int)(mainwindow->pagetime / duration);

  if(add_one_sec)
  {
    records += TIME_DIMENSION / duration;
  }

  fprintf(outputfile, "%-8i", records);

  if(fwrite(datrecduration, 8, 1, outputfile)!=1)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while writing to outputfile.");
    messagewindow.exec();
    fclose(outputfile);
    return;
  }

  fprintf(outputfile, "%-4i", signalcomps + edfplus);

  for(i=0; i<signalcomps; i++)
  {
    strcpy(scratchpad, signalcomp[i]->signallabel);
    strcat(scratchpad, "                ");
    if(fwrite(scratchpad, 16, 1, outputfile)!=1)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while writing to outputfile.");
      messagewindow.exec();
      fclose(outputfile);
      return;
    }
  }

  if(edfplus)
  {
    if(fwrite("EDF Annotations ", 16, 1, outputfile)!=1)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while writing to outputfile.");
      messagewindow.exec();
      fclose(outputfile);
      return;
    }
  }

  for(i=0; i<signalcomps; i++)
  {
    if(fwrite(signalcomp[i]->edfhdr->edfparam[signalcomp[i]->edfsignal[0]].transducer, 80, 1, outputfile)!=1)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while writing to outputfile.");
      messagewindow.exec();
      fclose(outputfile);
      return;
    }
  }

  if(edfplus)
  {
    for(i=0; i<80; i++)  fputc(' ', outputfile);
  }

  for(i=0; i<signalcomps; i++)
  {
    strcpy(scratchpad, signalcomp[i]->physdimension);
    strcat(scratchpad, "        ");
    if(fwrite(scratchpad, 8, 1, outputfile)!=1)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while writing to outputfile.");
      messagewindow.exec();
      fclose(outputfile);
      return;
    }
  }

  if(edfplus)
  {
    for(i=0; i<8; i++)  fputc(' ', outputfile);
  }

  for(i=0; i<signalcomps; i++)
  {
    if((signalcomp[i]->ecg_filter == NULL) && (signalcomp[i]->zratio_filter == NULL))
    {
      fseeko(signalcomp[i]->edfhdr->file_hdl, (long long)((signalcomp[i]->edfsignal[0] * 8) + (104 * signalcomp[i]->edfhdr->edfsignals) + 256), SEEK_SET);
      if(fread(scratchpad, 8, 1, signalcomp[i]->edfhdr->file_hdl)!=1)
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while reading from inputfile.");
        messagewindow.exec();
        fclose(outputfile);
        return;
      }
      if(fwrite(scratchpad, 8, 1, outputfile)!=1)
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while writing to outputfile.");
        messagewindow.exec();
        fclose(outputfile);
        return;
      }
    }

    if(signalcomp[i]->ecg_filter != NULL)
    {
      if(fwrite("0       ", 8, 1, outputfile)!=1)
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while writing to outputfile.");
        messagewindow.exec();
        fclose(outputfile);
        return;
      }
    }

    if(signalcomp[i]->zratio_filter != NULL)
    {
      if(fwrite("-1      ", 8, 1, outputfile)!=1)
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while writing to outputfile.");
        messagewindow.exec();
        fclose(outputfile);
        return;
      }
    }
  }

  if(edfplus)
  {
    if(fwrite("-1      ", 8, 1, outputfile)!=1)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while writing to outputfile.");
      messagewindow.exec();
      fclose(outputfile);
      return;
    }
  }

  for(i=0; i<signalcomps; i++)
  {
    if((signalcomp[i]->ecg_filter == NULL) && (signalcomp[i]->zratio_filter == NULL))
    {
      fseeko(signalcomp[i]->edfhdr->file_hdl, (long long)((signalcomp[i]->edfsignal[0] * 8) + (112 * signalcomp[i]->edfhdr->edfsignals) + 256), SEEK_SET);
      if(fread(scratchpad, 8, 1, signalcomp[i]->edfhdr->file_hdl)!=1)
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while reading from inputfile.");
        messagewindow.exec();
        fclose(outputfile);
        return;
      }
      if(fwrite(scratchpad, 8, 1, outputfile)!=1)
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while writing to outputfile.");
        messagewindow.exec();
        fclose(outputfile);
        return;
      }
    }

    if(signalcomp[i]->ecg_filter != NULL)
    {
      if(fwrite("1000    ", 8, 1, outputfile)!=1)
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while writing to outputfile.");
        messagewindow.exec();
        fclose(outputfile);
        return;
      }
    }

    if(signalcomp[i]->zratio_filter != NULL)
    {
      if(fwrite("1       ", 8, 1, outputfile)!=1)
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while writing to outputfile.");
        messagewindow.exec();
        fclose(outputfile);
        return;
      }
    }
  }

  if(edfplus)
  {
    if(fwrite("1       ", 8, 1, outputfile)!=1)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while writing to outputfile.");
      messagewindow.exec();
      fclose(outputfile);
      return;
    }
  }

  for(i=0; i<signalcomps; i++)
  {
    if((signalcomp[i]->ecg_filter == NULL) && (signalcomp[i]->zratio_filter == NULL))
    {
      fprintf(outputfile, "%-8i", signalcomp[i]->edfhdr->edfparam[signalcomp[i]->edfsignal[0]].dig_min);

      if(signalcomp[i]->edfhdr->edfparam[signalcomp[i]->edfsignal[0]].dig_min<0)
      {
        null_bytes[i].one_signed = 0;
      }
      else
      {
        null_bytes[i].one_signed = signalcomp[i]->edfhdr->edfparam[signalcomp[i]->edfsignal[0]].dig_min;
      }
    }
    else
    {
      if(fwrite("-32768  ", 8, 1, outputfile)!=1)
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while writing to outputfile.");
        messagewindow.exec();
        fclose(outputfile);
        return;
      }

      null_bytes[i].one_signed = -32768;
    }
  }

  if(edfplus)
  {
    if(fwrite("-32768  ", 8, 1, outputfile)!=1)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while writing to outputfile.");
      messagewindow.exec();
      fclose(outputfile);
      return;
    }
  }

  for(i=0; i<signalcomps; i++)
  {
    if((signalcomp[i]->ecg_filter == NULL) && (signalcomp[i]->zratio_filter == NULL))
    {
      fprintf(outputfile, "%-8i", signalcomp[i]->edfhdr->edfparam[signalcomp[i]->edfsignal[0]].dig_max);
    }
    else
    {
      if(fwrite("32767   ", 8, 1, outputfile)!=1)
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while writing to outputfile.");
        messagewindow.exec();
        fclose(outputfile);
        return;
      }
    }
  }

  if(edfplus)
  {
    if(fwrite("32767   ", 8, 1, outputfile)!=1)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while writing to outputfile.");
      messagewindow.exec();
      fclose(outputfile);
      return;
    }
  }

  for(i=0; i<signalcomps; i++)
  {
    strcpy(scratchpad, signalcomp[i]->edfhdr->edfparam[signalcomp[i]->edfsignal[0]].prefilter);
    strcat(scratchpad, "                                                                                ");
    for(p = strlen(scratchpad) - 1; p>=0; p--)
    {
      if(scratchpad[p]!=' ')  break;
    }
    p++;
    if(p) p++;

    for(j=0; j<signalcomp[i]->filter_cnt; j++)
    {
      if(signalcomp[i]->filter[j]->is_LPF == 1)
      {
        p += sprintf(scratchpad + p, "LP:%f", signalcomp[i]->filter[j]->cutoff_frequency);
      }

      if(signalcomp[i]->filter[j]->is_LPF == 0)
      {
        p += sprintf(scratchpad + p, "HP:%f", signalcomp[i]->filter[j]->cutoff_frequency);
      }

      for(k=(p-1); k>0; k--)
      {
        if(scratchpad[k]!='0')  break;
      }

      if(scratchpad[k]=='.')  scratchpad[k] = 0;
      else  scratchpad[k+1] = 0;

      strcat(scratchpad, "Hz ");

      p = strlen(scratchpad);

      if(p>80)  break;
    }

    for(j=0; j<signalcomp[i]->fidfilter_cnt; j++)
    {
      type = signalcomp[i]->fidfilter_type[j];

      frequency = signalcomp[i]->fidfilter_freq[j];

      frequency2 = signalcomp[i]->fidfilter_freq2[j];

      if(type == 0)
      {
        p += sprintf(scratchpad + p, "HP:%f", frequency);
      }

      if(type == 1)
      {
        p += sprintf(scratchpad + p, "LP:%f", frequency);
      }

      if(type == 2)
      {
        p += sprintf(scratchpad + p, "N:%f", frequency);
      }

      if(type == 3)
      {
        p += sprintf(scratchpad + p, "BP:%f", frequency);
      }

      if(type == 4)
      {
        p += sprintf(scratchpad + p, "BS:%f", frequency);
      }

      for(k=(p-1); k>0; k--)
      {
        if(scratchpad[k]!='0')  break;
      }

      if(scratchpad[k]=='.')  scratchpad[k] = 0;
      else  scratchpad[k+1] = 0;

      p = strlen(scratchpad);

      if((type == 3) || (type == 4))
      {
        p += sprintf(scratchpad + p, "-%f", frequency2);

        for(k=(p-1); k>0; k--)
        {
          if(scratchpad[k]!='0')  break;
        }

        if(scratchpad[k]=='.')  scratchpad[k] = 0;
        else  scratchpad[k+1] = 0;
      }

      strcat(scratchpad, "Hz ");

      p = strlen(scratchpad);

      if(p>80)  break;
    }

    for(j=0; j<signalcomp[i]->ravg_filter_cnt; j++)
    {
      if(signalcomp[i]->ravg_filter_type[j] == 0)
      {
        p += sprintf(scratchpad + p, "HP:%iSmpls ", signalcomp[i]->ravg_filter[j]->size);
      }

      if(signalcomp[i]->ravg_filter_type[j] == 1)
      {
        p += sprintf(scratchpad + p, "LP:%iSmpls ", signalcomp[i]->ravg_filter[j]->size);
      }

      p = strlen(scratchpad);

      if(p>80)  break;
    }

    if(signalcomp[i]->ecg_filter != NULL)
    {
      p += sprintf(scratchpad + p, "ECG:HR ");
    }

    if(signalcomp[i]->zratio_filter != NULL)
    {
      p += sprintf(scratchpad + p, "Z-ratio ");
    }

    for(;p<81; p++)
    {
      scratchpad[p] = ' ';
    }

    if(fwrite(scratchpad, 80, 1, outputfile)!=1)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while writing to outputfile.");
      messagewindow.exec();
      fclose(outputfile);
      return;
    }
  }

  if(edfplus)
  {
    for(i=0; i<80; i++)  fputc(' ', outputfile);
  }

  for(i=0; i<signalcomps; i++)
  {
    fprintf(outputfile, "%-8i", signalcomp[i]->edfhdr->edfparam[signalcomp[i]->edfsignal[0]].smp_per_record
     * duration_factor[signalcomp[i]->filenum]);
  }

  if(edfplus)
  {
    fprintf(outputfile, "%-8i", annot_smp_per_record);
  }

  for(i=0; i<signalcomps; i++)
  {
    for(j=0; j<32; j++)  fputc(' ', outputfile);
  }

  if(edfplus)
  {
    for(i=0; i<32; i++)  fputc(' ', outputfile);
  }

/////////////////////////////////////////////////////////////////////

  for(i=0; i<MAXSIGNALS; i++)  smpls_written[i] = 0;

  mainwindow->print_to_edf_active = 1;

  mainwindow->setup_viewbuf();

  viewbuf = mainwindow->viewbuf;

  if(viewbuf==NULL)
  {
    fclose(outputfile);
    return;
  }

  QApplication::setOverrideCursor(Qt::WaitCursor);

  for(records_written=0; records_written<records; records_written++)
  {
    qApp->processEvents();

    for(i=0; i<signalcomps; i++)
    {
      for(k=0; k<signalcomp[i]->edfhdr->edfparam[signalcomp[i]->edfsignal[0]].smp_per_record * duration_factor[signalcomp[i]->filenum]; k++)
      {
        if(smpls_preamble[i])
        {
          smpls_preamble[i]--;

          fputc(null_bytes[i].two[0], outputfile);
          if(fputc(null_bytes[i].two[1], outputfile)==EOF)
          {
            QApplication::restoreOverrideCursor();
            QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while writing to outputfile.");
            messagewindow.exec();
            fclose(outputfile);
            return;
          }
        }
        else
        {
          dig_value = 0;

          s2 = smpls_written[i] + signalcomp[i]->sample_timeoffset - signalcomp[i]->sample_start;

          for(j=0; j<signalcomp[i]->num_of_signals; j++)
          {
            if((smpls_written[i]<signalcomp[i]->sample_stop)&&(s2>=0))
            {
              if(signalcomp[i]->edfhdr->edf)
              {
                temp = *(((short *)(
                  viewbuf
                  + signalcomp[i]->viewbufoffset
                  + (signalcomp[i]->edfhdr->recordsize * (s2 / signalcomp[i]->edfhdr->edfparam[signalcomp[i]->edfsignal[j]].smp_per_record))
                  + signalcomp[i]->edfhdr->edfparam[signalcomp[i]->edfsignal[j]].buf_offset))
                  + (s2 % signalcomp[i]->edfhdr->edfparam[signalcomp[i]->edfsignal[j]].smp_per_record));
              }

              temp += signalcomp[i]->edfhdr->edfparam[signalcomp[i]->edfsignal[j]].offset;
              temp *= signalcomp[i]->factor[j];

              temp -= signalcomp[i]->edfhdr->edfparam[signalcomp[i]->edfsignal[j]].offset;
            }
            else
            {
              temp = 0;
            }

            dig_value += temp;
          }

          for(p=0; p<signalcomp[i]->filter_cnt; p++)
          {
            if(smpls_written[i]==signalcomp[i]->sample_start)
            {
              if(mainwindow->edfheaderlist[signalcomp[i]->filenum]->viewtime==0)
              {
                reset_filter(dig_value, signalcomp[i]->filter[p]);
              }
              else
              {
                signalcomp[i]->filter[p]->old_input = signalcomp[i]->filterpreset_a[p];
                signalcomp[i]->filter[p]->old_output = signalcomp[i]->filterpreset_b[p];
              }
            }

            dig_value = first_order_filter(dig_value, signalcomp[i]->filter[p]);
          }

          for(p=0; p<signalcomp[i]->ravg_filter_cnt; p++)
          {
            if(smpls_written[i]==signalcomp[i]->sample_start)
            {
              if(mainwindow->edfheaderlist[signalcomp[i]->filenum]->viewtime!=0)
              {
                ravg_filter_restore_buf(signalcomp[i]->ravg_filter[p]);
              }
            }

            dig_value = run_ravg_filter(dig_value, signalcomp[i]->ravg_filter[p]);
          }

          for(p=0; p<signalcomp[i]->fidfilter_cnt; p++)
          {
            if(smpls_written[i]==signalcomp[i]->sample_start)
            {
              if(mainwindow->edfheaderlist[signalcomp[i]->filenum]->viewtime!=0)
              {
                memcpy(signalcomp[i]->fidbuf[p], signalcomp[i]->fidbuf2[p], fid_run_bufsize(signalcomp[i]->fid_run[p]));
              }
            }

            dig_value = signalcomp[i]->fidfuncp[p](signalcomp[i]->fidbuf[p], dig_value);
          }

          if(signalcomp[i]->ecg_filter != NULL)
          {
            if(smpls_written[i]==signalcomp[i]->sample_start)
            {
              if(mainwindow->edfheaderlist[signalcomp[i]->filenum]->viewtime != 0)
              {
                ecg_filter_restore_buf(signalcomp[i]->ecg_filter);
              }
            }

            dig_value = run_ecg_filter(dig_value, signalcomp[i]->ecg_filter);

            dig_value = (dig_value * signalcomp[i]->edfhdr->edfparam[signalcomp[i]->edfsignal[0]].bitvalue * 65.536) - 32768.0;
          }

          if(signalcomp[i]->zratio_filter != NULL)
          {
            if(smpls_written[i]==signalcomp[i]->sample_start)
            {
              if(mainwindow->edfheaderlist[signalcomp[i]->filenum]->viewtime != 0)
              {
                zratio_filter_restore_buf(signalcomp[i]->zratio_filter);
              }
            }

            dig_value = run_zratio_filter(dig_value, signalcomp[i]->zratio_filter);

            dig_value = dig_value * signalcomp[i]->edfhdr->edfparam[signalcomp[i]->edfsignal[0]].bitvalue * 32768.0;
          }

          if((smpls_written[i]>=signalcomp[i]->sample_start)&&(smpls_written[i]<signalcomp[i]->sample_stop))
          {
            wr_var.one_signed = dig_value;

            if((signalcomp[i]->ecg_filter == NULL) && (signalcomp[i]->zratio_filter == NULL))
            {
              if(wr_var.one_signed>signalcomp[i]->edfhdr->edfparam[signalcomp[i]->edfsignal[0]].dig_max)
              {
                wr_var.one_signed = signalcomp[i]->edfhdr->edfparam[signalcomp[i]->edfsignal[0]].dig_max;
              }
              if(wr_var.one_signed<signalcomp[i]->edfhdr->edfparam[signalcomp[i]->edfsignal[0]].dig_min)
              {
                wr_var.one_signed = signalcomp[i]->edfhdr->edfparam[signalcomp[i]->edfsignal[0]].dig_min;
              }
            }
            else
            {
              if(wr_var.one_signed > 32767)
              {
                wr_var.one_signed = 32767;
              }
              if(wr_var.one_signed < -32768)
              {
                wr_var.one_signed = -32768;
              }
            }

            fputc(wr_var.four[0], outputfile);
            if(fputc(wr_var.four[1], outputfile)==EOF)
            {
              QApplication::restoreOverrideCursor();
              QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while writing to outputfile.");
              messagewindow.exec();
              fclose(outputfile);
              return;
            }
          }
          else
          {
            fputc(null_bytes[i].two[0], outputfile);
            if(fputc(null_bytes[i].two[1], outputfile)==EOF)
            {
              QApplication::restoreOverrideCursor();
              QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while writing to outputfile.");
              messagewindow.exec();
              fclose(outputfile);
              return;
            }
          }

          smpls_written[i]++;
        }
      }
    }

    if(edfplus)
    {
      tallen = fprintf(outputfile, "+%i.%07i",
      (int)(taltime / TIME_DIMENSION),
      (int)(taltime % TIME_DIMENSION));

      fputc(20, outputfile);
      fputc(20, outputfile);
      fputc(0, outputfile);

      tallen += 3;

      if(annotations_left)
      {
        if(mainwindow->viewtime_sync==VIEWTIME_SYNCED_ABSOLUT)
        {
          annot_difftime = (referencetime - mainwindow->edfheaderlist[annotationlist_nr]->utc_starttime) * TIME_DIMENSION;
        }

        if(mainwindow->viewtime_sync==VIEWTIME_SYNCED_OFFSET)
        {
          annot_difftime = (referencetime - mainwindow->edfheaderlist[mainwindow->sel_viewtime]->utc_starttime) * TIME_DIMENSION;
        }

        if((mainwindow->viewtime_sync==VIEWTIME_UNSYNCED) || (mainwindow->viewtime_sync==VIEWTIME_USER_DEF_SYNCED))
        {
          annot_difftime = (referencetime - mainwindow->edfheaderlist[mainwindow->sel_viewtime]->utc_starttime) * TIME_DIMENSION;
          annot_difftime += (mainwindow->edfheaderlist[annotationlist_nr]->viewtime - mainwindow->edfheaderlist[mainwindow->sel_viewtime]->viewtime);
        }

        if(annotationlist_nr != mainwindow->sel_viewtime)
        {
          annot_difftime -= mainwindow->edfheaderlist[mainwindow->sel_viewtime]->starttime_offset;
          annot_difftime += mainwindow->edfheaderlist[annotationlist_nr]->starttime_offset;
        }
      }

      while(annotations_left)
      {
        while(!annotations_pntr)
        {
          annotationlist_nr++;
          if(annotationlist_nr>=mainwindow->files_open)
          {
            annotations_left = 0;
            annotations_pntr = NULL;

            break;
          }
          annotations_pntr = mainwindow->annotationlist[annotationlist_nr];

          if(mainwindow->viewtime_sync==VIEWTIME_SYNCED_ABSOLUT)
          {
            annot_difftime = (referencetime - mainwindow->edfheaderlist[annotationlist_nr]->utc_starttime) * TIME_DIMENSION;
          }

          if(mainwindow->viewtime_sync==VIEWTIME_SYNCED_OFFSET)
          {
            annot_difftime = (referencetime - mainwindow->edfheaderlist[mainwindow->sel_viewtime]->utc_starttime) * TIME_DIMENSION;
          }

          if((mainwindow->viewtime_sync==VIEWTIME_UNSYNCED) || (mainwindow->viewtime_sync==VIEWTIME_USER_DEF_SYNCED))
          {
            annot_difftime = (referencetime - mainwindow->edfheaderlist[mainwindow->sel_viewtime]->utc_starttime) * TIME_DIMENSION;
            annot_difftime += (mainwindow->edfheaderlist[annotationlist_nr]->viewtime - mainwindow->edfheaderlist[mainwindow->sel_viewtime]->viewtime);
          }

          if(annotationlist_nr != mainwindow->sel_viewtime)
          {
            annot_difftime -= mainwindow->edfheaderlist[mainwindow->sel_viewtime]->starttime_offset;
            annot_difftime += mainwindow->edfheaderlist[annotationlist_nr]->starttime_offset;
          }
        }

        if(!annotations_left)  break;

        if(annotations_pntr)
        {
          l_temp = annotations_pntr->onset - annot_difftime;

          if((l_temp >= 0LL) && (l_temp < (mainwindow->pagetime + TIME_DIMENSION)))
          {
            tallen += fprintf(outputfile, "%+i.%07i",
            (int)(l_temp / TIME_DIMENSION),
            (int)(l_temp % TIME_DIMENSION));

            if(annotations_pntr->duration[0]!=0)
            {
              fputc(21, outputfile);
              tallen++;

              tallen += fprintf(outputfile, "%s", annotations_pntr->duration);
            }

            fputc(20, outputfile);
            tallen++;

            tallen += fprintf(outputfile, "%s", annotations_pntr->annotation);

            fputc(20, outputfile);
            fputc(0, outputfile);
            tallen += 2;

            annotations_pntr = annotations_pntr->next_annotation;

            break;
          }
          else
          {
            annotations_pntr = annotations_pntr->next_annotation;

            continue;
          }
        }
      }

      for(j=tallen; j<(annot_smp_per_record * 2); j++)
      {
        fputc(0, outputfile);
      }

      taltime += duration;
    }
  }

  QApplication::restoreOverrideCursor();

  fclose(outputfile);
}
Exemple #5
0
void UI_FINO2EDFwindow::SelectFileButton()
{
  FILE *inputfile=NULL,
       *outputfile=NULL;

  int i, j, k, p,
      temp,
      separator=';',
      edfsignals=0,
      ok,
      timestep,
      new_smpl_time=0,
      datarecords,
      str_start,
      column,
      line_nr;

  char txt_string[2048],
       path[512],
       outputfilename[MAX_PATH_LENGTH],
       line[2048],
       scratchpad[128],
       labels[MAX_SIGNALS][17],
       phys_dim[MAX_SIGNALS][9],
       phys_min[MAX_SIGNALS][9],
       phys_max[MAX_SIGNALS][9],
       patientname[81],
       recording[81],
       datetime[17];


  double sensitivity[MAX_SIGNALS],
         new_value[MAX_SIGNALS],
         old_value[MAX_SIGNALS];

  union{
         short two;
         char one[2];
       } var;



  for(j=0; j<MAX_SIGNALS; j++)
  {
    old_value[j] = 0.0;
  }

  enable_widgets(false);

  if(!(strlen(PatientnameLineEdit->text().toLatin1().data())))
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Invalid input", "Please enter a subjectname.");
    messagewindow.exec();
    enable_widgets(true);
    return;
  }

  if(!(strlen(RecordingLineEdit->text().toLatin1().data())))
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Invalid input", "Please enter a recordingdescription.");
    messagewindow.exec();
    enable_widgets(true);
    return;
  }

  strcpy(path, QFileDialog::getOpenFileName(0, "Select inputfile", QString::fromLocal8Bit(recent_opendir), "Text files (*.txt *.TXT)").toLocal8Bit().data());

  if(!strcmp(path, ""))
  {
    enable_widgets(true);
    return;
  }

  get_directory_from_path(recent_opendir, path, MAX_PATH_LENGTH);

  inputfile = fopeno(path, "rb");
  if(inputfile==NULL)
  {
    snprintf(txt_string, 2048, "Can not open file %s for reading.", path);
    QMessageBox messagewindow(QMessageBox::Critical, "Error", txt_string);
    messagewindow.exec();
    enable_widgets(true);
    return;
  }

/***************** check if the txtfile is valid ******************************/

  rewind(inputfile);

  if(fread(scratchpad, 5, 1, inputfile)!=1)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while reading the inputfile.");
    messagewindow.exec();
    fclose(inputfile);
    enable_widgets(true);
    return;
  }

  if(strncmp(scratchpad, "\"T\";", 4))
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Unknown data in file (1).");
    messagewindow.exec();
    fclose(inputfile);
    enable_widgets(true);
    return;
  }

  while(1)
  {
    temp = fgetc(inputfile);

    if(temp==EOF)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "Reached end of file unexpectedly (2).");
      messagewindow.exec();
      fclose(inputfile);
      enable_widgets(true);
      return;
    }

    if(temp=='\n')  break;
  }

  if(fread(scratchpad, 2, 1, inputfile)!=1)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while reading inputfile (3).");
    messagewindow.exec();
    fclose(inputfile);
    enable_widgets(true);
    return;
  }

  if(strncmp(scratchpad, "\"s\";", 4))
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Unknown data in file (4).");
    messagewindow.exec();
    fclose(inputfile);
    enable_widgets(true);
    return;
  }

/***************** collect items *****************************************/

  rewind(inputfile);

  while(1)
  {
    temp = fgetc(inputfile);

    if(temp==EOF)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "Reached end of file unexpectedly (5).");
      messagewindow.exec();
      fclose(inputfile);
      enable_widgets(true);
      return;
    }

    if(temp==separator)
    {
      break;
    }
  }

  i = 0;

  while(temp!='\n')
  {
    temp = fgetc(inputfile);

    if(temp==EOF)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "Reached end of file unexpectedly (6).");
      messagewindow.exec();
      fclose(inputfile);
      enable_widgets(true);
      return;
    }

    if(temp=='\r')
    {
      continue;
    }

    if((temp==separator)||(temp=='\n'))
    {
      if(edfsignals>=MAX_SIGNALS)
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "Too many labels/signals (7).");
        messagewindow.exec();
        fclose(inputfile);
        enable_widgets(true);
        return;
      }

      line[i] = 0;

      ok = 0;

      if(!strcmp(line, "\" reSYS\""))
      {
        strcpy(labels[edfsignals], "reSYS           ");
        strcpy(phys_dim[edfsignals], "mmHg    ");
        strcpy(phys_min[edfsignals], "-1024   ");
        strcpy(phys_max[edfsignals], "1024    ");
        sensitivity[edfsignals] = 31.0;
        ok = 1;
      }

      if(!strcmp(line, "\" fiSYS\""))
      {
        strcpy(labels[edfsignals], "fiSYS           ");
        strcpy(phys_dim[edfsignals], "mmHg    ");
        strcpy(phys_min[edfsignals], "-1024   ");
        strcpy(phys_max[edfsignals], "1024    ");
        sensitivity[edfsignals] = 31.0;
        ok = 1;
      }

      if(!strcmp(line, "\" reDIA\""))
      {
        strcpy(labels[edfsignals], "reDIA           ");
        strcpy(phys_dim[edfsignals], "mmHg    ");
        strcpy(phys_min[edfsignals], "-1024   ");
        strcpy(phys_max[edfsignals], "1024    ");
        sensitivity[edfsignals] = 31.0;
        ok = 1;
      }

      if(!strcmp(line, "\" fiDIA\""))
      {
        strcpy(labels[edfsignals], "fiDIA           ");
        strcpy(phys_dim[edfsignals], "mmHg    ");
        strcpy(phys_min[edfsignals], "-1024   ");
        strcpy(phys_max[edfsignals], "1024    ");
        sensitivity[edfsignals] = 31.0;
        ok = 1;
      }

      if(!strcmp(line, "\" reMAP\""))
      {
        strcpy(labels[edfsignals], "reMAP           ");
        strcpy(phys_dim[edfsignals], "mmHg    ");
        strcpy(phys_min[edfsignals], "-1024   ");
        strcpy(phys_max[edfsignals], "1024    ");
        sensitivity[edfsignals] = 31.0;
        ok = 1;
      }

      if(!strcmp(line, "\" fiMAP\""))
      {
        strcpy(labels[edfsignals], "fiMAP           ");
        strcpy(phys_dim[edfsignals], "mmHg    ");
        strcpy(phys_min[edfsignals], "-1024   ");
        strcpy(phys_max[edfsignals], "1024    ");
        sensitivity[edfsignals] = 31.0;
        ok = 1;
      }

      if(!strcmp(line, "\"  HR\""))
      {
        strcpy(labels[edfsignals], "HR              ");
        strcpy(phys_dim[edfsignals], "bpm     ");
        strcpy(phys_min[edfsignals], "-1024   ");
        strcpy(phys_max[edfsignals], "1024    ");
        sensitivity[edfsignals] = 31.0;
        ok = 1;
      }

      if(!strcmp(line, "\"   IBI\""))
      {
        strcpy(labels[edfsignals], "IBI             ");
        strcpy(phys_dim[edfsignals], "s       ");
        strcpy(phys_min[edfsignals], "-31.744 ");
        strcpy(phys_max[edfsignals], "31.744  ");
        sensitivity[edfsignals] = 1000.0;
        ok = 1;
      }

      if(!strcmp(line, "\"  SV\""))
      {
        strcpy(labels[edfsignals], "SV              ");
        strcpy(phys_dim[edfsignals], "ml      ");
        strcpy(phys_min[edfsignals], "-1024   ");
        strcpy(phys_max[edfsignals], "1024    ");
        sensitivity[edfsignals] = 31.0;
        ok = 1;
      }

      if(!strcmp(line, "\"    CO\""))
      {
        strcpy(labels[edfsignals], "CO              ");
        strcpy(phys_dim[edfsignals], "lpm     ");
        strcpy(phys_min[edfsignals], "-1024   ");
        strcpy(phys_max[edfsignals], "1024    ");
        sensitivity[edfsignals] = 31.0;
        ok = 1;
      }

      if(!strcmp(line, "\"   EJT\""))
      {
        strcpy(labels[edfsignals], "EJT             ");
        strcpy(phys_dim[edfsignals], "s       ");
        strcpy(phys_min[edfsignals], "-1024   ");
        strcpy(phys_max[edfsignals], "1024    ");
        sensitivity[edfsignals] = 31.0;
        ok = 1;
      }

      if(!strcmp(line, "\"    TPR\""))
      {
        strcpy(labels[edfsignals], "TPR             ");
        strcpy(phys_dim[edfsignals], "MU      ");
        strcpy(phys_min[edfsignals], "-1024   ");
        strcpy(phys_max[edfsignals], "1024    ");
        sensitivity[edfsignals] = 31.0;
        ok = 1;
      }

      if(!strcmp(line, "\" Artifact\""))
      {
        strcpy(labels[edfsignals], "Artifact        ");
        strcpy(phys_dim[edfsignals], "_TPSROD2");
        strcpy(phys_min[edfsignals], "0       ");
        strcpy(phys_max[edfsignals], "10000000");
        sensitivity[edfsignals] = 0.0063488;
        ok = 1;
      }

      if(!strcmp(line, "\" Zao\""))
      {
        strcpy(labels[edfsignals], "Zao             ");
        strcpy(phys_dim[edfsignals], "mMU     ");
        strcpy(phys_min[edfsignals], "-1024   ");
        strcpy(phys_max[edfsignals], "1024    ");
        sensitivity[edfsignals] = 31.0;
        ok = 1;
      }

      if(!strcmp(line, "\"   Cwk\""))
      {
        strcpy(labels[edfsignals], "Cwk             ");
        strcpy(phys_dim[edfsignals], "MU      ");
        strcpy(phys_min[edfsignals], "-1024   ");
        strcpy(phys_max[edfsignals], "1024    ");
        sensitivity[edfsignals] = 31.0;
        ok = 1;
      }

      if(!strcmp(line, "\" Height\""))
      {
        strcpy(labels[edfsignals], "Height          ");
        strcpy(phys_dim[edfsignals], "mmHg    ");
        strcpy(phys_min[edfsignals], "-1024   ");
        strcpy(phys_max[edfsignals], "1024    ");
        sensitivity[edfsignals] = 31.0;
        ok = 1;
      }

      if(!ok)
      {
        snprintf(txt_string, 2048, "Found unknown label/signal: %s", line);
        QMessageBox messagewindow(QMessageBox::Critical, "Error", txt_string);
        messagewindow.exec();
        fclose(inputfile);
        enable_widgets(true);
        return;
      }

      edfsignals++;

      i = 0;
    }

    if(temp==separator)
    {
      continue;
    }

    line[i++] = temp;
  }

  if(!edfsignals)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "There are no labels/signals.");
    messagewindow.exec();
    fclose(inputfile);
    enable_widgets(true);
    return;
  }

  p = sprintf(patientname, "%s", PatientnameLineEdit->text().toLatin1().data());
  latin1_to_ascii(patientname, p);
  for( ; p<80; p++)
  {
    patientname[p] = ' ';
  }
  patientname[80] = 0;

  p = sprintf(recording, "%s", RecordingLineEdit->text().toLatin1().data());
  latin1_to_ascii(recording, p);
  for( ; p<80; p++)
  {
    recording[p] = ' ';
  }
  recording[80] = 0;

  sprintf(datetime,
          "%02i.%02i.%02i%02i.%02i.%02i",
          StartDatetimeedit->date().day(),
          StartDatetimeedit->date().month(),
          StartDatetimeedit->date().year() % 100,
          StartDatetimeedit->time().hour(),
          StartDatetimeedit->time().minute(),
          StartDatetimeedit->time().second());
  datetime[16] = 0;


/***************** write header *****************************************/

  get_filename_from_path(outputfilename, path, MAX_PATH_LENGTH);
  remove_extension_from_filename(outputfilename);
  strcat(outputfilename, "_finometer.edf");

  path[0] = 0;
  if(recent_savedir[0]!=0)
  {
    strcpy(path, recent_savedir);
    strcat(path, "/");
  }
  strcat(path, outputfilename);

  strcpy(path, QFileDialog::getSaveFileName(0, "Output file", QString::fromLocal8Bit(path), "EDF files (*.edf *.EDF)").toLocal8Bit().data());

  if(!strcmp(path, ""))
  {
    enable_widgets(true);
    fclose(inputfile);
    return;
  }

  get_directory_from_path(recent_savedir, path, MAX_PATH_LENGTH);

  outputfile = fopeno(path, "wb");
  if(outputfile==NULL)
  {
    snprintf(txt_string, 2048, "Can not open file %s for writing.", path);
    QMessageBox messagewindow(QMessageBox::Critical, "Error", txt_string);
    messagewindow.exec();
    enable_widgets(true);
    fclose(inputfile);
    return;
  }

  fprintf(outputfile, "0       ");
  fprintf(outputfile, "%s", patientname);
  fprintf(outputfile, "%s", recording);
  fprintf(outputfile, "%s", datetime);
  fprintf(outputfile, "%-8i", 256 * edfsignals + 256);
  fprintf(outputfile, "                                            ");
  fprintf(outputfile, "-1      ");
  fprintf(outputfile, "0.01    ");
  fprintf(outputfile, "%-4i", edfsignals);

  for(i=0; i<edfsignals; i++)
  {
    fprintf(outputfile, "%s", labels[i]);
  }

  for(i=0; i<(80*edfsignals); i++)
  {
    fputc(' ', outputfile);
  }

  for(i=0; i<edfsignals; i++)
  {
    fprintf(outputfile, "%s", phys_dim[i]);
  }

  for(i=0; i<edfsignals; i++)
  {
    fprintf(outputfile, "%s", phys_min[i]);
  }

  for(i=0; i<edfsignals; i++)
  {
    fprintf(outputfile, "%s", phys_max[i]);
  }

  for(i=0; i<edfsignals; i++)
  {
    fprintf(outputfile, "-31744  ");
  }

  for(i=0; i<edfsignals; i++)
  {
    fprintf(outputfile, "31744   ");
  }

  for(i=0; i<(80*edfsignals); i++)
  {
    fputc(' ', outputfile);
  }

  for(i=0; i<edfsignals; i++)
  {
    fprintf(outputfile, "1       ");
  }

  for(i=0; i<(32*edfsignals); i++)
  {
    fputc(' ', outputfile);
  }

/***************** start conversion **************************************/

  rewind(inputfile);

  for(i=0; ; )
  {
    temp = fgetc(inputfile);

    if(temp==EOF)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "Reached end of file unexpectedly (8).");
      messagewindow.exec();
      fclose(inputfile);
      fclose(outputfile);
      enable_widgets(true);
      return;
    }

    if(temp=='\n')  i++;

    if(i>1)  break;
  }

  QApplication::setOverrideCursor(Qt::WaitCursor);

  for(k=0; k<10; k++)  qApp->processEvents();

  i = 0;

  column = 0;

  datarecords = 0;

  str_start = 0;

  line_nr = 2;

  while(1)
  {
    temp = fgetc(inputfile);

    if(temp==EOF)
    {
      for(k=0; k<edfsignals; k++)
      {
        temp = (int)(new_value[k] * sensitivity[k]);

        if(temp>31744)  temp = 31744;

        if(temp<-31744)  temp = -31744;

        var.two = (short)temp;

        fputc(var.one[0], outputfile);
        fputc(var.one[1], outputfile);
      }

      datarecords++;

      break;
    }

    line[i] = temp;

  /**************************************/

    if(line[i]==',')
    {
      line[i] = '.';
    }

    if((line[i]==separator)||(line[i]=='\n'))
    {
      if(column)
      {
        new_value[column-1] = atof(line + str_start);
      }
      else
      {
        new_smpl_time = (int)(atof(line + str_start) * 100.0);
      }

      if(line[i]=='\n')
      {
        /**************************************/

        line_nr++;

        if(column!=edfsignals)
        {
          QApplication::restoreOverrideCursor();
          snprintf(txt_string, 2048, "Number of separators in line %i is wrong.", line_nr);
          QMessageBox messagewindow(QMessageBox::Critical, "Error", txt_string);
          messagewindow.exec();
          fclose(inputfile);
          fclose(outputfile);
          enable_widgets(true);
          return;
        }

        timestep = new_smpl_time - datarecords;

        if(timestep<=0)
        {
          QApplication::restoreOverrideCursor();
          snprintf(txt_string, 2048, "Timestep <= 0 in line %i.", line_nr);
          QMessageBox messagewindow(QMessageBox::Critical, "Error", txt_string);
          messagewindow.exec();
          fclose(inputfile);
          fclose(outputfile);
          enable_widgets(true);
          return;
        }

        for(j=0; j<timestep; j++)
        {
          for(k=0; k<edfsignals; k++)
          {
            temp = (int)((old_value[k] + ((new_value[k] - old_value[k]) * ((double)j / (double)timestep))) * sensitivity[k]);

            if(temp>31744)  temp = 31744;

            if(temp<-31744)  temp = -31744;

            var.two = (short)temp;

            fputc(var.one[0], outputfile);
            fputc(var.one[1], outputfile);
          }

          datarecords++;
        }

        for(j=0; j<edfsignals; j++)
        {
          old_value[j] = new_value[j];
        }

        /**************************************/

        str_start = 0;

        i = 0;

        column = 0;

        continue;
      }

      str_start = i + 1;

      column++;
    }

  /**************************************/

    i++;

    if(i>2046)
    {
      QApplication::restoreOverrideCursor();
      snprintf(txt_string, 2048, "Line %i is too long.", line_nr);
      QMessageBox messagewindow(QMessageBox::Critical, "Error", txt_string);
      messagewindow.exec();
      fclose(inputfile);
      fclose(outputfile);
      enable_widgets(true);
      return;
    }
  }

  QApplication::restoreOverrideCursor();

  fseeko(outputfile, 236LL, SEEK_SET);

  fprintf(outputfile, "%-8i", datarecords);

  if(fclose(outputfile))
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while closing outputfile.");
    messagewindow.exec();
    enable_widgets(true);
    fclose(inputfile);
    return;
  }

  if(fclose(inputfile))
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while closing inputfile.");
    messagewindow.exec();
  }

  snprintf(txt_string, 2048, "Done, EDF file is located at %s", path);
  QMessageBox messagewindow(QMessageBox::Information, "Ready", txt_string);
  messagewindow.setIconPixmap(QPixmap(":/images/ok.png"));
  messagewindow.exec();

  enable_widgets(true);
}
Exemple #6
0
static
struct debug_info_source *debug_info_source_create_from_bin(struct bin_info *bin,
		uint64_t ip)
{
	int ret;
	struct debug_info_source *debug_info_src = NULL;
	struct source_location *src_loc = NULL;

	debug_info_src = g_new0(struct debug_info_source, 1);

	if (!debug_info_src) {
		goto end;
	}

	/* Lookup function name */
	ret = bin_info_lookup_function_name(bin, ip, &debug_info_src->func);
	if (ret) {
		goto error;
	}

	/* Can't retrieve src_loc from ELF, or could not find binary, skip. */
	if (!bin->is_elf_only || !debug_info_src->func) {
		/* Lookup source location */
		ret = bin_info_lookup_source_location(bin, ip, &src_loc);
		BT_LOGD("Failed to lookup source location: ret=%d", ret);
	}

	if (src_loc) {
		debug_info_src->line_no = src_loc->line_no;

		if (src_loc->filename) {
			debug_info_src->src_path = strdup(src_loc->filename);
			if (!debug_info_src->src_path) {
				goto error;
			}

			debug_info_src->short_src_path = get_filename_from_path(
					debug_info_src->src_path);
		}

		source_location_destroy(src_loc);
	}

	if (bin->elf_path) {
		debug_info_src->bin_path = strdup(bin->elf_path);
		if (!debug_info_src->bin_path) {
			goto error;
		}

		debug_info_src->short_bin_path = get_filename_from_path(
				debug_info_src->bin_path);

		ret = bin_info_get_bin_loc(bin, ip, &(debug_info_src->bin_loc));
		if (ret) {
			goto error;
		}
	}

end:
	return debug_info_src;

error:
	debug_info_source_destroy(debug_info_src);
	return NULL;
}
Exemple #7
0
int run_effect(char **urls, shared_options_data_t *shared_options_data, effect_options_data_t *options_data) {
    int ret_code = 0;
    double start, stop, total;
    
    vcf_file_t *vcf_file = vcf_open(shared_options_data->vcf_filename, shared_options_data->max_batches);
    if (!vcf_file) {
        LOG_FATAL("VCF file does not exist!\n");
    }
    
    ped_file_t *ped_file = NULL;
    if (shared_options_data->ped_filename) {
        ped_file = ped_open(shared_options_data->ped_filename);
        if (!ped_file) {
            LOG_FATAL("PED file does not exist!\n");
        }
        LOG_INFO("About to read PED file...\n");
        // Read PED file before doing any processing
        ret_code = ped_read(ped_file);
        if (ret_code != 0) {
            LOG_FATAL_F("Can't read PED file: %s\n", ped_file->filename);
        }
    }
    
    char *output_directory = shared_options_data->output_directory;
    size_t output_directory_len = strlen(output_directory);
    
    ret_code = create_directory(output_directory);
    if (ret_code != 0 && errno != EEXIST) {
        LOG_FATAL_F("Can't create output directory: %s\n", output_directory);
    }
    
    // Remove all .txt files in folder
    ret_code = delete_files_by_extension(output_directory, "txt");
    if (ret_code != 0) {
        return ret_code;
    }
    
    // Initialize environment for connecting to the web service
    ret_code = init_http_environment(0);
    if (ret_code != 0) {
        return ret_code;
    }
    
    // Output file descriptors
    static cp_hashtable *output_files = NULL;
    // Lines of the output data in the main .txt files
    static list_t *output_list = NULL;
    // Consequence type counters (for summary, must be kept between web service calls)
    static cp_hashtable *summary_count = NULL;
    // Gene list (for genes-with-variants, must be kept between web service calls)
    static cp_hashtable *gene_list = NULL;

    // Initialize collections of file descriptors and summary counters
    ret_code = initialize_output_files(output_directory, output_directory_len, &output_files);
    if (ret_code != 0) {
        return ret_code;
    }
    initialize_output_data_structures(shared_options_data, &output_list, &summary_count, &gene_list);
    initialize_ws_buffers(shared_options_data->num_threads);
    
    // Create job.status file
    char job_status_filename[output_directory_len + 10];
    sprintf(job_status_filename, "%s/job.status", output_directory);
    FILE *job_status = new_job_status_file(job_status_filename);
    if (!job_status) {
        LOG_FATAL("Can't create job status file\n");
    } else {
        update_job_status_file(0, job_status);
    }
    
 
#pragma omp parallel sections private(start, stop, total)
    {
#pragma omp section
        {
            LOG_DEBUG_F("Thread %d reads the VCF file\n", omp_get_thread_num());
            
            start = omp_get_wtime();
            
            ret_code = vcf_read(vcf_file, 1,
                                (shared_options_data->batch_bytes > 0) ? shared_options_data->batch_bytes : shared_options_data->batch_lines,
                                shared_options_data->batch_bytes <= 0);

            stop = omp_get_wtime();
            total = stop - start;

            if (ret_code) {
                LOG_ERROR_F("Error %d while reading the file %s\n", ret_code, vcf_file->filename);
            }

            LOG_INFO_F("[%dR] Time elapsed = %f s\n", omp_get_thread_num(), total);
            LOG_INFO_F("[%dR] Time elapsed = %e ms\n", omp_get_thread_num(), total*1000);

            notify_end_parsing(vcf_file);
        }
        
#pragma omp section
        {
            // Enable nested parallelism and set the number of threads the user has chosen
            omp_set_nested(1);
            
            LOG_DEBUG_F("Thread %d processes data\n", omp_get_thread_num());
            
            // Filters and files for filtering output
            filter_t **filters = NULL;
            int num_filters = 0;
            if (shared_options_data->chain != NULL) {
                filters = sort_filter_chain(shared_options_data->chain, &num_filters);
            }
            FILE *passed_file = NULL, *failed_file = NULL, *non_processed_file = NULL;
            get_filtering_output_files(shared_options_data, &passed_file, &failed_file);
            
            // Pedigree information (used in some filters)
            individual_t **individuals = NULL;
            khash_t(ids) *sample_ids = NULL;
            
            // Filename structure outdir/vcfname.errors
            char *prefix_filename = calloc(strlen(shared_options_data->vcf_filename), sizeof(char));
            get_filename_from_path(shared_options_data->vcf_filename, prefix_filename);
            char *non_processed_filename = malloc((strlen(shared_options_data->output_directory) + strlen(prefix_filename) + 9) * sizeof(char));
            sprintf(non_processed_filename, "%s/%s.errors", shared_options_data->output_directory, prefix_filename);
            non_processed_file = fopen(non_processed_filename, "w");
            free(non_processed_filename);
            
            // Maximum size processed by each thread (never allow more than 1000 variants per query)
            if (shared_options_data->batch_lines > 0) {
                shared_options_data->entries_per_thread = MIN(MAX_VARIANTS_PER_QUERY, 
                            ceil((float) shared_options_data->batch_lines / shared_options_data->num_threads));
            } else {
                shared_options_data->entries_per_thread = MAX_VARIANTS_PER_QUERY;
            }
            LOG_DEBUG_F("entries-per-thread = %d\n", shared_options_data->entries_per_thread);
    
            int i = 0;
            vcf_batch_t *batch = NULL;
            int ret_ws_0 = 0, ret_ws_1 = 0, ret_ws_2 = 0;
            
            start = omp_get_wtime();

            while (batch = fetch_vcf_batch(vcf_file)) {
                if (i == 0) {
                    // Add headers associated to the defined filters
                    vcf_header_entry_t **filter_headers = get_filters_as_vcf_headers(filters, num_filters);
                    for (int j = 0; j < num_filters; j++) {
                        add_vcf_header_entry(filter_headers[j], vcf_file);
                    }
                        
                    // Write file format, header entries and delimiter
                    if (passed_file != NULL) { write_vcf_header(vcf_file, passed_file); }
                    if (failed_file != NULL) { write_vcf_header(vcf_file, failed_file); }
                    if (non_processed_file != NULL) { write_vcf_header(vcf_file, non_processed_file); }
                    
                    LOG_DEBUG("VCF header written\n");
                    
                    if (ped_file) {
                        // Create map to associate the position of individuals in the list of samples defined in the VCF file
                        sample_ids = associate_samples_and_positions(vcf_file);
                        // Sort individuals in PED as defined in the VCF file
                        individuals = sort_individuals(vcf_file, ped_file);
                    }
                }
                
//                     printf("batch loaded = '%.*s'\n", 50, batch->text);
//                     printf("batch text len = %zu\n", strlen(batch->text));

//                 if (i % 10 == 0) {
                    LOG_INFO_F("Batch %d reached by thread %d - %zu/%zu records \n", 
                            i, omp_get_thread_num(),
                            batch->records->size, batch->records->capacity);
//                 }

                int reconnections = 0;
                int max_reconnections = 3; // TODO allow to configure?

                // Write records that passed to a separate file, and query the WS with them as args
                array_list_t *failed_records = NULL;
                int num_variables = ped_file? get_num_variables(ped_file): 0;
                array_list_t *passed_records = filter_records(filters, num_filters, individuals, sample_ids, num_variables, batch->records, &failed_records);
                if (passed_records->size > 0) {
                    // Divide the list of passed records in ranges of size defined in config file
                    int num_chunks;
                    int *chunk_sizes;
                    int *chunk_starts = create_chunks(passed_records->size, shared_options_data->entries_per_thread, &num_chunks, &chunk_sizes);
                    
                    do {
                        // OpenMP: Launch a thread for each range
                        #pragma omp parallel for num_threads(shared_options_data->num_threads)
                        for (int j = 0; j < num_chunks; j++) {
                            int tid = omp_get_thread_num();
                            LOG_DEBUG_F("[%d] WS invocation\n", tid);
                            LOG_DEBUG_F("[%d] -- effect WS\n", tid);
                            if (!reconnections || ret_ws_0) {
                                ret_ws_0 = invoke_effect_ws(urls[0], (vcf_record_t**) (passed_records->items + chunk_starts[j]), 
                                                            chunk_sizes[j], options_data->excludes);
                                parse_effect_response(tid, output_directory, output_directory_len, output_files, output_list, summary_count, gene_list);
                                free(effect_line[tid]);
                                effect_line[tid] = (char*) calloc (max_line_size[tid], sizeof(char));
                            }
                            
                            if (!options_data->no_phenotypes) {
                                if (!reconnections || ret_ws_1) {
                                    LOG_DEBUG_F("[%d] -- snp WS\n", omp_get_thread_num());
                                    ret_ws_1 = invoke_snp_phenotype_ws(urls[1], (vcf_record_t**) (passed_records->items + chunk_starts[j]), chunk_sizes[j]);
                                    parse_snp_phenotype_response(tid, output_list);
                                    free(snp_line[tid]);
                                    snp_line[tid] = (char*) calloc (snp_max_line_size[tid], sizeof(char));
                                }
                                 
                                if (!reconnections || ret_ws_2) {
                                    LOG_DEBUG_F("[%d] -- mutation WS\n", omp_get_thread_num());
                                    ret_ws_2 = invoke_mutation_phenotype_ws(urls[2], (vcf_record_t**) (passed_records->items + chunk_starts[j]), chunk_sizes[j]);
                                    parse_mutation_phenotype_response(tid, output_list);
                                    free(mutation_line[tid]);
                                    mutation_line[tid] = (char*) calloc (mutation_max_line_size[tid], sizeof(char));
                                }
                            }
                        }
                        
                        LOG_DEBUG_F("*** %dth web services invocation finished\n", i);
                        
                        if (ret_ws_0 || ret_ws_1 || ret_ws_2) {
                            if (ret_ws_0) {
                                LOG_ERROR_F("Effect web service error: %s\n", get_last_http_error(ret_ws_0));
                            }
                            if (ret_ws_1) {
                                LOG_ERROR_F("SNP phenotype web service error: %s\n", get_last_http_error(ret_ws_1));
                            }
                            if (ret_ws_2) {
                                LOG_ERROR_F("Mutations phenotype web service error: %s\n", get_last_http_error(ret_ws_2));
                            }
                            
                            // In presence of errors, wait 4 seconds before retrying
                            reconnections++;
                            LOG_ERROR_F("Some errors ocurred, reconnection #%d\n", reconnections);
                            sleep(4);
                        } else {
                            free(chunk_starts);
                            free(chunk_sizes);
                        }
                    } while (reconnections < max_reconnections && (ret_ws_0 || ret_ws_1 || ret_ws_2));
                }
                
                // If the maximum number of reconnections was reached still with errors, 
                // write the non-processed batch to the corresponding file
                if (reconnections == max_reconnections && (ret_ws_0 || ret_ws_1 || ret_ws_2)) {
                #pragma omp critical
                    {
                        write_vcf_batch(batch, non_processed_file);
                    }
                }
                
                // Write records that passed and failed filters to separate files, and free them
                write_filtering_output_files(passed_records, failed_records, passed_file, failed_file);
                free_filtered_records(passed_records, failed_records, batch->records);
                
                // Free batch and its contents
                vcf_batch_free(batch);
                
                i++;
            }

            stop = omp_get_wtime();

            total = stop - start;

            LOG_INFO_F("[%d] Time elapsed = %f s\n", omp_get_thread_num(), total);
            LOG_INFO_F("[%d] Time elapsed = %e ms\n", omp_get_thread_num(), total*1000);

            // Free resources
            if (passed_file) { fclose(passed_file); }
            if (failed_file) { fclose(failed_file); }
            if (non_processed_file) { fclose(non_processed_file); }
            
            // Free filters
            for (i = 0; i < num_filters; i++) {
                filter_t *filter = filters[i];
                filter->free_func(filter);
            }
            free(filters);
            
            // Decrease list writers count
            for (i = 0; i < shared_options_data->num_threads; i++) {
                list_decr_writers(output_list);
            }
        }
        
#pragma omp section
        {
            // Thread which writes the results to all_variants, summary and one file per consequence type
            int ret = 0;
            char *line;
            list_item_t* item = NULL;
            FILE *fd = NULL;
            
            FILE *all_variants_file = cp_hashtable_get(output_files, "all_variants");
            FILE *snp_phenotype_file = cp_hashtable_get(output_files, "snp_phenotypes");
            FILE *mutation_phenotype_file = cp_hashtable_get(output_files, "mutation_phenotypes");
            
            while ((item = list_remove_item(output_list)) != NULL) {
                line = item->data_p;
                
                // Type greater than 0: consequence type identified by its SO code
                // Type equals to -1: SNP phenotype
                // Type equals to -2: mutation phenotype
                if (item->type > 0) {
                    // Write entry in the consequence type file
                    fd = cp_hashtable_get(output_files, &(item->type));
                    int ret = fprintf(fd, "%s\n", line);
                    if (ret < 0) {
                        LOG_ERROR_F("Error writing to file: '%s'\n", line);
                    }
                    
                    // Write in all_variants
                    ret = fprintf(all_variants_file, "%s\n", line);
                    if (ret < 0) {
                        LOG_ERROR_F("Error writing to all_variants: '%s'\n", line);
                    }
                    
                } else if (item->type == SNP_PHENOTYPE) {
                    ret = fprintf(snp_phenotype_file, "%s\n", line);
                    if (ret < 0) {
                        LOG_ERROR_F("Error writing to snp_phenotypes: '%s'\n", line);
                    }
                    
                } else if (item->type == MUTATION_PHENOTYPE) {
                    ret = fprintf(mutation_phenotype_file, "%s\n", line);
                    if (ret < 0) {
                        LOG_ERROR_F("Error writing to mutation_phenotypes: '%s'\n", line);
                    }
                }
                
                free(line);
                list_item_free(item);
            }
            
        }
    }

    write_summary_file(summary_count, cp_hashtable_get(output_files, "summary"));
    write_genes_with_variants_file(gene_list, output_directory);
    write_result_file(shared_options_data, options_data, summary_count, output_directory);

    free_output_data_structures(output_files, summary_count, gene_list);
    free_ws_buffers(shared_options_data->num_threads);
    free(output_list);
    vcf_close(vcf_file);
    
    update_job_status_file(100, job_status);
    close_job_status_file(job_status);
    
    return ret_code;
}
Exemple #8
0
void UI_EDFDwindow::SelectFileButton()
{
  FILE *inputfile=NULL,
       *outputfile=NULL;

  int i,
      file_number,
      offset,
      offset_2,
      datarecords,
      datarecords_read,
      datarecords_written,
      cnt,
      annot_signal_size,
      annot_signal_size_2,
      annot_signal_nr,
      annot_signal_nr_2,
      annots_written,
      len,
      progress_steps;

  long long former_timestamp,
            next_timestamp,
            new_hdr_timestamp,
            chunk_starttime,
            chunk_endtime;

  char txt_string[2048],
       inputpath[MAX_PATH_LENGTH],
       output_path[MAX_PATH_LENGTH],
       *fileheader,
       *readbuf,
       *tal;

  struct annotationblock *annotationlist[1],
                         *annotblock;

  struct edfhdrblock *edfhdr=NULL;


  pushButton1->setEnabled(false);

  strcpy(inputpath, QFileDialog::getOpenFileName(0, "Select inputfile", QString::fromLocal8Bit(recent_opendir), "EDF/BDF files (*.edf *.EDF *.bdf *.BDF *.rec *.REC)").toLocal8Bit().data());

  if(!strcmp(inputpath, ""))
  {
    pushButton1->setEnabled(true);
    return;
  }

  get_directory_from_path(recent_opendir, inputpath, MAX_PATH_LENGTH);

  inputfile = fopeno(inputpath, "rb");
  if(inputfile==NULL)
  {
    snprintf(txt_string, 2048, "Error, can not open file %s for reading.\n", inputpath);
    textEdit1->append(QString::fromLocal8Bit(txt_string));
    pushButton1->setEnabled(true);
    return;
  }

  snprintf(txt_string, 2048, "Processing file %s", inputpath);
  textEdit1->append(txt_string);

/***************** check if the file is valid ******************************/

  EDFfileCheck EDFfilechecker;

  edfhdr = EDFfilechecker.check_edf_file(inputfile, txt_string);
  if(edfhdr==NULL)
  {
    fclose(inputfile);
    textEdit1->append("Error, file is not a valid EDF or BDF file.\n");
    pushButton1->setEnabled(true);
    return;
  }

  if(((!edfhdr->edfplus)&&(!edfhdr->bdfplus))||(!edfhdr->discontinuous))
  {
    free(edfhdr->edfparam);
    free(edfhdr);
    fclose(inputfile);
    textEdit1->append("Error, file is not an EDF+D or BDF+D file.\n");
    pushButton1->setEnabled(true);
    return;
  }

/****************** get annotations ******************************/

  edfhdr->file_hdl = inputfile;

  EDF_annotations annotations_func;

  annotationlist[0] = NULL;

  if(annotations_func.get_annotations(0, edfhdr, &annotationlist[0], 0))
  {
    free_annotations(annotationlist[0]);
    free(edfhdr->edfparam);
    free(edfhdr);
    fclose(inputfile);
    textEdit1->append("Error, there is an incompatibility with the annotations.\n");
    pushButton1->setEnabled(true);
    return;
  }

  if(edfhdr->annots_not_read)
  {
    free_annotations(annotationlist[0]);
    free(edfhdr->edfparam);
    free(edfhdr);
    fclose(inputfile);
    textEdit1->append("Aborted.\n");
    pushButton1->setEnabled(true);
    return;
  }

  annotblock = annotationlist[0];

/***************** start conversion ******************************/

  datarecords = edfhdr->datarecords;

  annot_signal_nr = edfhdr->annot_ch[0];

  offset = edfhdr->edfparam[annot_signal_nr].buf_offset;

  if(edfhdr->edfplus)
  {
    annot_signal_size = edfhdr->edfparam[annot_signal_nr].smp_per_record * 2;
  }
  else
  {
    annot_signal_size = edfhdr->edfparam[annot_signal_nr].smp_per_record * 3;
  }

  fileheader = (char *)calloc(1, edfhdr->hdrsize);
  if(fileheader==NULL)
  {
    textEdit1->append("Malloc error, (fileheader).\n");
    free_annotations(annotationlist[0]);
    free(edfhdr->edfparam);
    free(edfhdr);
    fclose(inputfile);
    pushButton1->setEnabled(true);
    return;
  }

  readbuf = (char *)calloc(1, edfhdr->recordsize);
  if(readbuf==NULL)
  {
    textEdit1->append("Malloc error, (readbuf).\n");
    free_annotations(annotationlist[0]);
    free(edfhdr->edfparam);
    free(edfhdr);
    free(fileheader);
    fclose(inputfile);
    pushButton1->setEnabled(true);
    return;
  }

  rewind(inputfile);
  if(fread(fileheader, edfhdr->hdrsize, 1, inputfile) != 1)
  {
    textEdit1->append("Read error.\n");
    free_annotations(annotationlist[0]);
    free(edfhdr->edfparam);
    free(edfhdr);
    free(fileheader);
    free(readbuf);
    fclose(inputfile);
    pushButton1->setEnabled(true);
    return;
  }

///////////////////////////////////////////////////////////////////

  file_number = 1;

  strcpy(output_path, inputpath);
  remove_extension_from_filename(output_path);
  if(edfhdr->edfplus)
  {
    sprintf(output_path + strlen(output_path), "_%04i.edf", file_number);
  }
  else
  {
    sprintf(output_path + strlen(output_path), "_%04i.bdf", file_number);
  }

  strcpy(txt_string, "Creating file ");
  len = strlen(txt_string);
  get_filename_from_path(txt_string + len, output_path, MAX_PATH_LENGTH - len);
  textEdit1->append(QString::fromLocal8Bit(txt_string));

  outputfile = fopeno(output_path, "w+b");
  if(outputfile==NULL)
  {
    textEdit1->append("Error, can not open outputfile for writing.\n");
    free_annotations(annotationlist[0]);
    free(edfhdr->edfparam);
    free(edfhdr);
    free(fileheader);
    free(readbuf);
    fclose(inputfile);
    pushButton1->setEnabled(true);
    return;
  }

  if(fwrite(fileheader, edfhdr->hdrsize, 1, outputfile) != 1)
  {
    textEdit1->append("Write error.\n");
    free_annotations(annotationlist[0]);
    free(edfhdr->edfparam);
    free(edfhdr);
    free(fileheader);
    free(readbuf);
    fclose(inputfile);
    fclose(outputfile);
    pushButton1->setEnabled(true);
    return;
  }

  QProgressDialog progress("Processing file...", "Abort", 0, datarecords);
  progress.setWindowModality(Qt::WindowModal);
  progress.setMinimumDuration(200);

  progress_steps = datarecords / 100;
  if(progress_steps < 1)
  {
    progress_steps = 1;
  }

  datarecords_written = 0;

  new_hdr_timestamp = 0LL;

  former_timestamp = 0LL;

  next_timestamp = 0LL;

  chunk_starttime = 0LL;

  chunk_endtime = 0LL;

  tal = readbuf + offset;

  fseeko(inputfile, (long long)(edfhdr->hdrsize), SEEK_SET);

  for(datarecords_read=0; datarecords_read<datarecords; datarecords_read++)
  {
    if(!(datarecords_read%progress_steps))
    {
      progress.setValue(datarecords_read);

      qApp->processEvents();

      if(progress.wasCanceled() == true)
      {
        textEdit1->append("Aborted.\n");

        break;
      }
    }

    if(fread(readbuf, edfhdr->recordsize, 1, inputfile) != 1)
    {
      progress.reset();
      textEdit1->append("Read error.\n");
      free_annotations(annotationlist[0]);
      free(edfhdr->edfparam);
      free(edfhdr);
      free(fileheader);
      free(readbuf);
      fclose(inputfile);
      fclose(outputfile);
      pushButton1->setEnabled(true);
      return;
    }

    if(edfhdr->nr_annot_chns>1)
    {
      for(i=1; i<edfhdr->nr_annot_chns; i++)
      {
        annot_signal_nr_2 = edfhdr->annot_ch[i];

        offset_2 = edfhdr->edfparam[annot_signal_nr_2].buf_offset;

        if(edfhdr->edfplus)
        {
          annot_signal_size_2 = edfhdr->edfparam[annot_signal_nr_2].smp_per_record * 2;
        }
        else
        {
          annot_signal_size_2 = edfhdr->edfparam[annot_signal_nr_2].smp_per_record * 3;
        }

        memset(readbuf + offset_2, 0, annot_signal_size_2);
      }
    }

    next_timestamp = get_datarecord_timestamp(tal);

    if(!datarecords_read)
    {
      former_timestamp = next_timestamp - edfhdr->long_data_record_duration;
    }

    if(next_timestamp!=(former_timestamp + edfhdr->long_data_record_duration))
    {
      chunk_endtime = next_timestamp;

      write_values_to_hdr(outputfile, new_hdr_timestamp, datarecords_written, edfhdr);

      annotblock = annotationlist[0];

      annots_written = 0;

      if(annotblock!=NULL)
      {
        while(annotblock!=NULL)
        {
          if(((annotblock->onset>=chunk_starttime)||(file_number==1))
             &&(annotblock->onset<chunk_endtime)
             &&(annots_written<datarecords_written))
          {
            fseeko(outputfile, (long long)(edfhdr->hdrsize + (annots_written * edfhdr->recordsize) + offset), SEEK_SET);

            for(cnt=1; ; cnt++)
            {
              if(fgetc(outputfile)==0)  break;
            }

            fseeko(outputfile, 0LL, SEEK_CUR);

            cnt += fprintf(outputfile, "+%i", (int)((annotblock->onset - new_hdr_timestamp) / TIME_DIMENSION));

            if(annotblock->onset%TIME_DIMENSION)
            {
              cnt += fprintf(outputfile, ".%07i", (int)((annotblock->onset - new_hdr_timestamp) % TIME_DIMENSION));

              fseeko(outputfile, -1LL, SEEK_CUR);

              while(fgetc(outputfile)=='0')
              {
                fseeko(outputfile, -2LL, SEEK_CUR);

                cnt--;
              }
            }

            fseeko(outputfile, 0LL, SEEK_CUR);

            if(annotblock->duration[0]!=0)
            {
              fputc(21, outputfile);

              cnt++;

              cnt += fprintf(outputfile, "%s", annotblock->duration);
            }

            fputc(20, outputfile);

            cnt++;

            for(i = 0; i < (annot_signal_size - cnt - 2); i++)
            {
             if(annotblock->annotation[i]==0)  break;

             fputc(annotblock->annotation[i], outputfile);

             cnt++;
            }

            fputc(20, outputfile);

            cnt++;

            for(i = cnt; i < annot_signal_size; i++)
            {
              fputc(0, outputfile);
            }

            annots_written++;
          }

          annotblock = annotblock->next_annotation;
        }
      }

      fclose(outputfile);

      datarecords_written = 0;

      new_hdr_timestamp = next_timestamp;

      new_hdr_timestamp -= next_timestamp % TIME_DIMENSION;

      chunk_starttime = next_timestamp;

      file_number++;

      strcpy(output_path, inputpath);
      remove_extension_from_filename(output_path);
      if(edfhdr->edfplus)
      {
        sprintf(output_path + strlen(output_path), "_%04i.edf", file_number);
      }
      else
      {
        sprintf(output_path + strlen(output_path), "_%04i.bdf", file_number);
      }

      strcpy(txt_string, "Creating file ");
      len = strlen(txt_string);
      get_filename_from_path(txt_string + len, output_path, MAX_PATH_LENGTH - len);
      textEdit1->append(txt_string);

      outputfile = fopeno(output_path, "w+b");
      if(outputfile==NULL)
      {
        textEdit1->append("Error, can not open outputfile for writing.\n");
        free_annotations(annotationlist[0]);
        free(edfhdr->edfparam);
        free(edfhdr);
        free(fileheader);
        free(readbuf);
        fclose(inputfile);
        pushButton1->setEnabled(true);
        return;
      }

      if(fwrite(fileheader, edfhdr->hdrsize, 1, outputfile) != 1)
      {
        textEdit1->append("Write error.\n");
        free_annotations(annotationlist[0]);
        free(edfhdr->edfparam);
        free(edfhdr);
        free(fileheader);
        free(readbuf);
        fclose(inputfile);
        fclose(outputfile);
        pushButton1->setEnabled(true);
        return;
      }
    }

    cnt = sprintf(tal, "+%i", (int)((next_timestamp - new_hdr_timestamp) / TIME_DIMENSION));

    if((next_timestamp - new_hdr_timestamp)%TIME_DIMENSION)
    {
      cnt += sprintf(tal + cnt, ".%07i", (int)((next_timestamp - new_hdr_timestamp) % TIME_DIMENSION));

      for(i=cnt-1; i>0; i--)
      {
        if(tal[i]!='0')  break;

        cnt--;
      }
    }

    tal[cnt++] = 20;
    tal[cnt++] = 20;

    for(i=cnt; i<annot_signal_size; i++)
    {
      tal[i] = 0;
    }

    if(fwrite(readbuf, edfhdr->recordsize, 1, outputfile) != 1)
    {
      progress.reset();
      textEdit1->append("Write error.\n");
      free_annotations(annotationlist[0]);
      free(edfhdr->edfparam);
      free(edfhdr);
      free(fileheader);
      free(readbuf);
      fclose(inputfile);
      fclose(outputfile);
      pushButton1->setEnabled(true);
      return;
    }

    datarecords_written++;

    former_timestamp = next_timestamp;
  }

  write_values_to_hdr(outputfile, new_hdr_timestamp, datarecords_written, edfhdr);

  annotblock = annotationlist[0];

  annots_written = 0;

  if(annotblock!=NULL)
  {
    while(annotblock!=NULL)
    {
      if((annotblock->onset>=chunk_starttime)&&(annots_written<datarecords_written))
      {
        fseeko(outputfile, (long long)(edfhdr->hdrsize + (annots_written * edfhdr->recordsize) + offset), SEEK_SET);

        for(cnt=1; ; cnt++)
        {
          if(fgetc(outputfile)==0)  break;
        }

        fseeko(outputfile, 0LL, SEEK_CUR);

        cnt += fprintf(outputfile, "+%i", (int)((annotblock->onset - new_hdr_timestamp) / TIME_DIMENSION));

        if(annotblock->onset%TIME_DIMENSION)
        {
          cnt += fprintf(outputfile, ".%07i", (int)((annotblock->onset - new_hdr_timestamp) % TIME_DIMENSION));

          fseeko(outputfile, -1LL, SEEK_CUR);

          while(fgetc(outputfile)=='0')
          {
            fseeko(outputfile, -2LL, SEEK_CUR);

            cnt--;
          }
        }

        fseeko(outputfile, 0LL, SEEK_CUR);

        if(annotblock->duration[0]!=0)
        {
          fputc(21, outputfile);

          cnt++;

          cnt += fprintf(outputfile, "%s", annotblock->duration);
        }

        fputc(20, outputfile);

        cnt++;

        for(i = 0; i < (annot_signal_size - cnt - 2); i++)
        {
          if(annotblock->annotation[i]==0)  break;

          fputc(annotblock->annotation[i], outputfile);

          cnt++;
        }

        fputc(20, outputfile);

        cnt++;

        for(i = cnt; i < annot_signal_size; i++)
        {
          fputc(0, outputfile);
        }

        annots_written++;
      }

      annotblock = annotblock->next_annotation;
    }
  }

  free_annotations(annotationlist[0]);
  free(edfhdr->edfparam);
  free(edfhdr);
  free(fileheader);
  free(readbuf);
  fclose(inputfile);
  fclose(outputfile);

  progress.reset();
  textEdit1->append("Done\n");

  pushButton1->setEnabled(true);
}
void UI_ReduceSignalsWindow::StartConversion()
{
  int i, j, k, n,
      new_edfsignals,
      datarecords=0,
      annot_smp_per_record,
      annot_recordsize,
      timestamp_digits=0,
      timestamp_decimals=0,
      annot_len,
      tallen=0,
      len,
      annot_cnt,
      annots_per_datrec=0,
      smplrt,
      tmp,
      val,
      progress_steps,
      datrecs_processed;

  char *readbuf=NULL,
       scratchpad[256];

  long long new_starttime,
            time_diff,
            onset_diff,
            taltime,
            l_temp,
            endtime=0,
            l_tmp;

  struct date_time_struct dts;

  struct annotationblock *new_annot_list=NULL,
                         *root_new_annot_list=NULL,
                         *annot_list=NULL;

  union {
          unsigned int one;
          signed int one_signed;
          unsigned short two[2];
          signed short two_signed[2];
          unsigned char four[4];
        } var;

  QProgressDialog progress("Processing file...", "Abort", 0, 1);
  progress.setWindowModality(Qt::WindowModal);
  progress.setMinimumDuration(200);


  pushButton3->setEnabled(false);
  pushButton4->setEnabled(false);
  pushButton5->setEnabled(false);
  pushButton6->setEnabled(false);
  spinBox1->setEnabled(false);
  spinBox2->setEnabled(false);
  spinBox3->setEnabled(false);
  spinBox4->setEnabled(false);
  radioButton1->setEnabled(false);
  radioButton2->setEnabled(false);
  label2->setEnabled(false);
  label3->setEnabled(false);

  if(edfhdr==NULL)
  {
    return;
  }

  if(file_num < 0)
  {
    return;
  }

  new_edfsignals = 0;

  annot_smp_per_record = 0;

  annot_cnt = 0;

  aa_filter_order = spinBox4->value() - 1;

  time_diff = (long long)(spinBox1->value() - 1) * edfhdr->long_data_record_duration;

  taltime = (time_diff + edfhdr->starttime_offset) % TIME_DIMENSION;

  endtime = (long long)(spinBox2->value() - (spinBox1->value() - 1)) * edfhdr->long_data_record_duration + taltime;

  for(i=0; i<edfhdr->edfsignals; i++)
  {
    if(!edfhdr->edfparam[i].annotation)
    {
      if(((QCheckBox *)(SignalsTablewidget->cellWidget(i, 0)))->checkState()==Qt::Checked)
      {
        signalslist[new_edfsignals] = i;

        dividerlist[new_edfsignals] = ((QComboBox *)(SignalsTablewidget->cellWidget(i, 1)))->itemData(((QComboBox *)(SignalsTablewidget->cellWidget(i, 1)))->currentIndex()).toInt();

        new_edfsignals++;
      }
    }
  }

  datarecords = spinBox2->value() - spinBox1->value() + 1;

  if(edfhdr->edfplus || edfhdr->bdfplus)
  {
    timestamp_decimals = get_tal_timestamp_decimal_cnt(edfhdr);
    if(timestamp_decimals < 0)
    {
      showpopupmessage("Error", "Internal error, get_tal_timestamp_decimal_cnt(");
      goto END_1;
    }

    timestamp_digits = get_tal_timestamp_digit_cnt(edfhdr);
    if(timestamp_digits < 0)
    {
      showpopupmessage("Error", "Internal error, get_tal_timestamp_digit_cnt(");
      goto END_1;
    }

    annot_list = mainwindow->annotationlist[file_num];

    while(annot_list != NULL)
    {
      l_temp = annot_list->onset - time_diff;

      if((l_temp >= 0LL) && (l_temp <= endtime))
      {
        annot_cnt++;

        edfplus_annotation_add_copy(&new_annot_list, annot_list);
      }

      annot_list = annot_list->next_annotation;
    }

    annot_list = new_annot_list;

    root_new_annot_list = new_annot_list;

    new_starttime = edfhdr->utc_starttime + ((time_diff + edfhdr->starttime_offset) / TIME_DIMENSION);

    onset_diff = (new_starttime - edfhdr->utc_starttime) * TIME_DIMENSION;

    while(annot_list != NULL)
    {
      annot_list->onset -= onset_diff;

      annot_list = annot_list->next_annotation;
    }

    edfplus_annotation_sort(&new_annot_list);

    annots_per_datrec = annot_cnt / datarecords;

    if(annot_cnt % datarecords)
    {
      annots_per_datrec++;
    }

    annot_len = get_max_annotation_strlen(&new_annot_list);

    if(!annot_cnt)
    {
      annots_per_datrec = 0;
    }

    annot_recordsize = (annot_len * annots_per_datrec) + timestamp_digits + timestamp_decimals + 4;

    if(timestamp_decimals)
    {
      annot_recordsize++;
    }

    if(edfhdr->edf)
    {
      annot_smp_per_record = annot_recordsize / 2;

      if(annot_recordsize % annot_smp_per_record)
      {
        annot_smp_per_record++;

        annot_recordsize = annot_smp_per_record * 2;
      }
    }
    else
    {
      annot_smp_per_record = annot_recordsize / 3;

      if(annot_recordsize % annot_smp_per_record)
      {
        annot_smp_per_record++;

        annot_recordsize = annot_smp_per_record * 3;
      }
    }
  }
  else
  {
    annot_smp_per_record = 0;

    annot_recordsize = 0;
  }

  readbuf = (char *)malloc(edfhdr->recordsize);
  if(readbuf==NULL)
  {
    showpopupmessage("Error", "Malloc error, (readbuf).");
    goto END_2;
  }
///////////////////////////////////////////////////////////////////

  for(i=0; i<new_edfsignals; i++)
  {
    if(dividerlist[i] > 1)
    {
      for(j=0; j<aa_filter_order; j++)
      {
        filterlist[i][j] = create_ravg_filter(1, dividerlist[i]);

        if(filterlist[i][j] == NULL)
        {
          showpopupmessage("Error", "Malloc error, (create_ravg_filter()).");

          goto END_3;
        }
      }
    }
  }
///////////////////////////////////////////////////////////////////

  outputpath[0] = 0;
  if(recent_savedir[0]!=0)
  {
    strcpy(outputpath, recent_savedir);
    strcat(outputpath, "/");
  }
  len = strlen(outputpath);
  get_filename_from_path(outputpath + len, inputpath, MAX_PATH_LENGTH - len);
  remove_extension_from_filename(outputpath);
  if(edfhdr->edf)
  {
    strcat(outputpath, "_reduced.edf");

    strcpy(outputpath, QFileDialog::getSaveFileName(0, "Save file", QString::fromLocal8Bit(outputpath), "EDF files (*.edf *.EDF)").toLocal8Bit().data());
  }
  else
  {
    strcat(outputpath, "_reduced.bdf");

    strcpy(outputpath, QFileDialog::getSaveFileName(0, "Save file", QString::fromLocal8Bit(outputpath), "BDF files (*.bdf *.BDF)").toLocal8Bit().data());
  }

  if(!strcmp(outputpath, ""))
  {
    goto END_3;
  }

  get_directory_from_path(recent_savedir, outputpath, MAX_PATH_LENGTH);

  if(mainwindow->file_is_opened(outputpath))
  {
    showpopupmessage("Reduce signals", "Error, selected file is in use.");
    goto END_3;
  }

  outputfile = fopeno(outputpath, "wb");
  if(outputfile==NULL)
  {
    showpopupmessage("Error", "Can not open outputfile for writing.");
    goto END_3;
  }

  new_starttime = edfhdr->utc_starttime + ((time_diff + edfhdr->starttime_offset) / TIME_DIMENSION);

  utc_to_date_time(new_starttime, &dts);

  rewind(inputfile);
  if(fread(scratchpad, 168, 1, inputfile)!=1)
  {
    showpopupmessage("Error", "Read error (1).");
    goto END_4;
  }

  if(edfhdr->edfplus || edfhdr->bdfplus)
  {
    if(scratchpad[98] != 'X')
    {
      sprintf(scratchpad + 98, "%02i-%s-%04i", dts.day, dts.month_str, dts.year);

      scratchpad[109] = ' ';
    }
  }

  if(fwrite(scratchpad, 168, 1, outputfile)!=1)
  {
    showpopupmessage("Error", "Write error (1).");
    goto END_4;
  }

  fprintf(outputfile, "%02i.%02i.%02i%02i.%02i.%02i",
          dts.day,
          dts.month,
          dts.year % 100,
          dts.hour,
          dts.minute,
          dts.second);

  if(edfhdr->edfplus || edfhdr->bdfplus)
  {
    fprintf(outputfile, "%-8i", new_edfsignals * 256 + 512);
  }
  else
  {
    fprintf(outputfile, "%-8i", new_edfsignals * 256 + 256);
  }
  if(edfhdr->edfplus)
  {
    fprintf(outputfile, "EDF+C");
    for(i=0; i<39; i++)
    {
      fputc(' ', outputfile);
    }
  }
  if(edfhdr->bdfplus)
  {
    fprintf(outputfile, "BDF+C");
    for(i=0; i<39; i++)
    {
      fputc(' ', outputfile);
    }
  }
  if((!edfhdr->edfplus) && (!edfhdr->bdfplus))
  {
    for(i=0; i<44; i++)
    {
      fputc(' ', outputfile);
    }
  }
  fprintf(outputfile, "%-8i", datarecords);
  snprintf(scratchpad, 256, "%f", edfhdr->data_record_duration);
  convert_trailing_zeros_to_spaces(scratchpad);
  if(scratchpad[7]=='.')
  {
    scratchpad[7] = ' ';
  }
  scratchpad[8] = 0;

  fprintf(outputfile, "%s", scratchpad);
  if(edfhdr->edfplus || edfhdr->bdfplus)
  {
    fprintf(outputfile, "%-4i", new_edfsignals + 1);
  }
  else
  {
    fprintf(outputfile, "%-4i", new_edfsignals);
  }

  for(i=0; i<new_edfsignals; i++)
  {
    fprintf(outputfile, "%s", edfhdr->edfparam[signalslist[i]].label);
  }
  if(edfhdr->edfplus)
  {
    fprintf(outputfile, "EDF Annotations ");
  }
  if(edfhdr->bdfplus)
  {
    fprintf(outputfile, "BDF Annotations ");
  }
  for(i=0; i<new_edfsignals; i++)
  {
    fprintf(outputfile, "%s", edfhdr->edfparam[signalslist[i]].transducer);
  }
  if(edfhdr->edfplus || edfhdr->bdfplus)
  {
    for(i=0; i<80; i++)
    {
      fputc(' ', outputfile);
    }
  }
  for(i=0; i<new_edfsignals; i++)
  {
    fprintf(outputfile, "%s", edfhdr->edfparam[signalslist[i]].physdimension);
  }
  if(edfhdr->edfplus || edfhdr->bdfplus)
  {
    for(i=0; i<8; i++)
    {
      fputc(' ', outputfile);
    }
  }
  for(i=0; i<new_edfsignals; i++)
  {
    snprintf(scratchpad, 256, "%f", edfhdr->edfparam[signalslist[i]].phys_min);
    convert_trailing_zeros_to_spaces(scratchpad);
    if(scratchpad[7]=='.')
    {
      scratchpad[7] = ' ';
    }
    scratchpad[8] = 0;
    fprintf(outputfile, "%s", scratchpad);
  }
  if(edfhdr->edfplus || edfhdr->bdfplus)
  {
    fprintf(outputfile, "-1      ");
  }
  for(i=0; i<new_edfsignals; i++)
  {
    snprintf(scratchpad, 256, "%f", edfhdr->edfparam[signalslist[i]].phys_max);
    convert_trailing_zeros_to_spaces(scratchpad);
    if(scratchpad[7]=='.')
    {
      scratchpad[7] = ' ';
    }
    scratchpad[8] = 0;
    fprintf(outputfile, "%s", scratchpad);
  }
  if(edfhdr->edfplus || edfhdr->bdfplus)
  {
    fprintf(outputfile, "1       ");
  }
  for(i=0; i<new_edfsignals; i++)
  {
    fprintf(outputfile, "%-8i", edfhdr->edfparam[signalslist[i]].dig_min);
  }
  if(edfhdr->edfplus)
  {
    fprintf(outputfile, "-32768  ");
  }
  if(edfhdr->bdfplus)
  {
    fprintf(outputfile, "-8388608");
  }
  for(i=0; i<new_edfsignals; i++)
  {
    fprintf(outputfile, "%-8i", edfhdr->edfparam[signalslist[i]].dig_max);
  }
  if(edfhdr->edfplus)
  {
    fprintf(outputfile, "32767   ");
  }
  if(edfhdr->bdfplus)
  {
    fprintf(outputfile, "8388607 ");
  }
  for(i=0; i<new_edfsignals; i++)
  {
    fprintf(outputfile, "%s", edfhdr->edfparam[signalslist[i]].prefilter);
  }
  if(edfhdr->edfplus || edfhdr->bdfplus)
  {
    for(i=0; i<80; i++)
    {
      fputc(' ', outputfile);
    }
  }
  for(i=0; i<new_edfsignals; i++)
  {
    fprintf(outputfile, "%-8i", edfhdr->edfparam[signalslist[i]].smp_per_record / dividerlist[i]);
  }
  if(edfhdr->edfplus || edfhdr->bdfplus)
  {
    fprintf(outputfile, "%-8i", annot_smp_per_record);
  }
  for(i=0; i<(new_edfsignals * 32); i++)
  {
   fputc(' ', outputfile);
  }
  if(edfhdr->edfplus || edfhdr->bdfplus)
  {
    for(i=0; i<32; i++)
    {
      fputc(' ', outputfile);
    }
  }
///////////////////////////////////////////////////////////////////

  progress.setRange(0, datarecords);
  progress.setValue(0);

  progress_steps = datarecords / 100;
  if(progress_steps < 1)
  {
    progress_steps = 1;
  }

  fseeko(inputfile, (long long)edfhdr->hdrsize + ((long long)(spinBox1->value() - 1) * (long long)edfhdr->recordsize), SEEK_SET);

  for(datrecs_processed=0; datrecs_processed<datarecords; datrecs_processed++)
  {
    if(!(datrecs_processed % progress_steps))
    {
      progress.setValue(datrecs_processed);

      qApp->processEvents();

      if(progress.wasCanceled() == true)
      {
        goto END_4;
      }
    }

    if(fread(readbuf, edfhdr->recordsize, 1, inputfile) != 1)
    {
      progress.reset();
      showpopupmessage("Error", "Read error (2).");
      goto END_4;
    }

    if(edfhdr->edf)
    {
      for(i=0; i<new_edfsignals; i++)
      {
        if(dividerlist[i] == 1)
        {
          smplrt = edfhdr->edfparam[signalslist[i]].smp_per_record;

          for(j=0; j<smplrt; j++)
          {
            fputc(readbuf[edfhdr->edfparam[signalslist[i]].buf_offset + (j * 2)], outputfile);
            if(fputc(readbuf[edfhdr->edfparam[signalslist[i]].buf_offset + (j * 2) + 1], outputfile)==EOF)
            {
              progress.reset();
              showpopupmessage("Error", "Write error (4).");
              goto END_4;
            }
          }
        }
        else
        {
          smplrt = edfhdr->edfparam[signalslist[i]].smp_per_record / dividerlist[i];

          for(j=0; j<smplrt; j++)
          {
            tmp = 0;

            for(k=0; k<dividerlist[i]; k++)
            {
              val = *(((signed short *)(readbuf + edfhdr->edfparam[signalslist[i]].buf_offset)) + (dividerlist[i] * j) + k);

              for(n=0; n<aa_filter_order; n++)
              {
                val = run_ravg_filter(val, filterlist[i][n]);
              }

              tmp += val;
            }

            tmp /= dividerlist[i];

            fputc(tmp & 0xff, outputfile);
            if(fputc((tmp >> 8) & 0xff, outputfile)==EOF)
            {
              progress.reset();
              showpopupmessage("Error", "Write error (4).");
              goto END_4;
            }
          }
        }
      }
    }
    else
    {
      for(i=0; i<new_edfsignals; i++)
      {
        if(dividerlist[i] == 1)
        {
          smplrt = edfhdr->edfparam[signalslist[i]].smp_per_record;

          for(j=0; j<smplrt; j++)
          {
            fputc(readbuf[edfhdr->edfparam[signalslist[i]].buf_offset + (j * 3)], outputfile);
            fputc(readbuf[edfhdr->edfparam[signalslist[i]].buf_offset + (j * 3) + 1], outputfile);
            if(fputc(readbuf[edfhdr->edfparam[signalslist[i]].buf_offset + (j * 3) + 2], outputfile)==EOF)
            {
              progress.reset();
              showpopupmessage("Error", "Write error (4).");
              goto END_4;
            }
          }
        }
        else
        {
          smplrt = edfhdr->edfparam[signalslist[i]].smp_per_record / dividerlist[i];

          for(j=0; j<smplrt; j++)
          {
            l_tmp = 0LL;

            for(k=0; k<dividerlist[i]; k++)
            {
              var.two[0] = *((unsigned short *)(readbuf + edfhdr->edfparam[signalslist[i]].buf_offset + (dividerlist[i] * j * 3) + (k * 3)));
              var.four[2] = *((unsigned char *)(readbuf + edfhdr->edfparam[signalslist[i]].buf_offset + (dividerlist[i] * j * 3) + (k * 3) + 2));

              if(var.four[2]&0x80)
              {
                var.four[3] = 0xff;
              }
              else
              {
                var.four[3] = 0x00;
              }

              for(n=0; n<aa_filter_order; n++)
              {
                var.one_signed = run_ravg_filter(var.one_signed, filterlist[i][n]);
              }

              l_tmp += var.one_signed;
            }

            l_tmp /= dividerlist[i];

            fputc(l_tmp & 0xff, outputfile);
            fputc((l_tmp >> 8) & 0xff, outputfile);
            if(fputc((l_tmp >> 16) & 0xff, outputfile)==EOF)
            {
              progress.reset();
              showpopupmessage("Error", "Write error (4).");
              goto END_4;
            }
          }
        }
      }
    }

    if(edfhdr->edfplus || edfhdr->bdfplus)
    {
      switch(timestamp_decimals)
      {
        case 0 : tallen = fprintf(outputfile, "+%i", (int)(taltime / TIME_DIMENSION));
                  break;
        case 1 : tallen = fprintf(outputfile, "+%i.%01i", (int)(taltime / TIME_DIMENSION), (int)((taltime % TIME_DIMENSION) / 1000000LL));
                  break;
        case 2 : tallen = fprintf(outputfile, "+%i.%02i", (int)(taltime / TIME_DIMENSION), (int)((taltime % TIME_DIMENSION) / 100000LL));
                  break;
        case 3 : tallen = fprintf(outputfile, "+%i.%03i", (int)(taltime / TIME_DIMENSION), (int)((taltime % TIME_DIMENSION) / 10000LL));
                  break;
        case 4 : tallen = fprintf(outputfile, "+%i.%04i", (int)(taltime / TIME_DIMENSION), (int)((taltime % TIME_DIMENSION) / 1000LL));
                  break;
        case 5 : tallen = fprintf(outputfile, "+%i.%05i", (int)(taltime / TIME_DIMENSION), (int)((taltime % TIME_DIMENSION) / 100LL));
                  break;
        case 6 : tallen = fprintf(outputfile, "+%i.%06i", (int)(taltime / TIME_DIMENSION), (int)((taltime % TIME_DIMENSION) / 10LL));
                  break;
        case 7 : tallen = fprintf(outputfile, "+%i.%07i", (int)(taltime / TIME_DIMENSION), (int)(taltime % TIME_DIMENSION));
                  break;
      }

      fputc(20, outputfile);
      fputc(20, outputfile);
      fputc(0, outputfile);

      tallen += 3;

      if(new_annot_list != NULL)
      {
        for(i=0; i<annots_per_datrec; i++)
        {
          if(new_annot_list != NULL)
          {
            len = snprintf(scratchpad, 256, "%+i.%07i",
            (int)(new_annot_list->onset / TIME_DIMENSION),
            (int)(new_annot_list->onset % TIME_DIMENSION));

            for(j=0; j<7; j++)
            {
              if(scratchpad[len - j - 1] != '0')
              {
                break;
              }
            }

            if(j)
            {
              len -= j;

              if(j == 7)
              {
                len--;
              }
            }

            if(fwrite(scratchpad, len, 1, outputfile) != 1)
            {
              progress.reset();
              showpopupmessage("Error", "Write error (5).");
              goto END_4;
            }

            tallen += len;

            if(new_annot_list->duration[0]!=0)
            {
              fputc(21, outputfile);
              tallen++;

              tallen += fprintf(outputfile, "%s", new_annot_list->duration);
            }

            fputc(20, outputfile);
            tallen++;

            tallen += fprintf(outputfile, "%s", new_annot_list->annotation);

            fputc(20, outputfile);
            fputc(0, outputfile);
            tallen += 2;

            new_annot_list = new_annot_list->next_annotation;
          }
        }
      }

      for(k=tallen; k<annot_recordsize; k++)
      {
        fputc(0, outputfile);
      }

      taltime += edfhdr->long_data_record_duration;
    }
  }
Exemple #10
0
void UI_SCPECG2EDFwindow::SelectFileButton()
{
  FILE *inputfile=NULL;

  int i, j, k, n, hdl, chns, sf, avm, blocks, *buf, encoding, compression, offset,
      abs_val_a[256],
      abs_val_b[256],
      var_tmp;

  unsigned short sh_tmp;

  long long filesize, ll_tmp, bits;

  char input_filename[MAX_PATH_LENGTH],
       txt_string[2048],
       edf_filename[MAX_PATH_LENGTH],
       scratchpad[MAX_PATH_LENGTH],
       *block,
       ch_tmp;

  union{
         unsigned long long ll_int;
         unsigned int one[2];
         unsigned short two[4];
         unsigned char four[8];
       } var;

  pushButton1->setEnabled(false);

  for(i=0; i<256; i++)
  {
    abs_val_a[i] = 0;
    abs_val_b[i] = 0;
  }

  strcpy(input_filename, QFileDialog::getOpenFileName(0, "Select inputfile", QString::fromLocal8Bit(recent_opendir), "SCP files (*.scp *.SCP)").toLocal8Bit().data());

  if(!strcmp(input_filename, ""))
  {
    pushButton1->setEnabled(true);
    return;
  }

  get_directory_from_path(recent_opendir, input_filename, MAX_PATH_LENGTH);

  inputfile = fopeno(input_filename, "rb");
  if(inputfile==NULL)
  {
    snprintf(txt_string, 2048, "Can not open file %s for reading.\n", input_filename);
    textEdit1->append(QString::fromLocal8Bit(txt_string));
    pushButton1->setEnabled(true);
    return;
  }

  get_filename_from_path(scratchpad, input_filename, MAX_PATH_LENGTH);

  snprintf(txt_string, 2048, "Read file: %s", scratchpad);
  textEdit1->append(QString::fromLocal8Bit(txt_string));

  fseeko(inputfile, 0LL, SEEK_END);
  filesize = ftello(inputfile);
  if(filesize<126)
  {
    textEdit1->append("Error, filesize is too small.\n");
    fclose(inputfile);
    pushButton1->setEnabled(true);
    return;
  }

  ll_tmp = 0LL;

  fseeko(inputfile, 2LL, SEEK_SET);

  if(fread(&ll_tmp, 4, 1, inputfile) != 1)
  {
    textEdit1->append("A read-error occurred (1)\n");
    fclose(inputfile);
    pushButton1->setEnabled(true);
    return;
  }

  if(ll_tmp != filesize)
  {
    textEdit1->append("Error, filesize does not match with header.\n");
    fclose(inputfile);
    pushButton1->setEnabled(true);
    return;
  }

  block = (char *)malloc(SPCECGBUFSIZE);
  if(block == NULL)
  {
    textEdit1->append("Malloc error (block 1)\n");
    fclose(inputfile);
    pushButton1->setEnabled(true);
    return;
  }

  rewind(inputfile);

  if(fread(&sh_tmp, 2, 1, inputfile) != 1)
  {
    textEdit1->append("A read-error occurred (2)\n");
    fclose(inputfile);
    free(block);
    pushButton1->setEnabled(true);
    return;
  }

  if(check_crc(inputfile, 2LL, filesize - 2LL, sh_tmp, block))
  {
    fclose(inputfile);
    free(block);
    pushButton1->setEnabled(true);
    return;
  }

  memset(&sp, 0, sizeof(struct section_prop_struct[12]));

  if(read_section_header(0, inputfile, 6LL, block))
  {
    fclose(inputfile);
    free(block);
    pushButton1->setEnabled(true);
    return;
  }

  if(strncmp(sp[0].reserved, "SCPECG", 6))
  {
    textEdit1->append("Error, reserved field of section header 0 does not contain string \"SCPECG\".\n");
    fclose(inputfile);
    free(block);
    pushButton1->setEnabled(true);
    return;
  }

  sp[0].file_offset = 6LL;

// printf("\nsection ID is %i\n"
//        "section file offset is %lli\n"
//        "section CRC is 0x%04X\n"
//        "section length is %i\n"
//        "section version is %i\n"
//        "section protocol version is %i\n",
//        sp[0].section_id,
//        sp[0].file_offset,
//        (int)sp[0].crc,
//        sp[0].section_length,
//        sp[0].section_version,
//        sp[0].section_protocol_version);

  if(read_data_section_zero(inputfile, block, filesize))
  {
    fclose(inputfile);
    free(block);
    pushButton1->setEnabled(true);
    return;
  }

  fseeko(inputfile, sp[6].file_offset + 16LL, SEEK_SET);

  if(fread(block, 6, 1, inputfile) != 1)
  {
    textEdit1->append("A read-error occurred\n");
    fclose(inputfile);
    free(block);
    pushButton1->setEnabled(true);
    return;
  }

  avm = *((unsigned short *)block);

  sf = 1000000 / *((unsigned short *)(block + 2));

  encoding = *((unsigned char *)(block + 4));

  compression = *((unsigned char *)(block + 5));

  if(compression != 0)
  {
    textEdit1->append("File contains bimodal compressed data which is not supported by this converter.\n ");
    fclose(inputfile);
    free(block);
    pushButton1->setEnabled(true);
    return;
  }

  fseeko(inputfile, sp[3].file_offset + 16LL, SEEK_SET);

  if(fread(scratchpad, 2, 1, inputfile) != 1)
  {
    textEdit1->append("A read-error occurred (40)\n");
    fclose(inputfile);
    free(block);
    pushButton1->setEnabled(true);
    return;
  }

  chns = *((unsigned char *)scratchpad);

  if(chns < 1)
  {
    textEdit1->append("Error, number of signals is less than one.\n ");
    fclose(inputfile);
    free(block);
    pushButton1->setEnabled(true);
    return;
  }

  if(chns > 256)
  {
    textEdit1->append("Error, number of signals is more than 256.\n ");
    fclose(inputfile);
    free(block);
    pushButton1->setEnabled(true);
    return;
  }

  if(scratchpad[1] & 1)
  {
    textEdit1->append("Reference beat subtraction used for compression which is not supported by this converter.\n ");
    fclose(inputfile);
    free(block);
    pushButton1->setEnabled(true);
    return;
  }

  if(!(scratchpad[1] & 4))
  {
    textEdit1->append("Leads are not simultaneously recorded which is not supported by this converter. (1)\n ");
    fclose(inputfile);
    free(block);
    pushButton1->setEnabled(true);
    return;
  }

// printf("chns is %u   AVM is %u   sf is %u   encoding is %u   compression is %u\n",
//        chns, avm, sf, encoding, compression);

  memset(&lp, 0, sizeof(struct lead_prop_struct[256]));

  fseeko(inputfile, sp[3].file_offset + 18LL, SEEK_SET);

  for(i=0; i<chns; i++)
  {
    if(fread(&(lp[i].start), 4, 1, inputfile) != 1)
    {
      textEdit1->append("A read-error occurred (30)\n");
      fclose(inputfile);
      free(block);
      pushButton1->setEnabled(true);
      return;
    }

    if(fread(&(lp[i].end), 4, 1, inputfile) != 1)
    {
      textEdit1->append("A read-error occurred (31)\n");
      fclose(inputfile);
      free(block);
      pushButton1->setEnabled(true);
      return;
    }

    if(fread(&(lp[i].label), 1, 1, inputfile) != 1)
    {
      textEdit1->append("A read-error occurred (32)\n");
      fclose(inputfile);
      free(block);
      pushButton1->setEnabled(true);
      return;
    }
  }

// for(i=0; i<chns; i++)
// {
//   printf("lp[i].start is %i   lp[i].end is %i\n", lp[i].start, lp[i].end);
// }

  if(chns > 1)
  {
    for(i=1; i<chns; i++)
    {
      if(lp[i].start != lp[0].start)
      {
        textEdit1->append("Error, leads are not simultaneously recorded. (2)\n");
        fclose(inputfile);
        free(block);
        pushButton1->setEnabled(true);
        return;
      }

      if(lp[i].end != lp[0].end)
      {
        textEdit1->append("Error, leads are not simultaneously recorded. (3)\n");
        fclose(inputfile);
        free(block);
        pushButton1->setEnabled(true);
        return;
      }
    }
  }

  for(i=0; i<chns; i++)
  {
    if(lp[i].start < 1)
    {
      textEdit1->append("Error, start sample number in section 3 is less than 1.\n");
      fclose(inputfile);
      free(block);
      pushButton1->setEnabled(true);
      return;
    }

    if(lp[i].end <= lp[i].start)
    {
      textEdit1->append("Error (56) (lp[i].end <= lp[i].start)\n");
      fclose(inputfile);
      free(block);
      pushButton1->setEnabled(true);
      return;
    }

    if(lp[i].start != 1)
    {
      textEdit1->append("Error (57) (lp[i].start != 1)\n");
      fclose(inputfile);
      free(block);
      pushButton1->setEnabled(true);
      return;
    }

    lp[i].start--;

    if((lp[i].end - lp[i].start) < sf)
    {
      textEdit1->append("Error, recording length is less than one second.\n");
      fclose(inputfile);
      free(block);
      pushButton1->setEnabled(true);
      return;
    }

    lp[i].samples = lp[i].end - lp[i].start;
  }

  fseeko(inputfile, sp[6].file_offset + 22LL, SEEK_SET);

  n = 0;

  for(i=0; i<chns; i++)
  {
    if(fread(block, 2, 1, inputfile) != 1)
    {
      textEdit1->append("A read-error occurred (41)\n");
      fclose(inputfile);
      free(block);
      pushButton1->setEnabled(true);
      return;
    }

    lp[i].bytes = *((unsigned short *)block);

    n += lp[i].bytes;

// printf("lead samples is %i   bytes is %i\n", lp[i].samples, lp[i].bytes);

    if(sp[2].present != 1)  // huffmantable
    {
      if(lp[i].bytes < (lp[i].samples * 2))
      {
        textEdit1->append("Error, lead samples is less than lead bytes.\n");
        fclose(inputfile);
        free(block);
        pushButton1->setEnabled(true);
        return;
      }
    }
  }

  if(n > (sp[6].section_length - 22 - (chns * 2)))
  {
    textEdit1->append("Error, total databytes is more than section size.\n");
    fclose(inputfile);
    free(block);
    pushButton1->setEnabled(true);
    return;
  }

//////////////////////////////// Huffman tables ////////////////////

  if(sp[2].present == 1)  // huffmantable
  {
    fseeko(inputfile, sp[2].file_offset + 16LL, SEEK_SET);

    if(fread(block, 13, 1, inputfile) != 1)
    {
      textEdit1->append("A read-error occurred (50)\n");
      fclose(inputfile);
      free(block);
      pushButton1->setEnabled(true);
      return;
    }

    ht.h_tables_cnt = *((unsigned short *)block);
    ht.code_structs_cnt = *((unsigned short *)(block + 2));
    ht.prefix_bits = *((unsigned char *)(block + 4));
    ht.total_bits = *((unsigned char *)(block + 5));
    ht.table_mode_switch = *((unsigned char *)(block + 6));
    ht.base_value = *((unsigned short *)(block + 7));
    ht.base_code = *((unsigned int *)(block + 9));

//   printf("ht.h_tables_cnt is %i   ht.code_structs_cnt is %i   ht.prefix_bits is %i   ht.total_bits is %i\n",
//         ht.h_tables_cnt, ht.code_structs_cnt, ht.prefix_bits, ht.total_bits);

    if(ht.h_tables_cnt != 19999)
    {
      textEdit1->append("Aborted, this converter does not support customized Huffmantables.\n");
      fclose(inputfile);
      free(block);
      pushButton1->setEnabled(true);
      return;
    }
  }

//////////////////////////////// patient data ////////////////////

  memset(&pat_dat, 0, sizeof(struct patient_data_struct));

  if(get_patient_data(inputfile))
  {
    fclose(inputfile);
    free(block);
    pushButton1->setEnabled(true);
    return;
  }

// printf("patient ID:          %s\n"
//        "patient lastname:    %s\n"
//        "patient firstname:   %s\n"
//        "patient sex:         %i\n"
//        "startdate year:      %i\n"
//        "startdate month:     %i\n"
//        "startdate day:       %i\n"
//        "starttime hour:      %i\n"
//        "starttime minute:    %i\n"
//        "starttime second:    %i\n"
//        "birthdate year:      %i\n"
//        "birthdate month:     %i\n"
//        "birthdate day:       %i\n"
//        "device model:        %s\n"
//        "language code:       %u\n"
//        "manufacturer:        %s\n",
//        pat_dat.pat_id,
//        pat_dat.last_name,
//        pat_dat.first_name,
//        pat_dat.sex,
//        pat_dat.startdate_year,
//        pat_dat.startdate_month,
//        pat_dat.startdate_day,
//        pat_dat.starttime_hour,
//        pat_dat.starttime_minute,
//        pat_dat.starttime_second,
//        pat_dat.birthdate_year,
//        pat_dat.birthdate_month,
//        pat_dat.birthdate_day,
//        pat_dat.device_model,
//        pat_dat.lang_code,
//        pat_dat.manufacturer);

////////////////////////// start conversion ///////////////////////////////

  free(block);

  buf = (int *)malloc(((lp[0].samples / sf) + 1) * chns * sf * sizeof(int));
  if(buf == NULL)
  {
    textEdit1->append("Malloc error (buf)\n");
    fclose(inputfile);
    pushButton1->setEnabled(true);
    return;
  }

  n = 0;

  for(i=0; i<chns; i++)
  {
    n += lp[i].bytes;
  }

  block = (char *)calloc(1, n + 64);
  if(block == NULL)
  {
    textEdit1->append("Malloc error (block 3)\n");
    fclose(inputfile);
    free(buf);
    pushButton1->setEnabled(true);
    return;
  }

  fseeko(inputfile, sp[6].file_offset + 22LL + (chns * 2LL), SEEK_SET);  // rhythm data

  if(fread(block, n, 1, inputfile) != 1)
  {
    textEdit1->append("A read-error occurred during conversion (70)\n");
    fclose(inputfile);
    free(buf);
    free(block);
    pushButton1->setEnabled(true);
    return;
  }

  offset = 0;

  for(j=0; j<chns; j++)
  {
    if(j > 0)
    {
      offset += lp[j - 1].bytes;
    }

    bits = 0LL;

    for(i=0; i<lp[j].samples; i++)
    {
      if(sp[2].present == 1)  // huffmantable present
      {
        if((bits / 8LL) > lp[j].bytes)
        {
          textEdit1->append("Error, (bits / 8) >= lp[j].bytes (71)\n");
          fclose(inputfile);
          free(buf);
          free(block);
          pushButton1->setEnabled(true);
          return;
        }

        memcpy(&var, block + offset + ((int)(bits / 8LL)), 5);

        for(k=0; k<5; k++)
        {
          var.four[k] = reverse_bitorder(var.four[k]);
        }

        var.ll_int >>= (int)(bits % 8LL);

        if((var.four[0] & 1) == 0)  // b00000001
        {
          buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = 0;
          bits++;
        } else
        if((var.four[0] & 7) == 1)  // b00000111
        {
          buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = 1;
          bits += 3LL;
        } else
        if((var.four[0] & 7) == 5)  // b00000111
        {
          buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = -1;
          bits += 3LL;
        } else
        if((var.four[0] & 15) == 3)  // b00001111
        {
          buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = 2;
          bits += 4LL;
        } else
        if((var.four[0] & 15) == 11)  // b00001111
        {
          buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = -2;
          bits += 4LL;
        } else
        if((var.four[0] & 31) == 7)  // b00011111
        {
          buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = 3;
          bits += 5LL;
        } else
        if((var.four[0] & 31) == 23)  // b00011111
        {
          buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = -3;
          bits += 5LL;
        } else
        if((var.four[0] & 63) == 15)  // b00111111
        {
          buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = 4;
          bits += 6LL;
        } else
        if((var.four[0] & 63) == 47)  // b00111111
        {
          buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = -4;
          bits += 6LL;
        } else
        if((var.four[0] & 127) == 31)  // b01111111
        {
          buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = 5;
          bits += 7LL;
        } else
        if((var.four[0] & 127) == 95)  // b01111111
        {
          buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = -5;
          bits += 7LL;
        } else
        if(var.four[0] == 63)  // b11111111
        {
          buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = 6;
          bits += 8LL;
        } else
        if(var.four[0] == 191)  // b11111111
        {
          buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = -6;
          bits += 8LL;
        } else
        if(var.four[0] == 127)  // b11111111
        {
          if((var.four[1] & 1) == 0)  // b00000001
          {
            buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = 7;
            bits += 9LL;
          }
          else
          {
            buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = -7;
            bits += 9LL;
          }
        } else
        if(var.four[0] == 255)  // b11111111
        {
          if((var.four[1] & 3) == 0)  // b00000011
          {
            buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = 8;
            bits += 10LL;
          } else
          if((var.four[1] & 3) == 2)  // b00000011
          {
            buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = -8;
            bits += 10LL;
          } else
          if((var.four[1] & 3) == 1)  // b00000011
          {
            var.ll_int >>= 2;
            var.four[1] = reverse_bitorder(var.four[1]);
            buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = *((signed char *)&(var.four[1]));  // 8-bit original
            bits += 18LL;
          } else
          if((var.four[1] & 3) == 3)  // b00000011
          {
            var.ll_int >>= 10;
            ch_tmp = reverse_bitorder(var.four[0]);
            var.four[0] = reverse_bitorder(var.four[1]);
            var.four[1] = ch_tmp;
            buf[((i / sf) * (sf * chns)) + (j * sf) + (i % sf)] = *((signed short *)&(var.two[0]));  // 16-bit original
            bits += 26LL;
          }
        }
      }
void UI_AverageCurveWindow::export_edf(void)
{
  int i, j, k, p,
      type,
      edf_hdl,
      smp_per_record,
      datarecords,
      smpls_left;

  char path[MAX_PATH_LENGTH],
       str[512];

  double *buf,
         frequency,
         frequency2;


  smp_per_record = signalcomp->edfhdr->edfparam[signalcomp->edfsignal[0]].smp_per_record;

  datarecords = avg_samples_on_screen / smp_per_record;

  smpls_left = avg_samples_on_screen % smp_per_record;

  path[0] = 0;
  if(mainwindow->recent_savedir[0]!=0)
  {
    strcpy(path, mainwindow->recent_savedir);
    strcat(path, "/");
  }
  get_filename_from_path(path + strlen(path), signalcomp->edfhdr->filename, 512);
  remove_extension_from_filename(path);
  sprintf(path + strlen(path), " averaging %s %i triggers [%s]",
          signalcomp->signallabel,
          avg_cnt,
          avg_annotation);

  if(signalcomp->edfhdr->edf)
  {
    strcat(path, ".edf");

    strcpy(path, QFileDialog::getSaveFileName(0, "Save as EDF", QString::fromLocal8Bit(path), "EDF files (*.edf *.EDF)").toLocal8Bit().data());
  }
  else
  {
    strcat(path, ".bdf");

    strcpy(path, QFileDialog::getSaveFileName(0, "Save as BDF", QString::fromLocal8Bit(path), "BDF files (*.bdf *.BDF)").toLocal8Bit().data());
  }

  if(!strcmp(path, ""))
  {
    return;
  }

  get_directory_from_path(mainwindow->recent_savedir, path, MAX_PATH_LENGTH);

  if(signalcomp->edfhdr->edf)
  {
    edf_hdl = edfopen_file_writeonly(path, EDFLIB_FILETYPE_EDFPLUS, 1);
  }
  else
  {
    edf_hdl = edfopen_file_writeonly(path, EDFLIB_FILETYPE_BDFPLUS, 1);
  }

  if(edf_hdl < 0)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Can not open output file for writing.");
    messagewindow.exec();
    return;
  }

  edf_set_samplefrequency(edf_hdl, 0, smp_per_record);

  if(edf_set_datarecord_duration(edf_hdl, signalcomp->edfhdr->long_data_record_duration / 100LL))
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Datarecordduration out of range.");
    messagewindow.exec();
    return;
  }

  if(signalcomp->edfhdr->edf)
  {
    edf_set_digital_maximum(edf_hdl, 0, 32767);
    edf_set_digital_minimum(edf_hdl, 0, -32768);
  }
  else
  {
    edf_set_digital_maximum(edf_hdl, 0, 8388607);
    edf_set_digital_minimum(edf_hdl, 0, -8388608);
  }

  edf_set_physical_maximum(edf_hdl, 0, avg_max_value);
  edf_set_physical_minimum(edf_hdl, 0, avg_min_value);
  edf_set_label(edf_hdl, 0, signalcomp->signallabel);
  edf_set_physical_dimension(edf_hdl, 0, signalcomp->physdimension);

  p = 0;

  for(j=0; j<signalcomp->fidfilter_cnt; j++)
  {
    type = signalcomp->fidfilter_type[j];

    frequency = signalcomp->fidfilter_freq[j];

    frequency2 = signalcomp->fidfilter_freq2[j];

    if(type == 0)
    {
      p += sprintf(str + p, "HP:%f", frequency);
    }

    if(type == 1)
    {
      p += sprintf(str + p, "LP:%f", frequency);
    }

    if(type == 2)
    {
      p += sprintf(str + p, "N:%f", frequency);
    }

    if(type == 3)
    {
      p += sprintf(str + p, "BP:%f", frequency);
    }

    if(type == 4)
    {
      p += sprintf(str + p, "BS:%f", frequency);
    }

    for(k=(p-1); k>0; k--)
    {
      if(str[k]!='0')  break;
    }

    if(str[k]=='.')  str[k] = 0;
    else  str[k+1] = 0;

    p = strlen(str);

    if((type == 3) || (type == 4))
    {
      p += sprintf(str + p, "-%f", frequency2);

      for(k=(p-1); k>0; k--)
      {
        if(str[k]!='0')  break;
      }

      if(str[k]=='.')  str[k] = 0;
      else  str[k+1] = 0;
    }

    strcat(str, "Hz ");

    p = strlen(str);

    if(p>80)  break;
  }

  for(j=0; j<signalcomp->ravg_filter_cnt; j++)
  {
    if(signalcomp->ravg_filter_type[j] == 0)
    {
      p += sprintf(str + p, "HP:%iSmpls ", signalcomp->ravg_filter[j]->size);
    }

    if(signalcomp->ravg_filter_type[j] == 1)
    {
      p += sprintf(str + p, "LP:%iSmpls ", signalcomp->ravg_filter[j]->size);
    }

    p = strlen(str);

    if(p>80)  break;
  }

  strcat(str, signalcomp->edfhdr->edfparam[signalcomp->edfsignal[0]].prefilter);
  edf_set_prefilter(edf_hdl, 0, str);
  edf_set_transducer(edf_hdl, 0, signalcomp->edfhdr->edfparam[signalcomp->edfsignal[0]].transducer);

  if((signalcomp->edfhdr->edfplus) || (signalcomp->edfhdr->bdfplus))
  {
    edf_set_patientname(edf_hdl, signalcomp->edfhdr->plus_patient_name);
    sprintf(str, "%i triggers \"%s\" averaged. %s", avg_cnt, avg_annotation, signalcomp->edfhdr->plus_recording_additional);
    edf_set_recording_additional(edf_hdl, str);
    edf_set_patientcode(edf_hdl, signalcomp->edfhdr->plus_patientcode);
    if(signalcomp->edfhdr->plus_gender[0] == 'M')
    {
      edf_set_gender(edf_hdl, 1);
    }
    if(signalcomp->edfhdr->plus_gender[0] == 'F')
    {
      edf_set_gender(edf_hdl, 0);
    }
    edf_set_patient_additional(edf_hdl, signalcomp->edfhdr->plus_patient_additional);
    edf_set_admincode(edf_hdl, signalcomp->edfhdr->plus_admincode);
    edf_set_technician(edf_hdl, signalcomp->edfhdr->plus_technician);
    edf_set_equipment(edf_hdl, signalcomp->edfhdr->plus_equipment);
  }
  else
  {
    edf_set_patientname(edf_hdl, signalcomp->edfhdr->patient);
    sprintf(str, "%i triggers \"%s\" averaged. %s", avg_cnt, avg_annotation, signalcomp->edfhdr->recording);
    edf_set_recording_additional(edf_hdl, str);
  }

  for(i=0; i<datarecords; i++)
  {
    edfwrite_physical_samples(edf_hdl, avgbuf + (i * smp_per_record));
  }

  if(smpls_left)
  {
    buf = (double *)calloc(1, smp_per_record * sizeof(double));
    if(buf == NULL)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "Malloc error (buf).");
      messagewindow.exec();
    }
    else
    {
      for(i=0; i<smpls_left; i++)
      {
        buf[i] = avgbuf[(datarecords * smp_per_record) + i];
      }

      edfwrite_physical_samples(edf_hdl, buf);

      free(buf);
    }
  }

  edfwrite_annotation_latin1(edf_hdl,
                             (avg_period * 10000.0) / (double)avg_trigger_position_ratio,
                             -1,
                             avg_annotation);

  edfclose_file(edf_hdl);
}
Exemple #12
0
void UI_BDF2EDFwindow::StartConversion()
{
  int i, j, k,
      datrecs,
      new_edfsignals,
      datarecords,
      len,
      progress_steps;

  char *readbuf,
       scratchpad[256];

  union {
          unsigned int one;
          signed int one_signed;
          unsigned short two[2];
          signed short two_signed[2];
          unsigned char four[4];
        } var;

  union {
          signed short one_short;
          unsigned char two_bytes[2];
        } var2;



  pushButton3->setEnabled(false);
  pushButton4->setEnabled(false);
  pushButton5->setEnabled(false);

  if(edfhdr==NULL)
  {
    return;
  }

  if(edfhdr->edfsignals>MAXSIGNALS)
  {
    return;
  }

  new_edfsignals = 0;

  for(i=0; i<edfhdr->edfsignals; i++)
  {
    if(!edfhdr->edfparam[i].annotation)
    {
      if(((QCheckBox *)(SignalsTablewidget->cellWidget(i, 0)))->checkState()==Qt::Checked)
      {
        signalslist[new_edfsignals] = i;

        annotlist[new_edfsignals] = 0;

        filterlist[new_edfsignals] = create_filter(0,
                                                  ((QDoubleSpinBox *)(SignalsTablewidget->cellWidget(i, 1)))->value(),
                                                  1.0 / (edfhdr->data_record_duration / edfhdr->edfparam[i].smp_per_record));

        dividerlist[new_edfsignals] = ((QDoubleSpinBox *)(SignalsTablewidget->cellWidget(i, 2)))->value();

        new_edfsignals++;
      }
    }
    else
    {
      signalslist[new_edfsignals] = i;

      annotlist[new_edfsignals] = 1;

      filterlist[new_edfsignals] = create_filter(0, 0.01,
                                                1.0 / (edfhdr->data_record_duration / edfhdr->edfparam[i].smp_per_record));
      dividerlist[new_edfsignals] = 1.0;

      new_edfsignals++;
    }
  }

  datarecords = edfhdr->datarecords;

  QProgressDialog progress("Converting...", "Abort", 0, datarecords, myobjectDialog);
  progress.setWindowModality(Qt::WindowModal);
  progress.setMinimumDuration(200);
  progress.reset();

  if(!new_edfsignals)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "You must select at least one signal.");
    messagewindow.exec();
    goto END_1;
  }

  readbuf = (char *)malloc(edfhdr->recordsize);
  if(readbuf==NULL)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Malloc error, (readbuf).");
    messagewindow.exec();
    goto END_2;
  }

/////////////////////////// write header ////////////////////////////////////////

  outputpath[0] = 0;

  if(recent_savedir[0]!=0)
  {
    strcpy(outputpath, recent_savedir);
    strcat(outputpath, "/");
  }
  len = strlen(outputpath);
  get_filename_from_path(outputpath + len, inputpath, MAX_PATH_LENGTH - len);
  remove_extension_from_filename(outputpath);

  strcat(outputpath, ".edf");

  strcpy(outputpath, QFileDialog::getSaveFileName(0, "Select outputfile", QString::fromLocal8Bit(outputpath), "EDF files (*.edf *.EDF)").toLocal8Bit().data());

  if(!strcmp(outputpath, ""))
  {
    goto END_2;
  }

  get_directory_from_path(recent_savedir, outputpath, MAX_PATH_LENGTH);

  if(mainwindow->file_is_opened(outputpath))
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Error, selected file is in use.");
    messagewindow.exec();
    goto END_2;
  }

  outputfile = fopeno(outputpath, "wb");
  if(outputfile==NULL)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Can not open outputfile for writing.");
    messagewindow.exec();
    goto END_2;
  }

  fprintf(outputfile, "0       ");
  fseeko(inputfile, 8LL, SEEK_SET);
  if(fread(scratchpad, 176, 1, inputfile)!=1)
  {
    showpopupmessage("Error", "Read error (1).");
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Read error (1).");
    messagewindow.exec();
    goto END_3;
  }
  if(fwrite(scratchpad, 176, 1, outputfile)!=1)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Write error (1).");
    messagewindow.exec();
    goto END_3;
  }
  fprintf(outputfile, "%-8i", new_edfsignals * 256 + 256);
  if(edfhdr->bdfplus)
  {
    if(edfhdr->discontinuous)
    {
      fprintf(outputfile, "EDF+D");
    }
    else
    {
      fprintf(outputfile, "EDF+C");
    }
    for(i=0; i<39; i++)
    {
      fputc(' ', outputfile);
    }
  }
  else
  {
    for(i=0; i<44; i++)
    {
      fputc(' ', outputfile);
    }
  }
  fprintf(outputfile, "%-8i", datarecords);
  snprintf(scratchpad, 256, "%f", edfhdr->data_record_duration);
  convert_trailing_zeros_to_spaces(scratchpad);
  if(scratchpad[7]=='.')
  {
    scratchpad[7] = ' ';
  }
  scratchpad[8] = 0;

  fprintf(outputfile, "%s", scratchpad);
  fprintf(outputfile, "%-4i", new_edfsignals);

  for(i=0; i<new_edfsignals; i++)
  {
    if(annotlist[i])
    {
      fprintf(outputfile, "EDF Annotations ");
    }
    else
    {
      fprintf(outputfile, "%s", edfhdr->edfparam[signalslist[i]].label);
    }
  }
  for(i=0; i<new_edfsignals; i++)
  {
    fprintf(outputfile, "%s", edfhdr->edfparam[signalslist[i]].transducer);
  }
  for(i=0; i<new_edfsignals; i++)
  {
    fprintf(outputfile, "%s", edfhdr->edfparam[signalslist[i]].physdimension);
  }
  for(i=0; i<new_edfsignals; i++)
  {
    if(annotlist[i])
    {
      fprintf(outputfile, "-1      ");
    }
    else
    {
      snprintf(scratchpad, 256, "%f", edfhdr->edfparam[signalslist[i]].bitvalue * -32768.0 * dividerlist[i]);
      convert_trailing_zeros_to_spaces(scratchpad);
      if(scratchpad[7]=='.')
      {
        scratchpad[7] = ' ';
      }
      scratchpad[8] = 0;
      fprintf(outputfile, "%s", scratchpad);
    }
  }
  for(i=0; i<new_edfsignals; i++)
  {
    if(annotlist[i])
    {
      fprintf(outputfile, "1       ");
    }
    else
    {
      snprintf(scratchpad, 256, "%f", edfhdr->edfparam[signalslist[i]].bitvalue * 32767.0 * dividerlist[i]);
      convert_trailing_zeros_to_spaces(scratchpad);
      if(scratchpad[7]=='.')
      {
        scratchpad[7] = ' ';
      }
      scratchpad[8] = 0;
      fprintf(outputfile, "%s", scratchpad);
    }
  }
  for(i=0; i<new_edfsignals; i++)
  {
    fprintf(outputfile, "-32768  ");
  }
  for(i=0; i<new_edfsignals; i++)
  {
    fprintf(outputfile, "32767   ");
  }
  for(i=0; i<new_edfsignals; i++)
  {
    if(annotlist[i])
    {
      for(j=0; j<80; j++)
      {
        fputc(' ', outputfile);
      }
    }
    else
    {
      snprintf(scratchpad, 256, "HP:%f", ((QDoubleSpinBox *)(SignalsTablewidget->cellWidget(signalslist[i], 1)))->value());
      remove_trailing_zeros(scratchpad);
      strcat(scratchpad, "Hz ");

      strcat(scratchpad, edfhdr->edfparam[signalslist[i]].prefilter);

      for(j=strlen(scratchpad); j<200; j++)
      {
        scratchpad[j] = ' ';
      }

      scratchpad[200] = 0;

      for(j=0; j<80; j++)
      {
        if(!strncmp(scratchpad + j, "No filtering", 12))
        {
          for(k=j; k<(j+12); k++)
          {
            scratchpad[k] = ' ';
          }
        }
      }

      for(j=0; j<80; j++)
      {
        if(!strncmp(scratchpad + j, "None", 4))
        {
          for(k=j; k<(j+4); k++)
          {
            scratchpad[k] = ' ';
          }
        }
      }

      for(j=0; j<80; j++)
      {
        if(!strncmp(scratchpad + j, "HP: DC;", 7))
        {
          for(k=j; k<(j+7); k++)
          {
            scratchpad[k] = ' ';
          }
        }
      }

      scratchpad[80] = 0;

      fprintf(outputfile, "%s", scratchpad);
    }
  }
  for(i=0; i<new_edfsignals; i++)
  {
    if(annotlist[i])
    {
      if(edfhdr->edfparam[signalslist[i]].smp_per_record % 2)
      {
        fprintf(outputfile, "%-8i", ((edfhdr->edfparam[signalslist[i]].smp_per_record * 15) / 10) + 1);
      }
      else
      {
        fprintf(outputfile, "%-8i", (edfhdr->edfparam[signalslist[i]].smp_per_record * 15) / 10);
      }
    }
    else
    {
      fprintf(outputfile, "%-8i", edfhdr->edfparam[signalslist[i]].smp_per_record);
    }
  }
  for(i=0; i<(new_edfsignals * 32); i++)
  {
   fputc(' ', outputfile);
  }

///////////////////////////// start conversion //////////////////////////////////////

  progress_steps = datarecords / 100;
  if(progress_steps < 1)
  {
    progress_steps = 1;
  }

  fseeko(inputfile, (long long)(edfhdr->hdrsize), SEEK_SET);

  for(datrecs=0; datrecs<datarecords; datrecs++)
  {
    if(!(datrecs%progress_steps))
    {
      progress.setValue(datrecs);

      qApp->processEvents();

      if(progress.wasCanceled() == true)
      {
        goto END_3;
      }
    }

    if(fread(readbuf, edfhdr->recordsize, 1, inputfile) != 1)
    {
      progress.reset();
      showpopupmessage("Error", "Read error (2).");
      goto END_3;
    }

    for(i=0; i<new_edfsignals; i++)
    {
      if(annotlist[i])
      {
        if(fwrite(readbuf + edfhdr->edfparam[signalslist[i]].buf_offset, edfhdr->edfparam[signalslist[i]].smp_per_record * 3, 1, outputfile)!=1)
        {
          progress.reset();
          showpopupmessage("Error", "Write error (2).");
          goto END_3;
        }

        if(edfhdr->edfparam[signalslist[i]].smp_per_record % 2)
        {
          if(fputc(0, outputfile)==EOF)
          {
            progress.reset();
            showpopupmessage("Error", "Write error (3).");
            goto END_3;
          }
        }
      }
      else
      {
        for(j=0; j<edfhdr->edfparam[signalslist[i]].smp_per_record; j++)
        {
          var.two[0] = *((unsigned short *)(readbuf + edfhdr->edfparam[signalslist[i]].buf_offset + (j * 3)));

          var.four[2] = *((unsigned char *)(readbuf + edfhdr->edfparam[signalslist[i]].buf_offset + (j * 3) + 2));

          if(var.four[2]&0x80)
          {
            var.four[3] = 0xff;
          }
          else
          {
            var.four[3] = 0x00;
          }

          var.one_signed += edfhdr->edfparam[signalslist[i]].offset;

          var.one_signed = first_order_filter(var.one_signed, filterlist[i]);

          var.one_signed /= dividerlist[i];

          if(var.one_signed>32767)  var.one_signed = 32767;

          if(var.one_signed<-32768)  var.one_signed = -32768;

          var2.one_short = var.one_signed;

          fputc(var2.two_bytes[0], outputfile);
          if(fputc(var2.two_bytes[1], outputfile)==EOF)
          {
            progress.reset();
            showpopupmessage("Error", "Write error (4).");
            goto END_3;
          }
        }
      }
    }
  }

  progress.reset();
  showpopupmessage("Ready", "Done.");

END_3:

  fclose(outputfile);
  outputfile = NULL;

END_2:

  free(readbuf);

END_1:

  for(i=0; i<new_edfsignals; i++)
  {
    free(filterlist[i]);
  }

  fclose(inputfile);
  inputfile = NULL;

  inputpath[0] = 0;
  outputpath[0] = 0;

  free_edfheader();

  label1->setText("");

  SignalsTablewidget->setRowCount(0);
}
Exemple #13
0
void UI_NEXFIN2EDFwindow::SelectFileButton()
{
  FILE *inputfile=NULL,
       *outputfile=NULL;

  int i, j, k, p,
      temp,
      separator=';',
      edfsignals=0,
      ok,
      timestep,
      new_smpl_time=0,
      str_start,
      column,
      line_nr;

  long long datarecords=-1LL,
            file_size;

  char txt_string[2048],
       path[512],
       outputfilename[MAX_PATH_LENGTH],
       line[2048],
       scratchpad[128],
       labels[MAX_SIGNALS][17],
       phys_dim[MAX_SIGNALS][9],
       phys_min[MAX_SIGNALS][9],
       phys_max[MAX_SIGNALS][9],
       patientname[81],
       recording[81],
       datetime[17];


  double sensitivity[MAX_SIGNALS],
         new_value[MAX_SIGNALS],
         old_value[MAX_SIGNALS];

  union{
         short two;
         char one[2];
       } var;


  if(radio100button->isChecked()==true)
  {
    file_type = 100;
  }

  if(radio103button->isChecked()==true)
  {
    file_type = 103;
  }

  if(radio032button->isChecked()==true)
  {
    file_type = 32;
  }

  for(j=0; j<MAX_SIGNALS; j++)
  {
    old_value[j] = 0.0;
  }

  enable_widgets(false);

  if(!(strlen(PatientnameLineEdit->text().toLatin1().data())))
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Invalid input", "Please enter a subject name.");
    messagewindow.exec();
    enable_widgets(true);
    return;
  }

  if(!(strlen(RecordingLineEdit->text().toLatin1().data())))
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Invalid input", "Please enter a recordingdescription.");
    messagewindow.exec();
    enable_widgets(true);
    return;
  }

  if(file_type==100)
  {
    strcpy(path, QFileDialog::getOpenFileName(0, "Select inputfile", QString::fromLocal8Bit(recent_opendir), "CSV files (*_100.csv *_100.CSV)").toLocal8Bit().data());
  }

  if(file_type==103)
  {
    strcpy(path, QFileDialog::getOpenFileName(0, "Select inputfile", QString::fromLocal8Bit(recent_opendir), "BIN files (*_103.bin *_103.BIN)").toLocal8Bit().data());
  }

  if(file_type==32)
  {
    strcpy(path, QFileDialog::getOpenFileName(0, "Select inputfile", QString::fromLocal8Bit(recent_opendir), "BIN files (*_032.bin *_032.BIN)").toLocal8Bit().data());
  }

  if(!strcmp(path, ""))
  {
    enable_widgets(true);
    return;
  }

  get_directory_from_path(recent_opendir, path, MAX_PATH_LENGTH);

  inputfile = fopeno(path, "rb");
  if(inputfile==NULL)
  {
    snprintf(txt_string, 2048, "Can not open file %s for reading.", path);
    QMessageBox messagewindow(QMessageBox::Critical, "Error", QString::fromLocal8Bit(txt_string));
    messagewindow.exec();
    enable_widgets(true);
    return;
  }

  if(file_type==100)
  {
/***************** check if the txtfile is valid ******************************/

  rewind(inputfile);

  if(fread(scratchpad, 32, 1, inputfile)!=1)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Can not read from file.");
    messagewindow.exec();
    fclose(inputfile);
    enable_widgets(true);
    return;
  }

  if(strncmp(scratchpad, "Time;IBI;HR;LVET;HRS;Sys;Dia;MAP", 32))
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Unknown data in file (1).");
    messagewindow.exec();
    fclose(inputfile);
    enable_widgets(true);
    return;
  }

/***************** collect items *****************************************/

  rewind(inputfile);

  while(1)
  {
    temp = fgetc(inputfile);

    if(temp==EOF)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "Reached end of file unexpectedly (5).");
      messagewindow.exec();
      fclose(inputfile);
      enable_widgets(true);
      return;
    }

    if(temp==separator)
    {
      break;
    }
  }

  i = 0;

  while(temp!='\n')
  {
    temp = fgetc(inputfile);

    if(temp==EOF)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "Reached end of file unexpectedly (6).");
      messagewindow.exec();
      fclose(inputfile);
      enable_widgets(true);
      return;
    }

    if(temp=='\r')
    {
      continue;
    }

    if(((temp==separator)||(temp=='\n'))&&(edfsignals<7))
    {
      if(edfsignals>=MAX_SIGNALS)
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "Too many labels/signals (7).");
        messagewindow.exec();
        fclose(inputfile);
        enable_widgets(true);
        return;
      }

      line[i] = 0;

      ok = 0;

      if(!strcmp(line, "IBI"))
      {
        strcpy(labels[edfsignals], "IBI             ");
        strcpy(phys_dim[edfsignals], "s       ");
        strcpy(phys_min[edfsignals], "-31.744 ");
        strcpy(phys_max[edfsignals], "31.744  ");
        sensitivity[edfsignals] = 1000.0;
        ok = 1;
      }

      if(!strcmp(line, "HR"))
      {
        strcpy(labels[edfsignals], "HR              ");
        strcpy(phys_dim[edfsignals], "bpm     ");
        strcpy(phys_min[edfsignals], "-1024   ");
        strcpy(phys_max[edfsignals], "1024    ");
        sensitivity[edfsignals] = 31.0;
        ok = 1;
      }

      if(!strcmp(line, "LVET"))
      {
        strcpy(labels[edfsignals], "LVET            ");
        strcpy(phys_dim[edfsignals], "s       ");
        strcpy(phys_min[edfsignals], "-10     ");
        strcpy(phys_max[edfsignals], "10      ");
        sensitivity[edfsignals] = 3174.4;
        ok = 1;
      }

      if(!strcmp(line, "HRS"))
      {
        strcpy(labels[edfsignals], "HRS             ");
        strcpy(phys_dim[edfsignals], "mmHg    ");
        strcpy(phys_min[edfsignals], "-1024   ");
        strcpy(phys_max[edfsignals], "1024    ");
        sensitivity[edfsignals] = 31.0;
        ok = 1;
      }

      if(!strcmp(line, "Sys"))
      {
        strcpy(labels[edfsignals], "Sys             ");
        strcpy(phys_dim[edfsignals], "mmHg    ");
        strcpy(phys_min[edfsignals], "-1024   ");
        strcpy(phys_max[edfsignals], "1024    ");
        sensitivity[edfsignals] = 31.0;
        ok = 1;
      }

      if(!strcmp(line, "Dia"))
      {
        strcpy(labels[edfsignals], "Dia             ");
        strcpy(phys_dim[edfsignals], "mmHg    ");
        strcpy(phys_min[edfsignals], "-1024   ");
        strcpy(phys_max[edfsignals], "1024    ");
        sensitivity[edfsignals] = 31.0;
        ok = 1;
      }

      if(!strcmp(line, "MAP"))
      {
        strcpy(labels[edfsignals], "MAP             ");
        strcpy(phys_dim[edfsignals], "mmHg    ");
        strcpy(phys_min[edfsignals], "-1024   ");
        strcpy(phys_max[edfsignals], "1024    ");
        sensitivity[edfsignals] = 31.0;
        ok = 1;
      }

      if(!ok)
      {
        snprintf(txt_string, 2048, "Found unknown label/signal: %s", line);
        QMessageBox messagewindow(QMessageBox::Critical, "Error", txt_string);
        messagewindow.exec();
        fclose(inputfile);
        enable_widgets(true);
        return;
      }

      edfsignals++;

      i = 0;
    }

    if(temp==separator)
    {
      continue;
    }

    line[i++] = temp;
  }

  if(!edfsignals)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "There are no labels/signals.");
    messagewindow.exec();
    fclose(inputfile);
    enable_widgets(true);
    return;
  }

  }  /********** end if(file_type==100)  ********************/

  if(file_type==103)
  {
    edfsignals = 1;
  }

  if(file_type==32)
  {
    if(analoginputscombobox->currentIndex()==1)
    {
      edfsignals = 4;
    }
    else
    {
      edfsignals = 1;
    }
  }

  p = sprintf(patientname, "%s", PatientnameLineEdit->text().toLatin1().data());
  latin1_to_ascii(patientname, p);
  for( ; p<80; p++)
  {
    patientname[p] = ' ';
  }
  patientname[80] = 0;

  p = sprintf(recording, "%s", RecordingLineEdit->text().toLatin1().data());
  latin1_to_ascii(recording, p);
  for( ; p<80; p++)
  {
    recording[p] = ' ';
  }
  recording[80] = 0;

  sprintf(datetime,
          "%02i.%02i.%02i%02i.%02i.%02i",
          StartDatetimeedit->date().day(),
          StartDatetimeedit->date().month(),
          StartDatetimeedit->date().year() % 100,
          StartDatetimeedit->time().hour(),
          StartDatetimeedit->time().minute(),
          StartDatetimeedit->time().second());
  datetime[16] = 0;


/***************** write header *****************************************/

  get_filename_from_path(outputfilename, path, MAX_PATH_LENGTH);
  remove_extension_from_filename(outputfilename);
  strcat(outputfilename, ".edf");

  path[0] = 0;
  if(recent_savedir[0]!=0)
  {
    strcpy(path, recent_savedir);
    strcat(path, "/");
  }
  strcat(path, outputfilename);

  strcpy(path, QFileDialog::getSaveFileName(0, "Output file", QString::fromLocal8Bit(path), "EDF files (*.edf *.EDF)").toLocal8Bit().data());

  if(!strcmp(path, ""))
  {
    enable_widgets(true);
    fclose(inputfile);
    return;
  }

  get_directory_from_path(recent_savedir, path, MAX_PATH_LENGTH);

  outputfile = fopeno(path, "wb");
  if(outputfile==NULL)
  {
    snprintf(txt_string, 2048, "Can not open file %s for writing.", path);
    QMessageBox messagewindow(QMessageBox::Critical, "Error", txt_string);
    messagewindow.exec();
    enable_widgets(true);
    fclose(inputfile);
    return;
  }

  fprintf(outputfile, "0       ");
  fprintf(outputfile, "%s", patientname);
  fprintf(outputfile, "%s", recording);
  fprintf(outputfile, "%s", datetime);
  fprintf(outputfile, "%-8i", 256 * edfsignals + 256);
  fprintf(outputfile, "                                            ");
  fprintf(outputfile, "-1      ");
  if(file_type==100)
  {
    fprintf(outputfile, "0.01    ");
  }
  if(file_type==103)
  {
    fprintf(outputfile, "0.005   ");
  }
  if(file_type==32)
  {
    fprintf(outputfile, "0.005   ");
  }
  fprintf(outputfile, "%-4i", edfsignals);

  if(file_type==100)
  {
    for(i=0; i<edfsignals; i++)
    {
      fprintf(outputfile, "%s", labels[i]);
    }
  }

  if(file_type==103)
  {
    for(i=0; i<edfsignals; i++)
    {
      fprintf(outputfile, "Blood pressure  ");
    }
  }

  if(file_type==32)
  {
    for(i=0; i<edfsignals; i++)
    {
      fprintf(outputfile, "AD-%i            ", i + 1);
    }
  }

  for(i=0; i<(80*edfsignals); i++)
  {
    fputc(' ', outputfile);
  }

  if(file_type==100)
  {
    for(i=0; i<edfsignals; i++)
    {
      fprintf(outputfile, "%s", phys_dim[i]);
    }
  }

  if(file_type==103)
  {
    for(i=0; i<edfsignals; i++)
    {
      fprintf(outputfile, "mmHg    ");
    }
  }

  if(file_type==32)
  {
    for(i=0; i<edfsignals; i++)
    {
      fprintf(outputfile, "mV      ");
    }
  }

  if(file_type==100)
  {
    for(i=0; i<edfsignals; i++)
    {
      fprintf(outputfile, "%s", phys_min[i]);
    }

    for(i=0; i<edfsignals; i++)
    {
      fprintf(outputfile, "%s", phys_max[i]);
    }
  }

  if(file_type==103)
  {
    for(i=0; i<edfsignals; i++)
    {
      fprintf(outputfile, "-8192   ");
    }

    for(i=0; i<edfsignals; i++)
    {
      fprintf(outputfile, "8191.75 ");
    }
  }

  if(file_type==32)
  {
    for(i=0; i<edfsignals; i++)
    {
      fprintf(outputfile, "-81920  ");
    }

    for(i=0; i<edfsignals; i++)
    {
      fprintf(outputfile, "81917.5 ");
    }
  }

  if(file_type==100)
  {
    for(i=0; i<edfsignals; i++)
    {
      fprintf(outputfile, "-31744  ");
    }

    for(i=0; i<edfsignals; i++)
    {
      fprintf(outputfile, "31744   ");
    }
  }

  if(file_type==103)
  {
    for(i=0; i<edfsignals; i++)
    {
      fprintf(outputfile, "-32768  ");
    }

    for(i=0; i<edfsignals; i++)
    {
      fprintf(outputfile, "32767   ");
    }
  }

  if(file_type==32)
  {
    for(i=0; i<edfsignals; i++)
    {
      fprintf(outputfile, "-32768  ");
    }

    for(i=0; i<edfsignals; i++)
    {
      fprintf(outputfile, "32767   ");
    }
  }

  for(i=0; i<(80*edfsignals); i++)
  {
    fputc(' ', outputfile);
  }

  for(i=0; i<edfsignals; i++)
  {
    fprintf(outputfile, "1       ");
  }

  for(i=0; i<(32*edfsignals); i++)
  {
    fputc(' ', outputfile);
  }

/***************** start conversion **************************************/

  rewind(inputfile);

  if(file_type==100)   /*** filetype is 100 **********/
  {

  for(i=0; ; )
  {
    temp = fgetc(inputfile);

    if(temp==EOF)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "Reached end of file unexpectedly (8).");
      messagewindow.exec();
      fclose(inputfile);
      fclose(outputfile);
      enable_widgets(true);
      return;
    }

    if(temp=='\n')  i++;

    if(i>0)  break;
  }

  QApplication::setOverrideCursor(Qt::WaitCursor);

  for(k=0; k<10; k++)  qApp->processEvents();

  i = 0;

  column = 0;

  datarecords = 0LL;

  str_start = 0;

  line_nr = 1;

  while(1)
  {
    temp = fgetc(inputfile);

    if(temp==EOF)
    {
      for(k=0; k<edfsignals; k++)
      {
        temp = (int)(new_value[k] * sensitivity[k]);

        if(temp>31744)  temp = 31744;

        if(temp<-31744)  temp = -31744;

        var.two = (short)temp;

        fputc(var.one[0], outputfile);
        fputc(var.one[1], outputfile);
      }

      datarecords++;

      break;
    }

    line[i] = temp;

  /**************************************/

    if(line[i]==',')
    {
      line[i] = '.';
    }

    if((line[i]==separator)||(line[i]=='\n'))
    {
      if(column)
      {
        new_value[column-1] = atof(line + str_start);
      }
      else
      {
        new_smpl_time = (int)(atof(line + str_start) * 100.0);
      }

      if(line[i]=='\n')
      {
        /**************************************/

        line_nr++;

        if(column!=edfsignals)
        {
          QApplication::restoreOverrideCursor();
          snprintf(txt_string, 2048, "Number of separators in line %i is wrong.", line_nr);
          QMessageBox messagewindow(QMessageBox::Critical, "Error", txt_string);
          messagewindow.exec();
          fclose(inputfile);
          fclose(outputfile);
          enable_widgets(true);
          return;
        }

        timestep = new_smpl_time - datarecords;

        if(timestep<=0)
        {
          QApplication::restoreOverrideCursor();
          snprintf(txt_string, 2048, "Timestep <= 0 in line %i.", line_nr);
          QMessageBox messagewindow(QMessageBox::Critical, "Error", txt_string);
          messagewindow.exec();
          fclose(inputfile);
          fclose(outputfile);
          enable_widgets(true);
          return;
        }

        for(j=0; j<timestep; j++)
        {
          for(k=0; k<edfsignals; k++)
          {
            temp = (int)((old_value[k] + ((new_value[k] - old_value[k]) * ((double)j / (double)timestep))) * sensitivity[k]);

            if(temp>31744)  temp = 31744;

            if(temp<-31744)  temp = -31744;

            var.two = (short)temp;

            fputc(var.one[0], outputfile);
            fputc(var.one[1], outputfile);
          }

          datarecords++;
        }

        for(j=0; j<edfsignals; j++)
        {
          old_value[j] = new_value[j];
        }

        /**************************************/

        str_start = 0;

        i = 0;

        column = 0;

        continue;
      }

      str_start = i + 1;

      column++;
    }

  /**************************************/

    i++;

    if(i>2046)
    {
      QApplication::restoreOverrideCursor();
      snprintf(txt_string, 2048, "Line %i is too long.", line_nr);
      QMessageBox messagewindow(QMessageBox::Critical, "Error", txt_string);
      messagewindow.exec();
      fclose(inputfile);
      fclose(outputfile);
      enable_widgets(true);
      return;
    }
  }

  }  /********** end if(file_type==100)  ********************/

  if((file_type==103) || (file_type==32))
  {
    fseeko(inputfile, 0LL, SEEK_END);

    file_size = ftello(inputfile);

    file_size /= 2LL;

    file_size /= edfsignals;

    rewind(inputfile);

    QApplication::setOverrideCursor(Qt::WaitCursor);

    for(k=0; k<10; k++)  qApp->processEvents();

    if(file_type==103)
    {
      for(datarecords=0LL; datarecords<file_size; datarecords++)
      {
        temp = fgetc(inputfile);
        fputc(temp, outputfile);

        temp = fgetc(inputfile);
        if(temp==EOF)
        {
          QApplication::restoreOverrideCursor();
          QMessageBox messagewindow(QMessageBox::Critical, "Error", "Reached end of file unexpectedly (18).");
          messagewindow.exec();
          fclose(inputfile);
          fclose(outputfile);
          enable_widgets(true);
          return;
        }
        fputc(temp, outputfile);
      }
    }

    if(file_type==32)
    {
      k = edfsignals * 2 - 1;

      for(datarecords=0LL; datarecords<file_size; datarecords++)
      {
        for(i=0; i<k; i++)
        {
          temp = fgetc(inputfile);
          fputc(temp, outputfile);
        }

        temp = fgetc(inputfile);
        if(temp==EOF)
        {
          QApplication::restoreOverrideCursor();
          QMessageBox messagewindow(QMessageBox::Critical, "Error", "Reached end of file unexpectedly (28).");
          messagewindow.exec();
          fclose(inputfile);
          fclose(outputfile);
          enable_widgets(true);
          return;
        }
        fputc(temp, outputfile);
      }
    }
  }

  QApplication::restoreOverrideCursor();

  fseeko(outputfile, 236LL, SEEK_SET);

#ifdef Q_OS_WIN32
  __mingw_fprintf(outputfile, "%-8lli", datarecords);
#else
  fprintf(outputfile, "%-8lli", datarecords);
#endif

  if(fclose(outputfile))
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while closing outputfile.");
    messagewindow.exec();
    enable_widgets(true);
    fclose(inputfile);
    return;
  }

  if(fclose(inputfile))
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while closing inputfile.");
    messagewindow.exec();
  }

  snprintf(txt_string, 2048, "Done, EDF file is located at %s", path);
  QMessageBox messagewindow(QMessageBox::Information, "Ready", QString::fromLocal8Bit(txt_string));
  messagewindow.setIconPixmap(QPixmap(":/images/ok.png"));
  messagewindow.exec();

  enable_widgets(true);
}
void UI_MIT2EDFwindow::SelectFileButton()
{
  FILE *header_inputfile=NULL,
       *data_inputfile=NULL,
       *annot_inputfile=NULL;

  int i, j, p, len, hdl, *buf;

  char header_filename[MAX_PATH_LENGTH],
       txt_string[2048],
       edf_filename[MAX_PATH_LENGTH],
       data_filename[MAX_PATH_LENGTH],
       annot_filename[MAX_PATH_LENGTH],
       filename_x[MAX_PATH_LENGTH],
       scratchpad[4096],
       *charpntr;

  unsigned char a_buf[128];

  long long filesize;

  pushButton1->setEnabled(false);

  strcpy(header_filename, QFileDialog::getOpenFileName(0, "Select inputfile", QString::fromLocal8Bit(recent_opendir), "MIT header files (*.hea *.HEA)").toLocal8Bit().data());

  if(!strcmp(header_filename, ""))
  {
    pushButton1->setEnabled(true);
    return;
  }

  get_directory_from_path(recent_opendir, header_filename, MAX_PATH_LENGTH);

  header_inputfile = fopeno(header_filename, "rb");
  if(header_inputfile==NULL)
  {
    snprintf(txt_string, 2048, "Can not open file %s for reading.\n", header_filename);
    textEdit1->append(QString::fromLocal8Bit(txt_string));
    pushButton1->setEnabled(true);
    return;
  }

  get_filename_from_path(filename_x, header_filename, MAX_PATH_LENGTH);

  snprintf(txt_string, 2048, "Read file: %s", filename_x);
  textEdit1->append(QString::fromLocal8Bit(txt_string));

  remove_extension_from_filename(filename_x);

  charpntr = fgets(scratchpad, 4095, header_inputfile);
  if(charpntr == NULL)
  {
    textEdit1->append("Can not read header file. (error 1)\n");
    fclose(header_inputfile);
    pushButton1->setEnabled(true);
    return;
  }

  len = strlen(charpntr);
  if(len < 6)
  {
    textEdit1->append("Can not read header file. (error 2)\n");
    fclose(header_inputfile);
    pushButton1->setEnabled(true);
    return;
  }

  for(i=0; i<len; i++)
  {
    if(charpntr[i] == ' ')
    {
      charpntr[i] = 0;

      break;
    }
  }

  if(i == len)
  {
    textEdit1->append("Can not read header file. (error 3)\n");
    fclose(header_inputfile);
    pushButton1->setEnabled(true);
    return;
  }

  if(strcmp(charpntr, filename_x))
  {
    textEdit1->append("Can not read header file. (error 4)\n");
    fclose(header_inputfile);
    pushButton1->setEnabled(true);
    return;
  }

  p = ++i;

  for(; i<len; i++)
  {
    if(charpntr[i] == ' ')
    {
      charpntr[i] = 0;

      break;
    }
  }

  if(i == p)
  {
    textEdit1->append("Can not read header file. (error 5)\n");
    fclose(header_inputfile);
    pushButton1->setEnabled(true);
    return;
  }

  mit_hdr.chns = atoi(charpntr + p);

  if(mit_hdr.chns < 1)
  {
    textEdit1->append("Error, number of signals is less than one. (error 6)\n");
    fclose(header_inputfile);
    pushButton1->setEnabled(true);
    return;
  }

  if(mit_hdr.chns > MAXSIGNALS)
  {
    textEdit1->append("Error, Too many signals in header. (error 7)\n");
    fclose(header_inputfile);
    pushButton1->setEnabled(true);
    return;
  }

  p = ++i;

  for(; i<len; i++)
  {
    if(charpntr[i] == ' ')
    {
      charpntr[i] = 0;

      break;
    }
  }

  if(i == p)
  {
    textEdit1->append("Can not read header file. (error 8)\n");
    fclose(header_inputfile);
    pushButton1->setEnabled(true);
    return;
  }

  mit_hdr.sf = atoi(charpntr + p);

  if(mit_hdr.sf < 1)
  {
    textEdit1->append("Error, samplefrequency is less than 1 Hz. (error 9)\n");
    fclose(header_inputfile);
    pushButton1->setEnabled(true);
    return;
  }

  if(mit_hdr.sf > 100000)
  {
    textEdit1->append("Error, samplefrequency is more than 100000 Hz. (error 10)\n");
    fclose(header_inputfile);
    pushButton1->setEnabled(true);
    return;
  }

  mit_hdr.smp_period = 1000000000LL / mit_hdr.sf;

  strcat(filename_x, ".dat");

  for(j=0; j<mit_hdr.chns; j++)
  {
    mit_hdr.adc_gain[j] = 200.0;

    mit_hdr.adc_resolution[j] = 12;

    mit_hdr.adc_zero[j] = 0;

    mit_hdr.init_val[j] = 0;

    sprintf(mit_hdr.label[j], "chan. %i", j + 1);

    charpntr = fgets(scratchpad, 4095, header_inputfile);
    if(charpntr == NULL)
    {
      textEdit1->append("Can not read header file. (error 11)\n");
      fclose(header_inputfile);
      pushButton1->setEnabled(true);
      return;
    }

    len = strlen(charpntr);
    if(len < 6)
    {
      textEdit1->append("Can not read header file. (error 12)\n");
      fclose(header_inputfile);
      pushButton1->setEnabled(true);
      return;
    }

    for(i=0; i<len; i++)
    {
      if(charpntr[i] == ' ')
      {
        charpntr[i] = 0;

        break;
      }
    }

    if(i == len)
    {
      textEdit1->append("Can not read header file. (error 13)\n");
      fclose(header_inputfile);
      pushButton1->setEnabled(true);
      return;
    }

    if(strcmp(charpntr, filename_x))
    {
      textEdit1->append("Error, filenames are different. (error 14)\n");
      fclose(header_inputfile);
      pushButton1->setEnabled(true);
      return;
    }

    p = ++i;

    for(; i<len; i++)
    {
      if(charpntr[i] == ' ')
      {
        charpntr[i] = 0;

        break;
      }
    }

    if(i == len)
    {
      textEdit1->append("Can not read header file. (error 15)\n");
      fclose(header_inputfile);
      pushButton1->setEnabled(true);
      return;
    }

    mit_hdr.format[j] = atoi(charpntr + p);

    if((mit_hdr.format[j] != 212) && (mit_hdr.format[j] != 16))
    {
      snprintf(txt_string, 2048, "Error, unsupported format: %i  (error 16)\n", mit_hdr.format[j]);
      textEdit1->append(txt_string);
      fclose(header_inputfile);
      pushButton1->setEnabled(true);
      return;
    }

    if(j>0)
    {
      if(mit_hdr.format[j] != mit_hdr.format[0])
      {
        textEdit1->append("Error, different formats in the same file. (error 17)\n");
        fclose(header_inputfile);
        pushButton1->setEnabled(true);
        return;
      }
    }

    p = ++i;

    for(; i<len; i++)
    {
      if(charpntr[i] == ' ')
      {
        charpntr[i] = 0;

        break;
      }
    }

    if(i == p)
    {
      continue;
    }

    mit_hdr.adc_gain[j] = atoi(charpntr + p);

    p = ++i;

    for(; i<len; i++)
    {
      if(charpntr[i] == ' ')
      {
        charpntr[i] = 0;

        break;
      }
    }

    if(i == p)
    {
      continue;
    }

    mit_hdr.adc_resolution[j] = atoi(charpntr + p);

    p = ++i;

    for(; i<len; i++)
    {
      if(charpntr[i] == ' ')
      {
        charpntr[i] = 0;

        break;
      }
    }

    if(i == p)
    {
      continue;
    }

    mit_hdr.adc_zero[j] = atoi(charpntr + p);

    p = ++i;

    for(; i<len; i++)
    {
      if(charpntr[i] == ' ')
      {
        charpntr[i] = 0;

        break;
      }
    }

    if(i == p)
    {
      continue;
    }

    mit_hdr.init_val[j] = atoi(charpntr + p);

    p = ++i;

    for(; i<len; i++)
    {
      if(charpntr[i] == ' ')
      {
        charpntr[i] = 0;

        break;
      }
    }

    if(i == p)
    {
      continue;
    }

    // skip

    p = ++i;

    for(; i<len; i++)
    {
      if(charpntr[i] == ' ')
      {
        charpntr[i] = 0;

        break;
      }
    }

    if(i == p)
    {
      continue;
    }

    // skip

    p = ++i;

    for(; i<len; i++)
    {
      if((charpntr[i] == '\n') || (charpntr[i] == '\r'))
      {
        charpntr[i] = 0;

        break;
      }
    }

    if(i == p)
    {
      continue;
    }

    strncpy(mit_hdr.label[j], charpntr + p, 16);

    mit_hdr.label[j][16] = 0;
  }

  fclose(header_inputfile);

  strcpy(data_filename, header_filename);

  remove_extension_from_filename(data_filename);

  strcpy(edf_filename, data_filename);

  strcpy(annot_filename, data_filename);

  strcat(data_filename, ".dat");

  strcat(edf_filename, ".edf");

  strcat(annot_filename, ".atr");

  data_inputfile = fopeno(data_filename, "rb");
  if(data_inputfile==NULL)
  {
    snprintf(txt_string, 2048, "Can not open file %s for reading.\n", data_filename);
    textEdit1->append(QString::fromLocal8Bit(txt_string));
    pushButton1->setEnabled(true);
    return;
  }

  fseeko(data_inputfile, 0LL, SEEK_END);
  filesize = ftello(data_inputfile);
  if(filesize < (mit_hdr.chns * mit_hdr.sf * 45 / 10))
  {
    textEdit1->append("Error, .dat filesize is too small.\n");
    fclose(data_inputfile);
    pushButton1->setEnabled(true);
    return;
  }

  mit_hdr.sf_div = 1;

  mit_hdr.sf_block = mit_hdr.sf;

  if(!(mit_hdr.sf % 10))
  {
    mit_hdr.sf_div = 10;

    mit_hdr.sf_block /= mit_hdr.sf_div;
  }
  else if(!(mit_hdr.sf % 8))
    {
      mit_hdr.sf_div = 8;

      mit_hdr.sf_block /= mit_hdr.sf_div;
    }
    else if(!(mit_hdr.sf % 4))
      {
        mit_hdr.sf_div = 4;

        mit_hdr.sf_block /= mit_hdr.sf_div;
      }
      else if(!(mit_hdr.sf % 2))
        {
          mit_hdr.sf_div = 2;

          mit_hdr.sf_block /= mit_hdr.sf_div;
        }

  hdl = edfopen_file_writeonly(edf_filename, EDFLIB_FILETYPE_EDFPLUS, mit_hdr.chns);

  if(hdl<0)
  {
    snprintf(txt_string, 2048, "Can not open file %s for writing.\n", edf_filename);
    textEdit1->append(QString::fromLocal8Bit(txt_string));
    fclose(data_inputfile);
    pushButton1->setEnabled(true);
    return;
  }

  for(i=0; i<mit_hdr.chns; i++)
  {
    if(edf_set_samplefrequency(hdl, i, mit_hdr.sf_block))
    {
      textEdit1->append("Error: edf_set_samplefrequency()\n");
      fclose(data_inputfile);
      edfclose_file(hdl);
      pushButton1->setEnabled(true);
      return;
    }
  }

  for(i=0; i<mit_hdr.chns; i++)
  {
    if(edf_set_digital_minimum(hdl, i, -32768))
    {
      textEdit1->append("Error: edf_set_digital_minimum()\n");
      fclose(data_inputfile);
      edfclose_file(hdl);
      pushButton1->setEnabled(true);
      return;
    }
  }

  for(i=0; i<mit_hdr.chns; i++)
  {
    if(edf_set_digital_maximum(hdl, i, 32767))
    {
      textEdit1->append("Error: edf_set_digital_maximum()\n");
      fclose(data_inputfile);
      edfclose_file(hdl);
      pushButton1->setEnabled(true);
      return;
    }
  }

  for(i=0; i<mit_hdr.chns; i++)
  {
    if(edf_set_label(hdl, i, mit_hdr.label[i]))
    {
      textEdit1->append("Error: edf_set_label()\n");
      fclose(data_inputfile);
      edfclose_file(hdl);
      pushButton1->setEnabled(true);
      return;
    }
  }

  for(i=0; i<mit_hdr.chns; i++)
  {
    if(edf_set_physical_dimension(hdl, i, "uV"))
    {
      textEdit1->append("Error: edf_set_physical_dimension()\n");
      fclose(data_inputfile);
      edfclose_file(hdl);
      pushButton1->setEnabled(true);
      return;
    }

    if(edf_set_physical_maximum(hdl, i, (double)((32767 - mit_hdr.adc_zero[i]) * 1000) / mit_hdr.adc_gain[i]))
    {
      textEdit1->append("Error: edf_set_physical_maximum()\n");
      fclose(data_inputfile);
      edfclose_file(hdl);
      pushButton1->setEnabled(true);
      return;
    }

    if(edf_set_physical_minimum(hdl, i, (double)((-32768 - mit_hdr.adc_zero[i]) * 1000) / mit_hdr.adc_gain[i]))
    {
      textEdit1->append("Error: edf_set_physical_minimum()\n");
      fclose(data_inputfile);
      edfclose_file(hdl);
      pushButton1->setEnabled(true);
      return;
    }
  }

  if(edf_set_datarecord_duration(hdl, 100000 / mit_hdr.sf_div))
  {
    textEdit1->append("Error: edf_set_datarecord_duration()\n");
    fclose(data_inputfile);
    edfclose_file(hdl);
    pushButton1->setEnabled(true);
    return;
  }

  buf = (int *)malloc(mit_hdr.sf_block * mit_hdr.chns * sizeof(int));
  if(buf == NULL)
  {
    textEdit1->append("Malloc() error (buf)\n");
    fclose(data_inputfile);
    edfclose_file(hdl);
    pushButton1->setEnabled(true);
    return;
  }

/////////////////// Start conversion //////////////////////////////////////////

  int k, blocks, tmp1, tmp2;

  fseeko(data_inputfile, 0LL, SEEK_SET);

  blocks = filesize / (mit_hdr.sf_block * mit_hdr.chns);

  QProgressDialog progress("Converting digitized signals ...", "Abort", 0, blocks);
  progress.setWindowModality(Qt::WindowModal);
  progress.setMinimumDuration(200);

  if(mit_hdr.format[0] == 212)
  {
    blocks *= 10;
    blocks /= 15;

    progress.setMaximum(blocks);

    for(k=0; k<blocks; k++)
    {
      if(!(k % 100))
      {
        progress.setValue(k);

        qApp->processEvents();

        if(progress.wasCanceled() == true)
        {
          textEdit1->append("Conversion aborted by user.\n");
          fclose(data_inputfile);
          edfclose_file(hdl);
          free(buf);
          pushButton1->setEnabled(true);
          return;
        }
      }

      for(i=0; i<mit_hdr.sf_block; i++)
      {
        for(j=0; j<mit_hdr.chns; j++)
        {
          if(j % 2)
          {
            tmp1 = fgetc(data_inputfile);
            tmp2 = fgetc(data_inputfile);

            if(tmp2 == EOF)
            {
              goto OUT;
            }

            buf[j * mit_hdr.sf_block + i] = (tmp1 & 0xf0) << 4;
            buf[j * mit_hdr.sf_block + i] += tmp2;
            if(buf[j * mit_hdr.sf_block + i] & 0x800)
            {
              buf[j * mit_hdr.sf_block + i] |= 0xfffff000;
            }
          }
          else
          {
            tmp1 = fgetc(data_inputfile);
            tmp2 = fgetc(data_inputfile);

            buf[j * mit_hdr.sf_block + i] = (tmp2 & 0x0f) << 8;
            buf[j * mit_hdr.sf_block + i] += tmp1;
            if(buf[j * mit_hdr.sf_block + i] & 0x800)
            {
              buf[j * mit_hdr.sf_block + i] |= 0xfffff000;
            }

            fseeko(data_inputfile, -1LL, SEEK_CUR);
          }
        }
      }

      if(edf_blockwrite_digital_samples(hdl, buf))
      {
        progress.reset();
        textEdit1->append("A write error occurred during conversion.\n");
        fclose(data_inputfile);
        edfclose_file(hdl);
        free(buf);
        pushButton1->setEnabled(true);
        return;
      }
    }
  }

  if(mit_hdr.format[0] == 16)
  {
    blocks /= 2;

    progress.setMaximum(blocks);

    for(k=0; k<blocks; k++)
    {
      if(!(k % 100))
      {
        progress.setValue(k);

        qApp->processEvents();

        if(progress.wasCanceled() == true)
        {
          textEdit1->append("Conversion aborted by user.\n");
          fclose(data_inputfile);
          edfclose_file(hdl);
          free(buf);
          pushButton1->setEnabled(true);
          return;
        }
      }

      for(i=0; i<mit_hdr.sf_block; i++)
      {
        for(j=0; j<mit_hdr.chns; j++)
        {
          tmp1 = fgetc(data_inputfile);
          if(tmp1 == EOF)
          {
            goto OUT;
          }

          tmp1 += (fgetc(data_inputfile) << 8);

          if(tmp1 & 0x8000)
          {
            tmp1 |= 0xffff0000;
          }

         buf[j * mit_hdr.sf_block + i] = tmp1;
        }
      }

      if(edf_blockwrite_digital_samples(hdl, buf))
      {
        progress.reset();
        textEdit1->append("A write error occurred during conversion.\n");
        fclose(data_inputfile);
        edfclose_file(hdl);
        free(buf);
        pushButton1->setEnabled(true);
        return;
      }
    }
  }

OUT:

  progress.reset();

  qApp->processEvents();

/////////////////// End conversion //////////////////////////////////////////

  fclose(data_inputfile);

  free(buf);

  int annot_code, tc=0, skip;

  long long bytes_read;

  get_filename_from_path(filename_x, annot_filename, MAX_PATH_LENGTH);

  annot_inputfile = fopeno(annot_filename, "rb");
  if(annot_inputfile==NULL)
  {
    remove_extension_from_filename(annot_filename);

    strcat(annot_filename, ".ari");

    annot_inputfile = fopeno(annot_filename, "rb");
  }

  if(annot_inputfile==NULL)
  {
    remove_extension_from_filename(annot_filename);

    strcat(annot_filename, ".ecg");

    annot_inputfile = fopeno(annot_filename, "rb");
  }

  if(annot_inputfile==NULL)
  {
    snprintf(txt_string, 2048, "Can not open file %s for reading.\n"
                               "Annotations can not be included.", filename_x);
    textEdit1->append(QString::fromLocal8Bit(txt_string));
  }
  else
  {
    snprintf(txt_string, 2048, "Read file: %s", filename_x);
    textEdit1->append(QString::fromLocal8Bit(txt_string));

    fseeko(annot_inputfile, 0LL, SEEK_END);
    filesize = ftello(annot_inputfile);

    progress.setLabelText("Converting annotations ...");
    progress.setMinimum(0);
    progress.setMaximum(filesize);

    fseeko(annot_inputfile, 0LL, SEEK_SET);

    for(bytes_read=0LL; bytes_read < filesize; bytes_read += 2LL)
    {
      if(!(bytes_read % 100))
      {
        progress.setValue(bytes_read);

        qApp->processEvents();

        if(progress.wasCanceled() == true)
        {
          textEdit1->append("Conversion aborted by user.\n");

          break;
        }
      }

      skip = 0;

      if(fread(a_buf, 2, 1, annot_inputfile) != 1)
      {
        break;
      }

#pragma GCC diagnostic ignored "-Wstrict-aliasing"

      if(*((unsigned short *)a_buf) == 0)  // end of file
      {
        break;
      }

      annot_code = a_buf[1] >> 2;

      if(annot_code == 59)
      {
        if(fread(a_buf, 4, 1, annot_inputfile) != 1)
        {
          break;
        }

        tc += (*((unsigned short *)a_buf) << 16);

        tc += *((unsigned short *)(a_buf + 2));
      }
      else if(annot_code == 63)
        {
          skip = *((unsigned short *)a_buf) & 0x3ff;

          if(skip % 2) skip++;
        }
        else if((annot_code >= 0) && (annot_code <= ACMAX))
          {
            tc += *((unsigned short *)a_buf) & 0x3ff;

#pragma GCC diagnostic warning "-Wstrict-aliasing"

            if(annot_code < 42)
            {
              edfwrite_annotation_latin1(hdl, ((long long)tc * mit_hdr.smp_period) / 100000LL, -1, annotdescrlist[annot_code]);
            }
            else
            {
              edfwrite_annotation_latin1(hdl, ((long long)tc * mit_hdr.smp_period) / 100000LL, -1, "user-defined");
            }
          }

      if(skip)
      {
        if(fseek(annot_inputfile, skip, SEEK_CUR) < 0)
        {
          break;
        }

        bytes_read += skip;
      }
    }

    fclose(annot_inputfile);
  }

  progress.reset();

  edfclose_file(hdl);

  textEdit1->append("Ready.\n");

  pushButton1->setEnabled(true);
}
Exemple #15
0
void UI_ECGExport::Export_RR_intervals()
{
  int i,
      len,
      signal_nr,
      type=-1,
      beat_cnt,
      samples_cnt,
      progress_steps,
      datarecords,
      whole_recording=0,
      import_as_annots=0,
      filenum=0;

  char path[MAX_PATH_LENGTH],
       str[2048];

  double *beat_interval_list,
         *buf;

  long long *beat_onset_list,
            datrecs,
            smpls_left,
            l_time=0LL;

  struct signalcompblock *signalcomp;


  FILE *outputfile;

  QList<QListWidgetItem *> selectedlist;

  struct annotationblock *annotation;


  selectedlist = list->selectedItems();

  if(selectedlist.size() < 1)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Select a signal first.");
    messagewindow.exec();
    return;
  }

  signal_nr = selectedlist.at(0)->data(Qt::UserRole).toInt();

  if((signal_nr < 0) || (signal_nr >= mainwindow->signalcomps))
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Invalid signalcomp number");
    messagewindow.exec();
    return;
  }

  signalcomp = mainwindow->signalcomp[signal_nr];

  if(signalcomp->ecg_filter == NULL)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Heart Rate detection is not activated for the selected signal.");
    messagewindow.exec();
    return;
  }

  if(checkBox2->checkState() == Qt::Checked)
  {
    import_as_annots = 1;
  }

  if(checkBox1->checkState() == Qt::Checked)
  {
    whole_recording = 1;

    class FilteredBlockReadClass blockrd;

    buf = blockrd.init_signalcomp(signalcomp, 1, 0);
    if(buf == NULL)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "Error, can not initialize FilteredBlockReadClass.");
      messagewindow.exec();
      return;
    }

    samples_cnt = blockrd.samples_in_buf();
    if(samples_cnt < 1)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "Error, samples_cnt is < 1.");
      messagewindow.exec();
      return;
    }

    filenum = signalcomp->filenum;

    reset_ecg_filter(signalcomp->ecg_filter);

    datarecords = signalcomp->edfhdr->datarecords;

    QProgressDialog progress("Processing file...", "Abort", 0, datarecords);
    progress.setWindowModality(Qt::WindowModal);
    progress.setMinimumDuration(200);

    progress_steps = datarecords / 100;
    if(progress_steps < 1)
    {
      progress_steps = 1;
    }

    for(i=0; i<signalcomp->edfhdr->datarecords; i++)
    {
      if(!(i%progress_steps))
      {
        progress.setValue(i);

        qApp->processEvents();

        if(progress.wasCanceled() == TRUE)
        {
          return;
        }
      }

      if(blockrd.process_signalcomp(i) != 0)
      {
        progress.reset();
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "Error while reading file.");
        messagewindow.exec();
        return;
      }
    }

    progress.reset();
  }

  beat_cnt = ecg_filter_get_beat_cnt(signalcomp->ecg_filter);

  beat_onset_list = ecg_filter_get_onset_beatlist(signalcomp->ecg_filter);

  beat_interval_list = ecg_filter_get_interval_beatlist(signalcomp->ecg_filter);

  if(beat_cnt < 4)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Error, not enough beats.");
    messagewindow.exec();
    return;
  }

  if(import_as_annots)
  {
    for(i=0; i<beat_cnt; i++)
    {
      if(whole_recording)
      {
        l_time = 0LL;
      }
      else
      {
        l_time = signalcomp->edfhdr->viewtime;
      }

      if(l_time < 0LL)
      {
        l_time = 0LL;
      }

      datrecs = beat_onset_list[i] / signalcomp->edfhdr->edfparam[signalcomp->edfsignal[0]].smp_per_record;

      smpls_left = beat_onset_list[i] % signalcomp->edfhdr->edfparam[signalcomp->edfsignal[0]].smp_per_record;

      l_time += (datrecs * signalcomp->edfhdr->long_data_record_duration);

      l_time += ((smpls_left * signalcomp->edfhdr->long_data_record_duration) / signalcomp->edfhdr->edfparam[signalcomp->edfsignal[0]].smp_per_record);

      if(!whole_recording)
      {
        l_time += (mainwindow->edfheaderlist[mainwindow->sel_viewtime]->viewtime - signalcomp->edfhdr->viewtime);
      }

      annotation = (struct annotationblock *)calloc(1, sizeof(struct annotationblock));
      if(annotation == NULL)
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "A memory allocation error occurred (annotation).");
        messagewindow.exec();
        return;
      }
      annotation->onset = l_time;
      strncpy(annotation->annotation, "R-onset", MAX_ANNOTATION_LEN);
      annotation->annotation[MAX_ANNOTATION_LEN] = 0;
      edfplus_annotation_add_item(&mainwindow->annotationlist[filenum], annotation);
    }

    if(mainwindow->annotations_dock[signalcomp->filenum] == NULL)
    {
      mainwindow->annotations_dock[filenum] = new UI_Annotationswindow(filenum, mainwindow);

      mainwindow->addDockWidget(Qt::RightDockWidgetArea, mainwindow->annotations_dock[filenum]->docklist, Qt::Vertical);

      if(!mainwindow->annotationlist[filenum])
      {
        mainwindow->annotations_dock[filenum]->docklist->hide();
      }
    }

    if(mainwindow->annotationlist[filenum])
    {
      mainwindow->annotations_dock[filenum]->docklist->show();

      mainwindow->annotations_edited = 1;

      mainwindow->annotations_dock[filenum]->updateList();

      mainwindow->save_act->setEnabled(TRUE);
    }
  }
  else
  {
    path[0] = 0;
    if(mainwindow->recent_savedir[0]!=0)
    {
      strcpy(path, mainwindow->recent_savedir);
      strcat(path, "/");
    }
    len = strlen(path);
    get_filename_from_path(path + len, signalcomp->edfhdr->filename, MAX_PATH_LENGTH - len);
    remove_extension_from_filename(path);
    strcat(path, "_RR_interval.txt");

    strcpy(path, QFileDialog::getSaveFileName(0, "Export RR-interval to ASCII", QString::fromLocal8Bit(path), "Text files (*.txt *.TXT)").toLocal8Bit().data());

    if(!strcmp(path, ""))
    {
      return;
    }

    get_directory_from_path(mainwindow->recent_savedir, path, MAX_PATH_LENGTH);

    outputfile = fopeno(path, "wb");
    if(outputfile==NULL)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "Error, can not open outputfile for writing.");
      messagewindow.exec();
      return;
    }

    if(radioButton1->isChecked() == TRUE)
    {
      type = 1;
    }

    if(radioButton2->isChecked() == TRUE)
    {
      type = 2;
    }

    if(radioButton3->isChecked() == TRUE)
    {
      type = 3;
    }

    if(type == 1)
    {
      for(i=0; i<beat_cnt; i++)
      {
        fprintf(outputfile, "%.4f\n", beat_interval_list[i]);
      }
    }

    if((type == 2) || (type == 3))
    {
      for(i=0; i<beat_cnt; i++)
      {
        if(whole_recording)
        {
          l_time = 0LL;
        }
        else
        {
          l_time = signalcomp->edfhdr->viewtime;
        }

        if(l_time < 0LL)
        {
          l_time = 0LL;
        }

        datrecs = beat_onset_list[i] / signalcomp->edfhdr->edfparam[signalcomp->edfsignal[0]].smp_per_record;

        smpls_left = beat_onset_list[i] % signalcomp->edfhdr->edfparam[signalcomp->edfsignal[0]].smp_per_record;

        l_time += (datrecs * signalcomp->edfhdr->long_data_record_duration);

        l_time += ((smpls_left * signalcomp->edfhdr->long_data_record_duration) / signalcomp->edfhdr->edfparam[signalcomp->edfsignal[0]].smp_per_record);

        if(!whole_recording)
        {
          l_time += (mainwindow->edfheaderlist[mainwindow->sel_viewtime]->viewtime - signalcomp->edfhdr->viewtime);
        }

        if(type == 2)
        {
          fprintf(outputfile, "%.4f\t%.4f\n", ((double)l_time) / TIME_DIMENSION, beat_interval_list[i]);
        }

        if(type == 3)
        {
          fprintf(outputfile, "%.4f\n", ((double)l_time) / TIME_DIMENSION);
        }
      }
    }

    fclose(outputfile);
  }

  myobjectDialog->close();

  if(!import_as_annots)
  {
    sprintf(str, "Done. The R-onsets and/or RR-intervals are exported to:\n\n%s", path);
    QMessageBox messagewindow(QMessageBox::Information, "Ready", str);
    messagewindow.setIconPixmap(QPixmap(":/images/ok.png"));
    messagewindow.exec();
  }

  reset_ecg_filter(signalcomp->ecg_filter);

  mainwindow->setup_viewbuf();
}
void UI_ExportAnnotationswindow::ExportButtonClicked()
{
  int i, j, n,
      len,
      csv_format=0,
      hdl,
      annot_cnt,
      temp,
      include_duration;

  char path[MAX_PATH_LENGTH],
       str[1024],
       separator;

  FILE *annotationfile=NULL;

  struct annotationblock *annot, *annot_list;

  struct edfhdrblock *hdr;

  struct date_time_struct tm;


  if(CSVRadioButton->isChecked() == true)
  {
    if(asciiSecondsRadioButton->isChecked() == true)
    {
      csv_format = 1;
    }

    if(asciiISOtimeRadioButton->isChecked() == true)
    {
      csv_format = 2;
    }

    if(asciiISOtimedateRadioButton->isChecked() == true)
    {
      csv_format = 3;
    }

    if(asciiISOtimeFractionRadioButton->isChecked() == true)
    {
      csv_format = 4;
    }

    if(asciiISOtimedateFractionRadioButton->isChecked() == true)
    {
      csv_format = 5;
    }
  }

  if(EDFplusRadioButton->isChecked() == true)
  {
    csv_format = 0;
  }

  if(XMLRadioButton->isChecked() == true)
  {
    csv_format = 8;
  }

   mainwindow->export_annotations_var->format = csv_format;

  if(separatorBox->currentIndex() == 0)
  {
    separator = ',';
    mainwindow->export_annotations_var->separator = 0;
  }
  else
  {
    separator = '\t';
    mainwindow->export_annotations_var->separator = 1;
  }

  if(durationCheckBox->checkState() == Qt::Checked)
  {
    include_duration = 1;
    mainwindow->export_annotations_var->duration = 1;
  }
  else
  {
    include_duration = 0;
    mainwindow->export_annotations_var->duration = 0;
  }

  if(!mainwindow->files_open)
  {
    ExportAnnotsDialog->close();
    return;
  }

  if(filelist->count() < 1)
  {
    ExportAnnotsDialog->close();
    return;
  }

  ExportButton->setEnabled(false);
  CloseButton->setEnabled(false);

  for(i=0; i<mainwindow->files_open; i++)
  {
    if(!strcmp(mainwindow->edfheaderlist[i]->filename, filelist->item(filelist->currentRow())->text().toLocal8Bit().data()))
    {
      break;
    }
  }

  if(i==mainwindow->files_open)
  {
    ExportAnnotsDialog->close();
    return;
  }

  n = i;

  if(mergeRadioButton->isChecked() == true)
  {
    n = mainwindow->sel_viewtime;
  }

  hdr = mainwindow->edfheaderlist[n];

  path[0] = 0;
  if(mainwindow->recent_savedir[0]!=0)
  {
    strcpy(path, mainwindow->recent_savedir);
    strcat(path, "/");
  }
  len = strlen(path);
  get_filename_from_path(path + len, mainwindow->edfheaderlist[n]->filename, MAX_PATH_LENGTH - len);
  remove_extension_from_filename(path);
  if((csv_format > 0) && (csv_format < 6))
  {
    strcat(path, "_annotations.txt");

    strcpy(path, QFileDialog::getSaveFileName(0, "Output file", QString::fromLocal8Bit(path), "Text files (*.txt *.TXT *.csv *.CSV)").toLocal8Bit().data());
  }

  if(csv_format == 8)
  {
    strcat(path, "_annotations.xml");

    strcpy(path, QFileDialog::getSaveFileName(0, "Output file", QString::fromLocal8Bit(path), "XML files (*.xml *.XML)").toLocal8Bit().data());
  }

  if(csv_format == 0)
  {
    strcat(path, "_annotations.edf");

    strcpy(path, QFileDialog::getSaveFileName(0, "Output file", QString::fromLocal8Bit(path), "EDF files (*.edf *.EDF)").toLocal8Bit().data());
  }

  if(!strcmp(path, ""))
  {
    ExportAnnotsDialog->close();
    return;
  }

  get_directory_from_path(mainwindow->recent_savedir, path, MAX_PATH_LENGTH);

  if(mainwindow->file_is_opened(path))
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Export annotations", "Error, selected file is in use.");
    messagewindow.exec();
    return;
  }

  annot_list = edfplus_annotation_copy_list(&mainwindow->annotationlist[n]);

  if(mergeRadioButton->isChecked() == true)
  {
    for(i=0; i < mainwindow->files_open; i++)
    {
      if(i != mainwindow->sel_viewtime)
      {
        annot_cnt = edfplus_annotation_count(&mainwindow->annotationlist[i]);

        for(j=0; j < annot_cnt; j++)
        {
          edfplus_annotation_add_copy(&annot_list, edfplus_annotation_item(&mainwindow->annotationlist[i], j));

          annot = edfplus_annotation_item(&annot_list, edfplus_annotation_count(&annot_list) - 1);

          annot->onset -= (mainwindow->edfheaderlist[i]->viewtime - mainwindow->edfheaderlist[mainwindow->sel_viewtime]->viewtime);
        }
      }
    }

    edfplus_annotation_sort(&annot_list);
  }

  annot_cnt = edfplus_annotation_count(&annot_list);

///////////////////////////// CSV (text) export //////////////////////////////////////

  if((csv_format > 0) && (csv_format < 6))
  {
    annotationfile = fopeno(path, "wb");
    if(annotationfile==NULL)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "Can not open annotationfile for writing.");
      messagewindow.exec();
      ExportAnnotsDialog->close();
      edfplus_annotation_delete_list(&annot_list);
      return;
    }

    if(include_duration)
    {
      fprintf(annotationfile, "Onset%cDuration%cAnnotation\n", separator, separator);
    }
    else
    {
      fprintf(annotationfile, "Onset%cAnnotation\n", separator);
    }

    for(j=0; j < annot_cnt; j++)
    {
      annot = edfplus_annotation_item(&annot_list, j);
      if(annot == NULL)
      {
        break;
      }
      strncpy(str, annot->annotation, 1024);
      str[1023] = 0;
      utf8_to_latin1(str);

      len = strlen(str);
      for(i=0; i<len; i++)
      {
        if((((unsigned char *)str)[i] < 32) || (((unsigned char *)str)[i] == ','))
        {
          str[i] = '.';
        }
      }

      if(csv_format == 1)
      {
        if(include_duration)
        {
          fprintf(annotationfile, "%+.7f%c%s%c%s\n", (double)(annot->onset - hdr->starttime_offset) / TIME_DIMENSION, separator, annot->duration, separator, str);
        }
        else
        {
          fprintf(annotationfile, "%+.7f%c%s\n", (double)(annot->onset - hdr->starttime_offset) / TIME_DIMENSION, separator, str);
        }
      }

      if(csv_format == 2)
      {
        temp = annot->onset % TIME_DIMENSION;

        if(temp < 0)
        {
          utc_to_date_time(hdr->utc_starttime + (annot->onset / TIME_DIMENSION) - 1, &tm);
        }
        else
        {
          utc_to_date_time(hdr->utc_starttime + (annot->onset / TIME_DIMENSION), &tm);
        }

        if(include_duration)
        {
          fprintf(annotationfile, "%02i:%02i:%02i%c%s%c%s\n", tm.hour, tm.minute, tm.second, separator, annot->duration, separator, str);
        }
        else
        {
          fprintf(annotationfile, "%02i:%02i:%02i%c%s\n", tm.hour, tm.minute, tm.second, separator, str);
        }
      }

      if(csv_format == 3)
      {
        temp = annot->onset % TIME_DIMENSION;

        if(temp < 0)
        {
          utc_to_date_time(hdr->utc_starttime + (annot->onset / TIME_DIMENSION) - 1, &tm);
        }
        else
        {
          utc_to_date_time(hdr->utc_starttime + (annot->onset / TIME_DIMENSION), &tm);
        }

        if(include_duration)
        {
          fprintf(annotationfile, "%04i-%02i-%02iT%02i:%02i:%02i%c%s%c%s\n", tm.year, tm.month, tm.day, tm.hour, tm.minute, tm.second, separator, annot->duration, separator, str);
        }
        else
        {
          fprintf(annotationfile, "%04i-%02i-%02iT%02i:%02i:%02i%c%s\n", tm.year, tm.month, tm.day, tm.hour, tm.minute, tm.second, separator, str);
        }
      }

      if(csv_format == 4)
      {
        temp = annot->onset % TIME_DIMENSION;

        if(temp < 0)
        {
          utc_to_date_time(hdr->utc_starttime + (annot->onset / TIME_DIMENSION) - 1, &tm);

          temp = TIME_DIMENSION + temp;
        }
        else
        {
          utc_to_date_time(hdr->utc_starttime + (annot->onset / TIME_DIMENSION), &tm);
        }

        if(include_duration)
        {
          fprintf(annotationfile, "%02i:%02i:%02i.%07i%c%s%c%s\n", tm.hour, tm.minute, tm.second, temp, separator, annot->duration, separator, str);
        }
        else
        {
          fprintf(annotationfile, "%02i:%02i:%02i.%07i%c%s\n", tm.hour, tm.minute, tm.second, temp, separator, str);
        }
      }

      if(csv_format == 5)
      {
        temp = annot->onset % TIME_DIMENSION;

        if(temp < 0)
        {
          utc_to_date_time(hdr->utc_starttime + (annot->onset / TIME_DIMENSION) - 1, &tm);

          temp = TIME_DIMENSION + temp;
        }
        else
        {
          utc_to_date_time(hdr->utc_starttime + (annot->onset / TIME_DIMENSION), &tm);
        }

        if(include_duration)
        {
          fprintf(annotationfile, "%04i-%02i-%02iT%02i:%02i:%02i.%07i%c%s%c%s\n", tm.year, tm.month, tm.day, tm.hour, tm.minute, tm.second, temp, separator, annot->duration, separator, str);
        }
        else
        {
          fprintf(annotationfile, "%04i-%02i-%02iT%02i:%02i:%02i.%07i%c%s\n", tm.year, tm.month, tm.day, tm.hour, tm.minute, tm.second, temp, separator, str);
        }
      }
    }

    fclose(annotationfile);

    edfplus_annotation_delete_list(&annot_list);

    QMessageBox messagewindow(QMessageBox::Information, "Ready", "Done.");
    messagewindow.setIconPixmap(QPixmap(":/images/ok.png"));
    messagewindow.exec();

    ExportAnnotsDialog->close();

    return;
  }

///////////////////////////// XML export //////////////////////////////////////

  if(csv_format == 8)
  {
    annotationfile = fopeno(path, "wb");
    if(annotationfile==NULL)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "Can not open annotationfile for writing.");
      messagewindow.exec();
      ExportAnnotsDialog->close();
      edfplus_annotation_delete_list(&annot_list);
      return;
    }

    fprintf(annotationfile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");

    fprintf(annotationfile, "<!-- Generated by " PROGRAM_NAME " " PROGRAM_VERSION " -->\n");

    fprintf(annotationfile, "<annotationlist>\n");

    utc_to_date_time(hdr->utc_starttime, &tm);

    fprintf(annotationfile, " <recording_start_time>%04i-%02i-%02iT%02i:%02i:%02i.%07i</recording_start_time>\n",
                            tm.year, tm.month, tm.day, tm.hour, tm.minute, tm.second, (int)hdr->starttime_offset);

    for(j=0; j < annot_cnt; j++)
    {
      annot = edfplus_annotation_item(&annot_list, j);
      if(annot == NULL)
      {
        break;
      }

      temp = annot->onset % TIME_DIMENSION;

      if(temp < 0)
      {
        utc_to_date_time(hdr->utc_starttime + (annot->onset / TIME_DIMENSION) - 1, &tm);

        temp = TIME_DIMENSION + temp;
      }
      else
      {
        utc_to_date_time(hdr->utc_starttime + (annot->onset / TIME_DIMENSION), &tm);
      }

      fprintf(annotationfile, " <annotation>\n"
                              "  <onset>%04i-%02i-%02iT%02i:%02i:%02i.%07i</onset>\n"
                              "  <duration>%s</duration>\n"
                              "  <description>",
                              tm.year, tm.month, tm.day, tm.hour, tm.minute, tm.second, temp, annot->duration);

      xml_fwrite_encode_entity(annotationfile, annot->annotation);

      fprintf(annotationfile,                     "</description>\n"
                              " </annotation>\n");
    }

    fprintf(annotationfile, "</annotationlist>\n");

    fclose(annotationfile);

    edfplus_annotation_delete_list(&annot_list);

    QMessageBox messagewindow(QMessageBox::Information, "Ready", "Done.");
    messagewindow.setIconPixmap(QPixmap(":/images/ok.png"));
    messagewindow.exec();

    ExportAnnotsDialog->close();

    return;
  }

///////////////////////////// EDFplus export //////////////////////////////////////

  if(csv_format == 0)
  {
    hdl = edfopen_file_writeonly(path, EDFLIB_FILETYPE_EDFPLUS, 0);
    if(hdl < 0)
    {
      switch(hdl)
      {
        case EDFLIB_MALLOC_ERROR : strcpy(str, "EDFlib: malloc error");
                                  break;
        case EDFLIB_NO_SUCH_FILE_OR_DIRECTORY : strcpy(str, "EDFlib: no such file or directory");
                                  break;
        case EDFLIB_MAXFILES_REACHED : strcpy(str, "EDFlib: maximum files reached");
                                  break;
        case EDFLIB_FILE_ALREADY_OPENED : strcpy(str, "EDFlib: file already opened");
                                  break;
        case EDFLIB_NUMBER_OF_SIGNALS_INVALID : strcpy(str, "EDFlib: number of signals is invalid");
                                  break;
        default : strcpy(str, "EDFlib: unknown error");
                                  break;
      }

      QMessageBox messagewindow(QMessageBox::Critical, "Error", str);
      messagewindow.exec();
      edfplus_annotation_delete_list(&annot_list);
      ExportAnnotsDialog->close();
      return;
    }

    utc_to_date_time(hdr->utc_starttime, &tm);
    edf_set_startdatetime(hdl, tm.year, tm.month, tm.day, tm.hour, tm.minute, tm.second);

    if((hdr->edfplus) || (hdr->bdfplus))
    {
      edf_set_patientname(hdl, hdr->plus_patient_name);
      edf_set_patientcode(hdl, hdr->plus_patientcode);
      if(!(strcmp(hdr->plus_gender, "Male")))
      {
        edf_set_gender(hdl, 1);
      }
      if(!(strcmp(hdr->plus_gender, "Female")))
      {
        edf_set_gender(hdl, 0);
      }
      if(hdr->plus_birthdate[0] != 0)
      {
        if(!(strncmp(hdr->plus_birthdate + 3, "jan", 3)))  n = 1;
        if(!(strncmp(hdr->plus_birthdate + 3, "feb", 3)))  n = 2;
        if(!(strncmp(hdr->plus_birthdate + 3, "mar", 3)))  n = 3;
        if(!(strncmp(hdr->plus_birthdate + 3, "apr", 3)))  n = 4;
        if(!(strncmp(hdr->plus_birthdate + 3, "may", 3)))  n = 5;
        if(!(strncmp(hdr->plus_birthdate + 3, "jun", 3)))  n = 6;
        if(!(strncmp(hdr->plus_birthdate + 3, "jul", 3)))  n = 7;
        if(!(strncmp(hdr->plus_birthdate + 3, "aug", 3)))  n = 8;
        if(!(strncmp(hdr->plus_birthdate + 3, "sep", 3)))  n = 9;
        if(!(strncmp(hdr->plus_birthdate + 3, "oct", 3)))  n = 10;
        if(!(strncmp(hdr->plus_birthdate + 3, "nov", 3)))  n = 11;
        if(!(strncmp(hdr->plus_birthdate + 3, "dec", 3)))  n = 12;
        edf_set_birthdate(hdl, atoi(hdr->plus_birthdate + 7), n, atoi(hdr->plus_birthdate));
      }
      edf_set_patient_additional(hdl, hdr->plus_patient_additional);
      edf_set_admincode(hdl, hdr->plus_admincode);
      edf_set_technician(hdl, hdr->plus_technician);
      edf_set_equipment(hdl, hdr->plus_equipment);
      edf_set_recording_additional(hdl, hdr->plus_recording_additional);
    }
    else
    {
      edf_set_patientname(hdl, hdr->patient);
      edf_set_recording_additional(hdl, hdr->recording);
    }

    int hasdot,
        decimals;

    for(j=0; j < annot_cnt; j++)
    {
      annot = edfplus_annotation_item(&annot_list, j);
      if(annot == NULL)
      {
        break;
      }

      if(annot->duration[0] == 0)
      {
        edfwrite_annotation_utf8(hdl, annot->onset / 1000LL, -1LL, annot->annotation);
      }
      else
      {
        strcpy(str, annot->duration);

        len = strlen(str);

        hasdot = 0;

        for(i=0; i<len; i++)
        {
          if(str[i] == '.')
          {
            hasdot = 1;

            for(decimals=0; decimals<4; decimals++)
            {
              str[i] = str[i+1];

              if(str[i] == 0)
              {
                for( ; decimals<4; decimals++)
                {
                  str[i] = '0';

                  i++;
                }

                i--;
              }

              i++;
            }

            str[i] = 0;

            break;
          }
        }

        if(!hasdot)
        {
          strcat(str, "0000");
        }

        edfwrite_annotation_utf8(hdl, annot->onset / 1000LL, atoi(str), annot->annotation);
      }
    }

    if(edfclose_file(hdl) != 0)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred: edfclose_file()");
      messagewindow.exec();
    }

    edfplus_annotation_delete_list(&annot_list);

    QMessageBox messagewindow(QMessageBox::Information, "Ready", "Done.");
    messagewindow.setIconPixmap(QPixmap(":/images/ok.png"));
    messagewindow.exec();

    ExportAnnotsDialog->close();
  }
}
Exemple #17
0
void UI_BI98002EDFwindow::SelectFileButton()
{
  int i, j, n,
      tmp,
      end_of_file,
      samplefreq=0,
      chns = 3,
      hdl,
      samplesize=1,
      bufsize,
      *buf2,
      datablocks,
      blocks_written,
      checked_modelnumber=0,
      checked_samplerate=0,
      checked_recordhours=0,
      checked_recorddate=0,
      checked_recordtime=0,
      startdate_year=0,
      startdate_month=0,
      startdate_day=0,
      starttime_hour=0,
      starttime_minute=0,
      starttime_second=0,
      progress_steps;

  char path[MAX_PATH_LENGTH],
       outputfilename[MAX_PATH_LENGTH],
       str[2048],
       str2[128],
       *buf1,
       tmp2,
       modelnumber_str[32];

  FILE *dcmfile,
       *evtfile;



  strcpy(path, QFileDialog::getOpenFileName(0, "Select inputfile", QString::fromLocal8Bit(recent_opendir), "DCM files (*.dcm *.DCM)").toLocal8Bit().data());

  if(!strcmp(path, ""))
  {
    return;
  }

  get_directory_from_path(recent_opendir, path, MAX_PATH_LENGTH);

  get_filename_from_path(outputfilename, path, MAX_PATH_LENGTH);

  dcmfile = fopeno(path, "rb");
  if(dcmfile==NULL)
  {
    snprintf(str, 2048, "Can not open file %s for reading.", path);
    QMessageBox messagewindow(QMessageBox::Critical, "Error", QString::fromLocal8Bit(str));
    messagewindow.exec();
    return;
  }

  remove_extension_from_filename(path);
  strcat(path, ".EVT");
  evtfile = fopeno(path, "rb");
  if(evtfile==NULL)
  {
    remove_extension_from_filename(path);
    strcat(path, ".evt");
    evtfile = fopeno(path, "rb");
    if(evtfile==NULL)
    {
      snprintf(str, 2048, "Can not open file %s for reading.", path);
      QMessageBox messagewindow(QMessageBox::Critical, "Error", str);
      messagewindow.exec();
      fclose(dcmfile);
      return;
    }
  }

/***************** check if the file is valid ******************************/

  for(end_of_file=0; end_of_file == 0; )
  {
    for(i=0; i<256; i++)
    {
      tmp = fgetc(evtfile);

      if(tmp == '\n')
      {
        break;
      }

      if(tmp == EOF)
      {
        end_of_file = 1;

        break;
      }

      str[i] = tmp;
    }

    str[i] = 0;

    if(!(strncmp(str, "Sampling Rate=", 14)))
    {
      samplefreq = atoi(str + 14);
      switch(samplefreq)
      {
        case  128 : break;
        case  256 : break;
        case  512 : break;
        case 1024 : break;

        default : QMessageBox messagewindow(QMessageBox::Critical, "Error", "Unknown samplerate.");
                  messagewindow.exec();
                  fclose(dcmfile);
                  fclose(evtfile);
                  return;
      }

      checked_samplerate = 1;
    }

    if(!(strncmp(str, "Model number=", 13)))
    {
      strncpy(modelnumber_str, str + 13, 8);
      modelnumber_str[8] = 0;

      if(strcmp(modelnumber_str, "TM SD01G") &&
         strcmp(modelnumber_str, "SD SD02G"))
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "Wrong modelnumber.");
        messagewindow.exec();
        fclose(dcmfile);
        fclose(evtfile);
        return;
      }

      checked_modelnumber = 1;
    }

    if(!(strncmp(str, "Record Date=", 12)))
    {
      strncpy(str2, str + 12, 10);
      str2[10] = 0;

      startdate_year = atoi(str2);
      startdate_month = atoi(str2 + 5);
      startdate_day = atoi(str2 + 8);

      if((startdate_year < 1970) || (startdate_year > 3000) ||
         (startdate_month < 1)   || (startdate_month > 12)  ||
         (startdate_day < 1)     || (startdate_day > 31))
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "Wrong record date.");
        messagewindow.exec();
        fclose(dcmfile);
        fclose(evtfile);
        return;
      }

      checked_recorddate = 1;
    }

    if(!(strncmp(str, "Record Time=", 12)))
    {
      strncpy(str2, str + 12, 10);
      str2[8] = 0;

      starttime_hour = atoi(str2);
      starttime_minute = atoi(str2 + 3);
      starttime_second = atoi(str2 + 6);

      if((starttime_hour < 0)  || (starttime_hour > 23)   ||
        (starttime_minute < 0) || (starttime_minute > 59) ||
        (starttime_second < 0) || (starttime_second > 59))
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "Wrong recordtime.");
        messagewindow.exec();
        fclose(dcmfile);
        fclose(evtfile);
        return;
      }

      checked_recordtime = 1;
    }

    if(!(strncmp(str, "Record Hours=", 13)))
    {
      strncpy(str2, str + 13, 10);
      str2[2] = 0;

      if((atoi(str2) != 24) && (atoi(str2) != 48))
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "Wrong record hours.");
        messagewindow.exec();
        fclose(dcmfile);
        fclose(evtfile);
        return;
      }

      checked_recordhours = 1;
    }
  }

  if(!checked_modelnumber ||
     !checked_samplerate  ||
     !checked_recordhours ||
     !checked_recorddate  ||
     !checked_recordtime)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Missing line.");
    messagewindow.exec();
    fclose(dcmfile);
    fclose(evtfile);
    return;
  }

///////////////////////////////////////////////////////////////////////////////////

  bufsize = chns * samplesize * samplefreq;

  buf1 = (char *)malloc(bufsize);
  if(buf1 == NULL)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Malloc error.");
    messagewindow.exec();
    fclose(dcmfile);
    fclose(evtfile);
    return;
  }

  buf2 = (int *)malloc(bufsize * sizeof(int));
  if(buf2 == NULL)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Malloc error.");
    messagewindow.exec();
    fclose(dcmfile);
    fclose(evtfile);
    free(buf1);
    return;
  }

///////////////////////////////////////////////////////////////////////////////////

  path[0] = 0;
  if(recent_savedir[0]!=0)
  {
    strcpy(path, recent_savedir);
    strcat(path, "/");
  }
  strcat(path, outputfilename);
  remove_extension_from_filename(path);
  strcat(path, ".edf");

  strcpy(path, QFileDialog::getSaveFileName(0, "Select outputfile", QString::fromLocal8Bit(path), "EDF files (*.edf *.EDF)").toLocal8Bit().data());

  if(!strcmp(path, ""))
  {
    fclose(dcmfile);
    fclose(evtfile);
    free(buf1);
    free(buf2);
    return;
  }

  get_directory_from_path(recent_savedir, path, MAX_PATH_LENGTH);

  hdl = edfopen_file_writeonly(path, EDFLIB_FILETYPE_EDFPLUS, chns);
  if(hdl<0)
  {
    snprintf(str, 2048, "Can not open file %s for writing.", path);
    QMessageBox messagewindow(QMessageBox::Critical, "Error", str);
    messagewindow.exec();
    fclose(dcmfile);
    fclose(evtfile);
    free(buf1);
    free(buf2);
    return;
  }

  for(i=0; i<chns; i++)
  {
    edf_set_samplefrequency(hdl, i, samplefreq);
  }

  for(i=0; i<chns; i++)
  {
    edf_set_digital_maximum(hdl, i, 127);
  }

  for(i=0; i<chns; i++)
  {
    edf_set_digital_minimum(hdl, i, -128);
  }

  for(i=0; i<chns; i++)
  {
    edf_set_physical_maximum(hdl, i, 2442.307692);
  }

  for(i=0; i<chns; i++)
  {
    edf_set_physical_minimum(hdl, i, -2461.538462);
  }

  for(i=0; i<chns; i++)
  {
    edf_set_physical_dimension(hdl, i, "uV");
  }

  edf_set_label(hdl, 0, "channel 1");

  edf_set_label(hdl, 1, "channel 2");

  edf_set_label(hdl, 2, "channel 3");

  edf_set_equipment(hdl, modelnumber_str);

  edf_set_patientname(hdl, "BI9800");

  edf_set_startdatetime(hdl, startdate_year, startdate_month, startdate_day, starttime_hour, starttime_minute, starttime_second);

  fseeko(dcmfile, 0LL, SEEK_END);
  datablocks = ftello(dcmfile) / bufsize;
  fseeko(dcmfile, 0LL, SEEK_SET);

  QProgressDialog progress("Converting...", "Cancel", 0, datablocks, myobjectDialog);
  progress.setWindowModality(Qt::WindowModal);
  progress.setMinimumDuration(200);

  progress_steps = datablocks / 100;
  if(progress_steps < 1)
  {
    progress_steps = 1;
  }

  for(blocks_written=0; ; blocks_written++)
  {
    if(!(blocks_written % progress_steps))
    {
      progress.setValue(blocks_written);

      qApp->processEvents();

      if(progress.wasCanceled() == true)
      {
        break;
      }
    }

    n = fread(buf1, bufsize, 1, dcmfile);
    if(n != 1)
    {
      break;
    }

    for(i=0; i<samplefreq; i++)
    {
      for(j=0; j<chns; j++)
      {
        tmp2 = buf1[(i * chns) + j] + 128;
        buf2[(j * samplefreq) + i] = tmp2;
      }
    }

    edf_blockwrite_digital_samples(hdl, buf2);
  }

  progress.reset();

  edfwrite_annotation_latin1(hdl, 0LL, -1LL, "Recording starts");

  fseeko(evtfile, 0LL, SEEK_SET);

  for(end_of_file=0; end_of_file == 0; )
  {
    for(i=0; i<256; i++)
    {
      tmp = fgetc(evtfile);

      if((tmp == '\n') || (tmp == '\r'))
      {
        break;
      }

      if(tmp == EOF)
      {
        end_of_file = 1;

        break;
      }

      str[i] = tmp;
    }

    str[i] = 0;

    if((isdigit(str[0])) && (isdigit(str[1])))
    {
      starttime_hour = atoi(str);
      starttime_minute = atoi(str + 3);
      starttime_second = atoi(str + 6);

      if((starttime_hour < 0)   || (starttime_hour > 23)   ||
         (starttime_minute < 0) || (starttime_minute > 59) ||
         (starttime_second < 0) || (starttime_second > 59))
      {
      }
      else
      {
        if(strlen(str) > 9)
        {
          edfwrite_annotation_latin1(hdl, (starttime_second + (starttime_minute * 60) + (starttime_hour * 3600)) * 10000, -1, str + 9);
        }
      }
    }
  }

  edfwrite_annotation_latin1(hdl, blocks_written * 10000LL, -1LL, "Recording ends");

  edfclose_file(hdl);

  fclose(dcmfile);
  fclose(evtfile);
  free(buf1);
  free(buf2);
}
Exemple #18
0
void UI_WAV2EDFwindow::SelectFileButton()
{
  FILE *inputfile=NULL;

  int i, j,
      edfsignals,
      sf,
      resolution,
      edf_hdl,
      readbufsize,
      *writebuf,
      bytes_per_sample,
      sf_divider;

unsigned int fmt_chunk_offset,
             data_chunk_offset,
             tmp;

  char path[MAX_PATH_LENGTH],
       outputfilename[MAX_PATH_LENGTH],
       scratchpad[512],
       *readbuf;

  long long blocks,
            leftover,
            progress_steps,
            k;

  union {
          unsigned int one;
          signed int one_signed;
          unsigned short two[2];
          signed short two_signed[2];
          unsigned char four[4];
        } var;


  enable_widgets(false);

  if(!(strlen(PatientnameLineEdit->text().toLatin1().data())))
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Invalid input", "Please enter a subject name.");
    messagewindow.exec();
    enable_widgets(true);
    return;
  }

  if(!(strlen(RecordingLineEdit->text().toLatin1().data())))
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Invalid input", "Please enter a recording description.");
    messagewindow.exec();
    enable_widgets(true);
    return;
  }

  strcpy(path, QFileDialog::getOpenFileName(0, "Select inputfile", QString::fromLocal8Bit(recent_opendir), "Text files (*.wav *.WAV)").toLocal8Bit().data());

  if(!strcmp(path, ""))
  {
    enable_widgets(true);
    return;
  }

  get_directory_from_path(recent_opendir, path, MAX_PATH_LENGTH);

  inputfile = fopeno(path, "rb");
  if(inputfile==NULL)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Can not open file for reading.");
    messagewindow.exec();
    enable_widgets(true);
    return;
  }

/***************** check if the wavefile is valid ******************************/

  rewind(inputfile);

  if(fread(scratchpad, 256, 1, inputfile)!=1)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while reading from inputfile.");
    messagewindow.exec();
    fclose(inputfile);
    enable_widgets(true);
    return;
  }

  if((strncmp(scratchpad, "RIFF", 4)) || (strncmp(scratchpad + 8, "WAVE", 4)))
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "File is not a Wave file.");
    messagewindow.exec();
    fclose(inputfile);
    enable_widgets(true);
    return;
  }

  fmt_chunk_offset = 12;

  while(1)
  {
    fseeko(inputfile, (long long)fmt_chunk_offset, SEEK_SET);

    if(fread(scratchpad, 256, 1, inputfile)!=1)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "Can not find fmt chunk.");
      messagewindow.exec();
      fclose(inputfile);
      enable_widgets(true);
      return;
    }

    if(strncmp(scratchpad, "fmt ", 4) == 0)
    {
      break;
    }

    tmp = *((unsigned int *)(scratchpad + 4));
    if(tmp < 2)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "Can not find fmt chunk.");
      messagewindow.exec();
      fclose(inputfile);
      enable_widgets(true);
      return;
    }

    if(tmp & 1)
    {
      tmp++;
    }

    fmt_chunk_offset += (tmp + 8);
  }

  if(*((signed short *)(scratchpad + 8)) != 1)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "File contains compressed data.\nCan not convert compressed data.");
    messagewindow.exec();
    fclose(inputfile);
    enable_widgets(true);
    return;
  }

  edfsignals = *((unsigned short *)(scratchpad + 10));

  if(edfsignals < 1)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Channels < 1");
    messagewindow.exec();
    fclose(inputfile);
    enable_widgets(true);
    return;
  }

  if(edfsignals > MAXSIGNALS)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Channels > MAXSIGNALS");
    messagewindow.exec();
    fclose(inputfile);
    enable_widgets(true);
    return;
  }

  sf = *((unsigned int *)(scratchpad + 12));

  if(sf < 1)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Samplefrequency < 1");
    messagewindow.exec();
    fclose(inputfile);
    enable_widgets(true);
    return;
  }

  if(sf > 500000)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Samplefrequency > 500000");
    messagewindow.exec();
    fclose(inputfile);
    enable_widgets(true);
    return;
  }

  resolution = *((unsigned short *)(scratchpad + 22));

  if(resolution < 8)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Resolution < 8 bit");
    messagewindow.exec();
    fclose(inputfile);
    enable_widgets(true);
    return;
  }

  if(resolution > 24)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Resolution > 24");
    messagewindow.exec();
    fclose(inputfile);
    enable_widgets(true);
    return;
  }

  if((resolution != 8) && (resolution != 16)  && (resolution != 24))
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Resolution (bitdepth) must be 8, 16 or 24 bit.");
    messagewindow.exec();
    fclose(inputfile);
    enable_widgets(true);
    return;
  }

  bytes_per_sample = 2;

  if(resolution > 16)
  {
    bytes_per_sample = 3;
  }

  if(resolution < 9)
  {
    bytes_per_sample = 1;
  }

///////////////////////////////////////////////////////////////////////////////

  data_chunk_offset = 12;

  while(1)
  {
    fseeko(inputfile, (long long)data_chunk_offset, SEEK_SET);

    if(fread(scratchpad, 256, 1, inputfile)!=1)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "Can not find data chunk.");
      messagewindow.exec();
      fclose(inputfile);
      enable_widgets(true);
      return;
    }

    if(strncmp(scratchpad, "data", 4) == 0)
    {
      break;
    }

    tmp = *((unsigned int *)(scratchpad + 4));
    if(tmp < 2)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "Can not find data chunk.");
      messagewindow.exec();
      fclose(inputfile);
      enable_widgets(true);
      return;
    }

    if(tmp & 1)
    {
      tmp++;
    }

    data_chunk_offset += (tmp + 8);
  }

///////////////////////////////////////////////////////////////////////////////

  sf_divider = 1;

  if((sf % 10) == 0)
  {
    sf_divider = 10;

    sf /= 10;
  }

  blocks = (long long)(*((int *)(scratchpad + 4)));

  blocks /= (sf * edfsignals * bytes_per_sample);

  fseeko(inputfile, 0LL, SEEK_END);

  leftover = ftello(inputfile) - (long long)data_chunk_offset - 8LL;

  leftover /= (sf * edfsignals * bytes_per_sample);

  if(blocks > leftover)
  {
    blocks = leftover;
  }

  if(blocks < 1LL)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Not enough data in file.");
    messagewindow.exec();
    fclose(inputfile);
    enable_widgets(true);
    return;
  }

  readbufsize = bytes_per_sample * sf * edfsignals;

  readbuf = (char *)malloc(readbufsize);
  if(readbuf == NULL)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "A memory allocation error occurred. (readbuf).");
    messagewindow.exec();
    fclose(inputfile);
    enable_widgets(true);
    return;
  }

  writebuf = (int *)malloc(sf * edfsignals * sizeof(int));
  if(writebuf == NULL)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "A memory allocation error occurred. (writebuf).");
    messagewindow.exec();
    free(readbuf);
    fclose(inputfile);
    enable_widgets(true);
    return;
  }

//  printf("resolution is %i    edfsignals is %i    sf is %i    blocks is %lli\n", resolution, edfsignals, sf, blocks);

/***************** create a new EDF file *****************************************/

  get_filename_from_path(outputfilename, path, MAX_PATH_LENGTH);
  remove_extension_from_filename(outputfilename);
  if(resolution > 16)
  {
    strcat(outputfilename, ".bdf");
  }
  else
  {
    strcat(outputfilename, ".edf");
  }

  path[0] = 0;
  if(recent_savedir[0]!=0)
  {
    strcpy(path, recent_savedir);
    strcat(path, "/");
  }
  strcat(path, outputfilename);

  if(resolution > 16)
  {
    strcpy(path, QFileDialog::getSaveFileName(0, "Output file", QString::fromLocal8Bit(path), "BDF files (*.bdf *.BDF)").toLocal8Bit().data());
  }
  else
  {
    strcpy(path, QFileDialog::getSaveFileName(0, "Output file", QString::fromLocal8Bit(path), "EDF files (*.edf *.EDF)").toLocal8Bit().data());
  }

  if(!strcmp(path, ""))
  {
    enable_widgets(true);
    fclose(inputfile);
    return;
  }

  get_directory_from_path(recent_savedir, path, MAX_PATH_LENGTH);

  if(resolution > 16)
  {
    edf_hdl = edfopen_file_writeonly(path, EDFLIB_FILETYPE_BDFPLUS, edfsignals);
  }
  else
  {
    edf_hdl = edfopen_file_writeonly(path, EDFLIB_FILETYPE_EDFPLUS, edfsignals);
  }

  if(edf_hdl < 0)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Can not open output file for writing.");
    messagewindow.exec();
    fclose(inputfile);
    free(readbuf);
    free(writebuf);
    enable_widgets(true);
    return;
  }

  for(i=0; i<edfsignals; i++)
  {
    edf_set_samplefrequency(edf_hdl, i, sf);
  }

  if(sf_divider != 1)
  {
    edf_set_datarecord_duration(edf_hdl, 100000 / sf_divider);
  }

  for(i=0; i<edfsignals; i++)
  {
    if(resolution > 16)
    {
      edf_set_digital_maximum(edf_hdl, i, 8388607);
    }
    else
    {
      if(resolution < 9)
      {
        edf_set_digital_maximum(edf_hdl, i, 127);
      }
      else
      {
        edf_set_digital_maximum(edf_hdl, i, 32767);
      }
    }
  }

  for(i=0; i<edfsignals; i++)
  {
    if(resolution > 16)
    {
      edf_set_digital_minimum(edf_hdl, i, -8388608);
    }
    else
    {
      if(resolution < 9)
      {
        edf_set_digital_minimum(edf_hdl, i, -128);
      }
      else
      {
        edf_set_digital_minimum(edf_hdl, i, -32768);
      }
    }
  }

  for(i=0; i<edfsignals; i++)
  {
    edf_set_physical_maximum(edf_hdl, i, PhysMaxSpinBox->value());
  }

  for(i=0; i<edfsignals; i++)
  {
    edf_set_physical_minimum(edf_hdl, i, PhysMaxSpinBox->value() * -1.0);
  }

  for(i=0; i<edfsignals; i++)
  {
    edf_set_physical_dimension(edf_hdl, i, PhysDimLineEdit->text().toLatin1().data());
  }

  for(i=0; i<edfsignals; i++)
  {
    sprintf(scratchpad, "channel %i", i + 1);

    edf_set_label(edf_hdl, i, scratchpad);
  }

  edf_set_patientname(edf_hdl, PatientnameLineEdit->text().toLatin1().data());

  edf_set_recording_additional(edf_hdl, RecordingLineEdit->text().toLatin1().data());

  edf_set_startdatetime(edf_hdl, StartDatetimeedit->date().year(), StartDatetimeedit->date().month(), StartDatetimeedit->date().day(),
                        StartDatetimeedit->time().hour(), StartDatetimeedit->time().minute(), StartDatetimeedit->time().second());

  edfwrite_annotation_latin1(edf_hdl, 0LL, -1, "Recording starts");

/***************** start conversion **************************************/

  fseeko(inputfile, (long long)data_chunk_offset + 8LL, SEEK_SET);

  QProgressDialog progress("Converting a Wave file ...", "Abort", 0, (int)blocks, myobjectDialog);
  progress.setWindowModality(Qt::WindowModal);
  progress.setMinimumDuration(200);

  progress_steps = blocks / 100LL;
  if(progress_steps < 1LL)
  {
    progress_steps = 1LL;
  }

  for(k=0LL; k<blocks; k++)
  {
    if(!(k%progress_steps))
    {
      progress.setValue((int)k);

      qApp->processEvents();

      if(progress.wasCanceled() == true)
      {
        edfclose_file(edf_hdl);
        fclose(inputfile);
        free(readbuf);
        free(writebuf);
        enable_widgets(true);
        return;
      }
    }

    if(fread(readbuf, readbufsize, 1, inputfile)!=1)
    {
      progress.reset();
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "A read error occurred during conversion.");
      messagewindow.exec();
      edfclose_file(edf_hdl);
      fclose(inputfile);
      free(readbuf);
      free(writebuf);
      enable_widgets(true);
      return;
    }

    if(bytes_per_sample == 1)
    {
      for(i=0; i<sf; i++)
      {
        for(j=0; j<edfsignals; j++)
        {
          writebuf[i + (j * sf)] = (signed char)(*(readbuf + (i * edfsignals) + j) + 128);
        }
      }
    }

    if(bytes_per_sample == 2)
    {
      for(i=0; i<sf; i++)
      {
        for(j=0; j<edfsignals; j++)
        {
          writebuf[i + (j * sf)] = *(((signed short *)readbuf) + (i * edfsignals) + j);
        }
      }
    }

    if(bytes_per_sample == 3)
    {
      for(i=0; i<sf; i++)
      {
        for(j=0; j<edfsignals; j++)
        {
          var.two[0] = *((unsigned short *)(readbuf + (i * edfsignals) + (j * 3)));

          var.four[2] = *((unsigned char *)(readbuf + (i * edfsignals * 3) + (j * 3) + 2));

          if(var.four[2]&0x80)
          {
            var.four[3] = 0xff;
          }
          else
          {
            var.four[3] = 0x00;
          }

          writebuf[i + (j * sf)] = var.one_signed;
        }
      }
    }

    if(edf_blockwrite_digital_samples(edf_hdl, writebuf))
    {
      progress.reset();
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "A write error occurred during conversion.");
      messagewindow.exec();
      edfclose_file(edf_hdl);
      fclose(inputfile);
      free(readbuf);
      free(writebuf);
      enable_widgets(true);
      return;
    }
  }

  progress.reset();

  edfwrite_annotation_latin1(edf_hdl, (blocks * 10000LL) / sf_divider, -1, "Recording ends");

  edfclose_file(edf_hdl);

  fclose(inputfile);

  QMessageBox messagewindow(QMessageBox::Information, "Ready", "Done.");
  messagewindow.setIconPixmap(QPixmap(":/images/ok.png"));
  messagewindow.exec();

  free(readbuf);
  free(writebuf);

  enable_widgets(true);
}