Beispiel #1
0
/*---------------------------------------------------------------*/
int main(int argc, char *argv[]) {
  int nargs, nthvtx, nnbrs1, nnbrs2, nthnbr, nbrvtxno1, nbrvtxno2;
  int nthface, annot1, annot2;
  VERTEX *vtx1, *vtx2;
  FACE *face1, *face2;
  float diff, maxdiff;

  nargs = handle_version_option (argc, argv, vcid, "$Name: stable5 $");
  if (nargs && argc - nargs == 1) exit (0);
  argc -= nargs;
  cmdline = argv2cmdline(argc,argv);
  uname(&uts);
  getcwd(cwd,2000);

  Progname = argv[0] ;
  argc --;
  argv++;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;
  if (argc == 0) usage_exit();
  parse_commandline(argc, argv);
  check_options();
  if (checkoptsonly) return(0);

  SUBJECTS_DIR = getenv("SUBJECTS_DIR");
  if (SUBJECTS_DIR == NULL) {
    printf("INFO: SUBJECTS_DIR not defined in environment\n");
    //exit(1);
  }
  if (SUBJECTS_DIR1 == NULL) SUBJECTS_DIR1 = SUBJECTS_DIR;
  if (SUBJECTS_DIR2 == NULL) SUBJECTS_DIR2 = SUBJECTS_DIR;

  if (surf1path == NULL && surfname == NULL) surfname = "orig";

  if (surf1path == NULL) {
    sprintf(tmpstr,"%s/%s/surf/%s.%s",SUBJECTS_DIR1,subject1,hemi,surfname);
    surf1path = strcpyalloc(tmpstr);
  }
  if (surf2path == NULL) {
    sprintf(tmpstr,"%s/%s/surf/%s.%s",SUBJECTS_DIR2,subject2,hemi,surfname);
    surf2path = strcpyalloc(tmpstr);
  }
  dump_options(stdout);

  //read-in each surface.  notice that the random number generator is
  //seeded with the same value prior to each read.  this is because in
  //the routine MRIScomputeNormals, if it finds a zero-length vertex
  //normal, is adds a random value to the x,y,z and recomputes the normal.
  //so if comparing identical surfaces, the seed must be the same so that
  //any zero-length vertex normals appear the same.
  setRandomSeed(seed) ;
  surf1 = MRISread(surf1path);
  if (surf1 == NULL) {
    printf("ERROR: could not read %s\n",surf1path);
    exit(1);
  }
  setRandomSeed(seed) ;
  surf2 = MRISread(surf2path);
  if (surf2 == NULL) {
    printf("ERROR: could not read %s\n",surf2path);
    exit(1);
  }
  printf("Number of vertices %d %d\n",surf1->nvertices,surf2->nvertices);
  printf("Number of faces    %d %d\n",surf1->nfaces,surf2->nfaces);

  //Number of Vertices ----------------------------------------
  if (surf1->nvertices != surf2->nvertices) {
    printf("Surfaces differ in number of vertices %d %d\n",
           surf1->nvertices,surf2->nvertices);
    exit(101);
  }
  //Number of Faces ------------------------------------------
  if (surf1->nfaces != surf2->nfaces) {
    printf("Surfaces differ in number of faces %d %d\n",
           surf1->nfaces,surf2->nfaces);
    exit(101);
  }

  //surf1->faces[10000].area = 100;
  //surf1->vertices[10000].x = 100;

  if (ComputeNormalDist) {
    double dist, dx, dy, dz, dot ;
    MRI    *mri_dist ;

    mri_dist = MRIalloc(surf1->nvertices,1,1,MRI_FLOAT) ;
    MRIScomputeMetricProperties(surf1) ;
    MRIScomputeMetricProperties(surf2) ;
    for (nthvtx=0; nthvtx < surf1->nvertices; nthvtx++) {
      vtx1 = &(surf1->vertices[nthvtx]);
      vtx2 = &(surf2->vertices[nthvtx]);
      dx = vtx2->x-vtx1->x ;
      dy = vtx2->y-vtx1->y ;
      dz = vtx2->z-vtx1->z ;
      dist = sqrt(dx*dx + dy*dy + dz*dz) ;
      dot = dx*vtx1->nx + dy*vtx1->ny + dz*vtx1->nz ;
      dist = dist * dot / fabs(dot) ;
      MRIsetVoxVal(mri_dist, nthvtx, 0, 0, 0, dist) ;
    }
    MRIwrite(mri_dist, out_fname) ;
    MRIfree(&mri_dist) ;
    exit(0);
  }

  maxdiff=0;

  //------------------------------------------------------------
  if (CheckSurf) {
    printf("Comparing surfaces\n");

    // Loop over vertices ---------------------------------------
    error_count=0;
    for (nthvtx=0; nthvtx < surf1->nvertices; nthvtx++) {
      vtx1 = &(surf1->vertices[nthvtx]);
      vtx2 = &(surf2->vertices[nthvtx]);
      if (vtx1->ripflag != vtx2->ripflag) {
        printf("Vertex %d differs in ripflag %c %c\n",
               nthvtx,vtx1->ripflag,vtx2->ripflag);
        if (++error_count>=MAX_NUM_ERRORS) break;
      }
      if (CheckXYZ) {
        diff=fabs(vtx1->x - vtx2->x);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Vertex %d differs in x %g %g\t(%g)\n",
                 nthvtx,vtx1->x,vtx2->x,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
        diff=fabs(vtx1->y - vtx2->y);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Vertex %d differs in y %g %g\t(%g)\n",
                 nthvtx,vtx1->y,vtx2->y,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
        diff=fabs(vtx1->z - vtx2->z);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Vertex %d differs in z %g %g\t(%g)\n",
                 nthvtx,vtx1->z,vtx2->z,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
      }
      if (CheckNXYZ) {
        diff=fabs(vtx1->nx - vtx2->nx);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Vertex %d differs in nx %g %g\t(%g)\n",
                 nthvtx,vtx1->nx,vtx2->nx,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
        diff=fabs(vtx1->ny - vtx2->ny);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Vertex %d differs in ny %g %g\t(%g)\n",
                 nthvtx,vtx1->ny,vtx2->ny,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
        diff=fabs(vtx1->nz - vtx2->nz);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Vertex %d differs in nz %g %g\t(%g)\n",
                 nthvtx,vtx1->nz,vtx2->nz,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
      }
      nnbrs1 = surf1->vertices[nthvtx].vnum;
      nnbrs2 = surf2->vertices[nthvtx].vnum;
      if (nnbrs1 != nnbrs2) {
        printf("Vertex %d has a different number of neighbors %d %d\n",
               nthvtx,nnbrs1,nnbrs2);
        if (++error_count>=MAX_NUM_ERRORS) break;
      }
      for (nthnbr=0; nthnbr < nnbrs1; nthnbr++) {
        nbrvtxno1 = surf1->vertices[nthvtx].v[nthnbr];
        nbrvtxno2 = surf2->vertices[nthvtx].v[nthnbr];
        if (nbrvtxno1 != nbrvtxno2) {
          printf("Vertex %d differs in the identity of the "
                 "%dth neighbor %d %d\n",nthvtx,nthnbr,nbrvtxno1,nbrvtxno2);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
      }
      if (error_count>=MAX_NUM_ERRORS) break;
    }// loop over vertices
    if (maxdiff>0) printf("maxdiff=%g\n",maxdiff);
    if (error_count > 0) {
      printf("Exiting after finding %d errors\n",error_count);
      if (error_count>=MAX_NUM_ERRORS) {
        printf("Exceeded MAX_NUM_ERRORS loop guard\n");
      }
      exit(103);
    }

    // Loop over faces ----------------------------------------
    error_count=0;
    for (nthface=0; nthface < surf1->nfaces; nthface++) {
      face1 = &(surf1->faces[nthface]);
      face2 = &(surf2->faces[nthface]);
      if (CheckNXYZ) {
        diff=fabs(face1->nx - face2->nx);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Face %d differs in nx %g %g\t(%g)\n",
                 nthface,face1->nx,face2->nx,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
        diff=fabs(face1->ny - face2->ny);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Face %d differs in ny %g %g\t(%g)\n",
                 nthface,face1->ny,face2->ny,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
        diff=fabs(face1->nz - face2->nz);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Face %d differs in nz %g %g\t(%g)\n",
                 nthface,face1->nz,face2->nz,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
      }
      diff=fabs(face1->area - face2->area);
      if (diff>maxdiff) maxdiff=diff;
      if (diff>thresh) {
        printf("Face %d differs in area %g %g\t(%g)\n",
               nthface,face1->area,face2->area,diff);
        if (++error_count>=MAX_NUM_ERRORS) break;
      }
      if (face1->ripflag != face2->ripflag) {
        printf("Face %d differs in ripflag %c %c\n",
               nthface,face1->ripflag,face2->ripflag);
        if (++error_count>=MAX_NUM_ERRORS) break;
      }
      for (nthvtx = 0; nthvtx < 3; nthvtx++) {
        if (face1->v[nthvtx] != face2->v[nthvtx]) {
          printf("Face %d differs in identity of %dth vertex %d %d\n",
                 nthface,nthvtx,face1->ripflag,face2->ripflag);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
      } // end loop over nthface vertex
      if (error_count>=MAX_NUM_ERRORS) break;
    } // end loop over faces
    if (maxdiff>0) printf("maxdiff=%g\n",maxdiff);
    if (error_count > 0) {
      printf("Exiting after finding %d errors\n",error_count);
      if (error_count>=MAX_NUM_ERRORS) {
        printf("Exceeded MAX_NUM_ERRORS loop guard\n");
      }
      exit(103);
    }

    printf("Surfaces are the same\n");
    exit(0);
  } // end check surf

  // -----------------------------------------------------------------
  if (CheckCurv) {
    printf("Checking curv file %s\n",curvname);
    sprintf(tmpstr,"%s/%s/surf/%s.%s",SUBJECTS_DIR1,subject1,hemi,curvname);
    printf("Loading curv file %s\n",tmpstr);
    if (MRISreadCurvatureFile(surf1, tmpstr) != 0) {
      printf("ERROR: reading curvature file %s\n",tmpstr);
      exit(1);
    }
    sprintf(tmpstr,"%s/%s/surf/%s.%s",SUBJECTS_DIR2,subject2,hemi,curvname);
    printf("Loading curv file %s\n",tmpstr);
    if (MRISreadCurvatureFile(surf2, tmpstr) != 0) {
      printf("ERROR: reading curvature file %s\n",tmpstr);
      exit(1);
    }
    error_count=0;
    for (nthvtx=0; nthvtx < surf1->nvertices; nthvtx++) {
      vtx1 = &(surf1->vertices[nthvtx]);
      vtx2 = &(surf2->vertices[nthvtx]);
      diff=fabs(vtx1->curv - vtx2->curv);
      if (diff>maxdiff) maxdiff=diff;
      if (diff > thresh) {
        printf("curv files differ at vertex %d %g %g\t(%g)\n",
               nthvtx,vtx1->curv,vtx2->curv,diff);
        if (++error_count>=MAX_NUM_ERRORS) break;
      }
    } // end loop over vertices
    if (maxdiff>0) printf("maxdiff=%g\n",maxdiff);
    if (error_count > 0) {
      printf("Exiting after finding %d errors\n",error_count);
      if (error_count>=MAX_NUM_ERRORS) {
        printf("Exceeded MAX_NUM_ERRORS loop guard\n");
      }
      exit(103);
    }
    printf("Curv files are the same\n");
    exit(0);
  } // end check curv

  // ---------------------------------------------------------
  if (CheckAParc) {
    printf("Checking AParc %s\n",aparcname);
    sprintf(tmpstr,"%s/%s/label/%s.%s.annot",
            SUBJECTS_DIR1,subject1,hemi,aparcname);
    printf("Loading aparc file %s\n",tmpstr);
    fflush(stdout);
    if (MRISreadAnnotation(surf1, tmpstr)) {
      printf("ERROR: MRISreadAnnotation() failed %s\n",tmpstr);
      exit(1);
    }
    if (aparc2name) aparcname = aparc2name;
    sprintf(tmpstr,"%s/%s/label/%s.%s.annot",
            SUBJECTS_DIR2,subject2,hemi,aparcname);
    printf("Loading aparc file %s\n",tmpstr);
    fflush(stdout);
    if (MRISreadAnnotation(surf2, tmpstr)) {
      printf("ERROR: MRISreadAnnotation() failed %s\n",tmpstr);
      exit(1);
    }
    error_count=0;
    for (nthvtx=0; nthvtx < surf1->nvertices; nthvtx++) {
      annot1 = surf1->vertices[nthvtx].annotation;
      annot2 = surf2->vertices[nthvtx].annotation;
      if (annot1 != annot2) {
        printf("aparc files differ at vertex %d: 1:%s 2:%s\n",
               nthvtx,
               CTABgetAnnotationName(surf1->ct,annot1),
               CTABgetAnnotationName(surf2->ct,annot2));
        if (++error_count>=MAX_NUM_ERRORS) break;
      }
    } // end loop over vertices
    if (error_count > 0) {
      printf("Exiting after finding %d errors\n",error_count);
      if (error_count>=MAX_NUM_ERRORS) {
        printf("Exceeded MAX_NUM_ERRORS loop guard\n");
      }
      exit(103);
    }
    printf("\n"
           "AParc files are the same\n"
           "------------------------\n");
    exit(0);
  }

  return 0;
}
Beispiel #2
0
int CLIB_ROUTINE main( int argc, char** argv)
{
/**************************************
 *
 *	m a i n
 *
 **************************************
 *
 * Functional description
 *	Install or remove Firebird.
 *
 **************************************/
	TEXT directory[MAXPATHLEN];

	USHORT sw_command = COMMAND_NONE;
	bool sw_version = false;

	// Let's get the root directory from the instance path of this program.
	// argv[0] is only _mostly_ guaranteed to give this info,
	// so we GetModuleFileName()
	const USHORT len = GetModuleFileName(NULL, directory, sizeof(directory));
	if (len == 0)
		return reg_error(GetLastError(), "GetModuleFileName", NULL);

	// Get to the last '\' (this one precedes the filename part). There is
	// always one after a call to GetModuleFileName().
	TEXT* p = directory + len;
	do {--p;} while (*p != '\\');

	// Get to the previous '\' (this one should precede the supposed 'bin\\' part).
	// There is always an additional '\' OR a ':'.
	do {--p;} while (*p != '\\' && *p != ':');
	*p = '\0';

	const TEXT* const* const end = argv + argc;
	while (++argv < end)
	{
		if (**argv != '-')
		{
			const TEXT* cmd;
			USHORT i;
			for (i = 0; cmd = commands[i].name; i++)
			{
				const TEXT* q = cmd;
				for (p = *argv; *p && UPPER(*p) == *q; ++p, ++q)
					;
				if (!*p && commands[i].abbrev <= (USHORT) (q - cmd))
					break;
			}
			if (!cmd)
			{
				printf("Unknown command \"%s\"\n", *argv);
				usage_exit();
			}
			sw_command = commands[i].code;
		}
		else
		{
			p = *argv + 1;
			switch (UPPER(*p))
			{
				case 'Z':
					sw_version = true;
					break;

				case '?':
					usage_exit();

				default:
					printf("Unknown switch \"%s\"\n", p);
					usage_exit();
			}
		}
	}

	if (sw_version)
		printf("instreg version %s\n", FB_VERSION);

	if (sw_command == COMMAND_NONE)
		usage_exit();

	HKEY hkey_node = HKEY_LOCAL_MACHINE;

	USHORT ret;
	switch (sw_command)
	{
		case COMMAND_INSTALL:
			ret = REGISTRY_install(hkey_node, directory, reg_error);
			if (ret != FB_SUCCESS)
				printf ("Firebird has not been installed in the registry.\n");
			else
				printf("Firebird has been successfully installed in the registry.\n");
			break;

		case COMMAND_REMOVE:
			ret = REGISTRY_remove(hkey_node, false, reg_error);
			if (ret != FB_SUCCESS)
				printf("Firebird has not been deleted from the registry.\n");
			else
				printf("Firebird has been successfully deleted from the registry.\n");
			break;

		default:
			ret = FB_SUCCESS;
	}

	if (hkey_node != HKEY_LOCAL_MACHINE)
		RegCloseKey(hkey_node);

	return (ret == FB_SUCCESS) ? FINI_OK : FINI_ERROR;
}
int
main (int argc, char *argv [])
{	SNDFILE	*infile, *outfile = NULL ;
	SF_INFO sfinfo ;

	sf_count_t	count ;
	double		src_ratio = -1.0, gain = 1.0 ;
	int			new_sample_rate = -1, k, converter, max_speed = SF_FALSE ;

	if (argc == 2 && strcmp (argv [1], "--version") == 0)
	{	char buffer [64], *cptr ;

		if ((cptr = strrchr (argv [0], '/')) != NULL)
			argv [0] = cptr + 1 ;
		if ((cptr = strrchr (argv [0], '\\')) != NULL)
			argv [0] = cptr + 1 ;

		sf_command (NULL, SFC_GET_LIB_VERSION, buffer, sizeof (buffer)) ;

		printf ("%s (%s,%s)\n", argv [0], src_get_version (), buffer) ;
		exit (0) ;
		} ;

	if (argc != 5 && argc != 7 && argc != 8)
		usage_exit (argv [0]) ;

	/* Set default converter. */
	converter = DEFAULT_CONVERTER ;

	for (k = 1 ; k < argc - 2 ; k++)
	{	if (strcmp (argv [k], "--max-speed") == 0)
			max_speed = SF_TRUE ;
		else if (strcmp (argv [k], "-to") == 0)
		{	k ++ ;
			new_sample_rate = parse_int_or_die (argv [k], "sample rate") ;
			}
		else if (strcmp (argv [k], "-by") == 0)
		{	k ++ ;
			src_ratio = atof (argv [k]) ;
			}
		else if (strcmp (argv [k], "-c") == 0)
		{	k ++ ;
			converter = parse_int_or_die (argv [k], "converter") ;
			}
		else
			usage_exit (argv [0]) ;
		} ;

	if (new_sample_rate <= 0 && src_ratio <= 0.0)
		usage_exit (argv [0]) ;

	if (src_get_name (converter) == NULL)
	{	printf ("Error : bad converter number.\n") ;
		usage_exit (argv [0]) ;
		} ;

	if (strcmp (argv [argc - 2], argv [argc - 1]) == 0)
	{	printf ("Error : input and output file names are the same.\n") ;
		exit (1) ;
		} ;

	memset (&sfinfo, 0, sizeof (sfinfo)) ;
	if ((infile = sf_open (argv [argc - 2], SFM_READ, &sfinfo)) == NULL)
	{	printf ("Error : Not able to open input file '%s'\n", argv [argc - 2]) ;
		exit (1) ;
		} ;

	printf ("Input File    : %s\n", argv [argc - 2]) ;
	printf ("Sample Rate   : %d\n", sfinfo.samplerate) ;
	printf ("Input Frames  : %ld\n\n", (long) sfinfo.frames) ;

	if (new_sample_rate > 0)
	{	src_ratio = (1.0 * new_sample_rate) / sfinfo.samplerate ;
		sfinfo.samplerate = new_sample_rate ;
		}
	else if (src_is_valid_ratio (src_ratio))
		sfinfo.samplerate = (int) floor (sfinfo.samplerate * src_ratio) ;
	else
	{	printf ("Not able to determine new sample rate. Exiting.\n") ;
		sf_close (infile) ;
		exit (1) ;
		} ;

	if (fabs (src_ratio - 1.0) < 1e-20)
	{	printf ("Target samplerate and input samplerate are the same. Exiting.\n") ;
		sf_close (infile) ;
		exit (0) ;
		} ;

	printf ("SRC Ratio     : %f\n", src_ratio) ;
	printf ("Converter     : %s\n\n", src_get_name (converter)) ;

	if (src_is_valid_ratio (src_ratio) == 0)
	{	printf ("Error : Sample rate change out of valid range.\n") ;
		sf_close (infile) ;
		exit (1) ;
		} ;

	/* Delete the output file length to zero if already exists. */
	remove (argv [argc - 1]) ;

	printf ("Output file   : %s\n", argv [argc - 1]) ;
	printf ("Sample Rate   : %d\n", sfinfo.samplerate) ;

	do
	{	sf_close (outfile) ;

		if ((outfile = sf_open (argv [argc - 1], SFM_WRITE, &sfinfo)) == NULL)
		{	printf ("Error : Not able to open output file '%s'\n", argv [argc - 1]) ;
			sf_close (infile) ;
			exit (1) ;
			} ;

		if (max_speed)
		{	/* This is mainly for the comparison program tests/src-evaluate.c */
			sf_command (outfile, SFC_SET_ADD_PEAK_CHUNK, NULL, SF_FALSE) ;
			}
		else
		{	/* Update the file header after every write. */
			sf_command (outfile, SFC_SET_UPDATE_HEADER_AUTO, NULL, SF_TRUE) ;
			} ;

		sf_command (outfile, SFC_SET_CLIPPING, NULL, SF_TRUE) ;

		count = sample_rate_convert (infile, outfile, converter, src_ratio, sfinfo.channels, &gain) ;
		}
	while (count < 0) ;

	printf ("Output Frames : %ld\n\n", (long) count) ;

	sf_close (infile) ;
	sf_close (outfile) ;

	return 0 ;
} /* main */
Beispiel #4
0
int main(int argc, char *argv[]) {
  char   **av, *in_fname;
  int    ac, nargs;
  MRIS    *mris;
  int    msec, minutes, seconds, nv, nf, ne, eno ;
  struct timeb start ;
  double total_volume;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mris_volume.c,v 1.6 2011/03/02 00:04:34 nicks Exp $", "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  TimerStart(&start) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (argc < 2)
    usage_exit(1) ;

  //  printf("command line parsing finished\n");

  /*** Read in the input surfaces ***/
  in_fname = argv[1] ;
  if (verbose) printf("reading %s...\n", in_fname) ;

  mris = MRISread(in_fname) ;
  if(mris == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface %s",
              Progname, in_fname) ;
  eno = MRIScomputeEulerNumber(mris, &nv, &nf, &ne) ;
  if (eno != 2)
    ErrorExit(ERROR_BADPARM, "%s: surface %s has an incorrect topology (eno=%d)",
              Progname, in_fname, eno) ;

  if(verbose) printf("surface file read in.\n");

  total_volume = MRISvolumeInSurf(mris);

  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  if (verbose)
    printf("Volume computation took %d minutes and %d seconds.\n", 
	   minutes, seconds) ;

  if (verbose)
    printf("total volume surrounded by the surface is %g\n", total_volume);
  else
    printf("%lf\n", total_volume);

  MRISfree(&mris);

  exit(0);
}
int
main(int argc, char *argv[]) {
  char        **av, *in_vol, *out_vol;
  int         ac, nargs;

  MRI         *mri_in, *mri_out, *mri_tmp ;
  LTA         *lta = 0;
  MATRIX *i_to_r_src = 0; /* src geometry of the input LTA */
  MATRIX *V_to_V = 0; /* Final voxel-to-voxel transform */
  MATRIX *r_to_i_dst = 0; /* dst geometry of the input LTA */
  MATRIX *m_tmp = 0;
  MATRIX *i_to_r_reg = 0; /* i_to_r of the volume after registration */
  MATRIX *r_to_i_out = 0; /* r_to_i of the final output volume */
  VOL_GEOM vgm_in;
  int x, y, z;
  double maxV, minV, value;
  int transform_type;
  //  MATRIX *i_to_r, *r_to_i;
  HISTOGRAM *h, *hsmooth ;
  float fmin, fmax, val, peak, smooth_peak;
  int i, nbins, bin;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_transform_to_COR.c,v 1.3 2011/03/02 00:04:25 nicks Exp $", "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
    usage_exit (0);
  argc -= nargs;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (argc < 3)
    usage_exit(0) ;

  in_vol = argv[1] ;
  out_vol = argv[2] ;

  printf("reading volume from %s...\n", in_vol) ;
  mri_in = MRIread(in_vol) ;
  if (!mri_in)
    ErrorExit(ERROR_NOFILE, "%s: could not read MRI volume %s", Progname,
              in_vol) ;

  /* Convert mri_in to float type */
  /* double would be more accurate */
  if (mri_in->type != MRI_FLOAT) {
    printf("Input volume type is %d\n", mri_in->type);
    printf("Change input volume to float type for convenience and accuracy");
    mri_tmp = MRIchangeType(mri_in, MRI_FLOAT, 0, 1.0, 1);
    MRIfree(&mri_in);
    mri_in = mri_tmp; //swap
  }

  /* Get input volume geometry, which is needed to compute i_to_r
   * and r_to_i of input volume. Note that i_to_r and r_to_i assumed
   * a certain prespecified c_r, c_a, c_s
   */
  getVolGeom(mri_in, &vgm_in);

  maxV = -10000.0;
  minV = 10000.0;
  for (z=0; z < mri_in->depth; z++)
    for (y=0; y< mri_in->height; y++)
      for (x=0; x < mri_in->width; x++) {
        if (MRIFvox(mri_in, x, y, z) > maxV )
          maxV = MRIFvox(mri_in, x, y,z) ;
        if (MRIFvox(mri_in, x, y, z) < minV )
          minV = MRIFvox(mri_in, x, y,z) ;
      }

  printf("Input volume has max = %g, min =%g\n", maxV, minV);

  printf("Scale input volume by %g \n", scale);

  maxV = -10000.0;
  minV = 10000.0;
  for (z=0; z < mri_in->depth; z++)
    for (y=0; y< mri_in->height; y++)
      for (x=0; x < mri_in->width; x++) {
        MRIFvox(mri_in, x, y, z) *= scale;
        if (MRIFvox(mri_in, x, y, z) > maxV )
          maxV = MRIFvox(mri_in, x, y,z) ;
        if (MRIFvox(mri_in, x, y, z) < minV )
          minV = MRIFvox(mri_in, x, y,z) ;
      }

  printf("Input volume after scaling has max = %g, min =%g\n", maxV, minV);

  /* Try to compute the Voxel_to_Voxel transform from the input volume
   * and the registration target/reference volume!
   * If no registration is involved, vox_to_vox is simply identity
   */
  /* Things become more complicated when allowing inverse transform */
  if (transform_flag) {


    printf("INFO: Applying transformation from file %s...\n",
           transform_fname);
    transform_type =  TransformFileNameType(transform_fname);

    /* Read in LTA transform file name */
    if (transform_type == MNI_TRANSFORM_TYPE ||
        transform_type == TRANSFORM_ARRAY_TYPE ||
        transform_type == REGISTER_DAT ||
        transform_type == FSLREG_TYPE
       ) {

      printf("Reading transform ...\n");
      lta = LTAreadEx(transform_fname) ;

      if (!lta)
        ErrorExit(ERROR_NOFILE, "%s: could not read transform file %s",
                  Progname, transform_fname) ;

      if (transform_type == FSLREG_TYPE) {
        if (lta_src == 0 || lta_dst == 0) {
          fprintf(stderr, "ERROR: fslmat does not have information on the src and dst volumes\n");
          fprintf(stderr, "ERROR: you must give options '-src' and '-dst' to specify the src and dst volume infos for the registration\n");
        }


        LTAmodifySrcDstGeom(lta, lta_src, lta_dst); // add src and dst information
        //The following is necessary to interpret FSLMAT correctly!!!
        LTAchangeType(lta, LINEAR_VOX_TO_VOX);
      }
      if (lta->xforms[0].src.valid == 0) {
        if (lta_src == 0) {
          fprintf(stderr, "The transform does not have the valid src volume info.\n");
          fprintf(stderr, "Either you give src volume info by option -src or\n");
          fprintf(stderr, "make the transform to have the valid src info.\n");
          ErrorExit(ERROR_BAD_PARM, "Bailing out...\n");
        } else {
          LTAmodifySrcDstGeom(lta, lta_src, NULL); // add src information
        }
      }
      if (lta->xforms[0].dst.valid == 0) {
        if (lta_dst == 0) {
          fprintf(stderr, "The transform does not have the valid dst volume info.\n");
          fprintf(stderr, "Either you give src volume info by option -dst or\n");
          fprintf(stderr, "make the transform to have the valid dst info.\n");
          fprintf(stderr, "If the dst was average_305, then you can set\n");
          fprintf(stderr, "environmental variable USE_AVERAGE305 true\n");
          fprintf(stderr, "instead.\n");
          ErrorExit(ERROR_BAD_PARM, "Bailing out...\n");
        } else {
          LTAmodifySrcDstGeom(lta, NULL, lta_dst); // add  dst information
        }
      }


      // The following procedure aims to apply an LTA computed from COR format to a volume in non-COR format, or vice versa, as long as they share the same RAS
      // first change to LINEAR RAS_TO_RAS using old info
      if (lta->type != LINEAR_RAS_TO_RAS) {
        LTAchangeType(lta, LINEAR_RAS_TO_RAS);
      }

      // now possiblly reset the src and dst
      if (lta_src != NULL) {
        //always trust the user
        LTAmodifySrcDstGeom(lta, lta_src, NULL);
      }
      if (lta_dst != NULL) {
        //always trust the user
        LTAmodifySrcDstGeom(lta, NULL, lta_dst);
      }

      if (lta->type == LINEAR_RAS_TO_RAS) {
        /* Convert it to VOX_TO_VOX */
        /* VOXELsrc_to_VOXELdst = R2Vdst*R2Rlta*V2Rsrc */
        /* Note whether the input should be identical to src or dst here depends
         * on whether the LTA here is the direct or inverse transform
         */
        i_to_r_src = vg_i_to_r(&lta->xforms[0].src);
        r_to_i_dst = vg_r_to_i(&lta->xforms[0].dst);

        if (!r_to_i_dst || !i_to_r_src)
          ErrorExit(ERROR_BADFILE, "%s: failed to extract volume geometries from input LTA file",Progname);
        m_tmp = MatrixMultiply(lta->xforms[0].m_L, i_to_r_src, NULL);
        V_to_V = MatrixMultiply(r_to_i_dst, m_tmp, NULL);
        MatrixFree(&m_tmp);

        MatrixFree(&i_to_r_src);
        MatrixFree(&r_to_i_dst);
      }
    } else {
      fprintf(stderr, "unknown transform type in file %s\n",
              transform_fname);
      exit(1);
    }

    if (invert_flag) {
      /* Geometry of input volume should match that of the dst of the LTA */
      if (MYvg_isEqual(&lta->xforms[0].dst, &vgm_in) == 0) {
        ErrorExit(ERROR_BADFILE, "%s: dst volume of lta doesn't match that of input volume",Progname);
      }

      i_to_r_reg = vg_i_to_r(&lta->xforms[0].src);

      if (!i_to_r_reg)
        ErrorExit(ERROR_BADFILE, "%s: failed to extract i_to_r of registered volume from LTA",Progname);

      m_tmp =  MatrixInverse(V_to_V, NULL);
      if (!m_tmp)
        ErrorExit(ERROR_BADPARM, "%s: transform is singular!", Progname);

      MatrixFree(&V_to_V);
      V_to_V = m_tmp;
    } else {
      /* Geometry of input volume should match that of the src of the LTA */
      if (MYvg_isEqual(&lta->xforms[0].src, &vgm_in) == 0) {
        ErrorExit(ERROR_BADFILE, "%s: src volume of lta doesn't match that of input volume",Progname);
      }

      i_to_r_reg = vg_i_to_r(&lta->xforms[0].dst);

      if (!i_to_r_reg)
        ErrorExit(ERROR_BADFILE, "%s: failed to extract i_to_r of registered volume from LTA",Progname);
    }

  } else {
    /* No registration transform need be applied */
    V_to_V = MatrixIdentity(4, NULL);
    i_to_r_reg = extract_i_to_r(mri_in);
    if (!i_to_r_reg)
      ErrorExit(ERROR_BADFILE, "%s: failed to extract i_to_r from input volume",Progname);
  }

  /* Now need to find the vox-to-vox transformation between registered volume
   * (or input volume itself if no registration involved) and the output
   * volume, either in COR format or as the out-like volume
   */
  /* Given a volume with a certain i_to_r, we need to compute the necessary
   * vox-to-voxel transform to change its i_to_r to like another volume.
   * The vox-to-vox is equal to R2V(r_to_i)_likevol*i_to_r_current_vol.
   */
  if (out_like_fname) {
    mri_tmp = MRIread(out_like_fname) ;
    if (!mri_tmp)
      ErrorExit(ERROR_NOFILE, "%s: could not read template volume from %s",out_like_fname) ;

    /* out_type = mri_tmp->type; */

    /* specify the out-type to float initially so as not to lose accuracy
     * during reslicing, will change type to correct type later.
     */
    mri_out = MRIalloc(mri_tmp->width, mri_tmp->height, mri_tmp->depth, MRI_FLOAT) ;

    MRIcopyHeader(mri_tmp, mri_out) ;
    MRIfree(&mri_tmp);
  } else  /* assume output is in COR format */
  {
    mri_out = MRIalloc(256, 256, 256, MRI_FLOAT) ;
    /* out_type = MRI_UCHAR; */

    /* Who says MRIlinearTransformInterp will change the header??
     * I don't think so!
     */
    //E/ set xyzc_ras to coronal ones.. - these'll get zorched
    //by MRIlinearTransformInterp() - copy again later - is there
    //any use in having them here now?  yes, so we can pass mri_out
    //to the ras2vox fns.


    mri_out->imnr0 = 1; /* what's this? */
    mri_out->imnr1 = 256; /* what's this? */
    mri_out->thick = 1.0;
    mri_out->ps = 1.0; /* what's this? */
    mri_out->xsize = mri_out->ysize = mri_out->zsize = 1.0;
    mri_out->xstart = mri_out->ystart = mri_out->zstart = -128.0;
    mri_out->xend = mri_out->yend = mri_out->zend = 128.0;
    mri_out->x_r =-1;
    mri_out->y_r = 0;
    mri_out->z_r = 0;
    mri_out->x_a = 0;
    mri_out->y_a = 0;
    mri_out->z_a = 1;
    mri_out->x_s = 0;
    mri_out->y_s =-1;
    mri_out->z_s = 0;

    /* In this case, the RAS itself is not fully determined, i.e., c_ras.
     * It's quite arbitrary, different values just change the final
     * sitting of the volume inside the RAS system.
     */
    /* NO! The C_RAS has to be set correctly, depending which target
     * volume the previous Vox_to_Vox transformation assumes!
     * When a registration is involved, the target volume is either
     * the src of LTA (direct) or the dst (inverse transform). When
     * just change format, the target volume is the input itself!!
     */
    if (transform_flag) {
      if (invert_flag) {
        mri_out->c_r = lta->xforms[0].src.c_r;
        mri_out->c_a = lta->xforms[0].src.c_a;
        mri_out->c_s = lta->xforms[0].src.c_s;

      } else {
        mri_out->c_r = lta->xforms[0].dst.c_r;
        mri_out->c_a = lta->xforms[0].dst.c_a;
        mri_out->c_s = lta->xforms[0].dst.c_s;
      }
    } else {
      mri_out->c_r = mri_in->c_r;
      mri_out->c_a = mri_in->c_a;
      mri_out->c_s = mri_in->c_s;
    }

    mri_out->ras_good_flag=1; /* What does this flag mean ? */

    /* since output is just transformed input */
    MRIcopyPulseParameters(mri_in, mri_out) ;

  }

  /* Compute the final input-to-output VOX_to_VOX transformation matrix */
  r_to_i_out = extract_r_to_i(mri_out);

  m_tmp = MatrixMultiply(r_to_i_out, i_to_r_reg, NULL);
  V_to_V = MatrixMultiply(m_tmp, V_to_V, V_to_V);
  MatrixFree(&m_tmp);

  printf("InterpMethod = %d\n", InterpMethod);

  /* Modify the MyMRIlinearTr... if I want to implement my cubic-B-spline
   * interpolation method. Otherwise, unnecessary
   */
  /* mri_out = MyMRIlinearTransformInterp(mri_in, mri_out, V_to_V, InterpMethod); */
  if (InterpMethod == SAMPLE_BSPLINE)
    mri_out = MRIlinearTransformInterpBSpline(mri_in, mri_out, V_to_V,
              SplineDegree);
  else
    mri_out = MRIlinearTransformInterp(mri_in, mri_out, V_to_V, InterpMethod);

  maxV = -10000.0;
  minV = 10000.0;
  for (z=0; z < mri_out->depth; z++)
    for (y=0; y< mri_out->height; y++)
      for (x=0; x < mri_out->width; x++) {
        if (MRIFvox(mri_out, x, y, z) > maxV )
          maxV = MRIFvox(mri_out, x, y,z) ;
        if (MRIFvox(mri_out, x, y, z) < minV )
          minV = MRIFvox(mri_out, x, y,z) ;
      }

  if (autoscale) {
    noscale = 1;

    /* compute histogram of output volume */

    fmin = minV;
    fmax = maxV;
    if (fmin < 0) fmin = 0;
    nbins = 256 ;
    h = HISTOalloc(nbins) ;
    hsmooth = HISTOcopy(h, NULL) ;
    HISTOclear(h, h) ;
    h->bin_size = (fmax-fmin)/255.0 ;

    for (i = 0 ; i < nbins ; i++)
      h->bins[i] = (i+1)*h->bin_size ;

    for (z=0; z < mri_out->depth; z++)
      for (y=0; y< mri_out->height; y++)
        for (x=0; x < mri_out->width; x++) {
          val = MRIFvox(mri_out, x, y, z);
          if (val <= 0) continue;

          bin = nint((val - fmin)/h->bin_size);
          if (bin >= h->nbins)
            bin = h->nbins-1;
          else if (bin < 0)
            bin = 0;

          h->counts[bin] += 1.0;
        }
    HISTOfillHoles(h) ;
    HISTOsmooth(h, hsmooth, 5)  ;
    peak =
      hsmooth->bins[HISTOfindHighestPeakInRegion(h, 1, h->nbins)] ;
    //   smooth_peak =
    //  hsmooth->bins[HISTOfindHighestPeakInRegion(hsmooth, 1, hsmooth->nbins)] ;

    smooth_peak =
      hsmooth->bins[HISTOfindLastPeak(hsmooth, 5, 0.8)] ;

    /*
      bin = nint((smooth_peak - fmin)/hsmooth->bin_size) ;

      printf("Highest peak has count = %d\n", (int)hsmooth->counts[bin]);

      bin = nint((420 - fmin)/hsmooth->bin_size) ;

      printf("bin at 420 has count = %d\n", (int)hsmooth->counts[bin]);
    */

    scale =  110.0/smooth_peak;
    printf("peak of output volume is %g, smooth-peak is %g, multiply by %g to scale it to 110\n", peak, smooth_peak, scale);
    for (z=0; z < mri_out->depth; z++)
      for (y=0; y< mri_out->height; y++)
        for (x=0; x < mri_out->width; x++) {
          val = MRIFvox(mri_out, x, y, z);
          MRIFvox(mri_out, x, y, z) = val*scale;
        }

  }


  printf("Output volume (before type-conversion) has max = %g, min =%g\n", maxV, minV);

  /* Finally change type to desired */
  if (mri_out->type != out_type) {
    printf("Change output volume to type %d\n", out_type);
    /* I need to modify the MIRchangeType function to make sure
     * it does roundoff instead of simple truncation!
     */
    /* Note if the last flag is set to 1, then it won't do scaling
       and small float numbers will become zero after convert to
       BYTE
    */
    if (out_type == 0 && noscale == 1) {
      //convert data to UCHAR
      mri_tmp = MRIalloc(mri_out->width, mri_out->height, mri_out->depth, out_type) ;
      MRIcopyHeader(mri_out, mri_tmp);
      for (z=0; z < mri_out->depth; z++)
        for (y=0; y< mri_out->height; y++)
          for (x=0; x < mri_out->width; x++) {
            value = floor(MRIgetVoxVal(mri_out, x, y, z, 0) + 0.5);
            if (value < 0 ) value = 0;
            if (value > 255) value = 255;
            MRIvox(mri_tmp,x,y,z) = (unsigned char)value;
          }
    } else
      mri_tmp = MRIchangeType(mri_out, out_type, thred_low, thred_high, noscale);

    MRIfree(&mri_out);
    mri_out = mri_tmp; //swap
  }

  MRIwrite(mri_out, out_vol) ;

  MRIfree(&mri_in);
  MRIfree(&mri_out);

  if (lta_src)
    MRIfree(&lta_src);
  if (lta_dst)
    MRIfree(&lta_dst);

  MatrixFree(&V_to_V);

  if (!r_to_i_out)
    MatrixFree(&r_to_i_out);

  if (!i_to_r_reg)
    MatrixFree(&i_to_r_reg);

  return(0) ;  /* for ansi */
}
Beispiel #6
0
/*----------------------------------------------------------------------
            Parameters:

           Description:
----------------------------------------------------------------------*/
static int
get_option(int argc, char *argv[]) {
  int  nargs = 0 ;
  char *option ;

  option = argv[1] + 1 ;            /* past '-' */
  if (!stricmp(option, "debug_voxel")) {
    Gx = atoi(argv[2]) ;
    Gy = atoi(argv[3]) ;
    Gz = atoi(argv[4]) ;
    debug_flag = 1;
    nargs = 3 ;
    printf("debugging voxel (%d, %d, %d)...\n", Gx, Gy, Gz) ;
  } else if (!stricmp(option, "window")) {
    window_flag = 1 ;
    window_size = atoi(argv[2]) ;
    nargs = 1;
    printf("interpolating volume to be isotropic 1mm^3\n") ;
  } else if (!stricmp(option, "shift")) {
    shift_value  = atof(argv[2]) ;
    nargs = 1;
    printf("shift output by %g before truncating at zero \n", shift_value) ;
  } else if (!stricmp(option, "out_type")) {
    out_type = atoi(argv[2]);
    nargs = 1;
    printf("Output type is %d\n", out_type);
  } else if (!stricmp(option, "conform")) {
    conform = 1 ;
    printf("interpolating volume to be isotropic 1mm^3\n") ;
  } else if (!stricmp(option, "use_one")) {
    USE_ONE = 1 ;
    printf("Using only the covariance matrix of first class as SW \n") ;
  } else if (!stricmp(option, "whole_volume")) {
    whole_volume = 1 ;
    printf("Synthesize background region too (if LDA)\n") ;
  } else if (!stricmp(option, "lda")) {
    ldaflag = 1;
    class1 = atoi(argv[2]) ;
    class2 = atoi(argv[3]) ;
    nargs = 2;
    printf("Using LDA method to generate synthesized volume (%d, %d) \n", class1, class2);
  } else if (!stricmp(option, "mask")) {
    mask_fname = argv[2];
    printf("using %s as mask for regions of interest \n", mask_fname);
    nargs = 1;
  } else if (!stricmp(option, "label")) {
    label_fname = argv[2];
    printf("using %s as segmentation volume \n", label_fname);
    nargs = 1;
  } else if (!stricmp(option, "synth")) {
    synth_fname = argv[2];
    printf("using %s as output for synthesized volume \n", synth_fname);
    nargs = 1;
  } else if (!stricmp(option, "weight")) {
    weight_fname = argv[2];
    printf("using %s as input for LDA weights \n", weight_fname);
    nargs = 1;
  } else if (!stricmp(option, "noconform")) {
    conform = 0 ;
    printf("inhibiting isotropic volume interpolation\n") ;
  } else if (!stricmp(option, "test")) {
    just_test = 1 ;
    printf("Test: set Sw to identity matrix.\n") ;
  } else if (!stricmp(option, "regularize")) {
    regularize = 1 ;
    lambda = atof(argv[2]);
    nargs = 1;
    printf("regularization for covarinace matrix, lambda = %g\n", lambda) ;
  } else if (!stricmp(option, "distance")) {
    compute_m_distance = 1 ;
    printf("Compute M distance between cluster centers.\n") ;
  } else switch (toupper(*option)) {
    case 'T':
      noise_threshold = atof(argv[2]) ;
      printf("Threshold for background noise = %g\n", noise_threshold) ;
      printf("The threshold is applied on first input volume.\n") ;
      nargs = 1 ;
      break ;
    case 'W':
      have_weight = 1;
      break;
    case '?':
    case 'U':
      usage_exit(0) ;
      break ;
    default:
      printf("unknown option %s\n", argv[1]) ;
      exit(1) ;
      break ;
    }

  return(nargs) ;
}
Beispiel #7
0
int
main(int argc, char *argv[]) {
  char         **av ;
  int          ac, nargs ;
  MRI          *mri_orig, *mri_norm, *mri_bias ;
  int          msec, minutes, seconds ;
  struct timeb start ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option
          (argc, argv,
           "$Id: mri_apply_bias.c,v 1.5 2011/03/02 00:04:13 nicks Exp $",
           "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  TimerStart(&start) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (argc < 4)
    usage_exit(1) ;

  mri_orig = MRIread(argv[1]) ;
  if (mri_orig == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read %s",Progname, argv[1]) ;
  mri_bias = MRIread(argv[2]) ;
  if (mri_bias == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read %s",Progname, argv[2]) ;

  if (xform_fname)
  {
    TRANSFORM    *transform ;
    MRI          *mri ;

    transform = TransformRead(xform_fname) ;
    if (transform == NULL)
      ErrorExit(ERROR_NOFILE, "%s: could not load transform %s", Progname, xform_fname) ;
    mri = MRIcloneDifferentType(mri_orig, MRI_FLOAT) ;
    TransformApplyInverse(transform, mri_bias, mri) ;
    MRIfree(&mri_bias) ; mri_bias = mri ;
    
  }
  mri_norm = apply_bias(mri_orig, NULL, mri_bias);

  fprintf(stderr, "writing to %s...\n", argv[3]) ;
  MRIwrite(mri_norm, argv[3]) ;
  MRIfree(&mri_norm) ;
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  fprintf(stderr, "bias correction took %d minutes and %d seconds.\n",
          minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
Beispiel #8
0
/* ------------------------------------------------------------------ */
static int parse_commandline(int argc, char **argv) {
  int  nargc , nargsused;
  char **pargv, *option ;

  if (argc < 1) usage_exit();

  nargc   = argc;
  pargv = argv;
  while (nargc > 0) {

    option = pargv[0];
    if (debug) printf("%d %s\n",nargc,option);
    nargc -= 1;
    pargv += 1;

    nargsused = 0;

    if (!strcasecmp(option, "--help"))  print_help() ;

    else if (!strcasecmp(option, "--version")) print_version() ;

    else if (!strcasecmp(option, "--debug"))   debug = 1;

    else if (!strcasecmp(option, "--oldtxtstyle"))    oldtxtstyle = 1;
    else if (!strcasecmp(option, "--plaintxtstyle"))  plaintxtstyle = 1;
    else if (!strcasecmp(option, "--mskinvert"))  mskinvert = 1;
    else if (!strcmp(option, "--fixxfm"))   fixxfm = 1;
    else if (!strcmp(option, "--nofixxfm")) fixxfm = 0;

    /* -------- ROI output file ------ */
    else if (!strcmp(option, "--roiavgtxt")) {
      if (nargc < 1) argnerr(option,1);
      roitxtfile = pargv[0];
      nargsused = 1;
    } else if (!strcmp(option, "--roiavg")) {
      if (nargc < 1) argnerr(option,1);
      roifile = pargv[0];
      nargsused = 1;
    }

    /* -------- source volume inputs ------ */
    else if (!strcmp(option, "--srcvol")) {
      if (nargc < 1) argnerr(option,1);
      srcvolid = IDnameFromStem(pargv[0]);
      if(srcvolid == NULL) srcvolid = pargv[0];
      nargsused = 1;
    } else if (!strcmp(option, "--srcfmt")) {
      if (nargc < 1) argnerr(option,1);
      srcfmt = pargv[0];
      nargsused = 1;
    } else if (!strcmp(option, "--srcreg")) {
      if (nargc < 1) argnerr(option,1);
      srcregfile = pargv[0];
      nargsused = 1;
    } else if (!strcmp(option, "--srcoldreg")) {
      srcoldreg = 1;
    } else if (!strcmp(option, "--srcwarp")) {
      if (nargc < 1) argnerr(option,1);
      srcwarp = pargv[0];
      nargsused = 1;
    }

    /* -------- label inputs ------ */
    else if (!strcmp(option, "--labelfile") ||
             !strcmp(option, "--label")) {
      if (nargc < 1) argnerr(option,1);
      labelfile = pargv[0];
      nargsused = 1;
    } else if (!strcmp(option, "--labelreg")) {
      if (nargc < 1) argnerr(option,1);
      src2lblregfile = pargv[0];
      nargsused = 1;
    } else if (!strcmp(option, "--labeltal")) {
      labeltal = 1;
      fixxfm = 1;
      nargsused = 0;
    } else if (!strcmp(option, "--talxfm")) {
      if (nargc < 1) argnerr(option,1);
      talxfm = pargv[0];
      labeltal = 1;
      fixxfm = 1;
      nargsused = 1;
    } else if (!strcmp(option, "--labelfillthresh")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%f",&labelfillthresh);
      nargsused = 1;
    }

    /* -------- mask volume inputs ------ */
    else if (!strcmp(option, "--mskvol")) {
      if (nargc < 1) argnerr(option,1);
      mskvolid = IDnameFromStem(pargv[0]);
      if(mskvolid == NULL) mskvolid = pargv[0];
      nargsused = 1;
    } else if (!strcmp(option, "--mskfmt")) {
      if (nargc < 1) argnerr(option,1);
      mskfmt = pargv[0];
      nargsused = 1;
    } 
    else if (!strcmp(option, "--msktail")) {
      if (nargc < 1) argnerr(option,1);
      msktail = pargv[0];
      nargsused = 1;
      if (strncasecmp(msktail,"abs",3) &&
          strncasecmp(msktail,"pos",3) &&
          strncasecmp(msktail,"neg",3)) {
        fprintf(stderr,"ERROR: msk tail = %s, must be abs, pos, or neg\n",
                msktail);
        exit(1);
      }
    } else if (!strcmp(option, "--mskthresh")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%f",&mskthresh);
      nargsused = 1;
    } else if (!strcmp(option, "--mskframe")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%d",&mskframe);
      nargsused = 1;
    } else if (!strcmp(option, "--finalmskvol")) {
      if (nargc < 1) argnerr(option,1);
      finalmskvolid = pargv[0];
      nargsused = 1;
    } else if (!strcmp(option, "--srcmskvol")) {
      if (nargc < 1) argnerr(option,1);
      srcmskvolid = pargv[0];
      nargsused = 1;
    } else if (!strcmp(option, "--finalmskcrs")) {
      if (nargc < 1) argnerr(option,1);
      finalmskcrs = pargv[0];
      nargsused = 1;
    } else if (!strcmp(option, "--list")) {
      if (nargc < 1) argnerr(option,1);
      ListFile = pargv[0];
      nargsused = 1;
    } else {
      fprintf(stderr,"ERROR: Option %s unknown\n",option);
      if (singledash(option))
        fprintf(stderr,"       Did you really mean -%s ?\n",option);
      //printf("Match %d\n",strcmp(option, "--roiavgtxt"));
      exit(-1);
    }
    nargc -= nargsused;
    pargv += nargsused;
  }
  return(0);
}
Beispiel #9
0
int
main(int argc, char *argv[]) {
  char               **av, *in_fname, *out_fname, path[STRLEN], fname[STRLEN],
  hemi[STRLEN], *cp ;
  int                ac, nargs ;
  MRI_SURFACE        *mris ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mris_reverse.c,v 1.10 2011/03/02 00:04:33 nicks Exp $", "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (argc < 3)
    usage_exit() ;

  in_fname = argv[1] ;
  out_fname = argv[2] ;

  if (patch_flag) {
    FileNamePath(in_fname, path) ;
    FileNameOnly(in_fname, hemi) ;
    cp = strchr(hemi, '.') ;
    if (cp)
      *cp = 0 ;
    else
      ErrorExit(ERROR_BADPARM, "%s: could not scan hemisphere from %s\n",
                in_fname) ;
    sprintf(fname, "%s/%s.%s", path, hemi, ORIG_NAME) ;
    mris = MRISread(fname) ;
    if (!mris)
      ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                Progname, fname) ;
    if (MRISreadPatch(mris, in_fname) != NO_ERROR)
      ErrorExit(Gerror, "%s: could not read patch\n", Progname) ;
  } else {
    mris = MRISread(in_fname) ;
    if (!mris)
      ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                Progname, in_fname) ;
  }

  FileNamePath(out_fname, path) ;
  MRISreverse(mris, which, 1) ;
  if (Gdiag & DIAG_SHOW)
    fprintf(stderr, "writing reversed surface to %s\n", out_fname) ;
  mris->type = MRIS_TRIANGULAR_SURFACE ;
  if (patch_flag)
    MRISwritePatch(mris, out_fname) ;
  else
    MRISwrite(mris, out_fname) ;
  exit(0) ;
  return(0) ;  /* for ansi */
}
Beispiel #10
0
int main(int argc, char* argv[])
{
    int sock, s_sock, client_fd;
    socklen_t client_size;
    struct sockaddr_in addr, client_addr;
    struct timeval tv;
    static pool pool;
    sigset_t mask;

    if (argc != 9)  usage_exit();

    // parse arguments
    STATE.port = (int)strtol(argv[1], (char**)NULL, 10);
    STATE.s_port = (int)strtol(argv[2], (char**)NULL, 10);
    strcpy(STATE.log_path, argv[3]);
    strcpy(STATE.lck_path, argv[4]);
    strcpy(STATE.www_path, argv[5]);
    strcpy(STATE.cgi_path, argv[6]);
    strcpy(STATE.key_path, argv[7]);
    strcpy(STATE.ctf_path, argv[8]);

    if (STATE.www_path[strlen(STATE.www_path)-1] == '/')
         STATE.www_path[strlen(STATE.www_path)-1] = '\0';

    daemonize();
    STATE.log = log_open(STATE.log_path);
    
    Log("Start Liso server. Server is running in background. \n");

    /* all networked programs must create a socket
     * PF_INET - IPv4 Internet protocols
     * SOCK_STREAM - sequenced, reliable, two-way, connection-based byte stream
     * 0 (protocol) - use default protocol
     */
    // create sock for HTTP connection
    if ((sock = socket(PF_INET, SOCK_STREAM, 0)) == -1)
    {
        Log("Error: failed creating socket for HTTP connection.\n");
        fclose(STATE.log);
        return EXIT_FAILURE;
    }

    STATE.sock = sock;
    Log("Create socket success: sock =  %d \n", sock);

    addr.sin_family = AF_INET;
    addr.sin_port = htons(STATE.port);
    addr.sin_addr.s_addr = INADDR_ANY;
    /* servers bind sockets to ports---notify the OS they accept connections */
    if (bind(sock, (struct sockaddr *) &addr, sizeof(addr)))
    {
        Log("Error: failed binding socket.\n");
        clean();
        return EXIT_FAILURE;
    }
    Log("Bind success! \n");

    if (listen(sock, MAX_CONN))
    {
        Log("Error: listening on socket.\n");
        clean();
        return EXIT_FAILURE;
    }
    Log("Listen success! >>>>>>>>>>>>>>>>>>>> \n");

    // create sock for HTTPS connection
    Log("Create sock for HTTPS connection \n");
    if ((s_sock = socket(PF_INET, SOCK_STREAM, 0)) == -1)
    {
        Log("Error: failed creating socket for HTTPS connection.\n");
        close(sock);
        fclose(STATE.log);
        return EXIT_FAILURE;
    }

    STATE.s_sock = s_sock;
    Log("Create HTTPS socket success: sock =  %d \n", s_sock);

    addr.sin_family = AF_INET;
    addr.sin_port = htons(STATE.s_port);
    addr.sin_addr.s_addr = INADDR_ANY;
    /* servers bind sockets to ports---notify the OS they accept connections */
    if (bind(s_sock, (struct sockaddr *) &addr, sizeof(addr)))
    {
        Log("Error: failed binding socket.\n");
        close(sock); close(s_sock); fclose(STATE.log);
        return EXIT_FAILURE;
    }
    Log("Bind success! \n");

    if (listen(s_sock, MAX_CONN))
    {
        Log("Error: listening on socket.\n");
        close(sock); close(s_sock); fclose(STATE.log);
        return EXIT_FAILURE;
    }
    Log("Listen success! >>>>>>>>>>>>>>>>>>>> \n");
    init_pool(&pool);

    // the main loop to wait for connections and serve requests
    while (KEEPON)
    {
       tv.tv_sec = 1; // timeout = 1 sec
       tv.tv_usec = 0;
       pool.ready_set = pool.read_set;

       sigemptyset(&mask);
       sigaddset(&mask, SIGHUP);
       sigprocmask(SIG_BLOCK, &mask, NULL);
       pool.nready = select(pool.maxfd+1, &pool.ready_set, NULL, NULL, &tv);
       sigprocmask(SIG_UNBLOCK, &mask, NULL);

       if (pool.nready < 0)
       {
           if (errno == EINTR)
           {
               Log("Shut down Server >>>>>>>>>>>>>>>>>>>> \n");
               break;
           }
          
           Log("Error: select error \n");
           continue;
       }

       // if there is new connection, accept and add the new client to pool
       if (FD_ISSET(sock, &pool.ready_set))
       {
           client_size = sizeof(client_addr);
           client_fd = accept(sock, (struct sockaddr *) &client_addr,
                              &client_size);

           if (client_fd < 0) ///TODO
           {
               Log("Error: accepting connection. \n");
               continue;
           }

           Log("accept client: client_fd=%d \n", client_fd);

           if (STATE.is_full)
           {
               pool.nready--;
               serve_error(client_fd, "503", "Service Unavailable",
                    "Server is too busy right now. Please try again later.", 1);
               close(client_fd);
           }
           else
              add_client(client_fd, &pool);
       }

       // process each ready connected descriptor
       check_clients(&pool);
    }

    lisod_shutdown();

    return EXIT_SUCCESS; // to make compiler happy
}
Beispiel #11
0
/*---------------------------------------------------------*/
int main(int argc, char **argv) {
  int n,err, f, nhits, r,c,s;
  float ipr, bpr, intensity;
  float *framepower=NULL, val;
  LTA *lta;
  int nargs;
  //int endian,roitype;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_vol2roi.c,v 1.32 2011/03/02 00:04:25 nicks Exp $", "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Progname = argv[0] ;
  argc --;
  argv++;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  if (argc == 0) usage_exit();

  parse_commandline(argc, argv);
  check_options();

  printf("--------------------------------------------------------\n");
  getcwd(tmpstr,2000);
  printf("%s\n",tmpstr);
  printf("%s\n",Progname);
  for (n=0;n<argc;n++) printf(" %s",argv[n]);
  printf("\n");
  printf("version %s\n",vcid);
  printf("--------------------------------------------------------\n");

  dump_options(stdout);

  /* --------- load in the (possibly 4-D) source volume --------------*/
  printf("Loading volume %s ...",srcvolid);
  mSrcVol = MRIread(srcvolid);
  if(mSrcVol == NULL) exit(1);
  printf("done\n");

  /* Dsrc: read the source registration file */
  if (srcregfile != NULL) {
    err = regio_read_register(srcregfile, &srcsubject, &ipr, &bpr,
                              &intensity, &Dsrc, &float2int_src);
    if (err) exit(1);
    printf("srcreg Dsrc -------------\n");
    MatrixPrint(stdout,Dsrc);
    printf("----------------------------------\n");
  } else Dsrc = NULL;

  /* Wsrc: Get the source warping Transform */
  Wsrc = NULL;
  /* Fsrc: Get the source FOV registration matrix */
  Fsrc = NULL;
  /* Qsrc: Compute the quantization matrix for src volume */
  Qsrc = FOVQuantMatrix(mSrcVol->width,  mSrcVol->height,  mSrcVol->depth,
                        mSrcVol->xsize,  mSrcVol->ysize,  mSrcVol->zsize);
  printf("ras2vox src (tkreg) Qsrc -------------\n");
  MatrixPrint(stdout,Qsrc);
  printf("----------------------------------\n");

  /* ----------- load in the label ----------------- */
  if (labelfile != NULL) {
    Label = LabelReadFile(labelfile);
    if (Label == NULL) exit(1);
    /* load in the source-to-label registration */
    if (src2lblregfile != NULL) {
      //err = regio_read_xfm(src2lblregfile, &Msrc2lbl);
      //if(err) exit(1);
      lta = LTAread(src2lblregfile);
      if (lta->type == LINEAR_VOX_TO_VOX) {
        printf("INFO: converting LTA to RAS\n");
        LTAvoxelTransformToCoronalRasTransform(lta);
      }
      Msrc2lbl = MatrixCopy(lta->xforms[0].m_L,NULL);
    } else if (labeltal) {
      /* Load the talairach.xfm and make it approp for reg.dat*/
      Msrc2lbl = DevolveXFM(srcsubject,NULL,talxfm);
      if (Msrc2lbl==NULL) exit(1);
    } else Msrc2lbl = NULL;
    if (Msrc2lbl != NULL) {
      printf("-- Source2Label %s ---- \n",src2lblregfile);
      MatrixPrint(stdout,Msrc2lbl);
      printf("-------------------------------\n");
    }
  } else {
    Label = NULL;
    Msrc2lbl = NULL;
  }

  /* -------------- load mask volume stuff -----------------------------*/
  if (mskvolid != NULL) {
    /* load the mask volume (single frame) */
    printf("Reading %s\n",mskvolid);
    mMskVol = MRIread(mskvolid);
    if(mMskVol == NULL) exit(1);
    if(mskframe > 0){
      mritmp = fMRIframe(mMskVol, mskframe, NULL);
      if(mritmp == NULL) exit(1);
      MRIfree(&mMskVol);
      mMskVol = mritmp;
    }

    /* Qmsk: Compute the quantization matrix for msk volume */
    /* crsFOV = Qmsk*xyzFOV */
    Qmsk = FOVQuantMatrix(mMskVol->width, mMskVol->height, mMskVol->depth,
                          mMskVol->xsize, mMskVol->ysize,  mMskVol->zsize);

    /* get the mask2source registration information */
    /* xyzSrc = Mmsk2src * xyzMsk */
    if (msk2srcregfile != NULL) {
      err = regio_read_mincxfm(msk2srcregfile, &Mmsk2src, NULL);
      if (err) exit(1);
    } else Mmsk2src = NULL;

    /* convert from Mask Anatomical to Src FOV */
    if (!msksamesrc) {
      mSrcMskVol = vol2vol_linear(mMskVol, Qmsk, NULL, NULL, Dmsk,
                                  Qsrc, Fsrc, Wsrc, Dsrc,
                                  mSrcVol->height, mSrcVol->width, mSrcVol->depth,
                                  Mmsk2src, INTERP_NEAREST, float2int_msk);
      if (mSrcMskVol == NULL) exit(1);
    } else mSrcMskVol = mMskVol;

    /* binarize the mask volume */
    mri_binarize(mSrcMskVol, mskthresh, msktail, mskinvert,
                 mSrcMskVol, &nmskhits);
  } else {
    mSrcMskVol = NULL;
    nmskhits = 0;
  }
  /*-------------- Done loading mask stuff -------------------------*/

  /* If this is a statistical volume, raise each frame to it's appropriate
     power (eg, stddev needs to be squared)*/
  if (is_sxa_volume(srcvolid)) {
    printf("INFO: Source volume detected as selxavg format\n");
    sxa = ld_sxadat_from_stem(srcvolid);
    if (sxa == NULL) exit(1);
    framepower = sxa_framepower(sxa,&f);
    if (f != mSrcVol->nframes) {
      fprintf(stderr," number of frames is incorrect (%d,%d)\n",
              f,mSrcVol->nframes);
      exit(1);
    }
    printf("INFO: Adjusting Frame Power\n");
    fflush(stdout);
    mri_framepower(mSrcVol,framepower);
  }

  /*--------- Prepare the final mask ------------------------*/
  if (Label != NULL) {
    mFinalMskVol = label2mask_linear(mSrcVol, Qsrc, Fsrc, Wsrc,
                                     Dsrc, mSrcMskVol,
                                     Msrc2lbl, Label, labelfillthresh, float2int_src,
                                     &nlabelhits, &nfinalhits);

    if (mFinalMskVol == NULL) exit(1);
  } else {
    mFinalMskVol = mSrcMskVol;
    nfinalhits = nmskhits;
  }

  if (!oldtxtstyle) {
    /* count the number of functional voxels = 1 in the mask */
    nfinalhits = 0;
    for (r=0;r<mFinalMskVol->height;r++) {
      for (c=0;c<mFinalMskVol->width;c++) {
        for (s=0;s<mFinalMskVol->depth;s++) {
          val = MRIgetVoxVal(mFinalMskVol,c,r,s,0);
          if (val > 0.5) nfinalhits ++;
        }
      }
    }
    if (Label != NULL)
      nlabelhits = CountLabelHits(mSrcVol, Qsrc, Fsrc,
                                  Wsrc, Dsrc, Msrc2lbl,
                                  Label, labelfillthresh,float2int_src);
    else  nlabelhits = 0;
  }

  /*-------------------------------------------------------*/
  /*--------- Map the volume into the ROI -----------------*/
  printf("Averging over ROI\n");
  fflush(stdout);
  mROI = vol2maskavg(mSrcVol, mFinalMskVol,&nhits);
  if (mROI == NULL) exit(1);
  printf("Done averging over ROI (nhits = %d)\n",nhits);
  /*-------------------------------------------------------*/

  /* ------- Save the final mask ------------------ */
  if (finalmskvolid != 0) {
    //mri_save_as_bvolume(mFinalMskVol,finalmskvolid,endian,BF_FLOAT);
    //MRIwriteAnyFormat(mFinalMskVol,finalmskvolid,"bfloat",-1,NULL);
    sprintf(tmpstr,"%s.%s",finalmskvolid,outext);
    MRIwrite(mFinalMskVol,tmpstr);
  }

  /* ------- Save CRS of the the final mask ------------------ */
  if (finalmskcrs != NULL) {
    fp = fopen(finalmskcrs,"w");
    if (fp==NULL) {
      fprintf(stderr,"ERROR: cannot open %s\n",finalmskcrs);
      exit(1);
    }
    for (r=0;r<mFinalMskVol->height;r++) {
      for (c=0;c<mFinalMskVol->width;c++) {
        for (s=0;s<mFinalMskVol->depth;s++) {
          val = MRIgetVoxVal(mFinalMskVol,c,r,s,0);
          if (val > 0.5) {
            fprintf(fp,"%d %d %d\n",c,r,s);
          }
        }
      }
    }
    fclose(fp);
  }

  /* If this is a statistical volume, lower each frame to it's appropriate
     power (eg, variance needs to be sqrt'ed) */
  if (is_sxa_volume(srcvolid)) {
    printf("INFO: Readjusting Frame Power\n");
    fflush(stdout);
    for (f=0; f < mROI->nframes; f++) framepower[f] = 1.0/framepower[f];
    mri_framepower(mROI,framepower);
  }

  /* save the target volume in an appropriate format */
  if(roifile != NULL){
    sprintf(tmpstr,"%s.%s",roifile,outext);
    MRIwrite(mROI,tmpstr);
    /* for a stat volume, save the .dat file */
    if (is_sxa_volume(srcvolid)) {
      sxa->nrows = 1;
      sxa->ncols = 1;
      sv_sxadat_by_stem(sxa,roifile);
    }
  }

  /* save as text */
  if(roitxtfile != NULL) {
    fp = fopen(roitxtfile,"w");
    if (fp==NULL) {
      fprintf(stderr,"ERROR: cannot open %s\n",roitxtfile);
      exit(1);
    }
    if (oldtxtstyle) {
      printf("INFO: saving as old style txt\n");
      fprintf(fp,"%d \n",nmskhits);
    }
    if (! plaintxtstyle ) {
      fprintf(fp,"%d \n",nlabelhits);
      fprintf(fp,"%d \n",nfinalhits);
    }
    for (f=0; f < mROI->nframes; f++)
      fprintf(fp,"%f\n",MRIgetVoxVal(mROI,0,0,0,f));
    fclose(fp);
  }

  /* ------- Mask the source and save it  ------------------ */
  if (srcmskvolid != 0) {
    for (r=0;r<mFinalMskVol->height;r++) {
      for (c=0;c<mFinalMskVol->width;c++) {
        for (s=0;s<mFinalMskVol->depth;s++) {
          val = MRIgetVoxVal(mFinalMskVol,c,r,s,0);
          if (val < 0.5) {
            for (f=0; f < mROI->nframes; f++)
              MRIFseq_vox(mSrcVol,c,r,s,f) = 0.0;
          }
        }
      }
    }
    MRIwrite(mSrcVol,srcmskvolid);
  }

  /* ------- Save as a text list  ------------------ */
  if (ListFile != 0) {
    fp = fopen(ListFile,"w");
    for (c=0;c<mFinalMskVol->width;c++) {
      for (r=0;r<mFinalMskVol->height;r++) {
        for (s=0;s<mFinalMskVol->depth;s++) {
          val = MRIFseq_vox(mFinalMskVol,c,r,s,0);
          if(val < 0.5) continue;
	  fprintf(fp,"%3d %3d %3d ",c,r,s);
	  for (f=0; f < mROI->nframes; f++){
	    val = MRIgetVoxVal(mSrcVol,c,r,s,f);
	    fprintf(fp,"%f ",val);
          }
	  fprintf(fp,"\n");
        }
      }
    }
    fclose(fp);
  }

  return(0);
}
Beispiel #12
0
int
main (int argc, char * argv [])
{	const char	*progname, *infilename, *outfilename ;
	SNDFILE		*infile = NULL, *outfile = NULL ;
	SF_INFO		sfinfo ;
	int			k, outfilemajor, outfileminor = 0, infileminor ;
	int			override_sample_rate = 0 ; /* assume no sample rate override. */

	progname = program_name (argv [0]) ;

	if (argc < 3 || argc > 5)
	{	usage_exit (progname) ;
		return 1 ;
		} ;

	infilename = argv [argc-2] ;
	outfilename = argv [argc-1] ;

	if (strcmp (infilename, outfilename) == 0)
	{	printf ("Error : Input and output filenames are the same.\n\n") ;
		usage_exit (progname) ;
		return 1 ;
		} ;

	if (strlen (infilename) > 1 && infilename [0] == '-')
	{	printf ("Error : Input filename (%s) looks like an option.\n\n", infilename) ;
		usage_exit (progname) ;
		return 1 ;
		} ;

	if (outfilename [0] == '-')
	{	printf ("Error : Output filename (%s) looks like an option.\n\n", outfilename) ;
		usage_exit (progname) ;
		return 1 ;
		} ;

	for (k = 1 ; k < argc - 2 ; k++)
	{	if (! strcmp (argv [k], "-pcms8"))
		{	outfileminor = SF_FORMAT_PCM_S8 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-pcmu8"))
		{	outfileminor = SF_FORMAT_PCM_U8 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-pcm16"))
		{	outfileminor = SF_FORMAT_PCM_16 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-pcm24"))
		{	outfileminor = SF_FORMAT_PCM_24 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-pcm32"))
		{	outfileminor = SF_FORMAT_PCM_32 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-float32"))
		{	outfileminor = SF_FORMAT_FLOAT ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-ulaw"))
		{	outfileminor = SF_FORMAT_ULAW ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-alaw"))
		{	outfileminor = SF_FORMAT_ALAW ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-ima-adpcm"))
		{	outfileminor = SF_FORMAT_IMA_ADPCM ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-ms-adpcm"))
		{	outfileminor = SF_FORMAT_MS_ADPCM ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-gsm610"))
		{	outfileminor = SF_FORMAT_GSM610 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-dwvw12"))
		{	outfileminor = SF_FORMAT_DWVW_12 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-dwvw16"))
		{	outfileminor = SF_FORMAT_DWVW_16 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-dwvw24"))
		{	outfileminor = SF_FORMAT_DWVW_24 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-vorbis"))
		{	outfileminor = SF_FORMAT_VORBIS ;
			continue ;
			} ;

		if (strstr (argv [k], "-override-sample-rate=") == argv [k])
		{	const char *ptr ;

			ptr = argv [k] + strlen ("-override-sample-rate=") ;
			override_sample_rate = atoi (ptr) ;
			continue ;
			} ;

		printf ("Error : Not able to decode argunment '%s'.\n", argv [k]) ;
		exit (1) ;
		} ;

	memset (&sfinfo, 0, sizeof (sfinfo)) ;

	if ((infile = sf_open (infilename, SFM_READ, &sfinfo)) == NULL)
	{	printf ("Not able to open input file %s.\n", infilename) ;
		puts (sf_strerror (NULL)) ;
		return 1 ;
		} ;

	/* Update sample rate if forced to something else. */
	if (override_sample_rate)
		sfinfo.samplerate = override_sample_rate ;

	infileminor = sfinfo.format & SF_FORMAT_SUBMASK ;

	if ((sfinfo.format = sfe_file_type_of_ext (outfilename, sfinfo.format)) == 0)
	{	printf ("Error : Not able to determine output file type for %s.\n", outfilename) ;
		return 1 ;
		} ;

	outfilemajor = sfinfo.format & (SF_FORMAT_TYPEMASK | SF_FORMAT_ENDMASK) ;

	if (outfileminor == 0)
		outfileminor = sfinfo.format & SF_FORMAT_SUBMASK ;

	if (outfileminor != 0)
		sfinfo.format = outfilemajor | outfileminor ;
	else
		sfinfo.format = outfilemajor | (sfinfo.format & SF_FORMAT_SUBMASK) ;

	if ((sfinfo.format & SF_FORMAT_TYPEMASK) == SF_FORMAT_XI)
		switch (sfinfo.format & SF_FORMAT_SUBMASK)
		{	case SF_FORMAT_PCM_16 :
					sfinfo.format = outfilemajor | SF_FORMAT_DPCM_16 ;
					break ;

			case SF_FORMAT_PCM_S8 :
			case SF_FORMAT_PCM_U8 :
					sfinfo.format = outfilemajor | SF_FORMAT_DPCM_8 ;
					break ;
			} ;

	if (sf_format_check (&sfinfo) == 0)
	{	printf ("Error : output file format is invalid (0x%08X).\n", sfinfo.format) ;
		return 1 ;
		} ;

	/* Open the output file. */
	if ((outfile = sf_open (outfilename, SFM_WRITE, &sfinfo)) == NULL)
	{	printf ("Not able to open output file %s : %s\n", outfilename, sf_strerror (NULL)) ;
		return 1 ;
		} ;

	/* Copy the metadata */
	copy_metadata (outfile, infile, sfinfo.channels) ;

	if ((outfileminor == SF_FORMAT_DOUBLE) || (outfileminor == SF_FORMAT_FLOAT)
			|| (infileminor == SF_FORMAT_DOUBLE) || (infileminor == SF_FORMAT_FLOAT)
			|| (infileminor == SF_FORMAT_VORBIS) || (outfileminor == SF_FORMAT_VORBIS))
		sfe_copy_data_fp (outfile, infile, sfinfo.channels) ;
	else
		sfe_copy_data_int (outfile, infile, sfinfo.channels) ;

	sf_close (infile) ;
	sf_close (outfile) ;

	return 0 ;
} /* main */
Beispiel #13
0
int
main (int argc, char * argv [])
{
	PARAMS params = { 1.0, -1, -1, 0, 0, 0, NULL } ;
	const char * filename ;
	int k ;

	if (argc < 4)
		usage_exit (argv [0]) ;

	for (k = 1 ; k < argc - 3 ; k++)
	{	if (strcmp (argv [k], "-from") == 0)
		{	k++ ;
			params.start_freq = parse_double_or_die (argv [k], "from frequency") ;
			continue ;
			} ;
		if (strcmp (argv [k], "-to") == 0)
		{	k++ ;
			params.end_freq = parse_double_or_die (argv [k], "to frequency") ;
			continue ;
			} ;
		if (strcmp (argv [k], "-amp") == 0)
		{	k++ ;
			params.amplitude = strtod (argv [k], NULL) ;
			continue ;
			} ;

		if (argv [k][0] == '-')
		{	params.sweep_func = parse_sweep_type (argv [k]) ;
			continue ;
			} ;

		printf ("\nUnknow option '%s'.\n\n", argv [k]) ;
		exit (1) ;
		} ;

	params.samplerate = parse_int_or_die (argv [argc - 3], "sample rate") ;
	params.seconds = parse_double_or_die (argv [argc - 2], "seconds") ;
	filename = argv [argc - 1] ;

	check_int_range ("sample rate", params.samplerate, 1000, 200 * 1000) ;
	check_double_range ("seconds", params.seconds, 0.1, 100.0) ;

	if (params.sweep_func == NULL)
		params.sweep_func = parse_sweep_type ("-log") ;
	if (params.start_freq <= 0.0)
		params.start_freq = 100.0 ;
	if (params.end_freq <= 0.0)
		params.end_freq = params.samplerate / 2.0 - 100.0 ;

	if (params.end_freq <= params.start_freq)
	{	printf ("\nError : end frequency %g < start frequency %g.\n\n", params.end_freq, params.start_freq) ;
		exit (1) ;
		} ;

	params.format = guess_major_format (filename) | SF_FORMAT_FLOAT ;

	generate_file (filename, &params) ;

	return 0 ;
} /* main */
Beispiel #14
0
/* --------------------------------------------- */
static int parse_commandline(int argc, char **argv) {
  int  nargc , nargsused;
  char **pargv, *option ;

  if (argc < 1) usage_exit();

  nargc = argc;
  pargv = argv;
  while (nargc > 0) {

    option = pargv[0];
    if (debug) printf("%d %s\n",nargc,option);
    nargc -= 1;
    pargv += 1;

    nargsused = 0;

    if (!strcasecmp(option, "--help"))  print_help() ;
    else if (!strcasecmp(option, "--version")) print_version() ;
    else if (!strcasecmp(option, "--debug"))   debug = 1;
    else if (!strcasecmp(option, "--checkopts"))   checkoptsonly = 1;
    else if (!strcasecmp(option, "--nocheckopts")) checkoptsonly = 0;
    else if (!strcasecmp(option, "--no-check-xyz")) CheckXYZ = 0;
    else if (!strcasecmp(option, "--no-check-nxyz")) CheckNXYZ = 0;
    else if (!strcasecmp(option, "--ndist")) {
      ComputeNormalDist = 1;
      out_fname = pargv[0];
      nargsused = 1;
    } else if (!strcasecmp(option, "--s1")) {
      if (nargc < 1) CMDargNErr(option,1);
      subject1 = pargv[0];
      nargsused = 1;
    } else if (!strcasecmp(option, "--s2")) {
      if (nargc < 1) CMDargNErr(option,1);
      subject2 = pargv[0];
      nargsused = 1;
    } else if (!strcasecmp(option, "--sd1")) {
      if (nargc < 1) CMDargNErr(option,1);
      SUBJECTS_DIR1 = pargv[0];
      nargsused = 1;
    } else if (!strcasecmp(option, "--sd2")) {
      if (nargc < 1) CMDargNErr(option,1);
      SUBJECTS_DIR2 = pargv[0];
      nargsused = 1;
    } else if (!strcasecmp(option, "--hemi")) {
      if (nargc < 1) CMDargNErr(option,1);
      hemi = pargv[0];
      nargsused = 1;
    } else if (!strcasecmp(option, "--surf")) {
      if (nargc < 1) CMDargNErr(option,1);
      surfname = pargv[0];
      CheckSurf=1;
      nargsused = 1;
    } else if (!strcasecmp(option, "--curv")) {
      if (nargc < 1) CMDargNErr(option,1);
      curvname = pargv[0];
      CheckCurv=1;
      nargsused = 1;
    } else if (!strcasecmp(option, "--aparc")) {
      if (nargc < 1) CMDargNErr(option,1);
      aparcname = pargv[0];
      CheckAParc=1;
      nargsused = 1;
    } else if (!strcasecmp(option, "--aparc2")) {
      if (nargc < 1) CMDargNErr(option,1);
      aparc2name = pargv[0];
      CheckAParc=1;
      nargsused = 1;
    } else if (!strcasecmp(option, "--thresh")) {
      if (nargc < 1) CMDargNErr(option,1);
      sscanf(pargv[0],"%lf",&thresh);
      nargsused = 1;
    } else if (!strcasecmp(option, "--maxerrs")) {
      if (nargc < 1) CMDargNErr(option,1);
      sscanf(pargv[0],"%d",&MAX_NUM_ERRORS);
      nargsused = 1;
    } else {
      if (surf1path == NULL) {
        surf1path = option;
        CheckSurf=1;
      } else if (surf2path == NULL) surf2path = option;
      else {
        fprintf(stderr,"ERROR: Option %s unknown\n",option);
        if (CMDsingleDash(option))
          fprintf(stderr,"       Did you really mean -%s ?\n",option);
        exit(-1);
      }
    }
    nargc -= nargsused;
    pargv += nargsused;
  }
  return(0);
}
Beispiel #15
0
int main_loop(int argc, const char **argv_) {
  vpx_codec_ctx_t       decoder;
  char                  *fn = NULL;
  int                    i;
  uint8_t               *buf = NULL;
  size_t                 bytes_in_buffer = 0, buffer_size = 0;
  FILE                  *infile;
  int                    frame_in = 0, frame_out = 0, flipuv = 0, noblit = 0;
  int                    do_md5 = 0, progress = 0;
  int                    stop_after = 0, postproc = 0, summary = 0, quiet = 1;
  int                    arg_skip = 0;
  int                    ec_enabled = 0;
  const VpxInterface *interface = NULL;
  const VpxInterface *fourcc_interface = NULL;
  unsigned long          dx_time = 0;
  struct arg               arg;
  char                   **argv, **argi, **argj;

  int                     single_file;
  int                     use_y4m = 1;
  vpx_codec_dec_cfg_t     cfg = {0};
#if CONFIG_VP8_DECODER
  vp8_postproc_cfg_t      vp8_pp_cfg = {0};
  int                     vp8_dbg_color_ref_frame = 0;
  int                     vp8_dbg_color_mb_modes = 0;
  int                     vp8_dbg_color_b_modes = 0;
  int                     vp8_dbg_display_mv = 0;
#endif
  int                     frames_corrupted = 0;
  int                     dec_flags = 0;
  int                     do_scale = 0;
  vpx_image_t             *scaled_img = NULL;
  int                     frame_avail, got_data;
  int                     num_external_frame_buffers = 0;
  struct ExternalFrameBufferList ext_fb_list = {0};

  const char *outfile_pattern = NULL;
  char outfile_name[PATH_MAX] = {0};
  FILE *outfile = NULL;

  MD5Context md5_ctx;
  unsigned char md5_digest[16];

  struct VpxDecInputContext input = {0};
  struct VpxInputContext vpx_input_ctx = {0};
  struct WebmInputContext webm_ctx = {0};
  input.vpx_input_ctx = &vpx_input_ctx;
  input.webm_ctx = &webm_ctx;

  /* Parse command line */
  exec_name = argv_[0];
  argv = argv_dup(argc - 1, argv_ + 1);

  for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
    memset(&arg, 0, sizeof(arg));
    arg.argv_step = 1;

    if (arg_match(&arg, &codecarg, argi)) {
      interface = get_vpx_decoder_by_name(arg.val);
      if (!interface)
        die("Error: Unrecognized argument (%s) to --codec\n", arg.val);
    } else if (arg_match(&arg, &looparg, argi)) {
      // no-op
    } else if (arg_match(&arg, &outputfile, argi))
      outfile_pattern = arg.val;
    else if (arg_match(&arg, &use_yv12, argi)) {
      use_y4m = 0;
      flipuv = 1;
    } else if (arg_match(&arg, &use_i420, argi)) {
      use_y4m = 0;
      flipuv = 0;
    } else if (arg_match(&arg, &flipuvarg, argi))
      flipuv = 1;
    else if (arg_match(&arg, &noblitarg, argi))
      noblit = 1;
    else if (arg_match(&arg, &progressarg, argi))
      progress = 1;
    else if (arg_match(&arg, &limitarg, argi))
      stop_after = arg_parse_uint(&arg);
    else if (arg_match(&arg, &skiparg, argi))
      arg_skip = arg_parse_uint(&arg);
    else if (arg_match(&arg, &postprocarg, argi))
      postproc = 1;
    else if (arg_match(&arg, &md5arg, argi))
      do_md5 = 1;
    else if (arg_match(&arg, &summaryarg, argi))
      summary = 1;
    else if (arg_match(&arg, &threadsarg, argi))
      cfg.threads = arg_parse_uint(&arg);
    else if (arg_match(&arg, &verbosearg, argi))
      quiet = 0;
    else if (arg_match(&arg, &scalearg, argi))
      do_scale = 1;
    else if (arg_match(&arg, &fb_arg, argi))
      num_external_frame_buffers = arg_parse_uint(&arg);

#if CONFIG_VP8_DECODER
    else if (arg_match(&arg, &addnoise_level, argi)) {
      postproc = 1;
      vp8_pp_cfg.post_proc_flag |= VP8_ADDNOISE;
      vp8_pp_cfg.noise_level = arg_parse_uint(&arg);
    } else if (arg_match(&arg, &demacroblock_level, argi)) {
      postproc = 1;
      vp8_pp_cfg.post_proc_flag |= VP8_DEMACROBLOCK;
      vp8_pp_cfg.deblocking_level = arg_parse_uint(&arg);
    } else if (arg_match(&arg, &deblock, argi)) {
      postproc = 1;
      vp8_pp_cfg.post_proc_flag |= VP8_DEBLOCK;
    } else if (arg_match(&arg, &mfqe, argi)) {
      postproc = 1;
      vp8_pp_cfg.post_proc_flag |= VP8_MFQE;
    } else if (arg_match(&arg, &pp_debug_info, argi)) {
      unsigned int level = arg_parse_uint(&arg);

      postproc = 1;
      vp8_pp_cfg.post_proc_flag &= ~0x7;

      if (level)
        vp8_pp_cfg.post_proc_flag |= level;
    } else if (arg_match(&arg, &pp_disp_ref_frame, argi)) {
      unsigned int flags = arg_parse_int(&arg);
      if (flags) {
        postproc = 1;
        vp8_dbg_color_ref_frame = flags;
      }
    } else if (arg_match(&arg, &pp_disp_mb_modes, argi)) {
      unsigned int flags = arg_parse_int(&arg);
      if (flags) {
        postproc = 1;
        vp8_dbg_color_mb_modes = flags;
      }
    } else if (arg_match(&arg, &pp_disp_b_modes, argi)) {
      unsigned int flags = arg_parse_int(&arg);
      if (flags) {
        postproc = 1;
        vp8_dbg_color_b_modes = flags;
      }
    } else if (arg_match(&arg, &pp_disp_mvs, argi)) {
      unsigned int flags = arg_parse_int(&arg);
      if (flags) {
        postproc = 1;
        vp8_dbg_display_mv = flags;
      }
    } else if (arg_match(&arg, &error_concealment, argi)) {
      ec_enabled = 1;
    }

#endif
    else
      argj++;
  }

  /* Check for unrecognized options */
  for (argi = argv; *argi; argi++)
    if (argi[0][0] == '-' && strlen(argi[0]) > 1)
      die("Error: Unrecognized option %s\n", *argi);

  /* Handle non-option arguments */
  fn = argv[0];

  if (!fn)
    usage_exit();

  /* Open file */
  infile = strcmp(fn, "-") ? fopen(fn, "rb") : set_binary_mode(stdin);

  if (!infile) {
    fprintf(stderr, "Failed to open file '%s'", strcmp(fn, "-") ? fn : "stdin");
    return EXIT_FAILURE;
  }
#if CONFIG_OS_SUPPORT
  /* Make sure we don't dump to the terminal, unless forced to with -o - */
  if (!outfile_pattern && isatty(fileno(stdout)) && !do_md5 && !noblit) {
    fprintf(stderr,
            "Not dumping raw video to your terminal. Use '-o -' to "
            "override.\n");
    return EXIT_FAILURE;
  }
#endif
  input.vpx_input_ctx->file = infile;
  if (file_is_ivf(input.vpx_input_ctx))
    input.vpx_input_ctx->file_type = FILE_TYPE_IVF;
  else if (file_is_webm(input.webm_ctx, input.vpx_input_ctx))
    input.vpx_input_ctx->file_type = FILE_TYPE_WEBM;
  else if (file_is_raw(input.vpx_input_ctx))
    input.vpx_input_ctx->file_type = FILE_TYPE_RAW;
  else {
    fprintf(stderr, "Unrecognized input file type.\n");
    return EXIT_FAILURE;
  }

  outfile_pattern = outfile_pattern ? outfile_pattern : "-";
  single_file = is_single_file(outfile_pattern);

  if (!noblit && single_file) {
    generate_filename(outfile_pattern, outfile_name, PATH_MAX,
                      vpx_input_ctx.width, vpx_input_ctx.height, 0);
    if (do_md5)
      MD5Init(&md5_ctx);
    else
      outfile = open_outfile(outfile_name);
  }

  if (use_y4m && !noblit) {
    if (!single_file) {
      fprintf(stderr, "YUV4MPEG2 not supported with output patterns,"
              " try --i420 or --yv12.\n");
      return EXIT_FAILURE;
    }

    if (vpx_input_ctx.file_type == FILE_TYPE_WEBM) {
      if (webm_guess_framerate(input.webm_ctx, input.vpx_input_ctx)) {
        fprintf(stderr, "Failed to guess framerate -- error parsing "
                "webm file?\n");
        return EXIT_FAILURE;
      }
    }
  }

  fourcc_interface = get_vpx_decoder_by_fourcc(vpx_input_ctx.fourcc);
  if (interface && fourcc_interface && interface != fourcc_interface)
    warn("Header indicates codec: %s\n", fourcc_interface->name);
  else
    interface = fourcc_interface;

  if (!interface)
    interface = get_vpx_decoder_by_index(0);

  dec_flags = (postproc ? VPX_CODEC_USE_POSTPROC : 0) |
              (ec_enabled ? VPX_CODEC_USE_ERROR_CONCEALMENT : 0);
  if (vpx_codec_dec_init(&decoder, interface->interface(), &cfg, dec_flags)) {
    fprintf(stderr, "Failed to initialize decoder: %s\n",
            vpx_codec_error(&decoder));
    return EXIT_FAILURE;
  }

  if (!quiet)
    fprintf(stderr, "%s\n", decoder.name);

#if CONFIG_VP8_DECODER

  if (vp8_pp_cfg.post_proc_flag
      && vpx_codec_control(&decoder, VP8_SET_POSTPROC, &vp8_pp_cfg)) {
    fprintf(stderr, "Failed to configure postproc: %s\n", vpx_codec_error(&decoder));
    return EXIT_FAILURE;
  }

  if (vp8_dbg_color_ref_frame
      && vpx_codec_control(&decoder, VP8_SET_DBG_COLOR_REF_FRAME, vp8_dbg_color_ref_frame)) {
    fprintf(stderr, "Failed to configure reference block visualizer: %s\n", vpx_codec_error(&decoder));
    return EXIT_FAILURE;
  }

  if (vp8_dbg_color_mb_modes
      && vpx_codec_control(&decoder, VP8_SET_DBG_COLOR_MB_MODES, vp8_dbg_color_mb_modes)) {
    fprintf(stderr, "Failed to configure macro block visualizer: %s\n", vpx_codec_error(&decoder));
    return EXIT_FAILURE;
  }

  if (vp8_dbg_color_b_modes
      && vpx_codec_control(&decoder, VP8_SET_DBG_COLOR_B_MODES, vp8_dbg_color_b_modes)) {
    fprintf(stderr, "Failed to configure block visualizer: %s\n", vpx_codec_error(&decoder));
    return EXIT_FAILURE;
  }

  if (vp8_dbg_display_mv
      && vpx_codec_control(&decoder, VP8_SET_DBG_DISPLAY_MV, vp8_dbg_display_mv)) {
    fprintf(stderr, "Failed to configure motion vector visualizer: %s\n", vpx_codec_error(&decoder));
    return EXIT_FAILURE;
  }
#endif


  if (arg_skip)
    fprintf(stderr, "Skipping first %d frames.\n", arg_skip);
  while (arg_skip) {
    if (read_frame(&input, &buf, &bytes_in_buffer, &buffer_size))
      break;
    arg_skip--;
  }

  if (num_external_frame_buffers > 0) {
    ext_fb_list.num_external_frame_buffers = num_external_frame_buffers;
    ext_fb_list.ext_fb = (struct ExternalFrameBuffer *)calloc(
        num_external_frame_buffers, sizeof(*ext_fb_list.ext_fb));
    if (vpx_codec_set_frame_buffer_functions(
            &decoder, get_vp9_frame_buffer, release_vp9_frame_buffer,
            &ext_fb_list)) {
      fprintf(stderr, "Failed to configure external frame buffers: %s\n",
              vpx_codec_error(&decoder));
      return EXIT_FAILURE;
    }
  }

  frame_avail = 1;
  got_data = 0;

  /* Decode file */
  while (frame_avail || got_data) {
    vpx_codec_iter_t  iter = NULL;
    vpx_image_t    *img;
    struct vpx_usec_timer timer;
    int                   corrupted;

    frame_avail = 0;
    if (!stop_after || frame_in < stop_after) {
      if (!read_frame(&input, &buf, &bytes_in_buffer, &buffer_size)) {
        frame_avail = 1;
        frame_in++;

        vpx_usec_timer_start(&timer);

        if (vpx_codec_decode(&decoder, buf, (unsigned int)bytes_in_buffer,
                             NULL, 0)) {
          const char *detail = vpx_codec_error_detail(&decoder);
          warn("Failed to decode frame %d: %s",
               frame_in, vpx_codec_error(&decoder));

          if (detail)
            warn("Additional information: %s", detail);
          goto fail;
        }

        vpx_usec_timer_mark(&timer);
        dx_time += (unsigned int)vpx_usec_timer_elapsed(&timer);
      }
    }

    vpx_usec_timer_start(&timer);

    got_data = 0;
    if ((img = vpx_codec_get_frame(&decoder, &iter))) {
      ++frame_out;
      got_data = 1;
    }

    vpx_usec_timer_mark(&timer);
    dx_time += (unsigned int)vpx_usec_timer_elapsed(&timer);

    if (vpx_codec_control(&decoder, VP8D_GET_FRAME_CORRUPTED, &corrupted)) {
      warn("Failed VP8_GET_FRAME_CORRUPTED: %s", vpx_codec_error(&decoder));
      goto fail;
    }
    frames_corrupted += corrupted;

    if (progress)
      show_progress(frame_in, frame_out, dx_time);

    if (!noblit && img) {
      const int PLANES_YUV[] = {VPX_PLANE_Y, VPX_PLANE_U, VPX_PLANE_V};
      const int PLANES_YVU[] = {VPX_PLANE_Y, VPX_PLANE_V, VPX_PLANE_U};
      const int *planes = flipuv ? PLANES_YVU : PLANES_YUV;

      if (do_scale) {
        if (frame_out == 1) {
          // If the output frames are to be scaled to a fixed display size then
          // use the width and height specified in the container. If either of
          // these is set to 0, use the display size set in the first frame
          // header. If that is unavailable, use the raw decoded size of the
          // first decoded frame.
          int display_width = vpx_input_ctx.width;
          int display_height = vpx_input_ctx.height;
          if (!display_width || !display_height) {
            int display_size[2];
            if (vpx_codec_control(&decoder, VP9D_GET_DISPLAY_SIZE,
                                  display_size)) {
              // As last resort use size of first frame as display size.
              display_width = img->d_w;
              display_height = img->d_h;
            } else {
              display_width = display_size[0];
              display_height = display_size[1];
            }
          }
          scaled_img = vpx_img_alloc(NULL, VPX_IMG_FMT_I420, display_width,
                                     display_height, 16);
        }

        if (img->d_w != scaled_img->d_w || img->d_h != scaled_img->d_h) {
          vpx_image_scale(img, scaled_img, kFilterBox);
          img = scaled_img;
        }
      }

      if (single_file) {
        if (use_y4m) {
          char buf[Y4M_BUFFER_SIZE] = {0};
          size_t len = 0;
          if (frame_out == 1) {
            // Y4M file header
            len = y4m_write_file_header(buf, sizeof(buf),
                                        vpx_input_ctx.width,
                                        vpx_input_ctx.height,
                                        &vpx_input_ctx.framerate, img->fmt);
            if (do_md5) {
              MD5Update(&md5_ctx, (md5byte *)buf, (unsigned int)len);
            } else {
              fputs(buf, outfile);
            }
          }

          // Y4M frame header
          len = y4m_write_frame_header(buf, sizeof(buf));
          if (do_md5) {
            MD5Update(&md5_ctx, (md5byte *)buf, (unsigned int)len);
          } else {
            fputs(buf, outfile);
          }
        }

        if (do_md5) {
          update_image_md5(img, planes, &md5_ctx);
        } else {
          write_image_file(img, planes, outfile);
        }
      } else {
        generate_filename(outfile_pattern, outfile_name, PATH_MAX,
                          img->d_w, img->d_h, frame_in);
        if (do_md5) {
          MD5Init(&md5_ctx);
          update_image_md5(img, planes, &md5_ctx);
          MD5Final(md5_digest, &md5_ctx);
          print_md5(md5_digest, outfile_name);
        } else {
          outfile = open_outfile(outfile_name);
          write_image_file(img, planes, outfile);
          fclose(outfile);
        }
      }
    }

    if (stop_after && frame_in >= stop_after)
      break;
  }

  if (summary || progress) {
    show_progress(frame_in, frame_out, dx_time);
    fprintf(stderr, "\n");
  }

  if (frames_corrupted)
    fprintf(stderr, "WARNING: %d frames corrupted.\n", frames_corrupted);

fail:

  if (vpx_codec_destroy(&decoder)) {
    fprintf(stderr, "Failed to destroy decoder: %s\n",
            vpx_codec_error(&decoder));
    return EXIT_FAILURE;
  }

  if (!noblit && single_file) {
    if (do_md5) {
      MD5Final(md5_digest, &md5_ctx);
      print_md5(md5_digest, outfile_name);
    } else {
      fclose(outfile);
    }
  }

  if (input.vpx_input_ctx->file_type == FILE_TYPE_WEBM)
    webm_free(input.webm_ctx);
  else
    free(buf);

  if (scaled_img) vpx_img_free(scaled_img);

  for (i = 0; i < ext_fb_list.num_external_frame_buffers; ++i) {
    free(ext_fb_list.ext_fb[i].data);
  }
  free(ext_fb_list.ext_fb);

  fclose(infile);
  free(argv);

  return frames_corrupted ? EXIT_FAILURE : EXIT_SUCCESS;
}
Beispiel #16
0
/*---------------------------------------------------------------*/
int main(int argc, char **argv)
{
  int c,r,s,f;
  double val,rval;
  FILE *fp;
  MRI *mritmp;

  Progname = argv[0] ;
  argc --;
  argv++;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  /* assign default geometry */
  cdircos[0] = 1.0;
  cdircos[1] = 0.0;
  cdircos[2] = 0.0;
  rdircos[0] = 0.0;
  rdircos[1] = 1.0;
  rdircos[2] = 0.0;
  sdircos[0] = 0.0;
  sdircos[1] = 0.0;
  sdircos[2] = 1.0;
  res[0] = 1.0;
  res[1] = 1.0;
  res[2] = 1.0;
  cras[0] = 0.0;
  cras[1] = 0.0;
  cras[2] = 0.0;
  res[3] = 2.0; /* TR */

  if (argc == 0) usage_exit();

  parse_commandline(argc, argv);
  check_options();
  dump_options(stdout);

  if(tempid != NULL) {
    printf("INFO: reading template header\n");
    if(! DoCurv) mritemp = MRIreadHeader(tempid,tempfmtid);
    else         mritemp = MRIread(tempid);
    if (mritemp == NULL) {
      printf("ERROR: reading %s header\n",tempid);
      exit(1);
    }
    if(NewVoxSizeSpeced){
      dim[0] = round(mritemp->width*mritemp->xsize/res[0]);
      dim[1] = round(mritemp->height*mritemp->ysize/res[1]);
      dim[2] = round(mritemp->depth*mritemp->zsize/res[2]);
      dim[3] = mritemp->nframes;
      res[3] = mritemp->tr;
      dimSpeced = 1;
    }
    if(dimSpeced){
      mritmp = MRIallocSequence(dim[0],dim[1],dim[2],MRI_FLOAT,dim[3]);
      MRIcopyHeader(mritemp,mritmp);
      MRIfree(&mritemp);
      mritemp = mritmp;
    }
    if(resSpeced){
      mritemp->xsize = res[0];
      mritemp->ysize = res[1];
      mritemp->zsize = res[2];
      mritemp->tr    = res[3];
    }

    dim[0] = mritemp->width;
    dim[1] = mritemp->height;
    dim[2] = mritemp->depth;
    if (nframes > 0) dim[3] = nframes;
    else             dim[3] = mritemp->nframes;
    mritemp->nframes = dim[3];
  }

  if(mritemp) {
    if(SpikeTP >= mritemp->nframes){
      printf("ERROR: SpikeTP = %d >= mritemp->nframes = %d\n",
             SpikeTP,mritemp->nframes);
      exit(1);
    }
  }

  printf("Synthesizing\n");
  srand48(seed);
  if (strcmp(pdfname,"gaussian")==0)
    mri = MRIrandn(dim[0], dim[1], dim[2], dim[3], gausmean, gausstd, NULL);
  else if (strcmp(pdfname,"uniform")==0)
    mri = MRIdrand48(dim[0], dim[1], dim[2], dim[3], 0, 1, NULL);
  else if (strcmp(pdfname,"const")==0)
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], ValueA, NULL);
  else if (strcmp(pdfname,"sphere")==0) {
    if(voxradius < 0)
      voxradius =
        sqrt( pow(dim[0]/2.0,2)+pow(dim[1]/2.0,2)+pow(dim[2]/2.0,2) )/2.0;
    printf("voxradius = %lf\n",voxradius);
    mri = MRIsphereMask(dim[0], dim[1], dim[2], dim[3],
                        dim[0]/2.0, dim[1]/2.0, dim[2]/2.0,
                        voxradius, ValueA, NULL);
  } else if (strcmp(pdfname,"delta")==0) {
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], delta_off_value, NULL);
    if (delta_crsf_speced == 0) {
      delta_crsf[0] = dim[0]/2;
      delta_crsf[1] = dim[1]/2;
      delta_crsf[2] = dim[2]/2;
      delta_crsf[3] = dim[3]/2;
    }
    printf("delta set to %g at %d %d %d %d\n",delta_value,delta_crsf[0],
           delta_crsf[1],delta_crsf[2],delta_crsf[3]);
    MRIFseq_vox(mri,
                delta_crsf[0],
                delta_crsf[1],
                delta_crsf[2],
                delta_crsf[3]) = delta_value;
  } else if (strcmp(pdfname,"chi2")==0) {
    rfs = RFspecInit(seed,NULL);
    rfs->name = strcpyalloc("chi2");
    rfs->params[0] = dendof;
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    printf("Synthesizing chi2 with dof=%d\n",dendof);
    RFsynth(mri,rfs,NULL);
  } else if (strcmp(pdfname,"z")==0) {
    printf("Synthesizing z \n");
    rfs = RFspecInit(seed,NULL);
    rfs->name = strcpyalloc("gaussian");
    rfs->params[0] = 0; // mean
    rfs->params[1] = 1; // std
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    RFsynth(mri,rfs,NULL);
  } else if (strcmp(pdfname,"t")==0) {
    printf("Synthesizing t with dof=%d\n",dendof);
    rfs = RFspecInit(seed,NULL);
    rfs->name = strcpyalloc("t");
    rfs->params[0] = dendof;
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    RFsynth(mri,rfs,NULL);
  } else if (strcmp(pdfname,"tr")==0) {
    printf("Synthesizing t with dof=%d as ratio of z/sqrt(chi2)\n",dendof);
    rfs = RFspecInit(seed,NULL);
    // numerator
    rfs->name = strcpyalloc("gaussian");
    rfs->params[0] = 0; // mean
    rfs->params[1] = 1; // std
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    RFsynth(mri,rfs,NULL);
    // denominator
    rfs->name = strcpyalloc("chi2");
    rfs->params[0] = dendof;
    mri2 = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    RFsynth(mri2,rfs,NULL);
    fMRIsqrt(mri2,mri2); // sqrt of chi2
    mri = MRIdivide(mri,mri2,mri);
    MRIscalarMul(mri, mri, sqrt(dendof)) ;
    MRIfree(&mri2);
  } else if (strcmp(pdfname,"F")==0) {
    printf("Synthesizing F with num=%d den=%d\n",numdof,dendof);
    rfs = RFspecInit(seed,NULL);
    rfs->name = strcpyalloc("F");
    rfs->params[0] = numdof;
    rfs->params[1] = dendof;
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    RFsynth(mri,rfs,NULL);
  } else if (strcmp(pdfname,"Fr")==0) {
    printf("Synthesizing F with num=%d den=%d as ratio of two chi2\n",
           numdof,dendof);
    rfs = RFspecInit(seed,NULL);
    rfs->name = strcpyalloc("chi2");
    // numerator
    rfs->params[0] = numdof;
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    RFsynth(mri,rfs,NULL);
    // denominator
    rfs->params[0] = dendof;
    mri2 = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    RFsynth(mri2,rfs,NULL);
    mri = MRIdivide(mri,mri2,mri);
    MRIscalarMul(mri, mri, (double)dendof/numdof) ;
    MRIfree(&mri2);
  } else if (strcmp(pdfname,"voxcrs")==0) {
    // three frames. 1st=col, 2nd=row, 3rd=slice
    printf("Filling with vox CRS\n");
    mri = MRIconst(dim[0], dim[1], dim[2], 3, 0, NULL);
    for(c=0; c < mri->width; c ++){
      for(r=0; r < mri->height; r ++){
        for(s=0; s < mri->depth; s ++){
          MRIsetVoxVal(mri,c,r,s,0,c);
          MRIsetVoxVal(mri,c,r,s,1,r);
          MRIsetVoxVal(mri,c,r,s,2,s);
        }
      }
    }
  } else if (strcmp(pdfname,"boundingbox")==0) {
    printf("Setting bounding box \n");
    if(mritemp == NULL)
      mritemp = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    mri = MRIsetBoundingBox(mritemp,&boundingbox,ValueA,ValueB);
    if(!mri) exit(1);
  } 
  else if (strcmp(pdfname,"checker")==0) {
    printf("Checker \n");
    mri=MRIchecker(mritemp,NULL);
    if(!mri) exit(1);
  } 
  else if (strcmp(pdfname,"sliceno")==0) {
    printf("SliceNo \n");
    if(mritemp == NULL){
      printf("ERROR: need --temp with sliceno\n");
      exit(1);
    }
    mri=MRIsliceNo(mritemp,NULL);
    if(!mri) exit(1);
  } 
  else if (strcmp(pdfname,"indexno")==0) {
    printf("IndexNo \n");
    if(mritemp == NULL){
      printf("ERROR: need --temp with indexno\n");
      exit(1);
    }
    mri=MRIindexNo(mritemp,NULL);
    if(!mri) exit(1);
  } 
  else if (strcmp(pdfname,"crs")==0) {
    printf("CRS \n");
    if(mritemp == NULL){
      printf("ERROR: need --temp with crs\n");
      exit(1);
    }
    mri=MRIcrs(mritemp,NULL);
    if(!mri) exit(1);
  } 
  else {
    printf("ERROR: pdf %s unrecognized, must be gaussian, uniform,\n"
	   "const, delta, checker\n", pdfname);
    exit(1);
  }
  if (tempid != NULL) {
    MRIcopyHeader(mritemp,mri);
    mri->type = MRI_FLOAT;
    // Override
    if(nframes > 0) mri->nframes = nframes;
    if(TR > 0) mri->tr = TR;
  } else {
    if(mri == NULL) {
      usage_exit();
    }
    mri->xsize = res[0];
    mri->ysize = res[1];
    mri->zsize = res[2];
    mri->tr    = res[3];
    mri->x_r = cdircos[0];
    mri->x_a = cdircos[1];
    mri->x_s = cdircos[2];
    mri->y_r = rdircos[0];
    mri->y_a = rdircos[1];
    mri->y_s = rdircos[2];
    mri->z_r = sdircos[0];
    mri->z_a = sdircos[1];
    mri->z_s = sdircos[2];
    if(!usep0){
      mri->c_r = cras[0];
      mri->c_a = cras[1];
      mri->c_s = cras[2];
    } 
    else MRIp0ToCRAS(mri, p0[0], p0[1], p0[2]);
  }

  if (gstd > 0) {
    if(!UseFFT){
      printf("Smoothing\n");
      MRIgaussianSmooth(mri, gstd, gmnnorm, mri); /* gmnnorm = 1 = normalize */
    }
    else {
      printf("Smoothing with FFT \n");
      mri2 = MRIcopy(mri,NULL);
      mri = MRI_fft_gaussian(mri2, mri,
                             gstd, gmnnorm); /* gmnnorm = 1 = normalize */
    }
    if (rescale) {
      printf("Rescaling\n");
      if (strcmp(pdfname,"z")==0)     RFrescale(mri,rfs,NULL,mri);
      if (strcmp(pdfname,"chi2")==0)  RFrescale(mri,rfs,NULL,mri);
      if (strcmp(pdfname,"t")==0)     RFrescale(mri,rfs,NULL,mri);
      if (strcmp(pdfname,"tr")==0)    RFrescale(mri,rfs,NULL,mri);
      if (strcmp(pdfname,"F")==0)     RFrescale(mri,rfs,NULL,mri);
      if (strcmp(pdfname,"Fr")==0)    RFrescale(mri,rfs,NULL,mri);
    }
  }

  if(DoHSC){
    // This multiplies each frame by a random number
    // between HSCMin HSCMax to simulate heteroscedastisity
    printf("Applying HSC %lf %lf\n",HSCMin,HSCMax);
    for(f=0; f < mri->nframes; f++){
      rval = (HSCMax-HSCMin)*drand48() + HSCMin;
      if(debug) printf("%3d %lf\n",f,rval);
      for(c=0; c < mri->width; c ++){
	for(r=0; r < mri->height; r ++){
	  for(s=0; s < mri->depth; s ++){
	    val = MRIgetVoxVal(mri,c,r,s,f);
	    MRIsetVoxVal(mri,c,r,s,f,rval*val);
	  }
        }
      }
    }
  }

  if(AddOffset) {
    printf("Adding offset\n");
    offset = MRIread(tempid);
    if(offset == NULL) exit(1);
    if(OffsetFrame == -1) OffsetFrame = nint(offset->nframes/2);
    printf("Offset frame %d\n",OffsetFrame);
    mritmp = fMRIframe(offset, OffsetFrame, NULL);
    if(mritmp == NULL) exit(1);
    MRIfree(&offset);
    offset = mritmp;
    fMRIaddOffset(mri, offset, NULL, mri);
  }

  if(SpikeTP > 0){
    printf("Spiking time point %d\n",SpikeTP);
    for(c=0; c < mri->width; c ++){
      for(r=0; r < mri->height; r ++){
        for(s=0; s < mri->depth; s ++){
          MRIsetVoxVal(mri,c,r,s,SpikeTP,1e9);
        }
      }
    }
  }

  if(DoAbs){
    printf("Computing absolute value\n");
    MRIabs(mri,mri);
  }

  if(!NoOutput){
    printf("Saving\n");
    if(!DoCurv)  MRIwriteAnyFormat(mri,volid,volfmt,-1,NULL);
    else {
      printf("Saving in curv format\n");
      MRIScopyMRI(surf, mri, 0, "curv");
      MRISwriteCurvature(surf,volid);
    }
  }

  if(sum2file){
    val = MRIsum2All(mri);
    fp = fopen(sum2file,"w");
    if(fp == NULL){
      printf("ERROR: opening %s\n",sum2file);
      exit(1);
    }
    printf("sum2all: %20.10lf\n",val);
    printf("vrf: %20.10lf\n",1/val);
    fprintf(fp,"%20.10lf\n",val);
  }

  return(0);
}
Beispiel #17
0
int
main(int argc, char *argv[]) {
  char   **av, *in_fname;
  int    ac, nargs, i, j,  x, y, z, width, height, depth;
  MRI    *mri_flash[MAX_IMAGES], *mri_label, *mri_mask, *mri_tmp;
  int    msec, minutes, seconds, nvolumes, nvolumes_total ;
  struct timeb start ;
  float max_val, min_val, value;
  float *LDAmean1, *LDAmean2, *LDAweight;
  int label;
  double sum_white, sum_gray;
  int count_white, count_gray;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_ms_LDA.c,v 1.4 2011/03/02 00:04:23 nicks Exp $", "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  TimerStart(&start) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (argc < 2)
    usage_exit(1) ;

  printf("command line parsing finished\n");

  if (have_weight == 0 && ldaflag == 0) {
    printf("Use -lda option to specify two class labels to optimize CNR on \n");
    usage_exit(0);
  }

  if (have_weight == 0 && label_fname == NULL) {
    printf("Use -label option to specify file for segmentation \n");
    usage_exit(0);
  }


  if (have_weight == 1 && weight_fname == NULL) {
    printf("Use -weight option to specify file for input LDA weights \n") ;
    usage_exit(0);
  }

  if (have_weight == 1 && synth_fname == NULL) {
    printf("Use -synth option to specify file for output synthesized volume \n") ;
    usage_exit(0);
  }

  //////////////////////////////////////////////////////////////////////////////////
  /*** Read in the input multi-echo volumes ***/
  nvolumes = 0 ;
  for (i = 1 ; i < argc; i++) {
    in_fname = argv[i] ;
    printf("reading %s...\n", in_fname) ;

    mri_flash[nvolumes] = MRIread(in_fname) ;
    if (mri_flash[nvolumes] == NULL)
      ErrorExit(ERROR_NOFILE, "%s: could not read volume %s",
                Progname, in_fname) ;
    /* conform will convert all data to UCHAR, which will reduce data resolution*/
    printf("%s read in. \n", in_fname) ;
    if (conform) {
      printf("embedding and interpolating volume\n") ;
      mri_tmp = MRIconform(mri_flash[nvolumes]) ;
      MRIfree(&mri_flash[nvolumes]);
      mri_flash[nvolumes] = mri_tmp ;
    }

    /* Change all volumes to float type for convenience */
    if (mri_flash[nvolumes]->type != MRI_FLOAT) {
      printf("Volume %d type is %d\n", nvolumes+1, mri_flash[nvolumes]->type);
      printf("Change data to float type \n");
      mri_tmp = MRIchangeType(mri_flash[nvolumes], MRI_FLOAT, 0, 1.0, 1);
      MRIfree(&mri_flash[nvolumes]);
      mri_flash[nvolumes] = mri_tmp; //swap
    }

    nvolumes++ ;
  }

  printf("All data read in\n");

  ///////////////////////////////////////////////////////////////////////////
  nvolumes_total = nvolumes ;   /* all volumes read in */

  for (i = 0 ; i < nvolumes ; i++) {
    for (j = i+1 ; j < nvolumes ; j++) {
      if ((mri_flash[i]->width != mri_flash[j]->width) ||
          (mri_flash[i]->height != mri_flash[j]->height) ||
          (mri_flash[i]->depth != mri_flash[j]->depth))
        ErrorExit(ERROR_BADPARM, "%s:\nvolumes %d (type %d) and %d (type %d) don't match (%d x %d x %d) vs (%d x %d x %d)\n",
                  Progname, i, mri_flash[i]->type, j, mri_flash[j]->type, mri_flash[i]->width,
                  mri_flash[i]->height, mri_flash[i]->depth,
                  mri_flash[j]->width, mri_flash[j]->height, mri_flash[j]->depth) ;
    }
  }

  width = mri_flash[0]->width;
  height = mri_flash[0]->height;
  depth = mri_flash[0]->depth;

  if (label_fname != NULL) {
    mri_label = MRIread(label_fname);
    if (!mri_label)
      ErrorExit(ERROR_NOFILE, "%s: could not read input volume %s\n",
                Progname, label_fname);

    if ((mri_label->width != mri_flash[0]->width) ||
        (mri_label->height != mri_flash[0]->height) ||
        (mri_label->depth != mri_flash[0]->depth))
      ErrorExit(ERROR_BADPARM, "%s: label volume size doesn't match data volumes\n", Progname);

    /* if(mri_label->type != MRI_UCHAR)
       ErrorExit(ERROR_BADPARM, "%s: label volume is not UCHAR type \n", Progname); */
  }

  if (mask_fname != NULL) {
    mri_mask = MRIread(mask_fname);
    if (!mri_mask)
      ErrorExit(ERROR_NOFILE, "%s: could not read input volume %s\n",
                Progname, mask_fname);

    if ((mri_mask->width != mri_flash[0]->width) ||
        (mri_mask->height != mri_flash[0]->height) ||
        (mri_mask->depth != mri_flash[0]->depth))
      ErrorExit(ERROR_BADPARM, "%s: mask volume size doesn't macth data volumes\n", Progname);

    if (mri_mask->type != MRI_UCHAR)
      ErrorExit(ERROR_BADPARM, "%s: mask volume is not UCHAR type \n", Progname);
  } else {

    if (have_weight == 1)
      noise_threshold = - 1e20;

    printf("Threshold input vol1 at %g to create mask \n", noise_threshold);
    printf("this threshold is useful to process skull-stripped data \n");

    mri_mask = MRIalloc(mri_flash[0]->width, mri_flash[0]->height, mri_flash[0]->depth, MRI_UCHAR);
    MRIcopyHeader(mri_flash[0], mri_mask);

    /* Simply set mask to be 1 everywhere */
    for (z=0; z < depth; z++)
      for (y=0; y< height; y++)
        for (x=0; x < width; x++) {

          if ((float)MRIgetVoxVal(mri_flash[0], x, y,z,0) < noise_threshold)
            MRIvox(mri_mask, x, y,z) = 0;
          else
            MRIvox(mri_mask, x, y,z) = 1;
        }
  }

  /* Normalize input volumes */
  if (normflag) {
    printf("Normalize input volumes to zero mean, variance 1\n");
    for (i=0; i <nvolumes_total; i++) {
      mri_flash[i] = MRInormalizeXH(mri_flash[i], mri_flash[i], mri_mask);
    }
    printf("Normalization done.\n");
  }

  if (0) {
    printf("Using both hemi-sphere by changing rh-labels\n");
    for (z=0; z < depth; z++)
      for (y=0; y< height; y++)
        for (x=0; x < width; x++) {
          label = (int)MRIgetVoxVal(mri_label, x, y,z,0);
          if (label == 41) /* white matter */
            MRIsetVoxVal(mri_label, x, y, z, 0, 2);
          else if (label == 42) /* gm */
            MRIsetVoxVal(mri_label, x, y, z, 0, 3);
        }
  }


  if (debug_flag && window_flag) {
    /* Limit LDA to a local window */
    printf("Local window size = %d\n", window_size);
    window_size /= 2;
    for (z=0; z < depth; z++)
      for (y=0; y< height; y++)
        for (x=0; x < width; x++) {
          if (MRIvox(mri_mask, x, y,z) == 0) continue;

          if (z < (Gz - window_size) || z >(Gz + window_size)
              || y <(Gy - window_size) || y > (Gy + window_size)
              || x < (Gx - window_size) || x > (Gx + window_size))
            MRIvox(mri_mask, x, y,z) = 0;
        }

  }

  LDAmean1 = (float *)malloc(nvolumes_total*sizeof(float));
  LDAmean2 = (float *)malloc(nvolumes_total*sizeof(float));
  LDAweight = (float *)malloc(nvolumes_total*sizeof(float));

  if (have_weight) {
    printf("Read in LDA weights from weight-file\n");
    input_weights_to_file(LDAweight, weight_fname, nvolumes_total);
  } else { /* compute LDA weights */
    printf("Compute LDA weights to maximize CNR for region %d and region %d\n", class1, class2);
    /* Compute class means */
    update_LDAmeans(mri_flash, mri_label, mri_mask, LDAmean1, LDAmean2, nvolumes_total, class1, class2);
    printf("class means computed \n");

    /* Compute Fisher's LDA weights */
    computeLDAweights(LDAweight, mri_flash, mri_label, mri_mask, LDAmean1, LDAmean2, nvolumes_total, class1, class2);

    if (weight_fname != NULL) {
      output_weights_to_file(LDAweight, weight_fname, nvolumes_total);
    }
  }

  printf("LDA weights are: \n");
  for (i=0; i < nvolumes_total; i++) {
    printf("%g ", LDAweight[i]);
  }
  printf("\n");

  if (synth_fname != NULL) {
    /* linear projection of input volumes to a 1D volume */
    min_val = 10000.0;
    max_val = -10000.0;
    for (z=0; z < depth; z++)
      for (y=0; y< height; y++)
        for (x=0; x < width; x++) {
          if (whole_volume == 0 && MRIvox(mri_mask, x, y, z) == 0) continue;

          value = 0.0;

          for (i=0; i < nvolumes_total; i++) {
            value += MRIFvox(mri_flash[i], x, y, z)*LDAweight[i];
          }

          //     if(value < 0) value = 0;

          if (max_val < value) max_val = value;
          if (min_val > value) min_val = value;

          /* Borrow mri_flash[0] to store the float values first */
          MRIFvox(mri_flash[0], x, y, z) = value;
        }

    printf("max_val = %g, min_val = %g \n", max_val, min_val);

    /* Check to make sure class1 has higher intensity than class2 */
    if (have_weight == 0) {
      sum_white =0;
      count_white = 0;
      sum_gray = 0;
      count_gray = 0;
      for (z=0; z < depth; z++) {
        if (count_white > 300 && count_gray > 300) break;
        for (y=0; y< height; y++) {
          for (x=0; x < width; x++) {

            if ((int)MRIgetVoxVal(mri_label, x, y,z,0) == class1) {
              sum_white += MRIFvox(mri_flash[0], x, y, z);
              count_white += 1;
            } else if ((int)MRIgetVoxVal(mri_label, x, y,z,0) == class2) {
              sum_gray += MRIFvox(mri_flash[0], x, y, z);
              count_gray += 1;
            }
          }
        }
      }

      if (count_white > 1 && count_gray > 1) {
        if (sum_white *count_gray < sum_gray*count_white) {
          for (z=0; z < depth; z++)
            for (y=0; y< height; y++)
              for (x=0; x < width; x++) {
                if (whole_volume == 0 && MRIvox(mri_mask, x, y, z) == 0) continue;
                value = MRIFvox(mri_flash[0], x, y, z);
                MRIFvox(mri_flash[0], x, y, z) = max_val - value;
              }
          max_val = max_val - min_val;
          min_val = 0;
        }
      }
    }

    /* The following is copied to be consistent with mri_synthesize */
    /* Don't know why add min_val, minus should make more sense */
    for (z=0; z < depth; z++)
      for (y=0; y< height; y++)
        for (x=0; x < width; x++) {
          if (whole_volume == 0 && MRIvox(mri_mask, x, y, z) == 0) {
            MRIFvox(mri_flash[0], x, y, z) = 0; /*background always set to 0 */
            continue;
          }
          /* Borrow mri_flash[0] to store the float values first */
          if (shift_value > 0) {
            value = MRIFvox(mri_flash[0], x, y, z) + shift_value;
            if (value < 0) value = 0;
            MRIFvox(mri_flash[0], x, y, z) = value;
          } else if (mask_fname != NULL)
            MRIFvox(mri_flash[0], x, y, z) -= min_val;
        }


    MRIfree(&mri_mask);
    if (mri_flash[0]->type == out_type) {
      mri_mask = MRIcopy(mri_flash[0], mri_mask);
    } else {
      mri_mask = MRIchangeType(mri_flash[0], out_type, 0.1, 0.99, 0);
    }

    /* Scale output to [0, 255] */
    if (0) {
      for (z=0; z < depth; z++)
        for (y=0; y< height; y++)
          for (x=0; x < width; x++) {
            if (whole_volume == 0 && MRIvox(mri_mask, x, y, z) == 0) continue;

            value = (MRIFvox(mri_flash[0], x, y, z) - min_val)*255.0/(max_val - min_val) + 0.5; /* +0.5 for round-off */

            if (value > 255.0) value = 255.0;
            if (value < 0) value = 0;

            /* Borrow mri_flash[0] to store the float values first */
            MRIvox(mri_mask, x, y, z) = (BUFTYPE) value;
          }
    }

    /* Output synthesized volume */
    MRIwrite(mri_mask, synth_fname);

  }

  free(LDAmean1);
  free(LDAmean2);
  free(LDAweight);

  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("LDA took %d minutes and %d seconds.\n", minutes, seconds) ;

  MRIfree(&mri_mask);

  if (label_fname)
    MRIfree(&mri_label);


  for (i=0; i < nvolumes_total; i++) {
    MRIfree(&mri_flash[i]);
  }
  exit(0);
}
Beispiel #18
0
/* ------------------------------------------------------------------ */
static int parse_commandline(int argc, char **argv) {
  int  i, nargc , nargsused;
  char **pargv, *option ;
  char tmpstr[1000];

  if (argc < 1) usage_exit();

  nargc   = argc;
  pargv = argv;
  while (nargc > 0) {

    option = pargv[0];
    if (debug) printf("%d %s\n",nargc,option);
    nargc -= 1;
    pargv += 1;

    nargsused = 0;

    if (!strcasecmp(option, "--help"))           print_help() ;
    else if (!strcasecmp(option, "--version"))   print_version() ;
    else if (!strcasecmp(option, "--debug"))     debug = 1;
    else if (!strcasecmp(option, "--abs"))       DoAbs = 1;
    else if (!strcasecmp(option, "--nogmnnorm")) gmnnorm = 0;
    else if (!strcasecmp(option, "--rescale"))   rescale=1;
    else if (!strcasecmp(option, "--norescale")) rescale=0;
    else if (!strcasecmp(option, "--no-output")) NoOutput = 1;
    else if (!strcasecmp(option, "--fft"))       UseFFT = 1;
    else if (!strcasecmp(option, "--offset"))    AddOffset=1;
    else if (!strcasecmp(option, "--offset-mid")){
      AddOffset = 1;
      OffsetFrame = -1;
    }
    else if (!strcmp(option, "--hsc")) {
      if (nargc < 2) argnerr(option,2);
      sscanf(pargv[0],"%lf",&HSCMin);
      sscanf(pargv[1],"%lf",&HSCMax);
      DoHSC = 1;
      nargsused = 2;
    }
    else if (!strcmp(option, "--sum2")) {
      if (nargc < 1) argnerr(option,1);
      sum2file = pargv[0];
      pdfname  = "delta";
      //NoOutput = 1;
      nframes  = 1;
      nargsused = 1;
    }
    else if (!strcmp(option, "--hsynth")) {
      // eres mask DoTnorm out
      if (nargc < 3) argnerr(option,3);
      mri = MRIread(pargv[0]);
      mask = MRIread(pargv[1]);
      sscanf(pargv[2],"%d",&DoTNorm);
      mri2 = fMRIhsynth(mri, mask, DoTNorm);
      MRIwrite(mri2,pargv[3]);
      exit(0);
      nargsused = 2;
    }
    else if (!strcmp(option, "--vol") || !strcmp(option, "--o")) {
      if (nargc < 1) argnerr(option,1);
      volid = pargv[0];
      nargsused = 1;
      if (nth_is_arg(nargc, pargv, 1)) {
        volfmt = pargv[1];
        nargsused ++;
        volfmtid = checkfmt(volfmt);
      } 
    }
    else if (!strcmp(option, "--temp") || !strcmp(option, "--template")) {
      if(DoCurv){
	printf("ERROR: cannot use --temp and --curv\n");
	exit(1);
      }
      if(nargc < 1) argnerr(option,1);
      tempid = pargv[0];
      nargsused = 1;
      if (nth_is_arg(nargc, pargv, 1)) {
        tempfmt = pargv[1];
        nargsused ++;
        tempfmtid = checkfmt(tempfmt);
      } else tempfmtid = getfmtid(tempid);
    } else if (!strcmp(option, "--curv")) {
      if(tempid != NULL){
	printf("ERROR: cannot use --temp and --curv\n");
	exit(1);
      }
      if(nargc < 2) argnerr(option,2);
      subject = pargv[0];
      hemi = pargv[1];
      DoCurv = 1;
      nargsused = 2;
      sprintf(tmpstr,"%s/%s/surf/%s.thickness",getenv("SUBJECTS_DIR"),subject,hemi);
      tempid = strcpyalloc(tmpstr);
    } else if ( !strcmp(option, "--dim") ) {
      if (nargc < 4) argnerr(option,4);
      for (i=0;i<4;i++) sscanf(pargv[i],"%d",&dim[i]);
      nargsused = 4;
      dimSpeced = 1;
    } 
    else if ( !strcmp(option, "--nframes") ) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%d",&nframes);
      nargsused = 1;
    } 
    else if ( !strcmp(option, "--TR") || !strcmp(option, "--tr") ) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%lf",&TR);
      nargsused = 1;
    } 
    else if ( !strcmp(option, "--res") ) {
      if (nargc < 4) argnerr(option,4);
      for (i=0;i<4;i++) sscanf(pargv[i],"%f",&res[i]);
      nargsused = 4;
      resSpeced = 1;
    } 
    else if ( !strcmp(option, "--vox-size") ) {
      if (nargc < 3) argnerr(option,3);
      for (i=0;i<3;i++) sscanf(pargv[i],"%f",&res[i]);
      nargsused = 4;
      resSpeced = 1;
      NewVoxSizeSpeced = 1;
    } 
    else if ( !strcmp(option, "--c_ras") ) {
      if (nargc < 3) argnerr(option,3);
      for (i=0;i<3;i++) sscanf(pargv[i],"%f",&cras[i]);
      nargsused = 3;
    } 
    else if ( !strcmp(option, "--p0") ) {
      if (nargc < 3) argnerr(option,3);
      for (i=0;i<3;i++) sscanf(pargv[i],"%f",&p0[i]);
      usep0 = 1;
      nargsused = 3;
    } 
    else if ( !strcmp(option, "--cdircos") ) {
      if (nargc < 3) argnerr(option,3);
      for (i=0;i<3;i++) sscanf(pargv[i],"%f",&cdircos[i]);
      nargsused = 3;
    } else if ( !strcmp(option, "--rdircos") ) {
      if (nargc < 3) argnerr(option,3);
      for (i=0;i<3;i++) sscanf(pargv[i],"%f",&rdircos[i]);
      nargsused = 3;
    } else if ( !strcmp(option, "--sdircos") ) {
      if (nargc < 3) argnerr(option,3);
      for (i=0;i<3;i++) sscanf(pargv[i],"%f",&sdircos[i]);
      nargsused = 3;
    } else if ( !strcmp(option, "--fwhm") ) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%f",&fwhm);
      gstd = fwhm/sqrt(log(256.0));
      nargsused = 1;
    } else if (!strcmp(option, "--precision")) {
      if (nargc < 1) argnerr(option,1);
      precision = pargv[0];
      nargsused = 1;
    } else if (!strcmp(option, "--seed")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%ld",&seed);
      nargsused = 1;
    } else if (!strcmp(option, "--seedfile")) {
      if (nargc < 1) argnerr(option,1);
      seedfile = pargv[0];
      nargsused = 1;
    } else if (!strcmp(option, "--pdf")) {
      if (nargc < 1) argnerr(option,1);
      pdfname = pargv[0];
      nargsused = 1;
    } else if (!strcmp(option, "--bb")) {
      if (nargc < 6) argnerr(option,6);
      sscanf(pargv[0],"%d",&boundingbox.x);
      sscanf(pargv[1],"%d",&boundingbox.y);
      sscanf(pargv[2],"%d",&boundingbox.z);
      sscanf(pargv[3],"%d",&boundingbox.dx);
      sscanf(pargv[4],"%d",&boundingbox.dy);
      sscanf(pargv[5],"%d",&boundingbox.dz);
      pdfname = "boundingbox";
      nargsused = 6;
    }
    else if (!strcasecmp(option, "--checker"))
      pdfname = "checker";
    else if (!strcmp(option, "--dof-num")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%d",&numdof);
      nargsused = 1;
    } else if (!strcmp(option, "--val-a")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%lf",&ValueA);
      nargsused = 1;
    } else if (!strcmp(option, "--val-b")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%lf",&ValueB);
      nargsused = 1;
    } else if (!strcmp(option, "--radius")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%lf",&voxradius);
      nargsused = 1;
    } else if (!strcmp(option, "--dof-den") || !strcmp(option, "--dof")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%d",&dendof);
      nargsused = 1;
    } else if (!strcmp(option, "--gmean")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%lf",&gausmean);
      nargsused = 1;
    } else if (!strcmp(option, "--gstd")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%lf",&gausstd);
      nargsused = 1;
    } else if (!strcmp(option, "--delta-crsf")) {
      if (nargc < 4) argnerr(option,4);
      sscanf(pargv[0],"%d",&delta_crsf[0]);
      sscanf(pargv[1],"%d",&delta_crsf[1]);
      sscanf(pargv[2],"%d",&delta_crsf[2]);
      sscanf(pargv[3],"%d",&delta_crsf[3]);
      delta_crsf_speced = 1;
      nargsused = 4;
    } else if (!strcmp(option, "--delta-val")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%lf",&delta_value);
      nargsused = 1;
    } else if (!strcmp(option, "--delta-val-off")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%lf",&delta_off_value);
      nargsused = 1;
    } else if (!strcmp(option, "--spike")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%d",&SpikeTP);
      nargsused = 1;
    } else {
      fprintf(stderr,"ERROR: Option %s unknown\n",option);
      if (singledash(option))
        fprintf(stderr,"       Did you really mean -%s ?\n",option);
      exit(-1);
    }
    nargc -= nargsused;
    pargv += nargsused;
  }
  return(0);
}
Beispiel #19
0
int
main (int argc, char *argv [])
{	const char	*progname, *outfilename ;
	SNDFILE		*outfile, **infiles ;
	SF_INFO		sfinfo_out, sfinfo_in ;
	void 		(*func) (SNDFILE*, SNDFILE*, int) ;
	int			k ;

	progname = program_name (argv [0]) ;

	if (argc < 4)
		usage_exit (progname) ;

	argv ++ ;
	argc -- ;

	argc -- ;
	outfilename = argv [argc] ;

	if ((infiles = calloc (argc, sizeof (SNDFILE*))) == NULL)
	{	printf ("\nError : Malloc failed.\n\n") ;
		exit (1) ;
	} ;

	memset (&sfinfo_in, 0, sizeof (sfinfo_in)) ;

	if ((infiles [0] = sf_open (argv [0], SFM_READ, &sfinfo_in)) == NULL)
	{	printf ("\nError : failed to open file '%s'.\n\n", argv [0]) ;
		exit (1) ;
	} ;

	sfinfo_out = sfinfo_in ;

	for (k = 1 ; k < argc ; k++)
	{	if ((infiles [k] = sf_open (argv [k], SFM_READ, &sfinfo_in)) == NULL)
		{	printf ("\nError : failed to open file '%s'.\n\n", argv [k]) ;
			exit (1) ;
		} ;

		if (sfinfo_in.channels != sfinfo_out.channels)
		{	printf ("\nError : File '%s' has %d channels (should have %d).\n\n", argv [k], sfinfo_in.channels, sfinfo_out.channels) ;
			exit (1) ;
		} ;
	} ;

	if ((outfile = sf_open (outfilename, SFM_WRITE, &sfinfo_out)) == NULL)
	{	printf ("\nError : Not able to open input file %s.\n", outfilename) ;
		puts (sf_strerror (NULL)) ;
		exit (1) ;
	} ;

	if ((sfinfo_out.format & SF_FORMAT_SUBMASK) == SF_FORMAT_DOUBLE ||
			(sfinfo_out.format & SF_FORMAT_SUBMASK) == SF_FORMAT_FLOAT)
		func = concat_data_fp ;
	else
		func = concat_data_int ;

	for (k = 0 ; k < argc ; k++)
	{	func (outfile, infiles [k], sfinfo_out.channels) ;
		sf_close (infiles [k]) ;
	} ;

	sf_close (outfile) ;
	free (infiles) ;

	return 0 ;
} /* main */
int
main(int argc, char *argv[]) {
  MRI_SURFACE  *mris ;
  char         **av, *curv_name, *surf_name, *hemi, fname[STRLEN],
  *cp, *subject_name, subjects_dir[STRLEN],
  **c1_subjects, **c2_subjects ;
  int          ac, nargs, n, num_class1, num_class2, i, nvertices,
  avgs, max_snr_avgs, nlabels = 0, done ;
  float        **c1_thickness, **c2_thickness, *curvs, *total_mean,
  *c1_mean, *c2_mean,
  *class_mean, *c1_var, *c2_var, *class_var,*pvals,
  **c1_avg_thickness,
  *vbest_snr, *vbest_avgs, *vtotal_var, *vsnr, **c2_avg_thickness,
  *vbest_pvalues, current_min_label_area, current_fthresh ;
  MRI_SP       *mrisp ;
  LABEL        *area, **labels = NULL ;
  FILE         *fp = NULL ;
  double       snr, max_snr ;
  struct timeb start ;
  int          msec, minutes, seconds ;
  double       **c1_label_thickness, **c2_label_thickness ;
  int          *sorted_indices = NULL, vno ;
  float        *test_thickness, *test_avg_thickness ;
  double       label_avg ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mris_classify_thickness.c,v 1.8 2011/03/02 00:04:29 nicks Exp $", "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  if (write_flag && DIAG_VERBOSE_ON)
    fp = fopen("scalespace.dat", "w") ;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  TimerStart(&start) ;

  /* subject_name hemi surface curvature */
  if (argc < 7)
    usage_exit() ;
  if (output_subject == NULL)
    ErrorExit(ERROR_BADPARM,
              "output subject must be specified with -o <subject name>");

  cp = getenv("SUBJECTS_DIR") ;
  if (!cp)
    ErrorExit(ERROR_BADPARM, "%s: SUBJECTS_DIR not defined in environment",
              Progname) ;

  strcpy(subjects_dir, cp) ;

  hemi = argv[1] ;
  surf_name = argv[2] ;
  curv_name = argv[3] ;

#define ARGV_OFFSET 4

  /* first determine the number of subjects in each class */
  num_class1 = 0 ;
  n = ARGV_OFFSET ;
  do {
    num_class1++ ;
    n++ ;
    if (argv[n] == NULL || n >= argc)
      ErrorExit(ERROR_BADPARM, "%s: must spectify ':' between class lists",
                Progname) ;
  } while (argv[n][0] != ':') ;

  /* find  # of vertices in output subject surface */
  sprintf(fname, "%s/%s/surf/%s.%s",
          subjects_dir,output_subject,hemi,surf_name);
  mris = MRISread(fname) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
              Progname, fname) ;
  nvertices = mris->nvertices ;
  MRISfree(&mris) ;

  total_mean = (float *)calloc(nvertices, sizeof(float)) ;
  if (!total_mean)
    ErrorExit(ERROR_NOMEMORY,
              "%s: could not allocate mean list of %d curvatures",
              Progname, n, nvertices) ;
  c1_mean = (float *)calloc(nvertices, sizeof(float)) ;
  if (!c1_mean)
    ErrorExit(ERROR_NOMEMORY,
              "%s: could not allocate c1 mean list of %d curvatures",
              Progname, n, nvertices) ;
  pvals = (float *)calloc(nvertices, sizeof(float)) ;
  if (!pvals)
    ErrorExit(ERROR_NOMEMORY,
              "%s: could not allocate pvals",
              Progname, n, nvertices) ;
  c2_mean = (float *)calloc(nvertices, sizeof(float)) ;
  if (!c2_mean)
    ErrorExit(ERROR_NOMEMORY,
              "%s: could not allocate c2 mean list of %d curvatures",
              Progname, n, nvertices) ;

  c1_var = (float *)calloc(nvertices, sizeof(float)) ;
  if (!c1_var)
    ErrorExit(ERROR_NOMEMORY,
              "%s: could not allocate c1 var list of %d curvatures",
              Progname, n, nvertices) ;
  c2_var = (float *)calloc(nvertices, sizeof(float)) ;
  if (!c2_var)
    ErrorExit(ERROR_NOMEMORY,
              "%s: could not allocate c2 var list of %d curvatures",
              Progname, n, nvertices) ;

  num_class2 = 0 ;
  n++ ; /* skip ':' */
  if (n >= argc)
    ErrorExit(ERROR_BADPARM, "%s: class2 list empty", Progname) ;
  do {
    num_class2++ ;
    n++ ;
    if (n >= argc)
      break ;
  } while (argv[n] != NULL) ;

  fprintf(stderr, "%d subjects in class 1, %d subjects in class 2\n",
          num_class1, num_class2) ;

  c1_subjects = (char **)calloc(num_class1, sizeof(char *)) ;
  c1_thickness = (float **)calloc(num_class1, sizeof(char *)) ;
  c1_avg_thickness = (float **)calloc(num_class1, sizeof(char *)) ;
  c2_subjects = (char **)calloc(num_class2, sizeof(char *)) ;
  c2_thickness = (float **)calloc(num_class2, sizeof(char *)) ;
  c2_avg_thickness = (float **)calloc(num_class2, sizeof(char *)) ;
  for (n = 0 ; n < num_class1 ; n++) {
    c1_subjects[n] = argv[ARGV_OFFSET+n] ;
    c1_thickness[n] = (float *)calloc(nvertices, sizeof(float)) ;
    c1_avg_thickness[n] = (float *)calloc(nvertices, sizeof(float)) ;
    if (!c1_thickness[n] || !c1_avg_thickness[n])
      ErrorExit(ERROR_NOMEMORY,
                "%s: could not allocate %dth list of %d curvatures",
                Progname, n, nvertices) ;

    strcpy(c1_subjects[n], argv[ARGV_OFFSET+n]) ;
    /*    fprintf(stderr, "class1[%d] - %s\n", n, c1_subjects[n]) ;*/
  }
  i = n+1+ARGV_OFFSET ;  /* starting index */
  for (n = 0 ; n < num_class2 ; n++) {
    c2_subjects[n] = argv[i+n] ;
    c2_thickness[n] = (float *)calloc(nvertices, sizeof(float)) ;
    c2_avg_thickness[n] = (float *)calloc(nvertices, sizeof(float)) ;
    if (!c2_thickness[n] || !c2_avg_thickness[n])
      ErrorExit(ERROR_NOMEMORY,
                "%s: could not allocate %dth list of %d curvatures",
                Progname, n, nvertices) ;
    strcpy(c2_subjects[n], argv[i+n]) ;
    /*    fprintf(stderr, "class2[%d] - %s\n", n, c2_subjects[n]) ;*/
  }

  if (label_name) {
    area = LabelRead(output_subject, label_name) ;
    if (!area)
      ErrorExit(ERROR_NOFILE, "%s: could not read label %s", Progname,
                label_name) ;
  } else
    area = NULL ;

  if (read_dir) {
    sprintf(fname, "%s/%s/surf/%s.%s",
            subjects_dir,output_subject,hemi,surf_name);
    mris = MRISread(fname) ;
    if (!mris)
      ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                Progname, fname) ;
    MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;

    /* real all the curvatures in for group1 */
    for (n = 0 ; n < num_class1+num_class2 ; n++) {
      /* transform each subject's curvature into the output subject's space */
      subject_name = n < num_class1 ? c1_subjects[n]:c2_subjects[n-num_class1];
      fprintf(stderr, "reading subject %d of %d: %s\n",
              n+1, num_class1+num_class2, subject_name) ;
      sprintf(fname, "%s/%s.%s", read_dir,hemi,subject_name);
      if (MRISreadValues(mris, fname) != NO_ERROR)
        ErrorExit(Gerror,
                  "%s: could not read curvature file %s",Progname,fname);
      if (area)
        MRISmaskNotLabel(mris, area) ;
      curvs = (n < num_class1) ? c1_thickness[n] : c2_thickness[n-num_class1] ;
      class_mean = (n < num_class1) ? c1_mean : c2_mean ;
      class_var = (n < num_class1) ? c1_var : c2_var ;
      MRISexportValVector(mris, curvs) ;
      cvector_accumulate(curvs, total_mean, nvertices) ;
      cvector_accumulate(curvs, class_mean, nvertices) ;
      cvector_accumulate_square(curvs, class_var, nvertices) ;
    }
  } else {

    /* real all the curvatures in for group1 */
    for (n = 0 ; n < num_class1+num_class2 ; n++) {
      /* transform each subject's curvature into the output subject's space */
      subject_name = n < num_class1 ? c1_subjects[n]:c2_subjects[n-num_class1];
      fprintf(stderr, "reading subject %d of %d: %s\n",
              n+1, num_class1+num_class2, subject_name) ;
      sprintf(fname, "%s/%s/surf/%s.%s",
              subjects_dir,subject_name,hemi,surf_name);
      mris = MRISread(fname) ;
      if (!mris)
        ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                  Progname, fname) ;
      MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;
      if (strchr(curv_name, '/') != NULL)
        strcpy(fname, curv_name) ;  /* full path specified */
      else
        sprintf(fname,"%s/%s/surf/%s.%s",
                subjects_dir,subject_name,hemi,curv_name);
      if (MRISreadCurvatureFile(mris, fname) != NO_ERROR)
        ErrorExit(Gerror,"%s: could no read curvature file %s",Progname,fname);
      mrisp = MRIStoParameterization(mris, NULL, 1, 0) ;
      MRISfree(&mris) ;

      sprintf(fname, "%s/%s/surf/%s.%s",
              subjects_dir,output_subject,hemi,surf_name);
      mris = MRISread(fname) ;
      if (!mris)
        ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                  Progname, fname) ;
      MRISfromParameterization(mrisp, mris, 0) ;
      if (area)
        MRISmaskNotLabel(mris, area) ;
      curvs = (n < num_class1) ? c1_thickness[n] : c2_thickness[n-num_class1] ;
      class_mean = (n < num_class1) ? c1_mean : c2_mean ;
      class_var = (n < num_class1) ? c1_var : c2_var ;
      MRISextractCurvatureVector(mris, curvs) ;
      cvector_accumulate(curvs, total_mean, nvertices) ;
      cvector_accumulate(curvs, class_mean, nvertices) ;
      cvector_accumulate_square(curvs, class_var, nvertices) ;
      MRISPfree(&mrisp) ;
      MRISfree(&mris) ;
    }
  }

  /* compute within-group means, and total mean */
  cvector_normalize(total_mean, num_class1+num_class2, nvertices) ;
  cvector_normalize(c1_mean, num_class1, nvertices) ;
  cvector_normalize(c2_mean, num_class2, nvertices) ;
  cvector_compute_variance(c1_var, c1_mean, num_class1, nvertices) ;
  cvector_compute_variance(c2_var, c2_mean, num_class2, nvertices) ;
  cvector_compute_t_test(c1_mean, c1_var, c2_mean, c2_var,
                         num_class1, num_class2, pvals, nvertices) ;

  sprintf(fname, "%s/%s/surf/%s.%s",
          subjects_dir,output_subject,hemi,surf_name);
  fprintf(stderr, "reading output surface %s...\n", fname) ;
  mris = MRISread(fname) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
              Progname, fname) ;

  if (area)
    MRISripNotLabel(mris, area) ;
  vbest_snr = cvector_alloc(nvertices) ;
  vbest_pvalues = cvector_alloc(nvertices) ;
  vbest_avgs = cvector_alloc(nvertices) ;
  vtotal_var = cvector_alloc(nvertices) ;
  vsnr = cvector_alloc(nvertices) ;

  if (read_dir == NULL)  /* recompute everything */
  {
    if (use_buggy_snr)
      cvector_multiply_variances(c1_var, c2_var, num_class1, num_class2,
                                 vtotal_var, nvertices) ;
    else
      cvector_add_variances(c1_var, c2_var, num_class1, num_class2,
                            vtotal_var, nvertices) ;
    if (use_no_distribution)
      snr = cvector_compute_dist_free_snr(c1_thickness, num_class1,
                                          c2_thickness, num_class2,
                                          c1_mean, c2_mean,
                                          vsnr, nvertices, &i);
    else
      snr = cvector_compute_snr(c1_mean, c2_mean, vtotal_var, vsnr, nvertices,
                                &i, 0.0f);
    fprintf(stderr,
            "raw SNR %2.2f, n=%2.4f, d=%2.4f, vno=%d\n",
            sqrt(snr), c1_mean[i]-c2_mean[i], sqrt(vtotal_var[i]), i) ;
    max_snr = snr ;
    max_snr_avgs = 0 ;
    cvector_track_best_snr(vsnr, vbest_snr, vbest_avgs, 0, nvertices) ;

    for (n = 0 ; n < num_class1 ; n++)
      cvector_copy(c1_thickness[n], c1_avg_thickness[n], nvertices) ;
    for (n = 0 ; n < num_class2 ; n++)
      cvector_copy(c2_thickness[n], c2_avg_thickness[n], nvertices) ;

    /* now incrementally average the data, keeping track of the best
       snr at each location, and at what scale it occurred. vbest_avgs
       and vbest_snr will contain the scale and the snr at that scale.
    */
    for (avgs = 1 ; avgs <= max_avgs ; avgs++) {
      /* c?_avg_thickness is the thickness at the current scale */
      if (!(avgs % 50))
        fprintf(stderr, "testing %d averages...\n", avgs) ;
      cvector_clear(c1_mean, nvertices) ;
      cvector_clear(c2_mean, nvertices) ;
      cvector_clear(c1_var, nvertices) ;
      cvector_clear(c2_var, nvertices) ;
      cvector_clear(total_mean, nvertices) ;
      for (n = 0 ; n < num_class1 ; n++) {
        MRISimportCurvatureVector(mris, c1_avg_thickness[n]) ;
        MRISaverageCurvatures(mris, 1) ;
        MRISextractCurvatureVector(mris, c1_avg_thickness[n]) ;
        cvector_accumulate(c1_avg_thickness[n], total_mean, nvertices) ;
        cvector_accumulate(c1_avg_thickness[n], c1_mean, nvertices) ;
        cvector_accumulate_square(c1_avg_thickness[n], c1_var, nvertices) ;
      }
      for (n = 0 ; n < num_class2 ; n++) {
        MRISimportCurvatureVector(mris, c2_avg_thickness[n]) ;
        MRISaverageCurvatures(mris, 1) ;
        MRISextractCurvatureVector(mris, c2_avg_thickness[n]) ;
        cvector_accumulate(c2_avg_thickness[n], total_mean, nvertices) ;
        cvector_accumulate(c2_avg_thickness[n], c2_mean, nvertices) ;
        cvector_accumulate_square(c2_avg_thickness[n], c2_var, nvertices) ;
      }
      cvector_normalize(total_mean, num_class1+num_class2, nvertices) ;
      cvector_normalize(c1_mean, num_class1, nvertices) ;
      cvector_normalize(c2_mean, num_class2, nvertices) ;
      cvector_compute_variance(c1_var, c1_mean, num_class1, nvertices) ;
      cvector_compute_variance(c2_var, c2_mean, num_class2, nvertices) ;
      if (use_buggy_snr)
        cvector_multiply_variances(c1_var, c2_var, num_class1, num_class2,
                                   vtotal_var, nvertices) ;
      else
        cvector_add_variances(c1_var, c2_var, num_class1, num_class2,
                              vtotal_var, nvertices) ;
      if (use_no_distribution)
        snr =
          cvector_compute_dist_free_snr(c1_avg_thickness,num_class1,
                                        c2_avg_thickness, num_class2, c1_mean,
                                        c2_mean, vsnr, nvertices, &i);
      else
        snr =
          cvector_compute_snr(c1_mean, c2_mean, vtotal_var, vsnr, nvertices,&i,
                              bonferroni ? log((double)avgs) : 0.0f);
      if (write_flag && DIAG_VERBOSE_ON) {
        fprintf(fp, "%d %2.1f  %2.2f %2.2f %2.2f ",
                avgs, sqrt((float)avgs), sqrt(snr), c1_mean[i]-c2_mean[i],
                sqrt(vtotal_var[i])) ;
        fflush(fp) ;
        for (n = 0 ; n < num_class1 ; n++)
          fprintf(fp, "%2.2f ", c1_avg_thickness[n][i]) ;
        for (n = 0 ; n < num_class2 ; n++)
          fprintf(fp, "%2.2f ", c2_avg_thickness[n][i]) ;
        fprintf(fp, "\n") ;
        fclose(fp) ;
      }
      if (snr > max_snr) {
        fprintf(stderr,
                "new max SNR found at avgs=%d (%2.1f mm)=%2.1f, n=%2.4f, "
                "d=%2.4f, vno=%d\n",
                avgs, sqrt((float)avgs), sqrt(snr), c1_mean[i]-c2_mean[i],
                sqrt(vtotal_var[i]), i) ;
        max_snr = snr ;
        max_snr_avgs = avgs ;
      }
      cvector_track_best_snr(vsnr, vbest_snr, vbest_avgs, avgs, nvertices) ;
    }
    if (compute_stats)
      cvector_compute_t(vbest_snr, vbest_pvalues,num_class1+num_class2,
                        nvertices) ;
    printf("max snr=%2.2f at %d averages\n", max_snr, max_snr_avgs) ;
    if (write_flag) {
      MRISimportValVector(mris, vbest_snr) ;
      sprintf(fname, "./%s.%s_best_snr", hemi,prefix) ;
      MRISwriteValues(mris, fname) ;
      MRISimportValVector(mris, vbest_avgs) ;
      sprintf(fname, "./%s.%s_best_avgs", hemi, prefix) ;
      MRISwriteValues(mris, fname) ;
      if (compute_stats) {
        MRISimportValVector(mris, vbest_pvalues) ;
        sprintf(fname, "./%s.%s_best_pval", hemi,prefix) ;
        MRISwriteValues(mris, fname) ;
      }
    }
  }
  else  /* read from directory containing precomputed optimal values */
  {
    sprintf(fname, "%s/%s.%s_best_snr", read_dir, hemi, prefix) ;
    if (MRISreadValues(mris, fname) != NO_ERROR)
      ErrorExit(Gerror, "%s: MRISreadValues(%s) failed",Progname,fname) ;
    MRISexportValVector(mris, vbest_snr) ;

    sprintf(fname, "%s/%s.%s_best_avgs", read_dir, hemi, prefix) ;
    if (MRISreadValues(mris, fname) != NO_ERROR)
      ErrorExit(Gerror, "%s: MRISreadValues(%s) failed",Progname,fname) ;
    MRISexportValVector(mris, vbest_avgs) ;
  }

  if (write_dir) {
    sprintf(fname, "%s/%s.%s_best_snr", write_dir, hemi,prefix) ;
    MRISimportValVector(mris, vbest_snr) ;
    if (MRISwriteValues(mris, fname) != NO_ERROR)
      ErrorExit(Gerror, "%s: MRISwriteValues(%s) failed",Progname,fname) ;

    sprintf(fname, "%s/%s.%s_best_avgs", write_dir, hemi, prefix) ;
    MRISimportValVector(mris, vbest_avgs) ;
    if (MRISwriteValues(mris, fname) != NO_ERROR)
      ErrorExit(Gerror, "%s: MRISwriteValues(%s) failed",Progname,fname) ;
  }

  if (nsort < -1)
    nsort = mris->nvertices ;

  if (nsort <= 0) {
    nlabels = 0 ;
    current_min_label_area = min_label_area ;
    for (done = 0, current_fthresh = fthresh ;
         !FZERO(current_fthresh) && !done ;
         current_fthresh *= 0.95) {
      int   npos_labels, nneg_labels ;
      LABEL **pos_labels, **neg_labels ;

      for (current_min_label_area = min_label_area ;
           current_min_label_area > 0.5 ;
           current_min_label_area *= 0.75) {
        MRISclearMarks(mris) ;
        sprintf(fname, "%s-%s_thickness", hemi, prefix ? prefix : "") ;
        mark_thresholded_vertices(mris, vbest_snr, vbest_avgs,current_fthresh);
        segment_and_write_labels(output_subject, fname, mris,
                                 &pos_labels, &npos_labels, 0,
                                 current_min_label_area) ;
        MRISclearMarks(mris) ;
        mark_thresholded_vertices(mris, vbest_snr,vbest_avgs,-current_fthresh);
        segment_and_write_labels(output_subject, fname, mris, &neg_labels,
                                 &nneg_labels, npos_labels,
                                 current_min_label_area) ;

        nlabels = nneg_labels + npos_labels ;
        if (nlabels) {
          labels = (LABEL **)calloc(nlabels, sizeof(LABEL *)) ;
          for (i = 0 ; i < npos_labels ; i++)
            labels[i] = pos_labels[i] ;
          for (i = 0 ; i < nneg_labels ; i++)
            labels[i+npos_labels] = neg_labels[i] ;
          free(pos_labels) ;
          free(neg_labels) ;
        }
        done = (nlabels >= min_labels) ;
        if (done)  /* found enough points */
          break ;

        /* couldn't find enough  points - free stuff and try again */
        for (i = 0 ; i < nlabels ; i++)
          LabelFree(&labels[i]) ;
        if (nlabels)
          free(labels) ;
#if 0
        fprintf(stderr,"%d labels found (min %d), reducing constraints...\n",
                nlabels, min_labels) ;
#endif
      }
    }

    printf("%d labels found with F > %2.1f and area > %2.0f\n",
           nlabels, current_fthresh, current_min_label_area) ;
    for (i = 0 ; i < nlabels ; i++)
      fprintf(stderr, "label %d: %d points, %2.1f mm\n",
              i, labels[i]->n_points, LabelArea(labels[i], mris)) ;
  }

  /* read or compute thickness at optimal scale and put it into
     c?_avg_thickness.
  */
  if (!read_dir) {
    fprintf(stderr, "extracting thickness at optimal scale...\n") ;

    /* now build feature vectors for each subject */
    extract_thickness_at_best_scale(mris, c1_avg_thickness, vbest_avgs,
                                    c1_thickness, nvertices, num_class1);
    fprintf(stderr, "extracting thickness for class 2...\n") ;
    extract_thickness_at_best_scale(mris, c2_avg_thickness, vbest_avgs,
                                    c2_thickness, nvertices, num_class2);
  } else  /* read in precomputed optimal thicknesses */
  {
    char fname[STRLEN] ;

    fprintf(stderr, "reading precomputed thickness vectors\n") ;
    for (n = 0 ; n < num_class1 ; n++) {
      sprintf(fname, "%s/%s.%s", read_dir, hemi, argv[ARGV_OFFSET+n]) ;
      fprintf(stderr, "reading thickness vector from %s...\n", fname) ;
      if (MRISreadValues(mris, fname) != NO_ERROR)
        ErrorExit(Gerror, "%s: could not read thickness file %s",
                  Progname,fname) ;
      MRISexportValVector(mris, c1_avg_thickness[n]) ;
    }
    for (n = 0 ; n < num_class2 ; n++) {
      sprintf(fname, "%s/%s.%s", read_dir, hemi,
              argv[n+num_class1+1+ARGV_OFFSET]) ;
      fprintf(stderr, "reading curvature vector from %s...\n", fname) ;
      if (MRISreadValues(mris, fname) != NO_ERROR)
        ErrorExit(Gerror, "%s: could not read thickness file %s",
                  Progname,fname) ;
      MRISexportValVector(mris, c2_avg_thickness[n]) ;
    }
  }

  if (write_dir)   /* write out optimal thicknesses */
  {
    char fname[STRLEN] ;

    for (n = 0 ; n < num_class1 ; n++) {
      sprintf(fname, "%s/%s.%s", write_dir, hemi, argv[ARGV_OFFSET+n]) ;
      fprintf(stderr, "writing curvature vector to %s...\n", fname) ;
      MRISimportValVector(mris, c1_avg_thickness[n]) ;
      MRISwriteValues(mris, fname) ;
    }
    for (n = 0 ; n < num_class2 ; n++) {
      sprintf(fname, "%s/%s.%s", write_dir, hemi,
              argv[n+num_class1+1+ARGV_OFFSET]) ;
      fprintf(stderr, "writing curvature vector to %s...\n", fname) ;
      MRISimportValVector(mris, c2_avg_thickness[n]) ;
      MRISwriteValues(mris, fname) ;
    }
  }


  /* should free c?_thickness here */

  if (nsort <= 0) {
    /* We have the thickness values at the most powerful scale stored for
       each subject in the c1_avg_thickness and c2_avg_thickness vectors.
       Now collapse them across each label and build  feature vector for
       classification.
    */
    c1_label_thickness = (double **)calloc(num_class1, sizeof(double *)) ;
    c2_label_thickness = (double **)calloc(num_class2, sizeof(double *)) ;
    for (n = 0 ; n < num_class1 ; n++)
      c1_label_thickness[n] = (double *)calloc(nlabels, sizeof(double)) ;
    for (n = 0 ; n < num_class2 ; n++)
      c2_label_thickness[n] = (double *)calloc(nlabels, sizeof(double)) ;

    fprintf(stderr, "collapsing thicknesses within labels for class 1\n") ;
    for (n = 0 ; n < num_class1 ; n++)
      for (i = 0 ; i < nlabels ; i++)
        c1_label_thickness[n][i] =
          cvector_average_in_label(c1_avg_thickness[n], labels[i], nvertices) ;
    fprintf(stderr, "collapsing thicknesses within labels for class 2\n") ;
    for (n = 0 ; n < num_class2 ; n++)
      for (i = 0 ; i < nlabels ; i++)
        c2_label_thickness[n][i] =
          cvector_average_in_label(c2_avg_thickness[n], labels[i], nvertices) ;
    sprintf(fname, "%s_%s_class1.dat", hemi,prefix) ;
    fprintf(stderr, "writing class 1 info to %s...\n", fname) ;
    fp = fopen(fname, "w") ;
    for (i = 0 ; i < nlabels ; i++)  /* for each row */
    {
      for (n = 0 ; n < num_class1 ; n++)  /* for each column */
        fprintf(fp, "%2.2f  ", c1_label_thickness[n][i]) ;
      fprintf(fp, "\n") ;
    }
    fclose(fp) ;

    sprintf(fname, "%s_%s_class2.dat", hemi,prefix) ;
    fprintf(stderr, "writing class 2 info to %s...\n", fname) ;
    fp = fopen(fname, "w") ;
    for (i = 0 ; i < nlabels ; i++) {
      for (n = 0 ; n < num_class2 ; n++)
        fprintf(fp, "%2.2f  ", c2_label_thickness[n][i]) ;
      fprintf(fp, "\n") ;
    }
    fclose(fp) ;
  } else {
    sorted_indices = cvector_sort(vbest_snr, nvertices) ;
    vno = sorted_indices[0] ;
    write_vertex_data("c1.dat", vno, c1_avg_thickness,num_class1);
    write_vertex_data("c2.dat", vno, c2_avg_thickness,num_class2);
    printf("sorting complete\n") ;

    /* re-write class means at these locations */
    sprintf(fname, "%s_%s_class1.dat", hemi,prefix) ;
    fprintf(stderr, "writing class 1 info to %s...\n", fname) ;
    fp = fopen(fname, "w") ;
    for (i = 0 ; i < nsort ; i++) {
      for (n = 0 ; n < num_class1 ; n++)
        fprintf(fp, "%2.2f  ", c1_avg_thickness[n][sorted_indices[i]]) ;
      fprintf(fp, "\n") ;
    }
    fclose(fp) ;
    sprintf(fname, "%s_%s_class2.dat", hemi,prefix) ;
    fprintf(stderr, "writing class 2 info to %s...\n", fname) ;
    fp = fopen(fname, "w") ;
    for (i = 0 ; i < nsort ; i++) {
      for (n = 0 ; n < num_class2 ; n++)
        fprintf(fp, "%2.2f  ", c2_avg_thickness[n][sorted_indices[i]]) ;
      fprintf(fp, "\n") ;
    }
    fclose(fp) ;
  }

  if (test_subject) {
    test_thickness = cvector_alloc(nvertices) ;
    test_avg_thickness = cvector_alloc(nvertices) ;
    MRISfree(&mris) ;
    fprintf(stderr, "reading subject %s\n", test_subject) ;
    sprintf(fname, "%s/%s/surf/%s.%s",
            subjects_dir,test_subject,hemi,surf_name);
    mris = MRISread(fname) ;
    if (!mris)
      ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                Progname, fname) ;
    MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;
    if (strchr(curv_name, '/') != NULL)
      strcpy(fname, curv_name) ;  /* full path specified */
    else
      sprintf(fname,"%s/%s/surf/%s.%s",
              subjects_dir,test_subject,hemi,curv_name);
    if (MRISreadCurvatureFile(mris, fname) != NO_ERROR)
      ErrorExit(Gerror,"%s: could no read curvature file %s",Progname,fname);
    mrisp = MRIStoParameterization(mris, NULL, 1, 0) ;
    MRISfree(&mris) ;

    sprintf(fname, "%s/%s/surf/%s.%s",
            subjects_dir,output_subject,hemi,surf_name);
    mris = MRISread(fname) ;
    if (!mris)
      ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                Progname, fname) ;
    MRISfromParameterization(mrisp, mris, 0) ;
    if (area)
      MRISmaskNotLabel(mris, area) ;
    MRISextractCurvatureVector(mris, test_thickness) ;
    for (avgs = 0 ; avgs <= max_avgs ; avgs++) {
      cvector_extract_best_avg(vbest_avgs, test_thickness,test_avg_thickness,
                               avgs-1, nvertices) ;
      MRISimportCurvatureVector(mris, test_thickness) ;
      MRISaverageCurvatures(mris, 1) ;
      MRISextractCurvatureVector(mris, test_thickness) ;
    }

    if (nsort <= 0) {
      sprintf(fname, "%s_%s.dat", hemi,test_subject) ;
      fprintf(stderr, "writing test subject feature vector to %s...\n",
              fname) ;
      fp = fopen(fname, "w") ;
      for (i = 0 ; i < nlabels ; i++)  /* for each row */
      {
        label_avg =
          cvector_average_in_label(test_avg_thickness, labels[i], nvertices) ;
        fprintf(fp, "%2.2f\n", label_avg) ;
      }
      fclose(fp) ;
    } else   /* use sorting instead of connected areas */
    {
      double classification, offset, w ;
      int    total_correct, total_wrong, first_wrong, vno ;


      sprintf(fname, "%s_%s.dat", hemi,test_subject) ;
      fprintf(stderr, "writing test subject feature vector to %s...\n",
              fname) ;
      fp = fopen(fname, "w") ;

      first_wrong = -1 ;
      total_wrong = total_correct = 0 ;
      for (i = 0 ; i < nsort ; i++) {
        vno = sorted_indices[i] ;
        fprintf(fp, "%2.2f\n ", test_avg_thickness[sorted_indices[i]]) ;
        offset = (c1_mean[vno]+c2_mean[vno])/2.0 ;
        w = (c1_mean[vno]-c2_mean[vno]) ;
        classification = (test_avg_thickness[vno] - offset) * w ;

        if (((classification < 0) && (true_class == 1)) ||
            ((classification > 0) && (true_class == 2))) {
          total_wrong++ ;
          if (first_wrong < 0)
            first_wrong = i ;
        } else
          total_correct++ ;
      }
      fclose(fp) ;
      fprintf(stderr, "%d of %d correct = %2.1f%% (first wrong %d (%d)),"
              "min snr=%2.1f\n",
              total_correct, total_correct+total_wrong,
              100.0*total_correct / (total_correct+total_wrong),
              first_wrong, first_wrong >= 0 ? sorted_indices[first_wrong]:-1,
              vbest_snr[sorted_indices[nsort-1]]) ;

      if (first_wrong >= 0) {
        write_vertex_data("c1w.dat", sorted_indices[first_wrong],
                          c1_avg_thickness,num_class1);
        write_vertex_data("c2w.dat", sorted_indices[first_wrong],
                          c2_avg_thickness,num_class2);
      }
    }
  }

  msec = TimerStop(&start) ;
  free(total_mean);
  free(c1_mean) ;
  free(c2_mean) ;
  free(c1_var);
  free(c2_var);
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  fprintf(stderr, "classification took %d minutes and %d seconds.\n",
          minutes, seconds) ;
  exit(0) ;
  return(0) ;  /* for ansi */
}
Beispiel #21
0
void parse_args(int argc, char **argv)
{
        char *tail;

        int c;
        int index;
        static struct option opts[] = {
                { "file",     required_argument, NULL, 'f' },
                { "loop",     required_argument, NULL, 'l' },
                { "infinite", no_argument,       NULL, 'i' },
                { "speed",    required_argument, NULL, 's' },
                { "port",     required_argument, NULL, 'p' },
                { "help",     no_argument,       NULL, 'h' },
                { 0 }
        };

        while (1) {
                c = getopt_long(argc, argv, "f:l:is:p:h", opts, &index);
                if (c == -1) break;

                switch (c) {
                case 'f':
                        filename = optarg;
                        break;
                case 'l':
                        loopcount = strtoul(optarg, &tail, 10);
                        if (*tail) {
                                fprintf(stderr,
                                        "invalid argument to loop: %s\n",
                                        optarg);
                                usage_exit(1);
                        }
                        break;
                case 'i':
                        loopcount = 0;
                        break;
                case 's':
                        speed = strtoul(optarg, &tail, 10);
                        if (*tail) speed = -1;

                        switch (speed) {
                        case 1:
                        case 100:
                                speed = RAW1394_ISO_SPEED_100;
                                break;
                        case 2:
                        case 200:
                                speed = RAW1394_ISO_SPEED_200;
                                break;
                        case 4:
                        case 400:
                                speed = RAW1394_ISO_SPEED_400;
                                break;
                        default:
                                fprintf(stderr,
                                        "invalid argument to speed: %s\n",
                                        optarg);
                                usage_exit(1);
                        }
                        break;
                case 'p':
                        which_port = strtoul(optarg, &tail, 10);
                        if (*tail) {
                                fprintf(stderr,
                                        "invalid argument to port: %s\n",
                                        optarg);
                                usage_exit(1);
                        }
                        break;
                case 'h':
                        usage_exit(0);
                case '?':
                        usage_exit(1);
                case 0:
                        break;
                default:
                        abort();
                }
        }

        argv += optind;
        argc -= optind;

        if (argc > 1) {
                fprintf(stderr, "Too many arguments.\n");
                usage_exit(1);
        }

        if (argc) filename = *argv;
}
Beispiel #22
0
int
main(int argc, char *argv[]) {
  char   **av, *label_name, *vol_name, *out_name ;
  int    ac, nargs ;
  int    msec, minutes, seconds,  i  ;
  LABEL  *area ;
  struct timeb start ;
  MRI    *mri,  *mri_seg ;
  Real   xw, yw, zw, xv, yv, zv, val;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_label_vals.c,v 1.16 2015/08/24 18:22:05 fischl Exp $", "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  TimerStart(&start) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (argc < 3)
    usage_exit(1) ;

  vol_name = argv[1] ;
  label_name = argv[2]  ;
  out_name = argv[3] ;

  mri = MRIread(vol_name) ;
  if (!mri)
    ErrorExit(ERROR_NOFILE, "%s: could not read volume from %s",Progname, vol_name) ;
  if (scaleup_flag) {
    float scale, fov_x, fov_y, fov_z  ;

    scale = 1.0/MIN(MIN(mri->xsize, mri->ysize),mri->zsize) ;
    fprintf(stderr, "scaling voxel sizes up by %2.2f\n", scale) ;
    mri->xsize *= scale ;
    mri->ysize *= scale ;
    mri->zsize *= scale ;
    fov_x = mri->xsize * mri->width;
    fov_y = mri->ysize * mri->height;
    fov_z = mri->zsize * mri->depth;
    mri->xend = fov_x / 2.0;
    mri->xstart = -mri->xend;
    mri->yend = fov_y / 2.0;
    mri->ystart = -mri->yend;
    mri->zend = fov_z / 2.0;
    mri->zstart = -mri->zend;

    mri->fov = (fov_x > fov_y ? (fov_x > fov_z ? fov_x : fov_z) : (fov_y > fov_z ? fov_y : fov_z) );
  }

  if (segmentation_flag >= 0) {
    int x, y, z  ;
    VECTOR *v_seg, *v_mri ;
    MATRIX *m_seg_to_mri ;

    v_seg = VectorAlloc(4, MATRIX_REAL) ;
    v_mri = VectorAlloc(4, MATRIX_REAL) ;
    VECTOR_ELT(v_seg, 4) = 1.0 ;
    VECTOR_ELT(v_mri, 4) = 1.0 ;

    mri_seg = MRIread(argv[2]) ;
    if (!mri_seg)
      ErrorExit(ERROR_NOFILE, "%s: could not read volume from %s",Progname, argv[2]) ;
    if (erode) {
      MRI *mri_tmp ;

      mri_tmp = MRIclone(mri_seg, NULL) ;
      MRIcopyLabel(mri_seg, mri_tmp, segmentation_flag) ;
      while (erode-- > 0)
        MRIerode(mri_tmp, mri_tmp) ;
      MRIcopy(mri_tmp, mri_seg) ;
      MRIfree(&mri_tmp) ;
    }

    m_seg_to_mri = MRIgetVoxelToVoxelXform(mri_seg, mri) ;
    for (x = 0  ; x  < mri_seg->width ; x++) {
      V3_X(v_seg) = x ;
      for (y = 0  ; y  < mri_seg->height ; y++) {
        V3_Y(v_seg) = y ;
        for (z = 0  ; z  < mri_seg->depth ; z++) {
          V3_Z(v_seg) = z ;
          if (MRIvox(mri_seg, x, y,  z) == segmentation_flag) {
            MatrixMultiply(m_seg_to_mri, v_seg, v_mri) ;
            xv = V3_X(v_mri) ;
            yv = V3_Y(v_mri) ;
            zv = V3_Z(v_mri) ;
            MRIsampleVolumeType(mri, xv,  yv, zv, &val, SAMPLE_NEAREST);
#if  0
            if (val < .000001) {
              val *= 1000000;
              printf("%f*0.000001\n", val);
            } else
#endif
              if (coords)
                printf("%2.1f %2.1f %2.1f %f\n", xv, yv, zv, val);
              else
                printf("%f\n", val);
          }
        }
      }
    }
    MatrixFree(&m_seg_to_mri) ;
    VectorFree(&v_seg) ;
    VectorFree(&v_mri) ;
  } else {
    if (cras == 1)
      fprintf(stderr,"using the label coordinates to be c_(r,a,s) != 0.\n");

    if (surface_dir) {
      MRI_SURFACE *mris ;
      char fname[STRLEN] ;
      sprintf(fname, "%s/%s.white", surface_dir, hemi) ;
      mris = MRISread(fname) ;
      if (mris == NULL)
        ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s...\n", Progname,fname) ;
      sprintf(fname, "%s/%s.thickness", surface_dir, hemi) ;
      if (MRISreadCurvatureFile(mris, fname) != NO_ERROR)
        ErrorExit(ERROR_BADPARM, "%s: could not read thickness file %s...\n", Progname,fname) ;

      if (annot_prefix)   /* read an annotation in and print vals in it */
      {
#define MAX_ANNOT 10000
        int   vno, annot_counts[MAX_ANNOT], index ;
        VERTEX *v ;
        Real  xw, yw, zw, xv, yv, zv, val ;
        float annot_means[MAX_ANNOT] ;
        FILE  *fp ;

        memset(annot_means, 0, sizeof(annot_means)) ;
        memset(annot_counts, 0, sizeof(annot_counts)) ;
        if (MRISreadAnnotation(mris, label_name) != NO_ERROR)
          ErrorExit(ERROR_BADPARM, "%s: could not read annotation file %s...\n", Progname,fname) ;
        if (mris->ct == NULL)
          ErrorExit(ERROR_BADPARM, "%s: annot file does not contain a color table, specifiy one with -t ", Progname);
        for (vno = 0 ; vno < mris->nvertices ; vno++) {
          v = &mris->vertices[vno] ;
          if (v->ripflag)
            continue ;
          CTABfindAnnotation(mris->ct, v->annotation, &index) ;
          if (index >= 0 && index < mris->ct->nentries) {
            annot_counts[index]++ ;
            xw = v->x + v->curv*.5*v->nx ;
            yw = v->y + v->curv*.5*v->ny ;
            zw = v->z + v->curv*.5*v->nz ;
            if (cras == 1)
              MRIworldToVoxel(mri, xw, yw,  zw, &xv, &yv, &zv) ;
            else
              MRIsurfaceRASToVoxel(mri, xw, yw, zw, &xv, &yv, &zv);
            MRIsampleVolume(mri, xv, yv, zv, &val) ;
            annot_means[index] += val ;
            sprintf(fname, "%s-%s-%s.dat", annot_prefix, hemi, mris->ct->entries[index]->name) ;
            fp = fopen(fname, "a") ;
            fprintf(fp, "%f\n", val) ;
            fclose(fp) ;
          }
        }
      }
      else  /* read label in and print vals in it */
      {
        area = LabelRead(NULL, label_name) ;
        if (!area)
          ErrorExit(ERROR_NOFILE, "%s: could not read label from %s",Progname, label_name) ;

      }
    } else {
      area = LabelRead(NULL, label_name) ;
      if (!area)
        ErrorExit(ERROR_NOFILE, "%s: could not read label from %s",Progname, label_name) ;

      for (i = 0 ;  i  < area->n_points ; i++) {

        xw =  area->lv[i].x ;
        yw =  area->lv[i].y ;
        zw =  area->lv[i].z ;
        if (cras == 1)
          MRIworldToVoxel(mri, xw, yw,  zw, &xv, &yv, &zv) ;
        else
          MRIsurfaceRASToVoxel(mri, xw, yw, zw, &xv, &yv, &zv);
        MRIsampleVolumeType(mri, xv,  yv, zv, &val, SAMPLE_NEAREST);
#if 0
        if (val < .000001) {
          val *= 1000000;
          printf("%f*0.000001\n", val);
        } else
#endif
          printf("%f\n", val);
      }
    }
  }
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;

  if (DIAG_VERBOSE_ON)
    fprintf(stderr, "label value extractiong took %d minutes and %d seconds.\n",
            minutes, seconds) ;

  exit(0) ;
  return(0) ;
}
Beispiel #23
0
int
main (int argc, char * argv [])
{	RENDER render =
	{	NULL, NULL, NULL,
		0, 0,				/* width, height */
		true, false, false, /* border, log_freq, gray_scale */
		0.0, 0.0, 0.0,		/* {min,max,fft}_freq */
		KAISER,
		SPEC_FLOOR_DB
		} ;
	int k ;

	if (argc < 5)
		usage_exit (argv [0], 0) ;

	for (k = 1 ; k < argc - 4 ; k++)
	{	double fval ;

		if (sscanf (argv [k], "--dyn-range=%lf", &fval) == 1)
		{	render.spec_floor_db = -1.0 * fabs (fval) ;
			continue ;
			}

		if (strcmp (argv [k], "--no-border") == 0)
		{	render.border = false ;
			continue ;
			} ;

		if (strcmp (argv [k], "--log-freq") == 0)
		{	render.log_freq = true ;
			continue ;
			} ;

		if (sscanf (argv [k], "--min-freq=%lf", &fval) == 1)
		{	if (fval < 0.0)
			{	printf ("--min-freq cannot be negative.\n") ;
				exit (1) ;
				} ;
			render.min_freq = fval ;
			continue ;
			}

		if (sscanf (argv [k], "--max-freq=%lf", &fval) == 1)
		{	render.max_freq = fabs (fval) ;
			continue ;
			}

		if (sscanf (argv [k], "--fft-freq=%lf", &fval) == 1)
		{	if (fval <= 0.0)
			{	printf ("--fft-freq must be positive.\n") ;
				exit (1) ;
				} ;
			render.fft_freq = fabs (fval) ;
			continue ;
			}

		if (sscanf (argv [k], "--dyn-range=%lf", &fval) == 1)
		{	render.spec_floor_db = -1.0 * fabs (fval) ;
			continue ;
			}

		if (strcmp (argv [k], "--gray-scale") == 0)
		{	render.gray_scale = true ;
			continue ;
			} ;

		if (strcmp (argv [k], "--rectangular") == 0)
		{	render.window_function = RECTANGULAR ;
			continue ;
			} ;

		if (strcmp (argv [k], "--kaiser") == 0)
		{	render.window_function = KAISER ;
			continue ;
			} ;

		if (strcmp (argv [k], "--nuttall") == 0)
		{	render.window_function = NUTTALL ;
			continue ;
			} ;

		if (strcmp (argv [k], "--hann") == 0)
		{	render.window_function = HANN ;
			continue ;
			} ;

		printf ("\nError : Bad command line argument '%s'\n", argv [k]) ;
		usage_exit (argv [0], 1) ;
		} ;

	render.sndfilepath = argv [k] ;
	render.width = parse_int_or_die (argv [k + 1], "width") ;
	render.height = parse_int_or_die (argv [k + 2], "height") ;
	render.pngfilepath = argv [k + 3] ;

	render.filename = strrchr (render.sndfilepath, '/') ;
	render.filename = (render.filename != NULL) ? render.filename + 1 : render.sndfilepath ;

	render_sndfile (&render) ;

	return 0 ;
} /* main */
int
main(int argc, char *argv[])
{
  char         **av, surf_fname[STRLEN], *template_fname, *hemi, *sphere_name,
  *cp, *subject, fname[STRLEN] ;
  int          ac, nargs, ino, sno, nbad = 0, failed, n,nfields;
  VERTEX *v;
  VALS_VP *vp;
  MRI_SURFACE  *mris ;
  MRI_SP       *mrisp, /* *mrisp_aligned,*/ *mrisp_template ;
  INTEGRATION_PARMS parms ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option
          (argc, argv,
           "$Id: mris_make_template.c,v 1.27 2011/03/02 00:04:33 nicks Exp $",
           "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  memset(&parms, 0, sizeof(parms)) ;
  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;
  /* setting default values for vectorial registration */
  setParms(&parms);

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++)
  {
    nargs = get_option(argc, argv,&parms) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (argc < 5) usage_exit() ;

  /* multiframe registration */
  if (multiframes) parms.flags |= IP_USE_MULTIFRAMES;

  if (!strlen(subjects_dir))  /* not specified on command line*/
  {
    cp = getenv("SUBJECTS_DIR") ;
    if (!cp)
      ErrorExit(ERROR_BADPARM,
                "%s: SUBJECTS_DIR not defined in environment.\n",
                Progname) ;
    strcpy(subjects_dir, cp) ;
  }
  hemi = argv[1] ;
  sphere_name = argv[2] ;
  template_fname = argv[argc-1] ;
  if (1 || !FileExists(template_fname))  /* first time - create it */
  {
    fprintf(stderr, "creating new parameterization...\n") ;
    if (multiframes)
    {
      mrisp_template = MRISPalloc(scale, atlas_size * IMAGES_PER_SURFACE );
      /*    if (no_rot)  /\* don't do rigid alignment *\/ */
      /*     mrisp_aligned = NULL ; */
      /*    else */
      /*     mrisp_aligned = MRISPalloc(scale, PARAM_FRAMES);  */
    }
    else
    {
      mrisp_template = MRISPalloc(scale, PARAM_IMAGES);
      /*    if (no_rot)  /\* don't do rigid alignment *\/ */
      /*     mrisp_aligned = NULL ; */
      /*    else */
      /*     mrisp_aligned = MRISPalloc(scale, PARAM_IMAGES);  */
    }

  }
  else
  {
    fprintf(stderr, "reading template parameterization from %s...\n",
            template_fname) ;
    /* mrisp_aligned = NULL ; */
    mrisp_template = MRISPread(template_fname) ;
    if (!mrisp_template)
      ErrorExit(ERROR_NOFILE, "%s: could not open template file %s",
                Progname, template_fname) ;
  }

  argv += 3 ;
  argc -= 3 ;
  for (ino = 0 ; ino < argc-1 ; ino++)
  {
    failed = 0 ;
    subject = argv[ino] ;
    fprintf(stderr, "\nprocessing subject %s (%d of %d)\n", subject,
            ino+1, argc-1) ;
    sprintf(surf_fname, "%s/%s/surf/%s.%s",
            subjects_dir, subject, hemi, sphere_name) ;
    fprintf(stderr, "reading spherical surface %s...\n", surf_fname) ;
    mris = MRISread(surf_fname) ;
    if (!mris)
    {
      nbad++ ;
      ErrorPrintf(ERROR_NOFILE, "%s: could not read surface file %s",
                  Progname, surf_fname) ;
      exit(1) ;
    }
    if (annot_name)
    {
      if (MRISreadAnnotation(mris, annot_name) != NO_ERROR)
        ErrorExit(ERROR_BADPARM,
                  "%s: could not read annot file %s",
                  Progname, annot_name) ;
      MRISripMedialWall(mris) ;
    }

    MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;
    MRIScomputeMetricProperties(mris) ;
    MRISstoreMetricProperties(mris) ;

    if (Gdiag & DIAG_WRITE)
    {
      char *cp1 ;

      FileNameOnly(template_fname, fname) ;
      cp = strchr(fname, '.') ;
      if (cp)
      {
        cp1 = strrchr(fname, '.') ;
        if (cp1 && cp1 != cp)
          strncpy(parms.base_name, cp+1, cp1-cp-1) ;
        else
          strcpy(parms.base_name, cp+1) ;
      }
      else
        strcpy(parms.base_name, "template") ;
      sprintf(fname, "%s.%s.out", hemi, parms.base_name);
      parms.fp = fopen(fname, "w") ;
      printf("writing output to '%s'\n", fname) ;
    }

    /* multiframe registration */
    if (multiframes)
    {
      nfields=parms.nfields;

      for ( n = 0; n < mris->nvertices ; n++) /* allocate the VALS_VP
                                                                 structure */
      {
        v=&mris->vertices[n];
        vp=calloc(1,sizeof(VALS_VP));
        vp->nvals=nfields;
        vp->orig_vals=(float*)malloc(nfields*sizeof(float)); /* before
                                                                blurring */
        vp->vals=(float*)malloc(nfields*sizeof(float));     /* values used by
                                                               MRISintegrate */
        v->vp=(void*)vp;
      }

      /* load the different fields */
      for (n = 0 ; n < parms.nfields ; n++)
      {
        if (parms.fields[n].name != NULL)
        {
          sprintf(surf_fname, "%s/%s/%s/%s.%s", subjects_dir,
                  subject, overlay_dir, hemi, parms.fields[n].name) ;
          printf("reading overlay file %s...\n", surf_fname) ;
          if (MRISreadValues(mris, surf_fname) != NO_ERROR)
            ErrorExit(ERROR_BADPARM, "%s: could not read overlay file %s",
                      Progname, surf_fname) ;
          MRIScopyValuesToCurvature(mris) ;
        }
        else if (ReturnFieldName(parms.fields[n].field))
        {
          /* read in precomputed curvature file */
          sprintf(surf_fname, "%s/%s/surf/%s.%s", subjects_dir,
                  subject, hemi, ReturnFieldName(parms.fields[n].field)) ;
          // fprintf(stderr,"\nreading field %d from %s(type=%d,frame=%d)\n",parms.fields[n].field,surf_fname,parms.fields[n].type,parms.fields[n].frame);
          if (MRISreadCurvatureFile(mris, surf_fname) != NO_ERROR)
          {
            fprintf(stderr,"\n\nXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n");
            fprintf(stderr, "%s: could not read curvature file '%s'\n",
                    Progname, surf_fname) ;
            failed = 1;
            break;
          }
        }
        else
        {                       /* compute curvature of surface */
          sprintf(surf_fname, "%s/%s/surf/%s.%s", subjects_dir,
                  subject, hemi, surface_names[parms.fields[n].field]) ;
          /*if(parms.fields[n].field==0)
           sprintf(fname, "inflated") ;
           else
           sprintf(fname, "smoothwm") ;*/
          //fprintf(stderr,"\ngenerating field %d(type=%d,frame=%d) (from %s)\n",parms.fields[n].field,parms.fields[n].type,parms.fields[n].frame,surf_fname);
          //     MRISsaveVertexPositions(mris, TMP_VERTICES) ;
          if (MRISreadVertexPositions(mris, surf_fname) != NO_ERROR)
          {
            fprintf(stderr,"\n\nXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n");
            ErrorPrintf(ERROR_NOFILE, "%s: could not read surface file %s",
                        Progname, surf_fname) ;
            fprintf(stderr,"setting up correlation coefficient to zero\n");
            parms.fields[n].l_corr=parms.fields[n].l_pcorr=0.0;
            failed=1;
            break;
          }

          if (nbrs > 1) MRISsetNeighborhoodSize(mris, nbrs) ;
          MRIScomputeMetricProperties(mris) ;
          MRIScomputeSecondFundamentalForm(mris) ;
          MRISuseMeanCurvature(mris) ;
          MRISaverageCurvatures(mris, navgs) ;
          MRISrestoreVertexPositions(mris, CANONICAL_VERTICES) ;
        }
        /*    if(parms.fields[n].field!=SULC_CORR_FRAME)*/
        MRISnormalizeField(mris,parms.fields[n].type,
                           parms.fields[n].which_norm); /* normalize values */
        MRISsetCurvaturesToOrigValues(mris,n);
        MRISsetCurvaturesToValues(mris,n);
      }

      if (failed)
      {
        fprintf(stderr,"\n\nXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n");
        fprintf(stderr,"Subject %s Failed",subject);
        fprintf(stderr,"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n\n");
        /* free cal structure*/
        for ( n = 0; n < mris->nvertices ; n++)
        {
          v=&mris->vertices[n];
          vp=(VALS_VP*)v->vp;
          free(vp->orig_vals);
          free(vp->vals);
          free(vp);
          v->vp=NULL;
        }
        /* free surface */
        MRISfree(&mris);
        /* go onto the next subject */
        continue;
      }
    }

    if (multiframes && (!no_rot))
    { /* rigid body alignment */
      parms.frame_no = 3 ;  /* don't use single field correlation functions */
      parms.l_corr = parms.l_pcorr = 0.0f ;

      parms.mrisp = MRIStoParameterization(mris, NULL, scale, 0) ;
      parms.mrisp_template = mrisp_template ;

      MRISrigidBodyAlignVectorGlobal(mris, &parms, 1.0, 64.0, 8) ;
      if (Gdiag & DIAG_WRITE) MRISwrite(mris, "sphere.rot.global") ;
      MRISrigidBodyAlignVectorLocal(mris, &parms) ;
      if (Gdiag & DIAG_WRITE) MRISwrite(mris, "sphere.rot.local") ;
      MRISPfree(&parms.mrisp) ;
      MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;
    };
    if ((!multiframes) && (!no_rot) && ino > 0)
    { /* rigid body alignment */
      sprintf(surf_fname, "%s/%s/surf/%s.%s",
              subjects_dir, subject, hemi, "sulc") ;
      if (MRISreadCurvatureFile(mris, surf_fname) != NO_ERROR)
      {
        ErrorPrintf(Gerror, "%s: could not read curvature file '%s'\n",
                    Progname, surf_fname) ;
        nbad++ ;
        MRISfree(&mris) ;
        continue ;
      }
      parms.frame_no = 3 ; /* use sulc for rigid registration */
      parms.mrisp = MRIStoParameterization(mris, NULL, scale, 0) ;
      parms.mrisp_template = mrisp_template ;
      parms.l_corr = 1.0f ;

      MRISrigidBodyAlignGlobal(mris, &parms, 1.0, 64.0, 8) ;
      if (Gdiag & DIAG_WRITE)
        MRISwrite(mris, "sphere.rot.global") ;
      MRISrigidBodyAlignLocal(mris, &parms) ;
      if (Gdiag & DIAG_WRITE)
        MRISwrite(mris, "sphere.rot.local") ;
      MRISPfree(&parms.mrisp) ;
      MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;
    }

    if (multiframes)
    {
      for (n = 0; n < parms.nfields ; n++)
      {
        MRISsetOrigValuesToCurvatures(mris,n);
        MRISaverageCurvatures(mris, parms.fields[n].navgs) ;
        mrisp = MRIStoParameterization(mris, NULL, scale, 0) ;
        MRISPcombine(mrisp,
                     mrisp_template,
                     parms.fields[n].frame * IMAGES_PER_SURFACE) ;
        MRISPfree(&mrisp) ;
      }
      /* free the VALS_VP structure */
      for ( n = 0; n < mris->nvertices ; n++)
      {
        v=&mris->vertices[n];
        vp=(VALS_VP*)v->vp;
        free(vp->orig_vals);
        free(vp->vals);
        free(vp);
        v->vp=NULL;
      }
      MRISfree(&mris) ;
    }
    else
    {
      for (sno = 0; sno < SURFACES ; sno++)
      {
        if (curvature_names[sno])  /* read in precomputed curvature file */
        {
          sprintf(surf_fname, "%s/%s/surf/%s.%s",
                  subjects_dir, subject, hemi, curvature_names[sno]) ;
          if (MRISreadCurvatureFile(mris, surf_fname) != NO_ERROR)
          {
            nbad++ ;
            ErrorPrintf(Gerror, "%s: could not read curvature file '%s'\n",
                        Progname, surf_fname) ;
            failed = 1 ;
            break ;
          }
          /* the two next lines were not in the original code */
          MRISaverageCurvatures(mris, navgs) ;
          MRISnormalizeCurvature(mris, which_norm) ;
        } else                       /* compute curvature of surface */
        {
          sprintf(surf_fname, "%s/%s/surf/%s.%s",
                  subjects_dir, subject, hemi, surface_names[sno]) ;
          if (MRISreadVertexPositions(mris, surf_fname) != NO_ERROR)
          {
            ErrorPrintf(ERROR_NOFILE, "%s: could not read surface file %s",
                        Progname, surf_fname) ;
            nbad++ ;
            failed = 1 ;
            break ;
          }

          if (nbrs > 1)
            MRISsetNeighborhoodSize(mris, nbrs) ;
          MRIScomputeMetricProperties(mris) ;
          MRIScomputeSecondFundamentalForm(mris) ;
          MRISuseMeanCurvature(mris) ;
          MRISaverageCurvatures(mris, navgs) ;
          MRISrestoreVertexPositions(mris, CANONICAL_VERTICES) ;
          MRISnormalizeCurvature(mris, which_norm) ;
        }
        fprintf(stderr, "computing parameterization for surface %s...\n",
                surf_fname);
        if (failed)
        {
          continue ;
          MRISfree(&mris) ;
        }
        mrisp = MRIStoParameterization(mris, NULL, scale, 0) ;
        MRISPcombine(mrisp, mrisp_template, sno*3) ;
        MRISPfree(&mrisp) ;
      }
      MRISfree(&mris) ;
    }
  }

#if 0
  if (mrisp_aligned)  /* new parameterization - use rigid alignment */
  {
    MRI_SP *mrisp_tmp ;

    if (Gdiag & DIAG_WRITE)
    {
      char *cp1 ;

      FileNameOnly(template_fname, fname) ;
      cp = strchr(fname, '.') ;
      if (cp)
      {
        cp1 = strrchr(fname, '.') ;
        if (cp1 && cp1 != cp)
          strncpy(parms.base_name, cp+1, cp1-cp-1) ;
        else
          strcpy(parms.base_name, cp+1) ;
      }
      else
        strcpy(parms.base_name, "template") ;
      sprintf(fname, "%s.%s.out", hemi, parms.base_name);
      parms.fp = fopen(fname, "w") ;
      printf("writing output to '%s'\n", fname) ;
    }
    for (ino = 0 ; ino < argc-1 ; ino++)
    {
      subject = argv[ino] ;
      if (Gdiag & DIAG_WRITE)
        fprintf(parms.fp, "processing subject %s\n", subject) ;
      fprintf(stderr, "processing subject %s\n", subject) ;
      sprintf(surf_fname, "%s/%s/surf/%s.%s",
              subjects_dir, subject, hemi, sphere_name) ;
      fprintf(stderr, "reading spherical surface %s...\n", surf_fname) ;
      mris = MRISread(surf_fname) ;
      if (!mris)
        ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                  Progname, surf_fname) ;
      MRIScomputeMetricProperties(mris) ;
      MRISstoreMetricProperties(mris) ;
      MRISsaveVertexPositions(mris, ORIGINAL_VERTICES) ;
      sprintf(surf_fname, "%s/%s/surf/%s.%s",
              subjects_dir, subject, hemi, "sulc") ;
      if (MRISreadCurvatureFile(mris, surf_fname) != NO_ERROR)
        ErrorExit(Gerror, "%s: could not read curvature file '%s'\n",
                  Progname, surf_fname) ;
      parms.frame_no = 3 ;
      parms.mrisp = MRIStoParameterization(mris, NULL, scale, 0) ;
      parms.mrisp_template = mrisp_template ;
      parms.l_corr = 1.0f ;

      MRISrigidBodyAlignGlobal(mris, &parms, 1.0, 32.0, 8) ;
      if (Gdiag & DIAG_WRITE)
        MRISwrite(mris, "sphere.rot.global") ;
      MRISrigidBodyAlignLocal(mris, &parms) ;
      if (Gdiag & DIAG_WRITE)
        MRISwrite(mris, "sphere.rot.local") ;
      MRISPfree(&parms.mrisp) ;

#if 0
      /* write out rotated surface */
      sprintf(surf_fname, "%s.rot", mris->fname) ;
      fprintf(stderr, "writing out rigidly aligned surface to '%s'\n",
              surf_fname) ;
      MRISwrite(mris, surf_fname) ;
#endif

      /* now generate new parameterization using the optimal alignment */
      for (sno = 0; sno < SURFACES ; sno++)
      {
        if (curvature_names[sno])  /* read in precomputed curvature file */
        {
          sprintf(surf_fname, "%s/%s/surf/%s.%s",
                  subjects_dir, subject, hemi, curvature_names[sno]) ;
          if (MRISreadCurvatureFile(mris, surf_fname) != NO_ERROR)
            ErrorExit(Gerror, "%s: could not read curvature file '%s'\n",
                      Progname, surf_fname) ;
        } else                       /* compute curvature of surface */
        {
          sprintf(surf_fname, "%s/%s/surf/%s.%s",
                  subjects_dir, subject, hemi, surface_names[sno]) ;
          if (MRISreadVertexPositions(mris, surf_fname) != NO_ERROR)
            ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                      Progname, surf_fname) ;

          if (nbrs > 1)
            MRISsetNeighborhoodSize(mris, nbrs) ;
          MRIScomputeMetricProperties(mris) ;
          MRIScomputeSecondFundamentalForm(mris) ;
          MRISuseMeanCurvature(mris) ;
          MRISaverageCurvatures(mris, navgs) ;
          MRISrestoreVertexPositions(mris, ORIGINAL_VERTICES) ;
          MRISnormalizeCurvature(mris) ;
        }
        fprintf(stderr, "computing parameterization for surface %s...\n",
                surf_fname);
        mrisp = MRIStoParameterization(mris, NULL, scale, 0) ;
        MRISPcombine(mrisp, mrisp_aligned, sno*3) ;
        MRISPfree(&mrisp) ;
      }
      MRISfree(&mris) ;
    }

    if (Gdiag & DIAG_WRITE)
      fclose(parms.fp) ;

    mrisp_tmp = mrisp_aligned ;
    mrisp_aligned = mrisp_template ;
    mrisp_template = mrisp_tmp ;
    MRISPfree(&mrisp_aligned) ;
  }
#endif
  fprintf(stderr,
          "writing updated template with %d subjects to %s...\n",
          argc-1-nbad, template_fname) ;
  MRISPwrite(mrisp_template, template_fname) ;
  MRISPfree(&mrisp_template) ;
  exit(0) ;
  return(0) ;  /* for ansi */
}
/*----------------------------------------------------------------------
  Parameters:

  Description:
  ----------------------------------------------------------------------*/
static int
get_option(int argc, char *argv[]) {
  int  nargs = 0 ;
  char *option ;

  option = argv[1] + 1 ;            /* past '-' */
  if (!stricmp(option, "debug_voxel")) {
    Gx = atoi(argv[2]) ;
    Gy = atoi(argv[3]) ;
    Gz = atoi(argv[4]) ;
    debug_flag = 1;
    nargs = 3 ;
    printf("debugging voxel (%d, %d, %d)...\n", Gx, Gy, Gz) ;
  } else if (!stricmp(option, "scaling")) {
    scale = atof(argv[2]);
    nargs = 1;
    printf("scale input by %g\n", scale);
  } else if (!stricmp(option, "low")) {
    thred_low = atof(argv[2]);
    nargs = 1;
    printf("Lower threshold for histogram scaling is %g\n", thred_low);
  } else if (!stricmp(option, "high")) {
    thred_high = atof(argv[2]);
    nargs = 1;
    printf("Higher threshold for histogram scaling is %g\n", thred_high);
  } else if (!stricmp(option, "noscale")) {
    noscale = 1;
    printf("do not do histogram scaling at output stage\n");
  } else if (!stricmp(option, "autoscale")) {
    autoscale = 1;
    printf("automatically scale output volume histo peak to 110 \n");
  } else if (!stricmp(option, "out_type")) {
    out_type = atoi(argv[2]);
    nargs = 1;
    printf("Output type is %d\n", out_type);
  } else if (!stricmp(option, "out_like") ||
             !stricmp(option, "like")) {
    out_like_fname = argv[2];
    nargs = 1;
    printf("Shape the output like the volume in file %s\n", out_like_fname);
  } else if (!stricmp(option, "transform") ||
             !stricmp(option, "at")) {
    transform_fname = argv[2];
    transform_flag = 1;
    nargs = 1;
    printf("Apply transformation specified by file %s\n", transform_fname);
  } else if (!stricmp(option, "lta_src") ||
             !stricmp(option, "src")
            ) {
    fprintf(stderr, "src volume for the given transform (given by -xform) is %s\n",argv[2]);
    fprintf(stderr, "Reading the src volume...\n");
    lta_src = MRIreadHeader(argv[2], MRI_VOLUME_TYPE_UNKNOWN);
    if (!lta_src) {
      ErrorExit(ERROR_BADPARM, "Could not read file %s\n", argv[2]);
    }
    nargs = 1;
  } else if (!stricmp(option, "lta_dst") ||
             !stricmp(option, "dst")
            ) {
    fprintf(stderr, "dst volume for the transform (given by -xform) is %s\n",argv[2]);
    fprintf(stderr, "Reading the dst volume...\n");

    lta_dst = MRIreadHeader(argv[2], MRI_VOLUME_TYPE_UNKNOWN);

    if (!lta_dst) {
      ErrorExit(ERROR_BADPARM, "Could not read file %s\n", argv[2]);
    }
    nargs = 1;
  } else if (!stricmp(option, "invert_transform") ||
             !stricmp(option, "ait")) {
    transform_fname = argv[2];
    transform_flag = 1;
    invert_flag = 1;
    nargs = 1;
    printf("Apply inversely the transformation specified by file %s\n", transform_fname);
  }
  /*E* Interpolation method.  Default is trilinear, other options are
    nearest, cubic, sinc.  You can say -foo or -interp foo.  For sinc,
    you can say -interp sinc 3 or -interp sinc -hw 3 or -sinc 3 or
    -sinc -hw 3.  Maybe -hw 3 should imply sinc, but right now it
    doesn't.  */

  else if (!stricmp(option, "st") ||
           !stricmp(option, "sample") ||
           !stricmp(option, "sample_type") ||
           !stricmp(option, "interp")) {
    nargs = 1;

    if (!stricmp(argv[2], "bspline"))
      InterpMethod = SAMPLE_BSPLINE;
    else
      InterpMethod = MRIinterpCode(argv[2]) ;

    if (InterpMethod==SAMPLE_SINC) {
      if ((argc<4) || !strncmp(argv[3],"-",1)) /*E* i.e. no sinchalfwindow value supplied */
      {
        printf("using sinc interpolation (default windowwidth is 6)\n");
      } else {
        sinchalfwindow = atoi(argv[3]);
        nargs = 2;
        printf("using sinc interpolation with windowwidth of %d\n", 2*sinchalfwindow);
      }
    } else if (InterpMethod == SAMPLE_BSPLINE) {
      if ((argc<4) || !strncmp(argv[3],"-",1)) /* i.e. no spline-degree value supplied */
      {
        printf("using BSPline interpolation (default Bspline degree is 3)\n");
      } else {
        SplineDegree = atoi(argv[3]);
        nargs = 2;
        printf("using BSpline interpolation with degree of %d\n", SplineDegree);
      }

    }
  } else if (!stricmp(option, "sinc")) {
    InterpMethod = SAMPLE_SINC;
    if ((argc<3) || !strncmp(argv[2],"-",1)) /*E* i.e. no sinchalfwindow value supplied */
    {
      printf("using sinc interpolation (default windowwidth is 6)\n");
    } else {
      sinchalfwindow = atoi(argv[2]);
      nargs = 1;
      printf("using sinc interpolation with windowwidth of %d\n", 2*sinchalfwindow);
    }
  } else if (!stricmp(option, "bspline")) {
    InterpMethod = SAMPLE_BSPLINE;
    if ((argc<3) || !strncmp(argv[2],"-",1)) /*E* i.e. no spline degree supplied */
    {
      printf("using cubic-bspline interpolation \n");
    } else {
      SplineDegree = atoi(argv[2]);
      nargs = 1;
      printf("using B-spline interpolation with degree of %d\n", SplineDegree);
    }
  } else if (!stricmp(option, "sinchalfwindow") ||
             !stricmp(option, "hw")) {
    InterpMethod = SAMPLE_SINC;
    sinchalfwindow = atoi(argv[2]);
    nargs = 1;
    printf("using sinc interpolation with windowwidth of %d\n", 2*sinchalfwindow);
  } else if (!stricmp(option, "trilinear")) {
    InterpMethod = SAMPLE_TRILINEAR;
    printf("using trilinear interpolation\n");
  } else if (!stricmp(option, "cubic")) {
    InterpMethod = SAMPLE_CUBIC;
    printf("using cubic interpolation\n");
  } else if (!stricmp(option, "nearest")) {
    InterpMethod = SAMPLE_NEAREST;
    printf("using nearest-neighbor interpolation\n");
  } else switch (toupper(*option)) {
    case '?':
    case 'U':
      usage_exit(0) ;
      break ;
    default:
      printf("unknown option %s\n", argv[1]) ;
      exit(1) ;
      break ;
    }

  return(nargs) ;
}
Beispiel #26
0
int main (int argc, char* const argv[])
{
    ssize_t bufsz = 0, niter = 0;
    const char *fname = NULL;
    int rc = 0;
    struct test_spec sp;

    static const int MIN_ARGC = 3;

    if (argc < MIN_ARGC) {
        usage_exit (argv[0]);
    }

    (void) memset (&sp, 0, sizeof(sp));
    rc = read_opt (argc, argv, &sp);
    if (rc) return EINVAL;
    /* uses getopt, exposes optind*/

    if (argc < (optind +  2)) { /* expecting at least 2 more arguments */
        (void) fprintf (stderr, "%s: expecting 2 mandatory parameters "
            "after option flags\n", argv[0]);
        usage_exit (argv[0]);
    }

    fname = argv[optind];
    ++optind;

    bufsz = (ssize_t) atol (argv[optind]);
    if ((bufsz < (ssize_t)MIN_BUFSZ) || (bufsz > (ssize_t)MAX_BUFSZ)) {
        (void) fprintf (stderr, "%s: buffer size [%s] must be within [%ld .. %ld] range\n",
            argv[0], argv[optind], (long)MIN_BUFSZ, (long)MAX_BUFSZ);
        return EINVAL;
    }
    sp.len = bufsz;
    ++optind;

    if (0 >= (niter = (ssize_t) atol (argv[optind]))) {
        (void) fprintf (stderr, "%s: invalid value for niter: %s\n",
            argv[0], argv[optind]);
        return EINVAL;
    }
    sp.niter = niter;
    ++optind;


    if (!sp.len)   sp.len     = MIN_BUFSZ;
    if (!sp.incr)  sp.incr    = MIN_INCR;
    if (!sp.nincr) sp.nincr   = MIN_NINCR;

    if (sp.num_chunks >= sp.len) {
        (void) fprintf (stderr, "%s: number of chunks (-U option) [%ld] "
            "should not exceed buffer size [%ld]\n", argv[0],
            (long)sp.num_chunks, (long)sp.len);
        return EINVAL;
    }

    setbuf (stdout, NULL);
    rc = run_odsync (fname, &sp);

    return rc;
}
Beispiel #27
0
void die(const char *fmt, ...) {
  LOG_ERROR(NULL);
  usage_exit();
}
int main(int argc, char *argv[])
{
  char **av, *surf_name, *out_prefix, *fname;

  int nargs, ac, i, nsubjects, total, index;

  double scalar, std, tmp, maxV, minV, meanV;

  MRI *SrcVals[2], *AvgVals;

  MRI_SURFACE *BaseSurf;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mris_diff_on_surface.c,v 1.3 2011/03/02 00:04:55 nicks Exp $", "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++)
  {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  /* command line: <surf> <datafile 1> <datafile 2> <output prefix> */

  if (argc != 5)
    usage_exit();

  surf_name = argv[1];
  out_prefix = argv[argc - 1];

  if (srctypestring == NULL || trgtypestring == NULL)
  {
    printf("Please specify both input and output data type!\n");
    usage_exit();
  }

  printf("Reading underlying surface file\n");
  BaseSurf = MRISread(surf_name);
  if (!BaseSurf)
    ErrorExit(ERROR_NOFILE, "%s:could not read surface %s", Progname, surf_name);

  printf("Base surface has %d vertices\n", BaseSurf->nvertices);


  /* Read in the first data file */
  fname = argv[2];
  /* only two data types are supported */
  if (!strcmp(srctypestring,"curv"))
  { /* curvature file */
    if (MRISreadCurvatureFile(BaseSurf, fname) != 0)
    {
      printf("ERROR: reading curvature file\n");
      exit(1);
    }
    SrcVals[0] = MRIcopyMRIS(NULL, BaseSurf, 0, "curv");
  }
  else if (!strcmp(srctypestring,"paint") || !strcmp(srctypestring,"w"))
  {
    MRISreadValues(BaseSurf,fname);
    SrcVals[0] = MRIcopyMRIS(NULL, BaseSurf, 0, "val");
  }
  else
  {
    printf("ERROR: unknown data file format\n");
    exit(1);
  }

  if (SrcVals[0] == NULL)
  {
    fprintf(stderr, "ERROR loading data values from %s\n", fname);
  }

  /* Read in the second data file */
  fname = argv[3];
  /* only two data types are supported */
  if (!strcmp(srctypestring,"curv"))
  { /* curvature file */
    if (MRISreadCurvatureFile(BaseSurf, fname) != 0)
    {
      printf("ERROR: reading curvature file\n");
      exit(1);
    }
    SrcVals[1] = MRIcopyMRIS(NULL, BaseSurf, 0, "curv");
  }
  else if (!strcmp(srctypestring,"paint") || !strcmp(srctypestring,"w"))
  {
    MRISreadValues(BaseSurf,fname);
    SrcVals[1] = MRIcopyMRIS(NULL, BaseSurf, 0, "val");
  }
  else
  {
    printf("ERROR: unknown data file format\n");
    exit(1);
  }

  if (SrcVals[1] == NULL)
  {
    fprintf(stderr, "ERROR loading data values from %s\n", fname);
  }

  if (debugflag)
  {
    for (i=0; i < 2; i++)
    {
      printf("Data%d at vertex %d has value %g\n",i, debugvtx,  MRIFseq_vox(SrcVals[i], debugvtx, 0, 0, 0));
    }
  }

#if 0
  AvgVals = MRIclone(SrcVals[0], NULL);

  if (negflag) /* Add the two data sets */
    AvgVals = MRIadd(SrcVals[0], SrcVals[1], AvgVals);
  else /* Data1 - Data2 */
    AvgVals = MRIsubtract(SrcVals[0], SrcVals[1], AvgVals);
#endif

  AvgVals = MRIcopy(SrcVals[0], NULL);

  if (negflag)
  {
    for (index=0; index < BaseSurf->nvertices; index++)
    {
      MRIFseq_vox(AvgVals, index, 0, 0, 0) =  MRIFseq_vox(SrcVals[0], index, 0, 0, 0) +
                                              MRIFseq_vox(SrcVals[1], index, 0, 0, 0);
    }
  }
  else
  {
    for (index=0; index < BaseSurf->nvertices; index++)
    {
      MRIFseq_vox(AvgVals, index, 0, 0, 0) =  MRIFseq_vox(SrcVals[0], index, 0, 0, 0) -
                                              MRIFseq_vox(SrcVals[1], index, 0, 0, 0);
    }
  }

  maxV = -1000.0;
  minV = 1000.0;
  meanV=0.0;

  for (index=0; index < BaseSurf->nvertices; index++)
  {
    scalar = MRIFseq_vox(AvgVals, index, 0, 0, 0);
    if (maxV < scalar) maxV = scalar;
    if (minV > scalar) minV = scalar;
    meanV += scalar;
  }

  meanV /= BaseSurf->nvertices;

  printf("Output max = %g, min = %g, mean = %g\n", maxV, minV, meanV);

  if (debugflag)
  {
    printf("Output at vertex %d has value %g\n", debugvtx,  MRIFseq_vox(AvgVals, debugvtx, 0, 0, 0));
  }

  if (pathflag)
    sprintf(fname, "%s", out_prefix);
  else
  {
    if (negflag)
      sprintf(fname, "%s.sum.w", out_prefix) ;
    else
      sprintf(fname, "%s.diff.w", out_prefix) ;
  }

  if (!strcmp(trgtypestring,"paint") || !strcmp(trgtypestring,"w"))
  {

    /* This function will remove a zero-valued vertices */
    /* Make sense, since default value is considered as zero */
    /* But it will confuse the processing with matlab! */
    /* So I copy the data to the curv field to force every value is
     *  written out
     */
    /* MRIScopyMRI(BaseSurf, AvgVals, framesave, "val");*/
    /* MRISwriteValues(BaseSurf,fname); */
    MRIScopyMRI(BaseSurf, AvgVals, framesave, "curv");
    MRISwriteCurvatureToWFile(BaseSurf,fname);

  }
  else
  {
    fprintf(stderr, "ERROR unknown output file format.\n");
  }

  /* Free memories */
  MRISfree(&BaseSurf);
  MRIfree(&AvgVals);
  for (i=0; i < 2; i++)
  {
    MRIfree(&SrcVals[i]);
  }

  return 0;
}
int
main(int argc, char *argv[]) {
  TRANSFORM    *transform = NULL ;
  char         **av, fname[STRLEN], *gca_fname, *subject_name, *cp ;
  int          ac, nargs, i, n ;
  int          msec, minutes, seconds, nsubjects ;
  struct timeb start ;
  GCA          *gca ;
  MRI          *mri_parc, *mri_T1, *mri_PD ;
  FILE         *fp ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_ca_tissue_parms.c,v 1.8 2011/03/02 00:04:14 nicks Exp $", "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  TimerStart(&start) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (!strlen(subjects_dir)) /* hasn't been set on command line */
  {
    cp = getenv("SUBJECTS_DIR") ;
    if (!cp)
      ErrorExit(ERROR_BADPARM, "%s: SUBJECTS_DIR not defined in environment",
                Progname);
    strcpy(subjects_dir, cp) ;
    if (argc < 3)
      usage_exit(1) ;
  }


  gca_fname = argv[1] ;
  nsubjects = argc-2 ;
  printf("computing average tissue parameters on %d subject\n",
         nsubjects) ;

  n = 0 ;

  printf("reading GCA from %s...\n", gca_fname) ;
  gca = GCAread(gca_fname) ;

  for (i = 0 ; i < nsubjects ; i++) {
    subject_name = argv[i+2] ;
    printf("processing subject %s, %d of %d...\n", subject_name,i+1,
           nsubjects);
    sprintf(fname, "%s/%s/mri/%s", subjects_dir, subject_name, parc_dir) ;
    if (DIAG_VERBOSE_ON)
      printf("reading parcellation from %s...\n", fname) ;
    mri_parc = MRIread(fname) ;
    if (!mri_parc)
      ErrorExit(ERROR_NOFILE, "%s: could not read parcellation file %s",
                Progname, fname) ;

    sprintf(fname, "%s/%s/mri/%s", subjects_dir, subject_name, T1_name) ;
    if (DIAG_VERBOSE_ON)
      printf("reading co-registered T1 from %s...\n", fname) ;
    mri_T1 = MRIread(fname) ;
    if (!mri_T1)
      ErrorExit(ERROR_NOFILE, "%s: could not read T1 data from file %s",
                Progname, fname) ;

    sprintf(fname, "%s/%s/mri/%s", subjects_dir, subject_name, PD_name) ;
    if (DIAG_VERBOSE_ON)
      printf("reading co-registered T1 from %s...\n", fname) ;
    mri_PD = MRIread(fname) ;
    if (!mri_PD)
      ErrorExit(ERROR_NOFILE, "%s: could not read PD data from file %s",
                Progname, fname) ;


    if (xform_name) {
      /*      VECTOR *v_tmp, *v_tmp2 ;*/

      sprintf(fname, "%s/%s/mri/%s", subjects_dir, subject_name, xform_name) ;
      printf("reading xform from %s...\n", fname) ;
      transform = TransformRead(fname) ;
      if (!transform)
        ErrorExit(ERROR_NOFILE, "%s: could not read xform from %s",
                  Progname, fname) ;
#if 0
      v_tmp = VectorAlloc(4,MATRIX_REAL) ;
      *MATRIX_RELT(v_tmp,4,1)=1.0 ;
      v_tmp2 = MatrixMultiply(lta->xforms[0].m_L, v_tmp, NULL) ;
      printf("RAS (0,0,0) -->\n") ;
      MatrixPrint(stdout, v_tmp2) ;
#endif

      if (transform->type == LINEAR_RAS_TO_RAS) {
        MATRIX *m_L ;
        m_L = ((LTA *)transform->xform)->xforms[0].m_L ;
        MRIrasXformToVoxelXform(mri_parc, mri_T1, m_L,m_L) ;
      }
#if 0
      v_tmp2 = MatrixMultiply(lta->xforms[0].m_L, v_tmp, v_tmp2) ;
      printf("voxel (0,0,0) -->\n") ;
      MatrixPrint(stdout, v_tmp2) ;
      VectorFree(&v_tmp) ;
      VectorFree(&v_tmp2) ;
      test(mri_parc, mri_T1, mri_PD, lta->xforms[0].m_L) ;
#endif
    }
    if (histo_parms)
      GCAhistogramTissueStatistics(gca,mri_T1,mri_PD,mri_parc,transform,histo_parms);
#if 0
    else
      GCAaccumulateTissueStatistics(gca, mri_T1, mri_PD, mri_parc, transform) ;
#endif

    MRIfree(&mri_parc) ;
    MRIfree(&mri_T1) ;
    MRIfree(&mri_PD) ;
  }
  GCAnormalizeTissueStatistics(gca) ;

  if (log_fname) {
    printf("writing tissue parameters to %s\n", log_fname) ;
    fp = fopen(log_fname, "w") ;
    for (n = 1 ; n < MAX_GCA_LABELS ; n++) {
      GCA_TISSUE_PARMS *gca_tp ;

      gca_tp = &gca->tissue_parms[n] ;
      if (gca_tp->total_training <= 0)
        continue ;
      fprintf(fp, "%d  %f  %f\n", n, gca_tp->T1_mean, gca_tp->PD_mean) ;
    }
    fclose(fp) ;
  }

  if (write_flag)
    GCAwrite(gca, gca_fname) ;
  GCAfree(&gca) ;
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("tissue parameter statistic calculation took %d minutes"
         " and %d seconds.\n", minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
int
main (int argc, char **argv)
{	STATE state ;
	SF_INFO sfinfo ;
	char pathname [512], ext [32], *cptr ;
	int ch, double_split ;

	if (argc != 2)
	{	if (argc != 1)
			puts ("\nError : need a single input file.\n") ;
		usage_exit () ;
		} ;

	memset (&state, 0, sizeof (state)) ;
	memset (&sfinfo, 0, sizeof (sfinfo)) ;

	if ((state.infile = sf_open (argv [1], SFM_READ, &sfinfo)) == NULL)
	{	printf ("\nError : Not able to open input file '%s'\n%s\n", argv [1], sf_strerror (NULL)) ;
		exit (1) ;
		} ;

	if (sfinfo.channels < 2)
	{	printf ("\nError : Input file '%s' only has one channel.\n", argv [1]) ;
		exit (1) ;
		} ;

	state.channels = sfinfo.channels ;
	sfinfo.channels = 1 ;

	snprintf (pathname, sizeof (pathname), "%s", argv [1]) ;
	if ((cptr = strrchr (pathname, '.')) == NULL)
		ext [0] = 0 ;
	else
	{	snprintf (ext, sizeof (ext), "%s", cptr) ;
		cptr [0] = 0 ;
		} ;

	printf ("Input file : %s\n", pathname) ;
	puts ("Output files :") ;

	for (ch = 0 ; ch < state.channels ; ch++)
	{	char filename [520] ;

		snprintf (filename, sizeof (filename), "%s_%02d%s", pathname, ch, ext) ;

		if ((state.outfile [ch] = sf_open (filename, SFM_WRITE, &sfinfo)) == NULL)
		{	printf ("Not able to open output file '%s'\n%s\n", filename, sf_strerror (NULL)) ;
			exit (1) ;
			} ;

		printf ("    %s\n", filename) ;
		} ;

	switch (sfinfo.format & SF_FORMAT_SUBMASK)
	{	case SF_FORMAT_FLOAT :
		case SF_FORMAT_DOUBLE :
		case SF_FORMAT_VORBIS :
			double_split = 1 ;
			break ;

		default :
			double_split = 0 ;
			break ;
		} ;

	if (double_split)
		deinterleave_double (&state) ;
	else
		deinterleave_int (&state) ;

	sf_close (state.infile) ;
	for (ch = 0 ; ch < MAX_CHANNELS ; ch++)
		if (state.outfile [ch] != NULL)
			sf_close (state.outfile [ch]) ;

	return 0 ;
} /* main */