示例#1
0
int UI_NK2EDFwindow::read_21e_file(char *e21filepath)
{
  int n,
      flag_eleclines=0,
      idx;

  char *electrode_name,
       electrode_name_buffer[ELECTRODE_NAME_MAXLEN],
       scratchpad[64],
       *charpntr;

  FILE *inputfile;


  remove_extension_from_filename(e21filepath);
  strcat(e21filepath, ".21E");
  inputfile = fopeno(e21filepath, "rb");
  if(inputfile==NULL)
  {
    remove_extension_from_filename(e21filepath);
    strcat(e21filepath, ".21e");
    inputfile = fopeno(e21filepath, "rb");
    if(inputfile==NULL)
    {
      return(1);
    }
  }

  while (!feof(inputfile))
  {
    charpntr = fgets(electrode_name_buffer, ELECTRODE_NAME_MAXLEN-1, inputfile);

    if(charpntr == NULL)
    {
      break;
    }

    if(strncmp(electrode_name_buffer, ELECTRODE_TAG, strlen(ELECTRODE_TAG)) == 0)
    {
      flag_eleclines = 1;
    }
    else
    {
      if(strncmp(electrode_name_buffer, ELECTRODE_UNTAG, strlen(ELECTRODE_UNTAG)) == 0)
      {
        flag_eleclines = 0;
      }
    }

    if(flag_eleclines)
    {
      if(strtok(electrode_name_buffer, "=") != NULL)
      {
        idx = atoi(electrode_name_buffer);

        electrode_name = strtok(NULL, "=");

        if(electrode_name != NULL)
        {
          n = strlen(electrode_name);

          if((n > 0)&&(electrode_name[n-1] == 10))
          {
            electrode_name[n-1] = 0;
          }

          if((n > 1)&&(electrode_name[n-2] == 13))
          {
            electrode_name[n-2] = 0;
          }

          n = strlen(electrode_name);

          if((idx >= 0) && (idx < 256))
          {
            if(n > 0)
            {
              strncpy(scratchpad, electrode_name, 16);

              strcat(scratchpad, "                ");

              latin1_to_ascii(scratchpad, 16);

              scratchpad[16] = 0;

              strcpy(labels[idx], scratchpad);
            }
            else
            {
              strcpy(labels[idx], "-               ");
            }
          }
        }
      }
    }
  }

  fclose(inputfile);

  return(0);
}
示例#2
0
int UI_NK2EDFwindow::convert_nk2edf(FILE *inputfile, FILE *outputfile, FILE *pntfile,  int offset, int edfplus, int n_logs, char *log_buf, int read_subevents)
{
  int i, j, k, p,
      temp,
      channels,
      samplefrequency,
      record_duration,
      raster,
      record_size,
      max_buf_records,
      bufsize,
      records_in_buf,
      seconds,
      deci_seconds,
      left_records,
      elapsed_time,
      error,
      records_written,
      progress_steps,
      n_log_processed;

  char *buf,
       *annotations,
       scratchpad[48];

/************************* filter events ******************************************/

  for(i=0; i<n_logs; i++)
  {
    elapsed_time = 36000 * (log_buf[(i * 45) + 20] - 48);
    elapsed_time += 3600 * (log_buf[(i * 45) + 21] - 48);
    elapsed_time += 600 * (log_buf[(i * 45) + 22] - 48);
    elapsed_time += 60 * (log_buf[(i * 45) + 23] - 48);
    elapsed_time += 10 * (log_buf[(i * 45) + 24] - 48);
    elapsed_time += log_buf[(i * 45) + 25] - 48;
    if(elapsed_time>=total_elapsed_time) break;
  }
  log_buf += i * 45;
  n_logs -= i;

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

  rewind(outputfile);

  fprintf(outputfile, "0       ");

  if(edfplus)
  {
    error = 0;
    fseeko(pntfile, 0x0604LL, SEEK_SET);
    if(fread(scratchpad, 10, 1, pntfile)!=1)
    {
      return(2);
    }
    scratchpad[10] = 0;
    latin1_to_ascii(scratchpad, strlen(scratchpad));
    for(i=0; i<10; i++)
    {
      if(scratchpad[i]==0)  break;
      if(scratchpad[i]==' ')  scratchpad[i] = '_';
    }
    if(i)
    {
      p = i;
      if(fwrite(scratchpad, i, 1, outputfile)!=1)
      {
        return(3);
      }
    }
    else
    {
      fputc('X', outputfile);
      p = 1;
    }
    fputc(' ', outputfile);
    p++;

    fseeko(pntfile, 0x064aLL, SEEK_SET);
    if(fread(scratchpad, 6, 1, pntfile)!=1)
    {
      return(2);
    }
    if(!strncmp(scratchpad, "Male", 4))  fputc('M', outputfile);
    else
    {
      if(!strncmp(scratchpad, "Female", 6))  fputc('F', outputfile);
      else  fputc('X', outputfile);
    }
    p++;
    fputc(' ', outputfile);
    p++;

    fseeko(pntfile, 0x0668LL, SEEK_SET);
    if(fread(scratchpad, 2, 1, pntfile)!=1)
    {
      return(2);
    }
    scratchpad[2] = 0;
    temp = atoi(scratchpad);
    if((temp<1)||(temp>31))  error = 1;
    for(i=0; i<2; i++)
    {
      if((scratchpad[i]<'0')||(scratchpad[i]>'9'))
      {
        error = 1;
        break;
      }
    }
    fseeko(pntfile, 0x0665LL, SEEK_SET);
    if(fread(scratchpad, 2, 1, pntfile)!=1)
    {
      return(2);
    }
    scratchpad[2] = 0;
    temp = atoi(scratchpad);
    if((temp<1)||(temp>12))  error = 1;
    fseeko(pntfile, 0x0660LL, SEEK_SET);
    if(fread(scratchpad, 4, 1, pntfile)!=1)
    {
      return(2);
    }
    scratchpad[4] = 0;
    temp = atoi(scratchpad);
    if((temp<1)||(temp>9999))  error = 1;
    for(i=0; i<4; i++)
    {
      if((scratchpad[i]<'0')||(scratchpad[i]>'9'))
      {
        error = 1;
        break;
      }
    }

    if(error)
    {
      fputc('X', outputfile);
      p++;
    }
    else
    {
      fseeko(pntfile, 0x0668LL, SEEK_SET);
      if(fread(scratchpad, 2, 1, pntfile)!=1)
      {
        return(2);
      }
      scratchpad[2] = 0;
      temp = atoi(scratchpad);
      if((temp<1)||(temp>31))
      {
        snprintf(scratchpad, 48, "01");
        error = 1;
      }
      for(i=0; i<2; i++)
      {
        if((scratchpad[i]<'0')||(scratchpad[i]>'9'))
        {
          snprintf(scratchpad, 48, "01");
          error = 1;
          break;
        }
      }
      if(fwrite(scratchpad, 2, 1, outputfile)!=1)
      {
        return(3);
      }
      p += 2;
      fputc('-', outputfile);
      p++;
      fseeko(pntfile, 0x0665LL, SEEK_SET);
      if(fread(scratchpad, 2, 1, pntfile)!=1)
      {
        return(2);
      }
      scratchpad[2] = 0;
      temp = atoi(scratchpad);
      switch(temp)
      {
        case  1 : strcpy(scratchpad, "JAN");
                  break;
        case  2 : strcpy(scratchpad, "FEB");
                  break;
        case  3 : strcpy(scratchpad, "MAR");
                  break;
        case  4 : strcpy(scratchpad, "APR");
                  break;
        case  5 : strcpy(scratchpad, "MAY");
                  break;
        case  6 : strcpy(scratchpad, "JUN");
                  break;
        case  7 : strcpy(scratchpad, "JUL");
                  break;
        case  8 : strcpy(scratchpad, "AUG");
                  break;
        case  9 : strcpy(scratchpad, "SEP");
                  break;
        case 10 : strcpy(scratchpad, "OCT");
                  break;
        case 11 : strcpy(scratchpad, "NOV");
                  break;
        case 12 : strcpy(scratchpad, "DEC");
                  break;
        default : strcpy(scratchpad, "JAN");
                  error = 1;
                  break;
      }
      if(fwrite(scratchpad, 3, 1, outputfile)!=1)
      {
        return(3);
      }
      p += 3;
      fputc('-', outputfile);
      p++;
      fseeko(pntfile, 0x0660LL, SEEK_SET);
      if(fread(scratchpad, 4, 1, pntfile)!=1)
      {
        return(2);
      }
      scratchpad[4] = 0;
      temp = atoi(scratchpad);
      if((temp<1)||(temp>9999))
      {
        snprintf(scratchpad, 48, "1800");
        error = 1;
      }
      for(i=0; i<4; i++)
      {
        if((scratchpad[i]<'0')||(scratchpad[i]>'9'))
        {
          snprintf(scratchpad, 48, "1800");
          error = 1;
          break;
        }
      }
      if(fwrite(scratchpad, 4, 1, outputfile)!=1)
      {
        return(3);
      }
      p += 4;
    }

    fputc(' ', outputfile);
    p++;

    fseeko(pntfile, 0x062eLL, SEEK_SET);
    if(fread(scratchpad, 20, 1, pntfile)!=1)
    {
      return(2);
    }
    scratchpad[20] = 0;
    latin1_to_ascii(scratchpad, strlen(scratchpad));
    for(i=0; i<20; i++)
    {
      if(scratchpad[i]==0)  break;
      if(scratchpad[i]==' ')  scratchpad[i] = '_';
    }
    if(i)
    {
      p += i;
      if(fwrite(scratchpad, i, 1, outputfile)!=1)
      {
        return(3);
      }
    }
    else
    {
      fputc('X', outputfile);
      p++;
    }

    for(i=0; i<80-p; i++)  fputc(' ', outputfile);

    if(fwrite("Startdate ", 10, 1, outputfile)!=1)
    {
      return(3);
    }
    p = 10;
    error = 0;
    fseeko(pntfile, 0x0046LL, SEEK_SET);
    if(fread(scratchpad, 2, 1, pntfile)!=1)
    {
      return(2);
    }
    scratchpad[2] = 0;
    temp = atoi(scratchpad);
    if((temp<1)||(temp>31))  error = 1;
    for(i=0; i<2; i++)
    {
      if((scratchpad[i]<'0')||(scratchpad[i]>'9'))
      {
        error = 1;
        break;
      }
    }
    fseeko(pntfile, 0x0044LL, SEEK_SET);
    if(fread(scratchpad, 2, 1, pntfile)!=1)
    {
      return(2);
    }
    scratchpad[2] = 0;
    temp = atoi(scratchpad);
    if((temp<1)||(temp>12))  error = 1;
    fseeko(pntfile, 0x0040LL, SEEK_SET);
    if(fread(scratchpad, 4, 1, pntfile)!=1)
    {
      return(2);
    }
    scratchpad[4] = 0;
    temp = atoi(scratchpad);
    if((temp<1970)||(temp>9999))  error = 1;
    for(i=0; i<4; i++)
    {
      if((scratchpad[i]<'0')||(scratchpad[i]>'9'))
      {
        error = 1;
        break;
      }
    }

    if(error)
    {
      fputc('X', outputfile);
      p++;
    }
    else
    {
      fseeko(pntfile, 0x0046LL, SEEK_SET);
      if(fread(scratchpad, 2, 1, pntfile)!=1)
      {
        return(2);
      }
      scratchpad[2] = 0;
      temp = atoi(scratchpad);
      if((temp<1)||(temp>31))  snprintf(scratchpad, 48, "01");
      for(i=0; i<2; i++)
      {
        if((scratchpad[i]<'0')||(scratchpad[i]>'9'))
        {
          snprintf(scratchpad, 48, "01");
          break;
        }
      }
      if(fwrite(scratchpad, 2, 1, outputfile)!=1)
      {
        return(3);
      }
      fputc('-', outputfile);
      fseeko(pntfile, 0x0044LL, SEEK_SET);
      if(fread(scratchpad, 2, 1, pntfile)!=1)
      {
        return(2);
      }
      scratchpad[2] = 0;
      temp = atoi(scratchpad);
      switch(temp)
      {
        case  1 : strcpy(scratchpad, "JAN");
                  break;
        case  2 : strcpy(scratchpad, "FEB");
                  break;
        case  3 : strcpy(scratchpad, "MAR");
                  break;
        case  4 : strcpy(scratchpad, "APR");
                  break;
        case  5 : strcpy(scratchpad, "MAY");
                  break;
        case  6 : strcpy(scratchpad, "JUN");
                  break;
        case  7 : strcpy(scratchpad, "JUL");
                  break;
        case  8 : strcpy(scratchpad, "AUG");
                  break;
        case  9 : strcpy(scratchpad, "SEP");
                  break;
        case 10 : strcpy(scratchpad, "OCT");
                  break;
        case 11 : strcpy(scratchpad, "NOV");
                  break;
        case 12 : strcpy(scratchpad, "DEC");
                  break;
        default : strcpy(scratchpad, "JAN");
                  break;
      }
      if(fwrite(scratchpad, 3, 1, outputfile)!=1)
      {
        return(3);
      }
      fputc('-', outputfile);
      fseeko(pntfile, 0x0040LL, SEEK_SET);
      if(fread(scratchpad, 4, 1, pntfile)!=1)
      {
        return(2);
      }
      scratchpad[4] = 0;
      temp = atoi(scratchpad);
      if((temp<1)||(temp>9999))  snprintf(scratchpad, 48, "1800");
      for(i=0; i<4; i++)
      {
        if((scratchpad[i]<'0')||(scratchpad[i]>'9'))
        {
          snprintf(scratchpad, 48, "1800");
          break;
        }
      }
      if(fwrite(scratchpad, 4, 1, outputfile)!=1)
      {
        return(3);
      }
      p += 11;
    }

    fputc(' ', outputfile);
    p++;

    fseeko(pntfile, 0x061cLL, SEEK_SET);
    if(fread(scratchpad, 10, 1, pntfile)!=1)
    {
      return(2);
    }
    scratchpad[10] = 0;
    latin1_to_ascii(scratchpad, strlen(scratchpad));
    for(i=0; i<10; i++)
    {
      if(scratchpad[i]==0)  break;
      if(scratchpad[i]==' ')  scratchpad[i] = '_';
    }
    if(i)
    {
      p += i;
      if(fwrite(scratchpad, i, 1, outputfile)!=1)
      {
        return(3);
      }
    }
    else
    {
      fputc('X', outputfile);
      p++;
    }

    fputc(' ', outputfile);
    p++;

    fseeko(pntfile, 0x06aaLL, SEEK_SET);
    if(fread(scratchpad, 20, 1, pntfile)!=1)
    {
      return(2);
    }
    scratchpad[20] = 0;
    latin1_to_ascii(scratchpad, strlen(scratchpad));
    for(i=0; i<20; i++)
    {
      if(scratchpad[i]==0)  break;
      if(scratchpad[i]==' ')  scratchpad[i] = '_';
    }
    if(i)
    {
      p += i;
      if(fwrite(scratchpad, i, 1, outputfile)!=1)
      {
        return(3);
      }
    }
    else
    {
      fputc('X', outputfile);
      p++;
    }

    fputc(' ', outputfile);
    p++;

    if(fwrite("Nihon_Kohden_", 13, 1, outputfile)!=1)
    {
      return(3);
    }
    p += 13;
    rewind(inputfile);
    if(fread(scratchpad, 16, 1, inputfile)!=1)
    {
      return(2);
    }
    scratchpad[16] = 0;
    latin1_to_ascii(scratchpad, strlen(scratchpad));
    for(i=0; i<16; i++)
    {
      if(scratchpad[i]==0)  break;
      if(scratchpad[i]==' ')  scratchpad[i] = '_';
    }
    if(fwrite(scratchpad, i, 1, outputfile)!=1)
    {
      return(3);
    }
    p += i;

    for(i=0; i<80-p; i++)  fputc(' ', outputfile);
  }
  else
  {
    fseeko(inputfile, 0x004fLL, SEEK_SET);
    if(fread(scratchpad, 32, 1, inputfile)!=1)
    {
      return(2);
    }
    scratchpad[32] = 0;
    latin1_to_ascii(scratchpad, strlen(scratchpad));
    for(i=0; i<32; i++)
    {
      if(scratchpad[i]==0)  break;
    }
    p = 80 - i;
    if(fwrite(scratchpad, i, 1, outputfile)!=1)
    {
      return(3);
    }
    for(i=0; i<p; i++)  fputc(' ', outputfile);

    if(fwrite("Nihon Kohden ", 13, 1, outputfile)!=1)
    {
      return(3);
    }
    rewind(inputfile);
    if(fread(scratchpad, 16, 1, inputfile)!=1)
    {
      return(2);
    }
    scratchpad[16] = 0;
    latin1_to_ascii(scratchpad, strlen(scratchpad));
    for(i=0; i<16; i++)
    {
      if(scratchpad[i]==0)  break;
    }
    p = 67 - i;
    if(fwrite(scratchpad, i, 1, outputfile)!=1)
    {
      return(3);
    }
    for(i=0; i<p; i++)  fputc(' ', outputfile);
  }

  fseeko(inputfile, (long long)(0x0016 + offset), SEEK_SET);
  temp = fgetc(inputfile);
  fprintf(outputfile, "%02u.", ((temp >> 4) * 10) + (temp & 15));
  fseeko(inputfile, (long long)(0x0015 + offset), SEEK_SET);
  temp = fgetc(inputfile);
  fprintf(outputfile, "%02u.", ((temp >> 4) * 10) + (temp & 15));
  fseeko(inputfile, (long long)(0x0014 + offset), SEEK_SET);
  temp = fgetc(inputfile);
  fprintf(outputfile, "%02u", ((temp >> 4) * 10) + (temp & 15));

  fseeko(inputfile, (long long)(0x0017 + offset), SEEK_SET);
  temp = fgetc(inputfile);
  fprintf(outputfile, "%02u.", ((temp >> 4) * 10) + (temp & 15));
  temp = fgetc(inputfile);
  fprintf(outputfile, "%02u.", ((temp >> 4) * 10) + (temp & 15));
  temp = fgetc(inputfile);
  fprintf(outputfile, "%02u", ((temp >> 4) * 10) + (temp & 15));

  fseeko(inputfile, (long long)(0x0026 + offset), SEEK_SET);
  channels = fgetc(inputfile) + 1;
  if(edfplus)
  {
    fprintf(outputfile, "%-8u", (channels + 1) * 256 + 256);
    fprintf(outputfile, "EDF+C");
    for(i=0; i<39; i++)  fputc(' ', outputfile);
  }
  else
  {
    fprintf(outputfile, "%-8u", channels * 256 + 256);
    for(i=0; i<44; i++)  fputc(' ', outputfile);
  }
  fseeko(inputfile, (long long)(0x001c + offset), SEEK_SET);
  if(fread((char *)(&record_duration), 4, 1, inputfile)!=1)
  {
    return(2);
  }
  if((record_duration < 10) || (record_duration > 99999999))
  {
    return(4);
  }
  fprintf(outputfile, "%-8u", record_duration);
  fprintf(outputfile, "0.1     ");
  if(edfplus)  fprintf(outputfile, "%-4u", channels + 1);
  else  fprintf(outputfile, "%-4u", channels);

  for(i=0; i<(channels - 1); i++)
  {
    fseeko(inputfile, (long long)(0x0027 + (i * 10) + offset), SEEK_SET);
    temp = fgetc(inputfile);
    if((temp < 0) || (temp > 255))
    {
      fprintf(outputfile, "%s", "-               ");
    }
    else
    {
      fprintf(outputfile, "%s", labels[temp]);
    }
  }

  fprintf(outputfile, "Events/Markers  ");

  if(edfplus)  fprintf(outputfile, "EDF Annotations ");

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

  for(i=0; i<(channels - 1); i++)
  {
    fseeko(inputfile, (long long)(0x0027 + (i * 10) + offset), SEEK_SET);
    temp = fgetc(inputfile);
    if(((temp<42)||(temp>73)) && (temp!=76) && (temp!=77))  fprintf(outputfile, "uV      ");
    else  fprintf(outputfile, "mV      ");
  }
  fprintf(outputfile, "        ");
  if(edfplus)  fprintf(outputfile, "        ");

  for(i=0; i<(channels - 1); i++)
  {
    fseeko(inputfile, (long long)(0x0027 + (i * 10) + offset), SEEK_SET);
    temp = fgetc(inputfile);
    if(((temp<42)||(temp>73)) && (temp!=76) && (temp!=77))  fprintf(outputfile, "-3200   ");
    else  fprintf(outputfile, "-12002.9");
  }
  fprintf(outputfile, "-1      ");
  if(edfplus)  fprintf(outputfile, "-1      ");

  for(i=0; i<(channels - 1); i++)
  {
    fseeko(inputfile, (long long)(0x0027 + (i * 10) + offset), SEEK_SET);
    temp = fgetc(inputfile);
    if(((temp<42)||(temp>73)) && (temp!=76) && (temp!=77))  fprintf(outputfile, "3199.902");
    else  fprintf(outputfile, "12002.56");
  }
  fprintf(outputfile, "1       ");
  if(edfplus)  fprintf(outputfile, "1       ");

  for(i=0; i<channels; i++)  fprintf(outputfile, "-32768  ");
  if(edfplus)  fprintf(outputfile, "-32768  ");

  for(i=0; i<channels; i++)  fprintf(outputfile, "32767   ");
  if(edfplus)  fprintf(outputfile, "32767   ");

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

  fseeko(inputfile, (long long)(0x001b + offset), SEEK_SET);
  samplefrequency = fgetc(inputfile) * 256;
  fseeko(inputfile, (long long)(0x001a + offset), SEEK_SET);
  samplefrequency += fgetc(inputfile);
  samplefrequency &= 0x3fff;
  for(i=0; i<channels; i++)  fprintf(outputfile, "%-8u", samplefrequency / 10);
  if(edfplus)  fprintf(outputfile, "%-8u", ANNOT_TRACKSIZE / 2);

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

/************************* write data ****************************************************/

  bufsize = 4194304;
  buf = (char *)calloc(1, bufsize);
  if(buf==NULL)  return(1);

  record_size = (samplefrequency / 10) * channels * 2;
  if(edfplus)  record_size += ANNOT_TRACKSIZE;

  max_buf_records = bufsize / record_size;

  raster = (samplefrequency / 10) * 2;

  seconds = 0;
  deci_seconds = 0;
  n_log_processed = 0;

  fseeko(inputfile, (long long)(0x0027LL + offset + ((channels - 1) * 10LL)), SEEK_SET);

  left_records = record_duration;

  QProgressDialog progress("Converting a waveform datablock...", NULL, 0, left_records);
  progress.setWindowModality(Qt::WindowModal);
  progress.setMinimumDuration(200);

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

  records_written = 0;

  while(left_records)
  {
    if(left_records>max_buf_records)  records_in_buf = max_buf_records;
    else  records_in_buf = left_records;

    for(i=0; i<records_in_buf; i++)
    {
      if(!(records_written%progress_steps))
      {
        progress.setValue(records_written);

        qApp->processEvents();
      }

      for(j=0; j<raster; j+=2)
      {
        for(k=0; k<(channels - 1); k++)
        {
          buf[j+(k*raster)+(i*record_size)] = fgetc(inputfile);
          buf[j+(k*raster)+(i*record_size)+1] = fgetc(inputfile) + 128;
        }
        buf[j+(k*raster)+(i*record_size)] = fgetc(inputfile);
        temp = fgetc(inputfile);
        if(temp==EOF)
        {
          free(buf);
          return(2);
        }
        buf[j+(k*raster)+(i*record_size)+1] = temp;
      }
      if(edfplus)
      {
        annotations = buf + (i * record_size) + (raster * channels);
        memset(annotations, 0, ANNOT_TRACKSIZE);
        p = sprintf(annotations, "%+i.%i", seconds, deci_seconds);
        annotations[p++] = 20;
        annotations[p++] = 20;
        for( ;n_log_processed < n_logs; n_log_processed++)
        {
          elapsed_time = 36000 * (log_buf[(n_log_processed * 45) + 20] - 48);
          elapsed_time += 3600 * (log_buf[(n_log_processed * 45) + 21] - 48);
          elapsed_time += 600 * (log_buf[(n_log_processed * 45) + 22] - 48);
          elapsed_time += 60 * (log_buf[(n_log_processed * 45) + 23] - 48);
          elapsed_time += 10 * (log_buf[(n_log_processed * 45) + 24] - 48);
          elapsed_time += log_buf[(n_log_processed * 45) + 25] - 48;
          if(elapsed_time>=total_elapsed_time)
          {
            elapsed_time -= total_elapsed_time;
            if(elapsed_time<(record_duration / 10))
            {
              p++;
              p += sprintf(annotations + p, "%+i", elapsed_time);
              if(read_subevents)
              {
                annotations[p] = '.';
                p++;
                strncpy(annotations + p, log_buf + (n_log_processed * 45) + 26, 3);
                p += 3;
              }
              annotations[p++] = 20;
              strncpy(annotations + p, log_buf + (n_log_processed * 45), 20);
              p += 20;
              annotations[p] = 20;

              n_log_processed++;

              break;
            }
          }
        }
      }
      if(++deci_seconds>9)
      {
        deci_seconds = 0;
        seconds++;
      }

      records_written++;
    }

    if(fwrite(buf, records_in_buf * record_size, 1, outputfile)!=1)
    {
      free(buf);
      return(3);
    }
    left_records -= records_in_buf;
  }

  progress.reset();

  total_elapsed_time += record_duration / 10;

  free(buf);

  return(0);
}
示例#3
0
/* Populates the sc->lines list with as many lines as possible.
 */
static void
get_more_lines (sws_configuration *sc)
{
  /* wrap anyway, if it's absurdly long. */
  int wrap_pix = (wrap_p ? sc->line_pixel_width : 10000);
  
  int col = 0;
  int col_pix = 0;

  char *s = sc->buf;

  int target = sc->buf_size - sc->buf_tail - 2;

  /* Fill as much as we can into sc->buf.
   */
  while (target > 0)
    {
      char c = textclient_getc (sc->tc);
      if (c <= 0)
        break;
      sc->buf[sc->buf_tail++] = c;
      sc->buf[sc->buf_tail] = 0;
      target--;
    }

  while (sc->total_lines < max_lines)
    {
      int cw;

      if (s >= sc->buf + sc->buf_tail)
        /* Reached end of buffer before end of line.  Bail. */
        return;

      cw = char_width (sc, *s);

      if (*s == '\r' || *s == '\n' ||
          col_pix + cw >= wrap_pix)
        {
          int L = s - sc->buf;

          if (*s == '\r' || *s == '\n')
            {
              if (*s == '\r' && s[1] == '\n')  /* swallow CRLF too */
                *s++ = 0;

              *s++ = 0;
            }
          else
            {
              /* We wrapped -- try to back up to the previous word boundary. */
              char *s2 = s;
              int n = 0;
              while (s2 > sc->buf && *s2 != ' ' && *s2 != '\t')
                s2--, n++;
              if (s2 > sc->buf)
                {
                  s = s2;
                  *s++ = 0;
                  L = s - sc->buf;
                }
            }

          sc->lines[sc->total_lines] = (char *) malloc (L+1);
          memcpy (sc->lines[sc->total_lines], sc->buf, L);
          sc->lines[sc->total_lines][L] = 0;

          if (!textures_p)
            latin1_to_ascii (sc->lines[sc->total_lines]);

          {
            char *t = sc->lines[sc->total_lines];
            char *ut = untabify (t);
            strip (ut, (alignment == 0), 1); /* if centering, strip
                                                leading whitespace too */
            sc->lines[sc->total_lines] = ut;
            free (t);
          }

          sc->total_lines++;

          if (sc->buf_tail > (s - sc->buf))
            {
              int i = sc->buf_tail - (s - sc->buf);
              memmove (sc->buf, s, i);
              sc->buf_tail = i;
              sc->buf[sc->buf_tail] = 0;
            }
          else
            {
              sc->buf_tail = 0;
            }

          sc->buf[sc->buf_tail] = 0;
          s = sc->buf;
          col = 0;
          col_pix = 0;
        }
      else
        {
          col++;
          col_pix += cw;
          if (*s == '\t')
            {
              int tab_pix = TAB_WIDTH * sc->char_width;
              col     = TAB_WIDTH * ((col / TAB_WIDTH) + 1);
              col_pix = tab_pix   * ((col / tab_pix)   + 1);
            }
          s++;
        }
    }
}
示例#4
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);
}
示例#5
0
void UI_LoadMontagewindow::LoadButtonClicked()
{
  int i, k, n, p,
      tmp,
      skip,
      found,
      signalcomps_read=0,
      signals_read,
      signal_cnt,
      filters_read,
      filter_cnt=0,
      ravg_filter_cnt=0,
      fidfilter_cnt=0,
      len,
      order=1,
      type=0,
      model=0,
      size=0,
      amp_cat[3],
      f_ruler_cnt=0;

  char *result,
       scratchpad[2048],
       str[128],
       *err,
       *filter_spec,
       spec_str[256];

  double frequency=1.0,
         frequency2=2.0,
         ripple=1.0;


  struct xml_handle *xml_hdl;

  struct signalcompblock *newsignalcomp;


  if(mainwindow->files_open==1)  n = 0;
  else  n = filelist->currentRow();

  if(mtg_path[0]==0)
  {
    strcpy(mtg_path, QFileDialog::getOpenFileName(0, "Load montage", QString::fromLocal8Bit(mainwindow->recent_montagedir), "Montage files (*.mtg *.MTG)").toLocal8Bit().data());

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

    get_directory_from_path(mainwindow->recent_montagedir, mtg_path, MAX_PATH_LENGTH);
  }

  xml_hdl = xml_get_handle(mtg_path);
  if(xml_hdl==NULL)
  {
    sprintf(scratchpad, "Can not open montage file:\n%s", mtg_path);
    QMessageBox messagewindow(QMessageBox::Critical, "Error", QString::fromLocal8Bit(scratchpad));
    messagewindow.exec();
    mainwindow->remove_recent_file_mtg_path(mtg_path);
    return;
  }

  if(strcmp(xml_hdl->elementname, PROGRAM_NAME "_montage"))
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "There seems to be an error in this montage file.");
    messagewindow.exec();
    xml_close(xml_hdl);
    return;
  }

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

  for(k=0; k<mainwindow->signalcomps; )
  {
    if(mainwindow->signalcomp[k]->filenum==n)
    {
      if(mainwindow->spectrumdock->signalcomp == mainwindow->signalcomp[k])
      {
        mainwindow->spectrumdock->clear();
        mainwindow->spectrumdock->dock->hide();
      }

      for(i=0; i<MAXSPECTRUMDIALOGS; i++)
      {
        p = mainwindow->signalcomp[k]->spectr_dialog[i];

        if(p != 0)
        {
          delete mainwindow->spectrumdialog[p - 1];

          mainwindow->spectrumdialog[p - 1] = NULL;
        }
      }

      for(i=0; i<MAXAVERAGECURVEDIALOGS; i++)
      {
        p = mainwindow->signalcomp[k]->avg_dialog[i];

        if(p != 0)
        {
          delete mainwindow->averagecurvedialog[p - 1];

          mainwindow->averagecurvedialog[p - 1] = NULL;
        }
      }

      if(mainwindow->signalcomp[k]->hascursor2)
      {
/*        crosshair_2_active = 0;
        crosshair_2_moving = 0;*/
      }

      if(mainwindow->signalcomp[k]->hascursor1)
      {
//         crosshair_1_active = 0;
//         crosshair_2_active = 0;
//         crosshair_1_moving = 0;
//         crosshair_2_moving = 0;

        for(i=0; i<mainwindow->signalcomps; i++)
        {
          mainwindow->signalcomp[i]->hascursor2 = 0;
        }
      }

      for(i=0; i<mainwindow->signalcomp[k]->filter_cnt; i++)
      {
        free(mainwindow->signalcomp[k]->filter[i]);
      }

      mainwindow->signalcomp[k]->filter_cnt = 0;

      for(i=0; i<mainwindow->signalcomp[k]->ravg_filter_cnt; i++)
      {
        free_ravg_filter(mainwindow->signalcomp[k]->ravg_filter[i]);
      }

      mainwindow->signalcomp[k]->ravg_filter_cnt = 0;

      for(i=0; i<mainwindow->signalcomp[k]->fidfilter_cnt; i++)
      {
        free(mainwindow->signalcomp[k]->fidfilter[i]);
        fid_run_free(mainwindow->signalcomp[k]->fid_run[i]);
        fid_run_freebuf(mainwindow->signalcomp[k]->fidbuf[i]);
        fid_run_freebuf(mainwindow->signalcomp[k]->fidbuf2[i]);
      }

      mainwindow->signalcomp[k]->fidfilter_cnt = 0;


      if(mainwindow->signalcomp[k]->ecg_filter != NULL)
      {
        free_ecg_filter(mainwindow->signalcomp[k]->ecg_filter);

        mainwindow->signalcomp[k]->ecg_filter = NULL;

        strcpy(mainwindow->signalcomp[k]->signallabel, mainwindow->signalcomp[k]->signallabel_bu);
        mainwindow->signalcomp[k]->signallabellen = mainwindow->signalcomp[k]->signallabellen_bu;
      }

      free(mainwindow->signalcomp[k]);

      for(i=k; i<mainwindow->signalcomps - 1; i++)
      {
        mainwindow->signalcomp[i] = mainwindow->signalcomp[i + 1];
      }

      mainwindow->signalcomps--;

      k = 0;
    }
    else
    {
      k++;
    }
  }

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

  while(1)
  {
    skip = 0;

    xml_goto_root(xml_hdl);

    signals_read = 0;

    if(xml_goto_nth_element_inside(xml_hdl, "signalcomposition", signalcomps_read))
    {
      break;
    }

    newsignalcomp = (struct signalcompblock *)calloc(1, sizeof(struct signalcompblock));
    if(newsignalcomp==NULL)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "Internal error: Memory allocation error:\n\"new signal composition\"");
      messagewindow.exec();
      xml_close(xml_hdl);
      return;
    }

    if(xml_goto_nth_element_inside(xml_hdl, "num_of_signals", 0))
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "There seems to be an error in this montage file.");
      messagewindow.exec();
      free(newsignalcomp);
      xml_close(xml_hdl);
      return;
    }
    result = xml_get_content_of_element(xml_hdl);
    signal_cnt = atoi(result);
    free(result);
    if((signal_cnt<1)||(signal_cnt>MAXSIGNALS))
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "There seems to be an error in this montage file.");
      messagewindow.exec();
      free(newsignalcomp);
      xml_close(xml_hdl);
      return;
    }
    newsignalcomp->edfhdr = mainwindow->edfheaderlist[n];
    newsignalcomp->filenum = n;
    newsignalcomp->num_of_signals = signal_cnt;
    newsignalcomp->hascursor1 = 0;
    newsignalcomp->hascursor2 = 0;
    newsignalcomp->hasoffsettracking = 0;
    newsignalcomp->hasgaintracking = 0;
    newsignalcomp->screen_offset = 0;
    newsignalcomp->filter_cnt = 0;
    newsignalcomp->ravg_filter_cnt = 0;
    newsignalcomp->ecg_filter = NULL;
    newsignalcomp->fidfilter_cnt = 0;
    newsignalcomp->hasruler = 0;
    newsignalcomp->polarity = 1;
    newsignalcomp->type = -1;

    xml_go_up(xml_hdl);
    if(!(xml_goto_nth_element_inside(xml_hdl, "alias", 0)))
    {
      result = xml_get_content_of_element(xml_hdl);
      if(result[0] != 0)
      {
        strncpy(newsignalcomp->alias, result, 16);
        newsignalcomp->alias[16] = 0;
        latin1_to_ascii(newsignalcomp->alias, 16);
        remove_trailing_spaces(newsignalcomp->alias);
        remove_leading_spaces(newsignalcomp->alias);
      }
      free(result);
      xml_go_up(xml_hdl);
    }

    if(xml_goto_nth_element_inside(xml_hdl, "voltpercm", 0))
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "There seems to be an error in this montage file.");
      messagewindow.exec();
      free(newsignalcomp);
      xml_close(xml_hdl);
      return;
    }
    result = xml_get_content_of_element(xml_hdl);
    newsignalcomp->voltpercm = atof(result);
    if(newsignalcomp->voltpercm==0.0)  newsignalcomp->voltpercm = 0.000000001;
    free(result);
    xml_go_up(xml_hdl);
    if(xml_goto_nth_element_inside(xml_hdl, "screen_offset", 0))
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "There seems to be an error in this montage file.");
      messagewindow.exec();
      free(newsignalcomp);
      xml_close(xml_hdl);
      return;
    }
    result = xml_get_content_of_element(xml_hdl);
    newsignalcomp->screen_offset = atof(result);
    free(result);
    xml_go_up(xml_hdl);

    if(!(xml_goto_nth_element_inside(xml_hdl, "polarity", 0)))
    {
      result = xml_get_content_of_element(xml_hdl);
      newsignalcomp->polarity = atoi(result);
      if(newsignalcomp->polarity != -1)
      {
        newsignalcomp->polarity = 1;
      }
      free(result);
      xml_go_up(xml_hdl);
    }

    if(xml_goto_nth_element_inside(xml_hdl, "color", 0))
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "There seems to be an error in this montage file.");
      messagewindow.exec();
      free(newsignalcomp);
      xml_close(xml_hdl);
      return;
    }
    result = xml_get_content_of_element(xml_hdl);
    newsignalcomp->color = atoi(result);
    if((newsignalcomp->color < 2) || (newsignalcomp->color > 18))
    {
      newsignalcomp->color = 2;
    }
    free(result);

    xml_go_up(xml_hdl);

    if(!(xml_goto_nth_element_inside(xml_hdl, "filter_cnt", 0)))
    {
      result = xml_get_content_of_element(xml_hdl);
      filter_cnt = atoi(result);
      if(filter_cnt < 0)  filter_cnt = 0;
      if(filter_cnt > MAXFILTERS)  filter_cnt = MAXFILTERS;
      free(result);

      xml_go_up(xml_hdl);
    }

    if(!(xml_goto_nth_element_inside(xml_hdl, "ravg_filter_cnt", 0)))
    {
      result = xml_get_content_of_element(xml_hdl);
      ravg_filter_cnt = atoi(result);
      if(ravg_filter_cnt < 0)  filter_cnt = 0;
      if(ravg_filter_cnt > MAXFILTERS)  ravg_filter_cnt = MAXFILTERS;
      free(result);

      xml_go_up(xml_hdl);
    }

    if(filter_cnt)
    {
      fidfilter_cnt = 0;
    }
    else
    {
      if(!(xml_goto_nth_element_inside(xml_hdl, "fidfilter_cnt", 0)))
      {
        result = xml_get_content_of_element(xml_hdl);
        fidfilter_cnt = atoi(result);
        if(fidfilter_cnt < 0)  fidfilter_cnt = 0;
        if(fidfilter_cnt > MAXFILTERS)  fidfilter_cnt = MAXFILTERS;
        free(result);

        xml_go_up(xml_hdl);
      }
    }

    for(signals_read=0; signals_read<signal_cnt; signals_read++)
    {
      if(xml_goto_nth_element_inside(xml_hdl, "signal", signals_read))
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "There seems to be an error in this montage file.");
        messagewindow.exec();
        free(newsignalcomp);
        xml_close(xml_hdl);
        return;
      }

      if(xml_goto_nth_element_inside(xml_hdl, "factor", 0))
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "There seems to be an error in this montage file.");
        messagewindow.exec();
        free(newsignalcomp);
        xml_close(xml_hdl);
        return;
      }
      result = xml_get_content_of_element(xml_hdl);
      newsignalcomp->factor[signals_read] = atoi(result);
      if(newsignalcomp->factor[signals_read] < -128)
      {
        newsignalcomp->factor[signals_read] = -128;
      }
      if(newsignalcomp->factor[signals_read] > 128)
      {
        newsignalcomp->factor[signals_read] = 128;
      }
      if(newsignalcomp->factor[signals_read] == 0)
      {
        newsignalcomp->factor[signals_read] = 1;
      }
      free(result);

      xml_go_up(xml_hdl);

      if(xml_goto_nth_element_inside(xml_hdl, "edfindex", 0))
      {
        if(xml_goto_nth_element_inside(xml_hdl, "label", 0))
        {
          QMessageBox messagewindow(QMessageBox::Critical, "Error", "There seems to be an error in this montage file.");
          messagewindow.exec();
          free(newsignalcomp);
          xml_close(xml_hdl);
          return;
        }
        result = xml_get_content_of_element(xml_hdl);

        remove_trailing_spaces(result);

        found = 0;

        for(i=0; i<newsignalcomp->edfhdr->edfsignals; i++)
        {
          strcpy(scratchpad, newsignalcomp->edfhdr->edfparam[i].label);

          remove_trailing_spaces(scratchpad);

          if(!strcmp(scratchpad, result))
          {
            newsignalcomp->edfsignal[signals_read] = i;

            if(newsignalcomp->edfhdr->edfparam[newsignalcomp->edfsignal[signals_read]].annotation)
            {
              found = 0;
            }
            else
            {
              found = 1;
            }
            break;
          }
        }
      }
      else
      {
        result = xml_get_content_of_element(xml_hdl);

        newsignalcomp->edfsignal[signals_read] = atoi(result);

        if((newsignalcomp->edfsignal[signals_read] < 0) || (newsignalcomp->edfsignal[signals_read] >= newsignalcomp->edfhdr->edfsignals))
        {
          found = 0;
        }
        else
        {
          if(newsignalcomp->edfhdr->edfparam[newsignalcomp->edfsignal[signals_read]].annotation)
          {
            found = 0;
          }
          else
          {
            found = 1;
          }
        }
      }

      free(result);

      if(!found)
      {
        free(newsignalcomp);
        skip = 1;
        signalcomps_read++;
        xml_go_up(xml_hdl);
        xml_go_up(xml_hdl);
        break;
      }

      if(signals_read)
      {
        if(newsignalcomp->edfhdr->edfparam[newsignalcomp->edfsignal[signals_read]].smp_per_record
          != newsignalcomp->edfhdr->edfparam[newsignalcomp->edfsignal[0]].smp_per_record)
        {
          free(newsignalcomp);
          skip = 1;
          signalcomps_read++;
          xml_go_up(xml_hdl);
          xml_go_up(xml_hdl);
          break;
        }
      }

      newsignalcomp->sensitivity[signals_read] = newsignalcomp->edfhdr->edfparam[newsignalcomp->edfsignal[signals_read]].bitvalue / (newsignalcomp->voltpercm * mainwindow->pixelsizefactor);

      if(!signals_read)
      {
        newsignalcomp->signallabel[0] = 0;
      }

      if(signal_cnt>1)
      {
        if(newsignalcomp->factor[signals_read]<0)
        {
          strcat(newsignalcomp->signallabel, "- ");
        }
        else
        {
          if(signals_read)
          {
            strcat(newsignalcomp->signallabel, "+ ");
          }
        }
      }
      strcpy(str, newsignalcomp->edfhdr->edfparam[newsignalcomp->edfsignal[signals_read]].label);
      strip_types_from_label(str);
      strcat(newsignalcomp->signallabel, str);
      strcat(newsignalcomp->signallabel, " ");
      len = strlen(newsignalcomp->signallabel);
      for(k=(len-1); k>0; k--)
      {
        if(newsignalcomp->signallabel[k]!=' ')  break;
      }
      newsignalcomp->signallabel[k+2] = 0;

      newsignalcomp->file_duration = newsignalcomp->edfhdr->long_data_record_duration * newsignalcomp->edfhdr->datarecords;

      newsignalcomp->signallabellen = strlen(newsignalcomp->signallabel);

      xml_go_up(xml_hdl);
      xml_go_up(xml_hdl);
    }

    if(skip)  continue;

    strcpy(newsignalcomp->physdimension, newsignalcomp->edfhdr->edfparam[newsignalcomp->edfsignal[0]].physdimension);
    remove_trailing_spaces(newsignalcomp->physdimension);

    for(filters_read=0; filters_read<filter_cnt; filters_read++)
    {
      if(xml_goto_nth_element_inside(xml_hdl, "filter", filters_read))
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "There seems to be an error in this montage file.");
        messagewindow.exec();
        free(newsignalcomp);
        xml_close(xml_hdl);
        return;
      }

      if(xml_goto_nth_element_inside(xml_hdl, "LPF", 0))
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "There seems to be an error in this montage file.");
        messagewindow.exec();
        free(newsignalcomp);
        xml_close(xml_hdl);
        return;
      }
      result = xml_get_content_of_element(xml_hdl);
      type = atoi(result);
      free(result);

      xml_go_up(xml_hdl);
      if(xml_goto_nth_element_inside(xml_hdl, "frequency", 0))
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "There seems to be an error in this montage file.");
        messagewindow.exec();
        free(newsignalcomp);
        xml_close(xml_hdl);
        return;
      }
      result = xml_get_content_of_element(xml_hdl);
      frequency = atof(result);
      free(result);

      if((type   < 0) || (type   >   1) || (frequency < 0.0001))
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "There seems to be an error in this montage file. (filter values)");
        messagewindow.exec();
        free(newsignalcomp);
        xml_close(xml_hdl);
        return;
      }

      if(frequency >= ((newsignalcomp->edfhdr->edfparam[newsignalcomp->edfsignal[0]].smp_per_record
                      / newsignalcomp->edfhdr->data_record_duration)
                      / 2.0))
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "The frequency of the filter(s) must be less than: samplerate / 2");
        messagewindow.exec();
        free(newsignalcomp);
        xml_close(xml_hdl);
        return;
      }

      if(type == 0)
      {
        sprintf(spec_str, "HpBu1/%f", frequency);
      }

      if(type == 1)
      {
        sprintf(spec_str, "LpBu1/%f", frequency);
      }

      filter_spec = spec_str;

      err = fid_parse(((double)(newsignalcomp->edfhdr->edfparam[newsignalcomp->edfsignal[0]].smp_per_record)) / newsignalcomp->edfhdr->data_record_duration,
                      &filter_spec,
                      &newsignalcomp->fidfilter[filters_read]);

      if(err != NULL)
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", err);
        messagewindow.exec();
        free(err);
        free(newsignalcomp);
        xml_close(xml_hdl);
        return;
      }

      newsignalcomp->fid_run[filters_read] = fid_run_new(newsignalcomp->fidfilter[filters_read],
                                                                         &newsignalcomp->fidfuncp[filters_read]);

      newsignalcomp->fidbuf[filters_read] = fid_run_newbuf(newsignalcomp->fid_run[filters_read]);
      newsignalcomp->fidbuf2[filters_read] = fid_run_newbuf(newsignalcomp->fid_run[filters_read]);

      newsignalcomp->fidfilter_freq[filters_read] = frequency;

      newsignalcomp->fidfilter_freq2[filters_read] = frequency * 1.12;

      newsignalcomp->fidfilter_ripple[filters_read] = -1.0;

      newsignalcomp->fidfilter_order[filters_read] = 1;

      newsignalcomp->fidfilter_type[filters_read] = type;

      newsignalcomp->fidfilter_model[filters_read] = 0;

      newsignalcomp->fidfilter_setup[filters_read] = 1;

      newsignalcomp->fidfilter_cnt = filters_read + 1;

      xml_go_up(xml_hdl);
      xml_go_up(xml_hdl);
    }

    for(filters_read=0; filters_read<ravg_filter_cnt; filters_read++)
    {
      if(xml_goto_nth_element_inside(xml_hdl, "ravg_filter", filters_read))
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "There seems to be an error in this montage file.");
        messagewindow.exec();
        free(newsignalcomp);
        xml_close(xml_hdl);
        return;
      }

      if(xml_goto_nth_element_inside(xml_hdl, "type", 0))
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "There seems to be an error in this montage file.");
        messagewindow.exec();
        free(newsignalcomp);
        xml_close(xml_hdl);
        return;
      }
      result = xml_get_content_of_element(xml_hdl);
      type = atoi(result);
      free(result);

      xml_go_up(xml_hdl);
      if(xml_goto_nth_element_inside(xml_hdl, "size", 0))
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "There seems to be an error in this montage file.");
        messagewindow.exec();
        free(newsignalcomp);
        xml_close(xml_hdl);
        return;
      }
      result = xml_get_content_of_element(xml_hdl);
      size = atoi(result);
      free(result);

      if((type   < 0) || (type   >   1) || (size < 2) || (size > 10000))
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "There seems to be an error in this montage file. (ravg_filter values)");
        messagewindow.exec();
        free(newsignalcomp);
        xml_close(xml_hdl);
        return;
      }

      newsignalcomp->ravg_filter[filters_read] = create_ravg_filter(type, size);
      if(newsignalcomp->ravg_filter[filters_read] == NULL)
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "A memory allocation error occurred when creating an ravg filter.");
        messagewindow.exec();
        free(newsignalcomp);
        xml_close(xml_hdl);
        return;
      }

      newsignalcomp->ravg_filter_size[filters_read] = size;

      newsignalcomp->ravg_filter_type[filters_read] = type;

      newsignalcomp->ravg_filter_cnt = filters_read + 1;

      xml_go_up(xml_hdl);
      xml_go_up(xml_hdl);
    }

    for(filters_read=0; filters_read<fidfilter_cnt; filters_read++)
    {
      if(xml_goto_nth_element_inside(xml_hdl, "fidfilter", filters_read))
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "There seems to be an error in this montage file. (fidfilter)");
        messagewindow.exec();
        free(newsignalcomp);
        xml_close(xml_hdl);
        return;
      }

      if(xml_goto_nth_element_inside(xml_hdl, "type", 0))
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "There seems to be an error in this montage file. (type)");
        messagewindow.exec();
        free(newsignalcomp);
        xml_close(xml_hdl);
        return;
      }
      result = xml_get_content_of_element(xml_hdl);
      type = atoi(result);
      free(result);

      xml_go_up(xml_hdl);
      if(xml_goto_nth_element_inside(xml_hdl, "model", 0))
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "There seems to be an error in this montage file. (model)");
        messagewindow.exec();
        free(newsignalcomp);
        xml_close(xml_hdl);
        return;
      }
      result = xml_get_content_of_element(xml_hdl);
      model = atoi(result);
      free(result);

      xml_go_up(xml_hdl);
      if(xml_goto_nth_element_inside(xml_hdl, "frequency", 0))
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "There seems to be an error in this montage file. (frequency)");
        messagewindow.exec();
        free(newsignalcomp);
        xml_close(xml_hdl);
        return;
      }
      result = xml_get_content_of_element(xml_hdl);
      frequency = atof(result);
      free(result);

      xml_go_up(xml_hdl);
      if(xml_goto_nth_element_inside(xml_hdl, "frequency2", 0))
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "There seems to be an error in this montage file. (frequency2)");
        messagewindow.exec();
        free(newsignalcomp);
        xml_close(xml_hdl);
        return;
      }
      result = xml_get_content_of_element(xml_hdl);
      frequency2 = atof(result);
      free(result);

      xml_go_up(xml_hdl);
      if(xml_goto_nth_element_inside(xml_hdl, "ripple", 0))
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "There seems to be an error in this montage file. (ripple)");
        messagewindow.exec();
        free(newsignalcomp);
        xml_close(xml_hdl);
        return;
      }
      result = xml_get_content_of_element(xml_hdl);
      ripple = atof(result);
      free(result);

      xml_go_up(xml_hdl);
      if(xml_goto_nth_element_inside(xml_hdl, "order", 0))
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "There seems to be an error in this montage file. (order)");
        messagewindow.exec();
        free(newsignalcomp);
        xml_close(xml_hdl);
        return;
      }
      result = xml_get_content_of_element(xml_hdl);
      order = atoi(result);
      free(result);

      if((model  < 0)         || (model  >   2)       ||
         (order  < 1)         || (order  > 100)       ||
         (type   < 0)         || (type   >   4)       ||
         (ripple < (-6.0))    || (ripple > (-0.1))    ||
         (frequency < 0.0001) || (frequency2 < 0.0001))
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "There seems to be an error in this montage file. (fidfilter values)");
        messagewindow.exec();
        free(newsignalcomp);
        xml_close(xml_hdl);
        return;
      }

      if(frequency >= ((newsignalcomp->edfhdr->edfparam[newsignalcomp->edfsignal[0]].smp_per_record
                      / newsignalcomp->edfhdr->data_record_duration)
                      / 2.0))
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "The frequency of the filter(s) must be less than: samplerate / 2");
        messagewindow.exec();
        free(newsignalcomp);
        xml_close(xml_hdl);
        return;
      }

      if(type > 2)
      {
        if(frequency2 >= ((newsignalcomp->edfhdr->edfparam[newsignalcomp->edfsignal[0]].smp_per_record
                        / newsignalcomp->edfhdr->data_record_duration)
                        / 2.0))
        {
          QMessageBox messagewindow(QMessageBox::Critical, "Error", "The frequency of the filter(s) must be less than: samplerate / 2");
          messagewindow.exec();
          free(newsignalcomp);
          xml_close(xml_hdl);
          return;
        }
      }

      if((type == 0) || (type == 1))
      {
        if(order > 8)
        {
          order = 8;
        }
      }

      if(type == 0)
      {
        if(model == 0)
        {
          sprintf(spec_str, "HpBu%i/%f", order, frequency);
        }

        if(model == 1)
        {
          sprintf(spec_str, "HpCh%i/%f/%f", order, ripple, frequency);
        }

        if(model == 2)
        {
          sprintf(spec_str, "HpBe%i/%f", order, frequency);
        }
      }

      if(type == 1)
      {
        if(model == 0)
        {
          sprintf(spec_str, "LpBu%i/%f", order, frequency);
        }

        if(model == 1)
        {
          sprintf(spec_str, "LpCh%i/%f/%f", order, ripple, frequency);
        }

        if(model == 2)
        {
          sprintf(spec_str, "LpBe%i/%f", order, frequency);
        }
      }

      if(type == 2)
      {
        if(order > 100)
        {
          order = 100;
        }

        if(order < 3)
        {
          order = 3;
        }

        if(model == 0)
        {
          sprintf(spec_str, "BsRe/%i/%f", order, frequency);
        }
      }

      if((type == 3) || (type == 4))
      {
        if(order < 2)
        {
          order = 2;
        }

        if(order % 2)
        {
          order++;
        }

        if(order > 16)
        {
          order = 16;
        }
      }

      if(type == 3)
      {
        if(model == 0)
        {
          sprintf(spec_str, "BpBu%i/%f-%f", order, frequency, frequency2);
        }

        if(model == 1)
        {
          sprintf(spec_str, "BpCh%i/%f/%f-%f", order, ripple, frequency, frequency2);
        }

        if(model == 2)
        {
          sprintf(spec_str, "BpBe%i/%f-%f", order, frequency, frequency2);
        }
      }

      if(type == 4)
      {
        if(model == 0)
        {
          sprintf(spec_str, "BsBu%i/%f-%f", order, frequency, frequency2);
        }

        if(model == 1)
        {
          sprintf(spec_str, "BsCh%i/%f/%f-%f", order, ripple, frequency, frequency2);
        }

        if(model == 2)
        {
          sprintf(spec_str, "BsBe%i/%f-%f", order, frequency, frequency2);
        }
      }

      filter_spec = spec_str;

      err = fid_parse(((double)(newsignalcomp->edfhdr->edfparam[newsignalcomp->edfsignal[0]].smp_per_record)) / newsignalcomp->edfhdr->data_record_duration,
                      &filter_spec,
                      &newsignalcomp->fidfilter[filters_read]);

      if(err != NULL)
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", err);
        messagewindow.exec();
        free(err);
        free(newsignalcomp);
        xml_close(xml_hdl);
        return;
      }

      newsignalcomp->fid_run[filters_read] = fid_run_new(newsignalcomp->fidfilter[filters_read],
                                                                         &newsignalcomp->fidfuncp[filters_read]);

      newsignalcomp->fidbuf[filters_read] = fid_run_newbuf(newsignalcomp->fid_run[filters_read]);
      newsignalcomp->fidbuf2[filters_read] = fid_run_newbuf(newsignalcomp->fid_run[filters_read]);

      newsignalcomp->fidfilter_freq[filters_read] = frequency;

      newsignalcomp->fidfilter_freq2[filters_read] = frequency2;

      newsignalcomp->fidfilter_ripple[filters_read] = ripple;

      newsignalcomp->fidfilter_order[filters_read] = order;

      newsignalcomp->fidfilter_type[filters_read] = type;

      newsignalcomp->fidfilter_model[filters_read] = model;

      newsignalcomp->fidfilter_setup[filters_read] = 1;

      newsignalcomp->fidfilter_cnt = filters_read + 1;

      xml_go_up(xml_hdl);
      xml_go_up(xml_hdl);
    }

    if(!xml_goto_nth_element_inside(xml_hdl, "ecg_filter", 0))
    {
      if(xml_goto_nth_element_inside(xml_hdl, "type", 0))
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "There seems to be an error in this montage file.");
        messagewindow.exec();
        free(newsignalcomp);
        xml_close(xml_hdl);
        return;
      }
      result = xml_get_content_of_element(xml_hdl);
      type = atoi(result);
      free(result);

      if(type == 1)
      {
        newsignalcomp->ecg_filter = create_ecg_filter(newsignalcomp->edfhdr->edfparam[newsignalcomp->edfsignal[0]].smp_per_record /
                                                      newsignalcomp->edfhdr->data_record_duration,
                                                      newsignalcomp->edfhdr->edfparam[newsignalcomp->edfsignal[0]].bitvalue,
                                                      mainwindow->powerlinefreq);
        if(newsignalcomp->ecg_filter == NULL)
        {
          QMessageBox messagewindow(QMessageBox::Critical, "Error", "A memory allocation error occurred when creating an ECG filter.");
          messagewindow.exec();
          free(newsignalcomp);
          xml_close(xml_hdl);
          return;
        }

        strcpy(newsignalcomp->signallabel_bu, newsignalcomp->signallabel);
        newsignalcomp->signallabellen_bu = newsignalcomp->signallabellen;
        strcpy(newsignalcomp->signallabel, "HR");
        newsignalcomp->signallabellen = strlen(newsignalcomp->signallabel);
        strcpy(newsignalcomp->physdimension_bu, newsignalcomp->physdimension);
        strcpy(newsignalcomp->physdimension, "bpm");
      }

      xml_go_up(xml_hdl);
      xml_go_up(xml_hdl);
    }

    if(newsignalcomp->ecg_filter == NULL)
    {
      if(!xml_goto_nth_element_inside(xml_hdl, "zratio_filter", 0))
      {
        if(xml_goto_nth_element_inside(xml_hdl, "type", 0))
        {
          QMessageBox messagewindow(QMessageBox::Critical, "Error", "There seems to be an error in this montage file.");
          messagewindow.exec();
          free(newsignalcomp);
          xml_close(xml_hdl);
          return;
        }
        result = xml_get_content_of_element(xml_hdl);
        type = atoi(result);
        free(result);

        xml_go_up(xml_hdl);

        if(type == 1)
        {
          if(xml_goto_nth_element_inside(xml_hdl, "crossoverfreq", 0))
          {
            QMessageBox messagewindow(QMessageBox::Critical, "Error", "There seems to be an error in this montage file.");
            messagewindow.exec();
            free(newsignalcomp);
            xml_close(xml_hdl);
            return;
          }
          result = xml_get_content_of_element(xml_hdl);
          newsignalcomp->zratio_crossoverfreq = atof(result);
          free(result);

          if((newsignalcomp->zratio_crossoverfreq < 5.0) || (newsignalcomp->zratio_crossoverfreq > 9.5))
          {
            newsignalcomp->zratio_crossoverfreq = 7.5;
          }

          newsignalcomp->zratio_filter = create_zratio_filter(newsignalcomp->edfhdr->edfparam[newsignalcomp->edfsignal[0]].smp_per_record,
                                                              newsignalcomp->edfhdr->long_data_record_duration,
                                                              newsignalcomp->zratio_crossoverfreq,
            newsignalcomp->edfhdr->edfparam[newsignalcomp->edfsignal[0]].bitvalue);

          if(newsignalcomp->zratio_filter == NULL)
          {
            QMessageBox messagewindow(QMessageBox::Critical, "Error", "A memory allocation error occurred when creating a Z-ratio filter.");
            messagewindow.exec();
            free(newsignalcomp);
            xml_close(xml_hdl);
            return;
          }

          strcpy(newsignalcomp->signallabel_bu, newsignalcomp->signallabel);
          newsignalcomp->signallabellen_bu = newsignalcomp->signallabellen;
          strcpy(newsignalcomp->signallabel, "Z-ratio ");
          strcat(newsignalcomp->signallabel, newsignalcomp->signallabel_bu);
          newsignalcomp->signallabellen = strlen(newsignalcomp->signallabel);
          strcpy(newsignalcomp->physdimension_bu, newsignalcomp->physdimension);
          strcpy(newsignalcomp->physdimension, "");

          xml_go_up(xml_hdl);
        }

        xml_go_up(xml_hdl);
      }
    }

    if(f_ruler_cnt == 0)
    {
      if(!xml_goto_nth_element_inside(xml_hdl, "floating_ruler", 0))
      {
        if(xml_goto_nth_element_inside(xml_hdl, "hasruler", 0))
        {
          QMessageBox messagewindow(QMessageBox::Critical, "Error", "There seems to be an error in this montage file.");
          messagewindow.exec();
          free(newsignalcomp);
          xml_close(xml_hdl);
          return;
        }
        result = xml_get_content_of_element(xml_hdl);
        tmp = atoi(result);
        free(result);

        xml_go_up(xml_hdl);

        if(tmp == 1)
        {
          f_ruler_cnt = 1;

          mainwindow->maincurve->ruler_x_position = 200;
          mainwindow->maincurve->ruler_y_position = 200;
          mainwindow->maincurve->floating_ruler_value = 0;

          if(!xml_goto_nth_element_inside(xml_hdl, "ruler_x_position", 0))
          {
            result = xml_get_content_of_element(xml_hdl);
            tmp = atoi(result);
            free(result);

            if((tmp >= 0) && (tmp < 5000))
            {
              mainwindow->maincurve->ruler_x_position = tmp;
            }

            xml_go_up(xml_hdl);
          }

          if(!xml_goto_nth_element_inside(xml_hdl, "ruler_y_position", 0))
          {
            result = xml_get_content_of_element(xml_hdl);
            tmp = atoi(result);
            free(result);

            if((tmp >= 0) && (tmp < 5000))
            {
              mainwindow->maincurve->ruler_y_position = tmp;
            }

            xml_go_up(xml_hdl);
          }

          if(!xml_goto_nth_element_inside(xml_hdl, "floating_ruler_value", 0))
          {
            result = xml_get_content_of_element(xml_hdl);
            tmp = atoi(result);
            free(result);

            if((tmp >= 0) && (tmp < 2))
            {
              mainwindow->maincurve->floating_ruler_value = tmp;
            }

            xml_go_up(xml_hdl);
          }

          newsignalcomp->hasruler = 1;
        }

        xml_go_up(xml_hdl);
      }
    }

    mainwindow->signalcomp[mainwindow->signalcomps] = newsignalcomp;

    mainwindow->signalcomps++;

    signalcomps_read++;
  }

  xml_goto_root(xml_hdl);

  if(!(xml_goto_nth_element_inside(xml_hdl, "pagetime", 0)))
  {
    result = xml_get_content_of_element(xml_hdl);
    mainwindow->pagetime = atoll(result);
    if(mainwindow->pagetime < 10000LL)
    {
      mainwindow->pagetime = 10000LL;
    }
    free(result);
  }

  xml_close(xml_hdl);

  if(LoadMontageDialog!=NULL) LoadMontageDialog->close();

  mainwindow->setMainwindowTitle(mainwindow->edfheaderlist[mainwindow->sel_viewtime]);

  if(mainwindow->files_open == 1)
  {
    strcpy(&mainwindow->recent_file_mtg_path[0][0], mtg_path);
  }


  for(i=0; i<3; i++)
  {
    amp_cat[i] = 0;
  }

  for(i=0; i<mainwindow->signalcomps; i++)
  {
    tmp = round_125_cat(mainwindow->signalcomp[i]->voltpercm);

    switch(tmp)
    {
      case 10 : amp_cat[0]++;
                break;
      case 20 : amp_cat[1]++;
                break;
      case 50 : amp_cat[2]++;
                break;
    }
  }

  mainwindow->amplitude_doubler = 10;

  if((amp_cat[1] > amp_cat[0]) && (amp_cat[1] >= amp_cat[2]))
  {
    mainwindow->amplitude_doubler = 20;
  }

  if((amp_cat[2] > amp_cat[0]) && (amp_cat[2] > amp_cat[1]))
  {
    mainwindow->amplitude_doubler = 50;
  }

  if(f_ruler_cnt == 1)
  {
    mainwindow->maincurve->ruler_active = 1;
  }

  mainwindow->setup_viewbuf();
}
示例#6
0
void UI_RAW2EDFapp::loadbuttonpressed()
{

  char path[MAX_PATH_LENGTH],
       *result;

  struct xml_handle *xml_hdl;

  strcpy(path, QFileDialog::getOpenFileName(0, "Load parameters", QString::fromLocal8Bit(recent_opendir), "Template files (*.template *.TEMPLATE)").toLocal8Bit().data());

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

  get_directory_from_path(recent_opendir, path, MAX_PATH_LENGTH);

  xml_hdl = xml_get_handle(path);
  if(xml_hdl==NULL)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Can not open file for reading.");
    messagewindow.exec();
    return;
  }

  if(strcmp(xml_hdl->elementname, PROGRAM_NAME "_raw2edf_template"))
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "There seems to be an error in this template.");
    messagewindow.exec();
    xml_close(xml_hdl);
    return;
  }

  if(!(xml_goto_nth_element_inside(xml_hdl, "sf", 0)))
  {
    result = xml_get_content_of_element(xml_hdl);
    if(result==NULL)
    {
      xml_close(xml_hdl);
      return;
    }

    raw2edf_var->sf = atoi(result);
    if(raw2edf_var->sf < 1)  raw2edf_var->sf = 1;
    if(raw2edf_var->sf > 1000000)  raw2edf_var->sf = 1000000;

    free(result);

    xml_go_up(xml_hdl);
  }

  if(!(xml_goto_nth_element_inside(xml_hdl, "chns", 0)))
  {
    result = xml_get_content_of_element(xml_hdl);
    if(result==NULL)
    {
      xml_close(xml_hdl);
      return;
    }

    raw2edf_var->chns = atoi(result);
    if(raw2edf_var->chns < 1)  raw2edf_var->chns = 1;
    if(raw2edf_var->chns > 256)  raw2edf_var->chns = 256;

    free(result);

    xml_go_up(xml_hdl);
  }

  if(!(xml_goto_nth_element_inside(xml_hdl, "phys_max", 0)))
  {
    result = xml_get_content_of_element(xml_hdl);
    if(result==NULL)
    {
      xml_close(xml_hdl);
      return;
    }

    raw2edf_var->phys_max = atoi(result);
    if(raw2edf_var->phys_max < 1)  raw2edf_var->phys_max = 1;
    if(raw2edf_var->phys_max > 10000000)  raw2edf_var->phys_max = 10000000;

    free(result);

    xml_go_up(xml_hdl);
  }

  if(!(xml_goto_nth_element_inside(xml_hdl, "straightbinary", 0)))
  {
    result = xml_get_content_of_element(xml_hdl);
    if(result==NULL)
    {
      xml_close(xml_hdl);
      return;
    }

    raw2edf_var->straightbinary = atoi(result);
    if(raw2edf_var->straightbinary < 0)  raw2edf_var->straightbinary = 0;
    if(raw2edf_var->straightbinary > 1)  raw2edf_var->straightbinary = 1;

    free(result);

    xml_go_up(xml_hdl);
  }

  if(!(xml_goto_nth_element_inside(xml_hdl, "endianness", 0)))
  {
    result = xml_get_content_of_element(xml_hdl);
    if(result==NULL)
    {
      xml_close(xml_hdl);
      return;
    }

    raw2edf_var->endianness = atoi(result);
    if(raw2edf_var->endianness < 0)  raw2edf_var->endianness = 0;
    if(raw2edf_var->endianness > 1)  raw2edf_var->endianness = 1;

    free(result);

    xml_go_up(xml_hdl);
  }

  if(!(xml_goto_nth_element_inside(xml_hdl, "samplesize", 0)))
  {
    result = xml_get_content_of_element(xml_hdl);
    if(result==NULL)
    {
      xml_close(xml_hdl);
      return;
    }

    raw2edf_var->samplesize = atoi(result);
    if(raw2edf_var->samplesize < 1)  raw2edf_var->samplesize = 1;
    if(raw2edf_var->samplesize > 2)  raw2edf_var->samplesize = 2;

    free(result);

    xml_go_up(xml_hdl);
  }

  if(!(xml_goto_nth_element_inside(xml_hdl, "offset", 0)))
  {
    result = xml_get_content_of_element(xml_hdl);
    if(result==NULL)
    {
      xml_close(xml_hdl);
      return;
    }

    raw2edf_var->offset = atoi(result);
    if(raw2edf_var->offset < 0)  raw2edf_var->offset = 0;
    if(raw2edf_var->offset > 1000000)  raw2edf_var->offset = 1000000;

    free(result);

    xml_go_up(xml_hdl);
  }

  if(!(xml_goto_nth_element_inside(xml_hdl, "skipblocksize", 0)))
  {
    result = xml_get_content_of_element(xml_hdl);
    if(result==NULL)
    {
      xml_close(xml_hdl);
      return;
    }

    raw2edf_var->skipblocksize = atoi(result);
    if(raw2edf_var->skipblocksize < 0)  raw2edf_var->skipblocksize = 0;
    if(raw2edf_var->skipblocksize > 1000000)  raw2edf_var->skipblocksize = 1000000;

    free(result);

    xml_go_up(xml_hdl);
  }

  if(!(xml_goto_nth_element_inside(xml_hdl, "skipbytes", 0)))
  {
    result = xml_get_content_of_element(xml_hdl);
    if(result==NULL)
    {
      xml_close(xml_hdl);
      return;
    }

    raw2edf_var->skipbytes = atoi(result);
    if(raw2edf_var->skipbytes < 1)  raw2edf_var->skipbytes = 1;
    if(raw2edf_var->skipbytes > 1000000)  raw2edf_var->skipbytes = 1000000;

    free(result);

    xml_go_up(xml_hdl);
  }

  if(!(xml_goto_nth_element_inside(xml_hdl, "phys_dim", 0)))
  {
    result = xml_get_content_of_element(xml_hdl);
    if(result==NULL)
    {
      xml_close(xml_hdl);
      return;
    }

    strncpy(raw2edf_var->phys_dim, result, 16);
    raw2edf_var->phys_dim[15] = 0;
    latin1_to_ascii(raw2edf_var->phys_dim, 16);
    remove_leading_spaces(raw2edf_var->phys_dim);
    remove_trailing_spaces(raw2edf_var->phys_dim);

    free(result);

    xml_go_up(xml_hdl);
  }

  xml_close(xml_hdl);

  SamplefreqSpinbox->setValue(raw2edf_var->sf);

  SignalsSpinbox->setValue(raw2edf_var->chns);

  PhysicalMaximumSpinbox->setValue(raw2edf_var->phys_max);

  EncodingCombobox->setCurrentIndex(raw2edf_var->straightbinary);

  EndiannessCombobox->setCurrentIndex(raw2edf_var->endianness);

  SampleSizeSpinbox->setValue(raw2edf_var->samplesize);

  OffsetSpinbox->setValue(raw2edf_var->offset);

  skipblocksizeSpinbox->setValue(raw2edf_var->skipblocksize);

  skipbytesSpinbox->setValue(raw2edf_var->skipbytes);
}
示例#7
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);
}