Ejemplo n.º 1
0
/*----------------------------------------------------------------------
            Parameters:

           Description:
              return the number of frames stored in the file 'fname'
----------------------------------------------------------------------*/
int
ImageNumFrames(const char*fname)
{
  IMAGE  I ;
  FILE   *fp ;
  int    frame, type, ecode, nframes ;
  char   buf[100] ;

  ImageUnpackFileName(fname, &frame, &type, buf) ;
  fname = buf ;
  if ((frame >= 0) || (type != HIPS_IMAGE))
    return(1) ;

  fp = fopen(fname, "rb") ;
  if (!fp)
    ErrorReturn(ERROR_NO_FILE,
                (ERROR_NO_FILE, "ImageNumFrame(%s) could not open file\n",
                 fname)) ;

  ecode = fread_header(fp, &I, fname) ;
  if (ecode != HIPS_OK)
    ErrorReturn(ERROR_NO_FILE,
                (ERROR_NO_FILE,
                 "ImageNumFrame: fread_header failed (%d)\n",ecode));

  nframes = I.num_frame ;
  fclose(fp) ;
  free_hdrcon(&I) ;
  return(nframes) ;
}
Ejemplo n.º 2
0
static float *get_afni_float(FILE *fp, int count, char *name)
{

  float *buf = NULL;
  int i;
  char line[STRLEN];
  char *c;
  char *e;
  char blank_flag;

  buf = (float *)malloc(count * sizeof(float));

  for (i = 0;i < count;)
  {

    fgets(line, STRLEN, fp);

    blank_flag = 1;
    for (c = line;*c != '\0';c++)
      if (!isspace(*c))
        blank_flag = 0;

    if (feof(fp))
    {
      free(buf);
      errno = 0;
      ErrorReturn(NULL, (ERROR_BADPARM, "get_afni_float(): hit EOF while reading %d floats for %s", count, name));
    }

    if (blank_flag)
    {
      free(buf);
      errno = 0;
      ErrorReturn(NULL, (ERROR_BADPARM, "get_afni_float(): hit a blank line while reading %d floats for %s", count, name));
    }

    if (strncmp(line, "type", 4) == 0)
    {
      free(buf);
      errno = 0;
      ErrorReturn(NULL, (ERROR_BADPARM, "get_afni_float(): hit a type line while reading %d floats for %s", count, name));
    }

    for (c = line;*c != '\0';)
    {
      for (;isspace(*c) && *c != '\0';c++);
      if (*c != '\0')
      {
        buf[i] = (float)strtod(c, &e);
        c = e;
        i++;
      }
    }
  }

  return(buf);

} /* end get_afni_float() */
Ejemplo n.º 3
0
int CMAclaimPoints(CMAoutlineField *field, short label, short *points, int n_points, short seed_x, short seed_y)
{

  int i, j;
  short x, y;

  if (label < 0 || label > MAX_CMA_LABEL)
    ErrorReturn(ERROR_BADPARM, (ERROR_BADPARM, "CMAclaimPoints(): label out of range (label is %d, MAX_CMA_LABEL is %d)", label, MAX_CMA_LABEL));

  if (seed_x < 0 || seed_x >= field->width)
    ErrorReturn(ERROR_BADPARM, (ERROR_BADPARM, "CMAclaimPoints(): seed point out of range (seed_x = %d, field width = %d)", seed_x, field->width));
  if (seed_y < 0 || seed_y >= field->height)
    ErrorReturn(ERROR_BADPARM, (ERROR_BADPARM, "CMAclaimPoints(): seed point out of range (seed_y = %d, field height = %d)", seed_y, field->height));

  CMAclearFillField(field);

  for (i = 0;i < n_points;i++)
  {
    x = points[2*i];
    y = points[2*i+1];
    if (x < 0 || x >= field->width)
      ErrorReturn(ERROR_BADPARM, (ERROR_BADPARM, "CMAclaimPoints(): outline point out of range (x)"));
    if (y < 0 || y >= field->height)
      ErrorReturn(ERROR_BADPARM, (ERROR_BADPARM, "CMAclaimPoints(): outline point out of range (y)"));
    field->fill_field[y][x] = CMA_FILL_OUTLINE;
    field->outline_points_field[y][x] = 1;
  }

  CMAfill(field, seed_x, seed_y);

  for (i = 0;i < field->width;i++)
  {
    for (j = 0;j < field->height;j++)
    {

      if (field->fill_field[j][i] == CMA_FILL_INTERIOR)
      {
        field->claim_field[j][i].n_claims = 1;
        field->claim_field[j][i].interior_claim_flag = TRUE;
        field->claim_field[j][i].claim_labels[0] = label;
      }

      if (field->fill_field[j][i] == CMA_FILL_OUTLINE)
      {
        if (field->claim_field[j][i].n_claims < MAX_OUTLINE_CLAIMS)
        {
          field->claim_field[j][i].claim_labels[field->claim_field[j][i].n_claims] = label;
          field->claim_field[j][i].n_claims++;
          field->claim_field[j][i].interior_claim_flag = FALSE;
        }
      }

    }
  }

  return(NO_ERROR);

} /* end CMAclaimPoints() */
Ejemplo n.º 4
0
/*-----------------------------------------------------
        Parameters:

        Returns value:

        Description
------------------------------------------------------*/
IMAGE *
ImageRead(const char*fname)
{
  IMAGE   *I = NULL ;
  MATRIX  *mat ;
  FILE    *fp ;
  int     type, frame ;
  char    buf[STRLEN] ;

  strcpy(buf, fname) ;   /* don't destroy callers string */

  ImageUnpackFileName(buf, &frame, &type, buf) ;

  switch (type)
  {
  case TIFF_IMAGE:
    I = TiffReadImage(buf, frame) ;
    if (I == NULL)
      return(NULL) ;
    break ;
  case MATLAB_IMAGE:
    DiagPrintf(DIAG_WRITE,
               "ImageRead: buf=%s, frame=%d, type=%d (M=%d,H=%d)\n",
               buf, frame, type , MATLAB_IMAGE, HIPS_IMAGE);
    mat = MatlabRead(buf) ;
    if (!mat)
      ErrorReturn(NULL, (ERROR_NO_FILE, "ImageRead(%s) failed\n", buf)) ;
    I = ImageFromMatrix(mat, NULL) ;
    ImageInvert(I, I) ;
    MatrixFree(&mat) ;
    break ;
  case HIPS_IMAGE:
    fp = fopen(buf, "rb") ;
    if (!fp)
      ErrorReturn(NULL, (ERROR_NO_FILE, "ImageRead(%s, %d) failed\n",
                         buf, frame)) ;
    I = ImageFRead(fp, buf, frame, 1) ;
    fclose(fp) ;
    break ;
  case JPEG_IMAGE:
    I = JPEGReadImage(buf);
    break ;
  case PGM_IMAGE:
    I = PGMReadImage(buf);
    break;
  case PPM_IMAGE:
    I = PPMReadImage(buf);
    break;
  case PBM_IMAGE:
    I = PBMReadImage(buf);
    break;
  case RGBI_IMAGE:
    I= RGBReadImage(buf);
  default:
    break ;
  }
  return(I) ;
}
Ejemplo n.º 5
0
LP_ANSWER_FILE *
LPAFcreate(char *out_fname, int argc, char *argv[])
{
  LP_ANSWER_FILE *lpaf ;
  int            i, nentries, nfiles, entryno ;

  nfiles = 0 ;
  for (i = 0 ; i < argc ; i++)
  {
    nentries = FileNumberOfEntries(argv[i]) ;
    nfiles += nentries ;
  }

  if (nfiles <= 0)
    ErrorReturn(NULL, (ERROR_NO_FILE, "LPAFcreate: no valid files specified"));

  lpaf = (LP_ANSWER_FILE *)calloc(1, sizeof(*lpaf)) ;
  if (!lpaf)
    ErrorExit(ERROR_NO_MEMORY, "LPAFcreate: allocation failed") ;
  if (out_fname)   /* write output to file as well as into image file */
  {
    strcpy(lpaf->fname, out_fname) ;
    unlink(lpaf->fname) ;
    lpaf->fp = fopen(lpaf->fname, "a+b") ;
    if (!lpaf->fp)
      ErrorReturn(NULL,
                  (ERROR_NO_FILE,"LPAFcreate: could not open %s",out_fname));
  }
  else
    lpaf->fp = NULL ;

  lpaf->nfiles = nfiles ;
  lpaf->last_written = lpaf->current = 0 ;
  lpaf->filelist = (char **)calloc(nfiles, sizeof(char *)) ;
  if (!lpaf->filelist)
    ErrorExit(ERROR_NO_MEMORY, "LPAFcreate: allocation failed") ;
  lpaf->coords = (LP_BOX *)calloc(nfiles, sizeof(LP_BOX)) ;
  if (!lpaf->coords)
    ErrorExit(ERROR_NO_MEMORY, "LPAFcreate: allocation failed") ;
  lpaf->last_written = 0 ;

  /* now fill out filelist array */
  entryno = 0 ;
  for (i = 0 ; i < argc ; i++)
  {
    nentries = lpafFillEntries(lpaf, argv[i], entryno) ;
    entryno += nentries ;
  }

  for (i = 0 ; i < lpaf->nfiles ; i++)
    lpaf->coords[i].fpos = -1L ;

  lpafDump(stderr, lpaf) ;

  return(lpaf) ;
}
Ejemplo n.º 6
0
/* returns the label with the greatest claim to a given pixel */
short CMAtotalClaims(CMAoutlineField *field, int x, int y)
{

  float claim_totals[MAX_CMA_LABEL+1];
  float best_claim;
  short best_index;
  int i;

  if (x < 0 || x >= field->width)
    ErrorReturn(-1, (ERROR_BADPARM, "CMAtotalClaims(): x out of range (x = %d, field->width = %d)", x, field->width));

  if (y < 0 || y >= field->height)
    ErrorReturn(-1, (ERROR_BADPARM, "CMAtotalClaims(): y out of range (y = %d, field->height = %d)", y, field->height));

  for (i = 0;i < MAX_CMA_LABEL;i++)
    claim_totals[i] = 0.0;

  /* center point (x, y checks done above) */
  CMAaddWeightedTotals(&(field->claim_field[y][x]), OTL_CLAIM_WEIGHT_CENTER, claim_totals);

  /* immediately adjoining points */
  if (x-1 >= 0)
    CMAaddWeightedTotals(&(field->claim_field[y  ][x-1]), OTL_CLAIM_WEIGHT_SIDE, claim_totals);
  if (x+1 < field->width)
    CMAaddWeightedTotals(&(field->claim_field[y  ][x+1]), OTL_CLAIM_WEIGHT_SIDE, claim_totals);
  if (y-1 >= 0)
    CMAaddWeightedTotals(&(field->claim_field[y-1][x  ]), OTL_CLAIM_WEIGHT_SIDE, claim_totals);
  if (y+1 < field->height)
    CMAaddWeightedTotals(&(field->claim_field[y+1][x  ]), OTL_CLAIM_WEIGHT_SIDE, claim_totals);

  /* diagonally adjoining points */
  if (x-1 >= 0 && y-1 >= 0)
    CMAaddWeightedTotals(&(field->claim_field[y-1][x-1]), OTL_CLAIM_WEIGHT_SIDE, claim_totals);
  if (x-1 >= 0 && y+1 < field->height)
    CMAaddWeightedTotals(&(field->claim_field[y+1][x-1]), OTL_CLAIM_WEIGHT_SIDE, claim_totals);
  if (x+1 < field->width && y-1 >= 0)
    CMAaddWeightedTotals(&(field->claim_field[y-1][x+1]), OTL_CLAIM_WEIGHT_SIDE, claim_totals);
  if (x+1 < field->width && y+1 < field->height)
    CMAaddWeightedTotals(&(field->claim_field[y+1][x+1]), OTL_CLAIM_WEIGHT_SIDE, claim_totals);

  /* find the highest claim and its index */
  best_claim = claim_totals[0];
  best_index = 0;
  for (i = 1;i <= MAX_CMA_LABEL;i++)
  {
    if (claim_totals[i] > best_claim)
    {
      best_claim = claim_totals[i];
      best_index = i;
    }
  }

  return(best_index);

} /* end CMAtotalClaims() */
Ejemplo n.º 7
0
static int convert_single_label_to_path (char* fname, char* ofname) {
  LABEL* label           = NULL;
  int    label_vno;
  int    num_paths;
  PATH** paths           = NULL;
  int    err;

  /* Read the label file. */
  label = LabelRead (NULL, fname);
  if (NULL == label) {
    ErrorReturn (ERROR_BADFILE,
                 (ERROR_BADFILE, "Couldn't read %s", fname));
  }

  /* Count the number of sentinels, -99999 vnos in the label; we only
     want one path, so this is just to check if this is a
     multiple-path label file. */
  num_paths = 0;
  for (label_vno = 0; label_vno < label->n_points; label_vno++) {
    if (-99999 == label->lv[label_vno].vno)
      num_paths++;
  }

  /* Make sure we only got one paths. */
  if (num_paths > 1) {
    printf ("WARNING: Found multiple paths in label file.\n"
	    "Maybe you didn't mean to use the single option?\n"
	    "Converting it to a single path.\n");
  }

  /* Allocate path objects. */
  paths = (PATH**) calloc (1, sizeof(PATH*));
  if (NULL == paths) {
    ErrorReturn (ERROR_NO_MEMORY,
                 (ERROR_NO_MEMORY, "Couldn't allocate %d paths", 1));
  }

  err = PathCreateFromLabel (label, &paths[0]);
  if (ERROR_NONE != err) {
    free (paths);
    return err;
  }

  /* Write the path file. */
  err = PathWriteMany (ofname, 1, paths);
  if (0 != err) {
    ErrorReturn (ERROR_BADFILE,
                 (ERROR_BADFILE, "Couldn't write to %s", ofname));
  }

  PathFree (&paths[0]);
  free (paths);

  return (ERROR_NONE);
}
Ejemplo n.º 8
0
/*---------------------------------------------------------------*/
LABEL   *LabelReadFile(char *labelfile) {
  LABEL  *area ;
  char   *fname, line[STRLEN], *cp;
  FILE   *fp ;
  int    vno, nlines ;
  float  x, y, z, stat ;

  fname = labelfile;

  area = (LABEL *)calloc(1, sizeof(LABEL)) ;
  if (!area)
    ErrorExit(ERROR_NOMEMORY,"%s: could not allocate LABEL struct.",Progname);

  /* read in the file */
  fp = fopen(fname, "r") ;
  if (!fp)
    ErrorReturn(NULL, (ERROR_NOFILE, "%s: could not open label file %s",
                       Progname, fname)) ;

  cp = fgetl(line, 199, fp) ;
  if (!cp)
    ErrorReturn(NULL,
                (ERROR_BADFILE, "%s: empty label file %s", Progname, fname)) ;
  if (!sscanf(cp, "%d", &area->n_points))
    ErrorReturn(NULL,
                (ERROR_BADFILE, "%s: could not scan # of lines from %s",
                 Progname, fname)) ;
  area->max_points = area->n_points ;
  area->lv = (LABEL_VERTEX *)calloc(area->n_points, sizeof(LABEL_VERTEX)) ;
  if (!area->lv)
    ErrorExit(ERROR_NOMEMORY,
              "%s: LabelRead(%s) could not allocate %d-sized vector",
              Progname, labelfile, sizeof(LV)*area->n_points) ;
  nlines = 0 ;
  while ((cp = fgetl(line, 199, fp)) != NULL) {
    if (sscanf(cp, "%d %f %f %f %f", &vno, &x, &y, &z, &stat) != 5)
      ErrorReturn(NULL, (ERROR_BADFILE, "%s: could not parse %dth line in %s",
                         Progname, area->n_points, fname)) ;
    area->lv[nlines].x = x ;
    area->lv[nlines].y = y ;
    area->lv[nlines].z = z ;
    area->lv[nlines].stat = stat ;
    area->lv[nlines].vno = vno ;
    nlines++ ;
  }

  fclose(fp) ;
  if (!nlines)
    ErrorReturn(NULL,
                (ERROR_BADFILE,
                 "%s: no data in label file %s", Progname, fname));
  return(area) ;
}
Ejemplo n.º 9
0
LTA *ltaReadFileEx(const char *fname)
{
  FILE             *fp;
  LINEAR_TRANSFORM *lt ;
  int              i, nxforms, type ;
  char             line[STRLEN], *cp ;
  LTA              *lta ;

  fp = fopen(fname,"r");
  if (fp==NULL)
    ErrorReturn(NULL,
                (ERROR_BADFILE, "ltaReadFile(%s): can't open file",fname));
  cp = fgetl(line, 199, fp) ;
  if (cp == NULL)
  {
    fclose(fp) ;
    ErrorReturn(NULL, (ERROR_BADFILE, "ltaReadFile(%s): can't read data",fname));
  }
  sscanf(cp, "type      = %d\n", &type) ;
  cp = fgetl(line, 199, fp) ;
  sscanf(cp, "nxforms   = %d\n", &nxforms) ;
  lta = LTAalloc(nxforms, NULL) ;
  lta->type = type ;
  for (i = 0 ; i < lta->num_xforms ; i++)
  {
    lt = &lta->xforms[i] ;
    fscanf(fp, "mean      = %f %f %f\n", &lt->x0, &lt->y0, &lt->z0) ;
    fscanf(fp, "sigma     = %f\n", &lt->sigma) ;
    MatrixAsciiReadFrom(fp, lt->m_L) ;
  }
  // oh, well this is the added part
  for (i=0; i < lta->num_xforms; i++)
  {
    if (fgets(line, 199, fp))
    {
      if (strncmp(line, "src volume info", 15)==0)
      {
        char *p;
        readVolGeom(fp, &lta->xforms[i].src);
        p = fgets(line, 199, fp);
        if (strncmp(line, "dst volume info", 15)==0)
          readVolGeom(fp, &lta->xforms[i].dst);
      }
    }
  }
  fclose(fp) ;
  return(lta) ;
}
Ejemplo n.º 10
0
/*-----------------------------------------------------
        Parameters:

        Returns value:

        Description
------------------------------------------------------*/
MRI *
MRIsscalarMul(MRI *mri_src, MRI *mri_dst, float scalar) {
  int     width, height, depth, x, y, z, frame ;
  short   *psrc, *pdst ;

  width = mri_src->width ;
  height = mri_src->height ;
  depth = mri_src->depth ;
  if (!mri_dst)
    mri_dst = MRIclone(mri_src, NULL) ;

  for (frame = 0 ; frame < mri_src->nframes ; frame++) {
    for (z = 0 ; z < depth ; z++) {
      for (y = 0 ; y < height ; y++) {
        switch (mri_src->type) {
        case MRI_SHORT:
          psrc = &MRISseq_vox(mri_src, 0, y, z, frame) ;
          pdst = &MRISseq_vox(mri_dst, 0, y, z, frame) ;
          for (x = 0 ; x < width ; x++)
            *pdst++ = *psrc++ * scalar ;
          break ;
        default:
          ErrorReturn(NULL,
                      (ERROR_UNSUPPORTED,
                       "MRIsscalarMul: unsupported type %d", mri_src->type)) ;
        }
      }
    }
  }
  return(mri_dst) ;
}
Ejemplo n.º 11
0
static char *get_afni_string(FILE *fp, int count, char *name)
{

  char *buf;
  int i;
  char c;

  buf = (char *)malloc(count+1);

  c = fgetc(fp);

  if (c != '\'')
  {
    free(buf);
    errno = 0;
    ErrorReturn(NULL, (ERROR_BADPARM, "get_afni_string(): afni header string %s does not start with \"'\"", name));
  }

  for (i = 0;i < count;i++)
  {

    if (feof(fp))
    {
      free(buf);
      errno = 0;
      ErrorReturn(NULL, (ERROR_BADPARM, "get_afni_string(): end of file reached at %d of %d bytes of string %s", i+1, count, name));
    }

    c = fgetc(fp);

    if (i == count - 1 && c != '~')
    {
      errno = 0;
      ErrorPrintf(ERROR_BADPARM, "warning: string %s does not end with \"~\"", name);
    }

    buf[i] = (c == '~' ? '\0' : c);

  }

  buf[count] = '\0';

  for (c = fgetc(fp) ; c != '\n' && !feof(fp) ; c = fgetc(fp));

  return(buf);

} /* end get_afni_string() */
Ejemplo n.º 12
0
int MRIwriteControlPoints(const MPoint *pointArray,
                          int count,
                          int useRealRAS,
                          const char *fname)
{
  FILE *fp;
  int i;
  int res;
  time_t time;

  if (Gdiag & DIAG_SHOW)
    fprintf(stderr, "Writing control points to %s...\n", fname) ;

  if (useRealRAS > 1 || useRealRAS < 0)
    ErrorReturn(ERROR_BADPARM,
                (ERROR_BADPARM,
                 "MRIwriteControlPoints useRealRAS must"
                 " be 0 (surfaceRAS) or 1 (scannerRAS) but %d\n",
                 useRealRAS))

    fp = fopen(fname, "w") ;
  if (!fp)
    ErrorReturn(ERROR_BADPARM,
                (ERROR_BADPARM, "MRIwriteControlPoints(%s): could not"
                 " open file", fname)) ;
  for (i=0 ; i < count; ++i)
  {
    if ((res = fprintf(fp, "%f %f %f\n",
                       pointArray[i].x,
                       pointArray[i].y,
                       pointArray[i].z))< 0)
      ErrorReturn(ERROR_BADPARM,
                  (ERROR_BADPARM, "MRIwriteControlPoints(%s): could not"
                   " write file", fname)) ;
  }
  // if res < 0, then error
  res=fprintf(fp, "info\n");
  res=fprintf(fp, "numpoints %d\n", count);
  res=fprintf(fp, "useRealRAS %d\n", useRealRAS);
  res=fprintf(fp, "written by %s on %s\n",
              cuserid(0), asctime(localtime(&time)));
  res=fclose(fp);

  return (NO_ERROR);
}
Ejemplo n.º 13
0
int
LPAFread(LPAF *lpaf, int current)
{
  LP_BOX *lpb ;
  char   line[300], *cp ;

  lpb = &lpaf->coords[current] ;

  if (LPAFreadImageAnswer(lpaf, current) <= 0)  /* not in image file */
  {
    if (!lpaf->fp || (lpb->fpos < 0))
      return(0) ;     /* hasn't been written yet */

    if (fseek(lpaf->fp, lpb->fpos, SEEK_SET) < 0)
      ErrorReturn(-1, (ERROR_BADFILE, "LPAFread could not seek to %ld",
                       lpb->fpos)) ;

    cp = fgetl(line, 299, lpaf->fp) ;
    if (!cp)
      ErrorReturn(-1, (ERROR_BADFILE, "LPAFread: could not read line")) ;

    if (sscanf(cp, FILE_FMT,
               lpaf->filelist[current], &lpb->xc, &lpb->yc,
               &lpb->xp[0], &lpb->yp[0], &lpb->xp[1], &lpb->yp[1],
               &lpb->xp[2], &lpb->yp[2], &lpb->xp[3], &lpb->yp[3]) != 11)
      ErrorReturn(-1,
                  (ERROR_BADFILE, "LPAFread: could not scan all parms from %s",
                   cp)) ;

  }

#if 0
  {
    int i ;

    for (i = 0 ; i < NPOINTS ; i++)
      fprintf(stderr, "(%d, %d) ", lpb->xp[i], lpb->yp[i]) ;
    fprintf(stderr, "\n") ;
  }
#endif

  return(abs(lpb->xc) < INIT_VAL) ;  /* handles garbages as well as unwritten */
}
Ejemplo n.º 14
0
static int NumPy_CheckObject(PyObject *ob, int t, char *obname,
                             char *tname, char *funname)
{   char buf[255];
    if (! PyArray_Check(ob))
    {   sprintf(buf,"Expected an array for parameter %s in lapack_dge.%s",obname, funname);
        ErrorReturn(buf);
        return 0;
    }
    if (!(((PyArrayObject *)ob)->flags & CONTIGUOUS))
    {   sprintf(buf,"Parameter %s is not contiguous in lapack_dge.%s",obname, funname);
        ErrorReturn(buf);
        return 0;
    }
    if (!(((PyArrayObject *)ob)->descr->type_num == t))
    {   sprintf(buf,"Parameter %s is not of type %s in lapack_lite.%s",obname,tname, funname);
        ErrorReturn(buf);
        return 0;
    }
    return 1;
}
Ejemplo n.º 15
0
/*--------------------------------------------------------------------*/
static int guess_file_type (char* fname, int* is_path, int *is_label) {
  FILE*  fp         = NULL;
  char*  line       = NULL;
  size_t size       = 1024;
  char*  needle     = NULL;
  int    found      = 0;

  *is_path = 0;
  *is_label = 0;
  found = 0;

  /* First just check the path checker. */
  if (PathIsPathFile (fname)) {
    *is_path = 1;
    return (ERROR_NONE);
  }

  /* Open the file. */
  fp = fopen (fname, "r");
  if (NULL == fp) {
    printf ("ERROR: Couldn't open %s\n", fname);
    return 1;
  }

  /* Line buffer. */
  line = (char*) malloc (size);

  while (!feof(fp) && !found) {
    /* Get a line. */
    getline (&line, &size, fp);

    /* If it's a comment line. */
    if (line[0] == '#') {
      /* Look for the label string. It's a label file if so. */
      needle = strstr( line, "label" );
      if ( NULL != needle ) {
        *is_label = 1;
        found = 1;
        break;
      }
    }
  }

  fclose( fp );

  free (line);

  if (!found)
    ErrorReturn (ERROR_BADFILE,
                 (ERROR_BADFILE, "Couldn't identify %s", fname));

  return (ERROR_NONE);
}
Ejemplo n.º 16
0
int
RFwrite(RANDOM_FOREST *rf, char *fname) 
{
  FILE   *fp ;
  int    err ;

  fp = fopen(fname, "w") ;
  if (fp == NULL)
    ErrorReturn(ERROR_NOFILE, (ERROR_NOFILE, "RFwrite(%s): could not open file",fname));
  err = RFwriteInto(rf, fp);
  fclose(fp) ;
  return(err) ;
}
Ejemplo n.º 17
0
/*-----------------------------------------------------
        Parameters:

        Returns value:

        Description
------------------------------------------------------*/
int
ImageWrite(IMAGE *I, const char*fname)
{
  FILE  *fp ;
  int   ecode ;

  fp = fopen(fname, "wb") ;
  if (!fp)
    ErrorReturn(-1, (ERROR_NO_FILE, "ImageWrite(%s) failed\n", fname)) ;

  ecode = ImageFWrite(I, fp, fname) ;
  fclose(fp) ;
  return(0) ;
}
Ejemplo n.º 18
0
/*-----------------------------------------------------
        Parameters:

        Returns value:

        Description
------------------------------------------------------*/
IMAGE *
ImageReadFrames(const char*fname, int start, int nframes)
{
  IMAGE *I ;
  FILE  *fp ;

  fp = fopen(fname, "rb") ;
  if (!fp)
    ErrorReturn(NULL, (ERROR_NO_FILE, "ImageReadFrames(%s) fopen failed\n",
                       fname)) ;

  I = ImageFRead(fp, fname, start, nframes) ;
  fclose(fp) ;
  return(I) ;
}
Ejemplo n.º 19
0
static LTA  *
ltaFSLread(const char *fname) {
  LTA              *lta ;
  LINEAR_TRANSFORM *lt ;
  char             *cp, line[1000] ;
  FILE             *fp ;
  int              row ;
  MATRIX           *m_L ;

  fp = fopen(fname, "r") ;
  if (!fp)
    ErrorReturn(NULL,
                (ERROR_NOFILE, "ltFSLread: could not open file %s",fname));

  lta = LTAalloc(1, NULL) ;
  lt = &lta->xforms[0] ;
  lt->sigma = 1.0f ;
  lt->x0 = lt->y0 = lt->z0 = 0 ;

  m_L = lt->m_L ;
  for (row = 1 ; row <= 3 ; row++) {
    cp = fgetl(line, 900, fp) ;
    if (!cp) {
      LTAfree(&lta) ;
      ErrorReturn(NULL,
                  (ERROR_BADFILE, "ltFSLread: could not read row %d from %s",
                   row, fname)) ;
    }
    sscanf(cp, "%f %f %f %f",
           MATRIX_RELT(m_L,row,1), MATRIX_RELT(m_L,row,2),
           MATRIX_RELT(m_L,row,3), MATRIX_RELT(m_L,row,4)) ;
  }
  fclose(fp) ;
  lta->type = LINEAR_VOX_TO_VOX;
  return(lta) ;
}
Ejemplo n.º 20
0
static int
write_vertex_data(char *fname, int index, float **v, int nclass) {
  FILE  *fp ;
  int   i ;

  fp = fopen(fname, "w") ;
  if (!fp)
    ErrorReturn(ERROR_BADFILE,
                (ERROR_BADFILE, "write_vertex_data: could not open %s",fname));
  for (i = 0 ; i < nclass ; i++) {
    fprintf(fp, "%2.3f\n", v[i][index]) ;
  }
  fclose(fp) ;
  return(NO_ERROR) ;
}
Ejemplo n.º 21
0
int addToList(MRIS *surf, int vno) {

  struct d_node *dn_new, *dn_this;

  dn_new = (struct d_node *)malloc(sizeof(struct d_node));
  if (dn_new == NULL) {
    ErrorReturn(ERROR_NO_MEMORY, (ERROR_NO_MEMORY, "list(): error in malloc()"));
  }

  dn_new->vno = vno;
  dn_new->val = surf->vertices[vno].val;
  dn_new->next = NULL;

  /* - case 1: no elements in the list yet - */

  if (d_list == NULL) {
    d_list = dn_new;
    return(NO_ERROR);
  }

  /* - case 2: the dn_new element goes at the front of the list - */

  if (dn_new->val < d_list->val) {
    dn_new->next = d_list;
    d_list = dn_new;
    return(NO_ERROR);
  }

  /* - place "dn_new" in the list - */

  /* "dn_this" will always precede "dn_new" */

  dn_this = d_list;

  while (dn_this->next != NULL) {
    if (dn_this->next->val > dn_new->val) {
      dn_new->next = dn_this->next;
      dn_this->next = dn_new;
      return(NO_ERROR);
    }
    dn_this = dn_this->next;
  }

  dn_this->next = dn_new;

  return(NO_ERROR);

} /* end list() */
Ejemplo n.º 22
0
/*--------------------------------------------------------------------*/
static int convert_single_path_to_label (char* fname, char* ofname) {
  int     err;
  int     num_paths;
  PATH**  paths       = NULL;
  LABEL*  label       = NULL;
  int     path_index;

  /* Read the paths file. */
  err = PathReadMany (fname, &num_paths, &paths);
  if (ERROR_NONE != err) {
    ErrorReturn (ERROR_BADFILE,
                 (ERROR_BADFILE, "Couldn't read %s", fname));
  }

  /* Warn if we have more than one path. */
  if (num_paths != 1) {
    printf ("WARNING: Found multiple paths in label file.\n"
	    "Maybe you didn't mean to use the single option?\n"
	    "Converting it to a single path.\n");
  }

  /* Convert our first path. */
  err = PathConvertToLabel (paths[0], &label);
  if (ERROR_NONE != err) {
    for (path_index = 0; path_index < num_paths; path_index++)
      PathFree (&paths[path_index]);
    free (paths);
    return err;
  }

  /* Delete all the paths. */
  for (path_index = 0; path_index < num_paths; path_index++) {
    PathFree (&paths[path_index]);
  }

  /* Free our paths variable. */
  free (paths);

  /* Write the label file. */
  LabelWrite (label, ofname);

  /* Free the label. */
  LabelFree (&label);

  return (ERROR_NONE);
}
Ejemplo n.º 23
0
/*-----------------------------------------------------
        Parameters:

        Returns value:

        Description
          read an image from file and convert it to the specified
          format.
------------------------------------------------------*/
IMAGE *
ImageReadType(const char*fname, int pixel_format)
{
  IMAGE *Itmp, *I ;

  Itmp = ImageRead(fname) ;
  if (!Itmp)
    ErrorReturn(NULL, (ERROR_NO_FILE,
                       "ImageReadType(%s, %d): could not read image",
                       fname, pixel_format)) ;
  if (Itmp->pixel_format != pixel_format)
  {
    I = ImageAlloc(Itmp->rows, Itmp->cols, pixel_format, Itmp->num_frame) ;
    ImageCopy(Itmp, I) ;
    ImageFree(&Itmp) ;
  }
  else
    I = Itmp ;

  return(I) ;
}
Ejemplo n.º 24
0
static int
lpafFillEntries(LP_ANSWER_FILE *lpaf, char *fname, int entryno)
{
  int  nentries, type, i, num ;
  char buf[100], *base_name, line[200], *cp ;
  FILE *fp ;

  nentries = FileNumberOfEntries(fname) ;
  type = FileType(fname) ;
  base_name = FileFullName(fname) ;

  for (i = 0 ; i < nentries ; i++)
  {
    switch (type)
    {
    case LIST_FILE:
      fp = fopen(base_name, "rb") ;
      if (!fp)
        ErrorReturn(0, (ERROR_NO_FILE, "lpafFillEntries: could not open %s\n",
                        base_name)) ;
      cp = fgetl(line, 199, fp) ;
      nentries = 0 ;
      while (cp)
      {
        sscanf(cp, "%s", buf) ;
        num = lpafFillEntries(lpaf, buf, entryno+nentries) ;
        nentries += num ;
        cp = fgetl(line, 199, fp) ;
      }
      fclose(fp) ;
      break ;
    default:
      sprintf(buf, "%s#%d", base_name, i) ;
      lpaf->filelist[entryno+i] = (char *)calloc(strlen(buf)+1, sizeof(char));
      strcpy(lpaf->filelist[entryno+i], buf) ;
      break ;
    }
  }
  return(nentries) ;
}
Ejemplo n.º 25
0
/*-----------------------------------------------------
        Parameters:

        Returns value:

        Description
------------------------------------------------------*/
IMAGE *
ImageReadHeader(const char*fname)
{
  IMAGE   *I = NULL ;
  FILE    *fp ;
  int     type, frame ;
  char    buf[100] ;

  strcpy(buf, fname) ;   /* don't destroy callers string */

  ImageUnpackFileName(buf, &frame, &type, buf) ;

  fp = fopen(buf, "rb") ;
  if (!fp)
    ErrorReturn(NULL, (ERROR_NO_FILE, "ImageReadHeader(%s, %d) failed\n",
                       buf, frame)) ;

  I = ImageFReadHeader(fp, buf) ;
  fclose(fp) ;

  return(I) ;
}
Ejemplo n.º 26
0
int
LPAFwrite(LPAF *lpaf, int current)
{
  LP_BOX *lpb ;

  LPAFwriteImageAnswer(lpaf, current) ;

  if (lpaf->fp)
  {
    lpb = &lpaf->coords[current] ;
    if (lpb->fpos >= 0L)   /* overwrite previous entry */
    {
      if (fseek(lpaf->fp, lpb->fpos, SEEK_SET) < 0)
        ErrorReturn(-1, (ERROR_BADFILE, "LPAFwrite could not seek to %ld",
                         lpb->fpos)) ;
    }
    else
      lpb->fpos = ftell(lpaf->fp) ;

    if (current > lpaf->last_written)
      lpaf->last_written = current ;
    else   /* write out rest of file */
    {}

    fprintf(lpaf->fp, FILE_FMT,
            lpaf->filelist[current], lpb->xc, lpb->yc,
            lpb->xp[0], lpb->yp[0], lpb->xp[1], lpb->yp[1],
            lpb->xp[2], lpb->yp[2], lpb->xp[3], lpb->yp[3]) ;

    if (lpaf->flush++ >= NFLUSH)
    {
      fflush(lpaf->fp) ;
      lpaf->flush = 0 ;
    }
  }
  return(0) ;
}
Ejemplo n.º 27
0
/*-----------------------------------------------------
  Parameters:

  Returns value:

  Description
  ------------------------------------------------------*/
MRI *
MRIsegmentToImage(MRI *mri_src, MRI *mri_dst, MRI_SEGMENTATION *mriseg, int s)
{
  int          v, x, y, z, smin, smax ;
  MRI_SEGMENT  *mseg ;

  if (!mri_dst)
    mri_dst = MRIclone(mri_src, NULL) ;

  if (s >= mriseg->nsegments)
    ErrorReturn(mri_dst,
                (ERROR_BADPARM, "MRIsegmentToImage: invalid segment #%d",s));

  if (s < 0)  // do all segments
  {
    smin = 0 ;
    smax = mriseg->nsegments-1 ;
  }
  else  // just do one segment
    smin = smax = s ;

  for (s = smin ; s <= smax ; s++)
  {
    mseg = &mriseg->segments[s] ;
    
    for (v = 0 ; v < mseg->nvoxels ; v++)
    {
      x = mseg->voxels[v].x ;
      y = mseg->voxels[v].y ;
      z = mseg->voxels[v].z ;
      MRIsetVoxVal(mri_dst, x, y, z,0, MRIgetVoxVal(mri_src, x, y, z, 0)) ;
    }
  }

  return(mri_dst) ;
}
Ejemplo n.º 28
0
MRI *
MRIsegmentFill(MRI_SEGMENTATION *mriseg, int s, MRI *mri, float fillval)
{
  int          v, x, y, z ;
  MRI_SEGMENT  *mseg ;

  if (s < 0 || s >= mriseg->nsegments)
    ErrorReturn(NULL, 
                (ERROR_BADPARM, "MRIsegmentFill: invalid segment #%d",s));
  mseg = &mriseg->segments[s] ;

  if (mri == NULL)
    mri = MRIclone(mriseg->mri, NULL) ;

  for (v = 0 ; v < mseg->nvoxels ; v++)
  {
    x = mseg->voxels[v].x ;
    y = mseg->voxels[v].y ;
    z = mseg->voxels[v].z ;
    MRIsetVoxVal(mri, x, y, z,0, fillval) ;
  }

  return(mri) ;
}
Ejemplo n.º 29
0
MATRIX *
regio_read_surfacexform_from_register_dat(char *fname, MRI_SURFACE *mris, 
                                          MRI *mri, char **subject)
{
  MATRIX *Ta, *Sa, *invT, *A, *R, *S, *invSa, *T, *m1, *m2, *B ;
  float  pres, bres, intensity ;
  int    float2int ;
  MRI *mri_surf = MRIallocHeader(mris->vg.width, mris->vg.height, 
                                 mris->vg.depth, MRI_UCHAR,1) ;

  if (regio_read_register(fname, subject, &pres, &bres, &intensity,&B,&float2int) != 0)
    ErrorReturn(NULL, (ERROR_NOFILE, 
                       "regio_read_surfacexform_from_register_dat(%s) failed",
                       fname)) ;


  MRIcopyVolGeomToMRI(mri_surf, &mris->vg) ;

  T = MRIxfmCRS2XYZtkreg(mri) ;
  S = MRIgetVoxelToRasXform(mri) ;
  Ta = MRIxfmCRS2XYZtkreg(mri_surf);
  Sa = MRIgetVoxelToRasXform(mri_surf);
  invSa = MatrixInverse(Sa, NULL) ;
  invT = MatrixInverse(T,NULL);
  A  = MatrixMultiply(S,invT, NULL);
  
  m1 = MatrixMultiply(A, B, NULL) ;
  m2 = MatrixMultiply(invSa, m1, NULL) ;
  R = MatrixMultiply(Ta, m2, NULL) ;
  MatrixFree(&A) ; MatrixFree(&Ta) ; MatrixFree(&Sa) ; MatrixFree(&invT) ;
  MatrixFree(&B) ; MatrixFree(&m1) ; MatrixFree(&m2) ; MatrixFree(&S) ; 
  MatrixFree(&invSa);
  MatrixFree(&T) ;
  MRIfree(&mri_surf) ;
  return(R) ;
}
Ejemplo n.º 30
0
/*------------------------------------------------------*/
MRI *afniRead(const char *fname, int read_volume)
{

  FILE *fp;
  char header_fname[STRLEN];
  char *c;
  MRI *mri, *header;
  int big_endian_flag;
  long brik_file_length;
  long nvoxels;
  int bytes_per_voxel;
  int i, j, k;
  int swap_flag;
  AF af;
  float scaling = 1.;
  void *pmem = 0;
  float *pf;
  short *ps;
  unsigned char *pc;

  float det;
  float xfov, yfov, zfov;
  float fMin = 0.;
  float fMax = 0.;
  float flMin = 0.;
  float flMax = 0.;
  int initialized = 0;
  int frame;
  int bytes;

  strcpy(header_fname, fname);
  c = strrchr(header_fname, '.');

  if (c == NULL)
  {
    errno = 0;
    ErrorReturn(NULL, (ERROR_BADPARM, "afniRead(): bad file name %s", fname));
  }

  if (strcmp(c, ".BRIK") != 0)
  {
    errno = 0;
    ErrorReturn(NULL, (ERROR_BADPARM, "afniRead(): bad file name %s", fname));
  }

  sprintf(c, ".HEAD");

  if ((fp = fopen(header_fname, "r")) == NULL)
  {
    errno = 0;
    ErrorReturn(NULL, (ERROR_BADFILE, "afniRead(): error opening file %s", header_fname));
  }

  // initialize AFNI structure
  AFinit(&af);

  // read header file
  if (!readAFNIHeader(fp, &af))
    return (NULL);

  printAFNIHeader(&af);

  // well, we don't have time
  if (af.numtypes != 1) // should be the same as af.dataset_rank[1] = subbricks
  {
    errno = 0;
    // ErrorReturn(NULL, (ERROR_UNSUPPORTED, "afniRead(): nframes = %d (only 1 frame supported)", af.numtypes));
    printf("INFO: number of frames dataset_rank[1] = %d : numtypes = %d \n",
           af.dataset_rank[1], af.numtypes);
  }
  // byteorder_string : required field
  if (strcmp(af.byteorder_string, "MSB_FIRST") == 0)
    big_endian_flag = 1;
  else if (strcmp(af.byteorder_string, "LSB_FIRST") == 0)
    big_endian_flag = 0;
  else
  {
    errno = 0;
    ErrorReturn(NULL, (ERROR_BADPARM, "read_afni_header(): unrecognized byte order string %s",
                       af.byteorder_string));
  }
  // brick_types : required field
  if (af.brick_types[0] == 2 // int
      || af.brick_types[0] > 3 )// 4 = double, 5 = complex, 6 = rgb
  {
    errno = 0;
    ErrorReturn(NULL,
                (ERROR_BADPARM,
                 "afniRead(): unsupported data type %d, Must be 0 (byte), 1(short), or 3(float)",
                 af.brick_types[0]));
  }
  //////////////////////////////////////////////////////////////////////////////////
  // now we allocate space for MRI
  // dataset_dimensions : required field
  header = MRIallocHeader(af.dataset_dimensions[0],
                          af.dataset_dimensions[1],
                          af.dataset_dimensions[2],
                          MRI_UCHAR,
                          af.dataset_rank[1]
                          );
  // set number of frames
  header->nframes = af.dataset_rank[1];

  // direction cosines (use orient_specific)
  // orient_specific : required field
  header->x_r = afni_orientations[af.orient_specific[0]][0];
  header->x_a = afni_orientations[af.orient_specific[0]][1];
  header->x_s = afni_orientations[af.orient_specific[0]][2];
  header->y_r = afni_orientations[af.orient_specific[1]][0];
  header->y_a = afni_orientations[af.orient_specific[1]][1];
  header->y_s = afni_orientations[af.orient_specific[1]][2];
  header->z_r = afni_orientations[af.orient_specific[2]][0];
  header->z_a = afni_orientations[af.orient_specific[2]][1];
  header->z_s = afni_orientations[af.orient_specific[2]][2];

  /* --- quick determinant check --- */
  det = + header->x_r * (header->y_a * header->z_s - header->z_a * header->y_s)
        - header->x_a * (header->y_r * header->z_s - header->z_r * header->y_s)
        + header->x_s * (header->y_r * header->z_a - header->z_r * header->y_a);

  if (det == 0)
  {
    MRIfree(&header);
    errno = 0;
    ErrorReturn(NULL,
                (ERROR_BADPARM,
                 "read_afni_header(): error in orientations %d, %d, %d (direction cosine matrix has determinant zero)",
                 af.orient_specific[0], af.orient_specific[1], af.orient_specific[2]));
  }
  // sizes use delta
  // delta : required field
  header->xsize = af.delta[0];
  header->ysize = af.delta[1];
  header->zsize = af.delta[2];

  // uses origin
  // origin : required field
  header->c_r = header->x_r * (header->xsize * (header->width-1.0)/2.0 + af.origin[0]) +
                header->y_r * (header->ysize * (header->height-1.0)/2.0 + af.origin[1]) +
                header->z_r * (header->zsize * (header->depth-1.0)/2.0 + af.origin[2]);

  header->c_a = header->x_a * (header->xsize * (header->width-1.0)/2.0 + af.origin[0]) +
                header->y_a * (header->ysize * (header->height-1.0)/2.0 + af.origin[1]) +
                header->z_a * (header->zsize * (header->depth-1.0)/2.0 + af.origin[2]);

  header->c_s = header->x_s * (header->xsize * (header->width-1.0)/2.0 + af.origin[0]) +
                header->y_s * (header->ysize * (header->height-1.0)/2.0 + af.origin[1]) +
                header->z_s * (header->zsize * (header->depth-1.0)/2.0 + af.origin[2]);

  header->ras_good_flag = 1;

  if (header->xsize < 0)
    header->xsize = -header->xsize;

  if (header->ysize < 0)
    header->ysize = -header->ysize;

  if (header->zsize < 0)
    header->zsize = -header->zsize;

  header->imnr0 = 1;
  header->imnr1 = header->depth;

  header->ps = header->xsize;
  header->thick = header->zsize;

  header->xend = (header->width  / 2.0) * header->xsize;
  header->xstart = -header->xend;
  header->yend = (header->height / 2.0) * header->ysize;
  header->ystart = -header->yend;
  header->zend = (header->depth  / 2.0) * header->zsize;
  header->zstart = -header->zend;

  xfov = header->xend - header->xstart;
  yfov = header->yend - header->ystart;
  zfov = header->zend - header->zstart;

  header->fov = ( xfov > yfov ? (xfov > zfov ? xfov : zfov ) : (yfov > zfov ? yfov : zfov ) );

#if (BYTE_ORDER==LITTLE_ENDIAN)
  //#ifdef Linux
  swap_flag = big_endian_flag;
#else
  swap_flag = !big_endian_flag;
#endif

  if ((fp = fopen(fname, "r")) == NULL)
  {
    MRIfree(&header);
    errno = 0;
    ErrorReturn(NULL, (ERROR_BADFILE, "afniRead(): error opening file %s", header_fname));
  }

  fseek(fp, 0, SEEK_END);
  brik_file_length = ftell(fp);
  fseek(fp, 0, SEEK_SET);

  // number of voxels consecutive

  nvoxels = header->width * header->height * header->depth * header->nframes;

  if (brik_file_length % nvoxels)
  {
    fclose(fp);
    MRIfree(&header);
    errno = 0;
    ErrorReturn(NULL, (ERROR_BADFILE, "afniRead(): BRIK file length (%d) is not divisible by the number of voxels (%d)", brik_file_length, nvoxels));
  }
  // bytes_per_voxel = brik_file_length / nvoxels; // this assumes one frame
  bytes_per_voxel = af.brick_types[0] + 1; // 0(byte)-> 1, 1(short) -> 2, 3(float)->4

  bytes = header->width*header->height*header->depth*bytes_per_voxel;

  // this check is for nframes = 1 case which is the one we are supporting
  if (bytes_per_voxel != brik_file_length/nvoxels)
  {
    fclose(fp);
    MRIfree(&header);
    errno = 0;
    ErrorReturn(NULL,
                (ERROR_UNSUPPORTED,
                 "afniRead(): type info stored in header does not agree with the file size: %d != %d/%d",
                 bytes_per_voxel, brik_file_length/nvoxels));
  }

  // if brick_float_facs != 0 then we scale values to be float
  if (af.numfacs != 0 && af.brick_float_facs[0] != 0.)
  {
    header->type = MRI_FLOAT;
    scaling = af.brick_float_facs[0];
  }
  else
  {
    if (bytes_per_voxel == 1)
      header->type = MRI_UCHAR;
    else if (bytes_per_voxel == 2)
      header->type = MRI_SHORT;
    else if (bytes_per_voxel == 4)
      header->type = MRI_FLOAT;
    else
    {
      fclose(fp);
      MRIfree(&header);
      errno = 0;
      ErrorReturn(NULL, (ERROR_UNSUPPORTED, "afniRead(): don't know what to do with %d bytes per voxel", bytes_per_voxel));
    }
  }

  ///////////////////////////////////////////////////////////////////////
  if (read_volume)
  {
    // mri = MRIalloc(header->width, header->height, header->depth, header->type);
    mri = MRIallocSequence(header->width, header->height, header->depth,
                           header->type, header->nframes) ;
    MRIcopyHeader(header, mri);

    for (frame = 0; frame < header->nframes; ++frame)
    {
      initialized = 0;
      for (k = 0;k < mri->depth;k++)
      {
        for (j = 0;j < mri->height;j++)
        {
          if (af.brick_float_facs[frame])
            scaling = af.brick_float_facs[frame];
          else
            scaling = 1.;
          {
            pmem = (void *) malloc(bytes_per_voxel*mri->width);
            if (pmem)
            {
              if (fread(pmem, bytes_per_voxel, mri->width, fp) != mri->width)
              {
                fclose(fp);
                MRIfree(&header);
                errno = 0;
                ErrorReturn(NULL, (ERROR_BADFILE, "afniRead(): error reading from file %s", fname));
              }
              // swap bytes
              if (swap_flag)
              {
                if (bytes_per_voxel == 2) // short
                {
                  swab(pmem, pmem, mri->width * 2);
                }
                else if (bytes_per_voxel == 4) // float
                {
                  pf = (float *) pmem;
                  for (i = 0;i < mri->width;i++, pf++)
                    *pf = swapFloat(*pf);
                }
              }
              // now scaling
              if (bytes_per_voxel == 1) // byte
              {
                pc = (unsigned char *) pmem;
                for (i=0; i < mri->width; i++)
                {
                  if (scaling == 1.)
                    MRIseq_vox(mri, i, j, k, frame) = *pc;
                  else
                    MRIFseq_vox(mri, i, j, k, frame) = ((float) (*pc))*scaling;
                  ++pc;
                }
                findMinMaxByte((unsigned char *) pmem, mri->width, &flMin, &flMax);
              }
              if (bytes_per_voxel == 2) // short
              {
                ps = (short *) pmem;
                for (i=0; i < mri->width; i++)
                {
                  // if (*ps != 0)
                  //   printf("%d ", *ps);
                  if (scaling == 1.)
                    MRISseq_vox(mri, i, j, k, frame) = *ps;
                  else
                    MRIFseq_vox(mri, i, j, k, frame) = ((float) (*ps))*scaling;
                  ++ps;
                }
                findMinMaxShort((short *) pmem, mri->width, &flMin, &flMax);
              }
              else if (bytes_per_voxel == 4) // float
              {
                pf = (float *) pmem;
                for (i=0; i < mri->width; i++)
                {

                  MRIFseq_vox(mri, i, j, k, frame) = (*pf)*scaling;
                  ++pf;
                }
                findMinMaxFloat((float *) pmem, mri->width, &flMin, &flMax);
              }
              free(pmem);
              //
              if (initialized == 0)
              {
                fMin = flMin;
                fMax = flMax;
                initialized = 1;
              }
              else
              {
                if (flMin < fMin)
                  fMin = flMin;
                if (flMax > fMax)
                  fMax = flMax;
                // printf("\n fmin =%f, fmax = %f, local min = %f, max = %f\n", fMin, fMax, flMin, flMax);
              }
            }
            else
            {
              fclose(fp);
              MRIfree(&header);
              errno = 0;
              ErrorReturn(NULL,
                          (ERROR_BADFILE, "afniRead(): could not allocate memory for reading %s", fname));
            }
          }
        } // height
      } // depth
      // valid only for nframs == 1
      {
        printf("BRICK_STATS min = %f <--> actual min = %f\n",
               af.brick_stats[0+2*frame], fMin*scaling);
        printf("BRICK_STATS max = %f <--> actual max = %f\n",
               af.brick_stats[1+2*frame], fMax*scaling);
      }
    } // nframes
  }
  else // not reading volume
    mri = MRIcopy(header, NULL);

  strcpy(mri->fname, fname);

  fclose(fp);

  MRIfree(&header);
  AFclean(&af);

  return(mri);

} /* end afniRead() */