Esempio n. 1
0
int
main(int argc, char *argv[])
{
  char         **av, *in_surf_fname, *out_fname, fname[STRLEN], *cp ;
  int          ac, nargs, msec, err ;
  MRI_SURFACE  *mris ;
  struct timeb then ;
  float        max_dim ;

  char cmdline[CMD_LINE_LEN] ;

  make_cmd_version_string
  (argc, argv,
   "$Id: mris_sphere.c,v 1.57 2011/03/02 00:04:34 nicks Exp $",
   "$Name: stable5 $", cmdline);

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

#ifdef FS_CUDA
  /* print GPU device info */
  MRISCdeviceInfo();
#endif // FS_CUDA

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

  memset(&parms, 0, sizeof(parms)) ;
  parms.dt = .05 ;
  parms.projection = PROJECT_ELLIPSOID ;
  parms.tol = .5 /*1e-1*/ ;
  parms.n_averages = 1024 ;
  parms.min_averages = 0 ;
  parms.l_angle = 0.0 /* L_ANGLE */ ;
  parms.l_area = 0.0 /* L_AREA */ ;
  parms.l_neg = 0.0 ;
  parms.l_dist = 1.0 ;
  parms.l_spring = 0.0 ;
  parms.l_area = 1.0 ;
  parms.l_boundary = 0.0 ;
  parms.l_curv = 0.0 ;
  parms.niterations = 25 ;
  parms.write_iterations = 1000 ;
  parms.a = parms.b = parms.c = 0.0f ;  /* ellipsoid parameters */
  parms.dt_increase = 1.01 /* DT_INCREASE */;
  parms.dt_decrease = 0.99 /* DT_DECREASE*/ ;
  parms.error_ratio = 1.03 /*ERROR_RATIO */;
  parms.integration_type = INTEGRATE_LINE_MINIMIZE ;
  parms.momentum = 0.9 ;
  parms.desired_rms_height = -1.0 ;
  parms.base_name[0] = 0 ;
  parms.Hdesired = 0.0 ;   /* a flat surface */
  parms.nbhd_size = 7 ;
  parms.max_nbrs = 8 ;

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

  parms.scale = scale ;

  if (argc != 3) // catches args beyond the expected two
  {
    usage_exit() ;
  }

  parms.base_dt = base_dt_scale * parms.dt ;
  in_surf_fname = argv[1] ;
  out_fname = argv[2] ;

  printf("%s\n",vcid);
  printf("  %s\n",MRISurfSrcVersion());
  fflush(stdout);

  if (parms.base_name[0] == 0)
  {
    FileNameOnly(out_fname, fname) ;
    cp = strchr(fname, '.') ;
    if (cp)
    {
      strcpy(parms.base_name, cp+1) ;
    }
    else
    {
      strcpy(parms.base_name, "sphere") ;
    }
  }

  mris = MRISread(in_surf_fname) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
              Progname, in_surf_fname) ;

  MRISaddCommandLine(mris, cmdline) ;

  fprintf(stderr, "reading original vertex positions...\n") ;
  if (!FZERO(disturb))
  {
    mrisDisturbVertices(mris, disturb) ;
  }
  if (quick == 0)
  {
    // don't need original properties unless preserving metric
    err = MRISreadOriginalProperties(mris, orig_name) ;
    if(err)
    {
      exit(1);
    }
  }
  if (smooth_avgs > 0)
  {
    MRISsaveVertexPositions(mris, TMP_VERTICES) ;
    MRISrestoreVertexPositions(mris, ORIGINAL_VERTICES) ;
    MRISaverageVertexPositions(mris, smooth_avgs) ;
    MRISsaveVertexPositions(mris, ORIGINAL_VERTICES) ;
    MRISrestoreVertexPositions(mris, TMP_VERTICES) ;
  }

  if (!FZERO(ralpha) || !FZERO(rbeta) || !FZERO(rgamma))
  {
    MRISrotate(mris,mris,RADIANS(ralpha),RADIANS(rbeta),RADIANS(rgamma)) ;
    //                if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
    MRISwrite(mris, "rot") ;
  }
  fprintf(stderr, "unfolding cortex into spherical form...\n");
  if (talairach)
  {
    MRIStalairachTransform(mris, mris) ;
    MRISwrite(mris, "tal") ;
  }

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

    lta = LTAread(xform_fname) ;
    if (lta == NULL)
    {
      ErrorExit(ERROR_NOFILE, "%s: could not load %s", xform_fname) ;
    }
    mri = MRIread(vol_fname) ;
    if (mri == NULL)
    {
      ErrorExit(ERROR_NOFILE, "%s: could not load %s", vol_fname) ;
    }
    transform.type = lta->type ;
    transform.xform = (void *)lta ;
    MRIStransform(mris, mri, &transform, mri) ;
    MRIfree(&mri) ;
    LTAfree(&lta) ;
    MRISwrite(mris, "xfm") ;
  }
#if 0
  max_dim = MAX(abs(mris->xlo), abs(mris->xhi)) ;
  max_dim = MAX(abs(max_dim), abs(mris->ylo)) ;
  max_dim = MAX(abs(max_dim), abs(mris->yhi)) ;
  max_dim = MAX(abs(max_dim), abs(mris->zlo)) ;
  max_dim = MAX(abs(max_dim), abs(mris->zhi)) ;
#else
  max_dim = MAX(abs(mris->xhi-mris->xlo), abs(mris->yhi-mris->ylo)) ;
  max_dim = MAX(max_dim,abs(mris->zhi-mris->zlo)) ;
#endif
  if (max_dim > .75*DEFAULT_RADIUS)
  {
    float ratio = .75*DEFAULT_RADIUS / (max_dim) ;
    printf("scaling brain by %2.3f...\n", ratio) ;
    MRISscaleBrain(mris, mris, ratio) ;
  }

  if (target_radius < 0)
  {
    target_radius = sqrt(mris->total_area / (4*M_PI)) ;
    printf("setting target radius to be %2.3f to match surface areas\n",
           target_radius) ;
  }
  //  MRISsampleAtEachDistance(mris, parms.nbhd_size, parms.max_nbrs) ;
  if (!load && inflate)
  {
    INTEGRATION_PARMS inflation_parms ;

    MRIScenter(mris, mris) ;
    memset(&inflation_parms, 0, sizeof(INTEGRATION_PARMS)) ;
    strcpy(inflation_parms.base_name, parms.base_name) ;
    inflation_parms.write_iterations = parms.write_iterations ;
    inflation_parms.niterations = inflate_iterations ;
    inflation_parms.l_spring_norm = l_spring_norm ;
    inflation_parms.l_spring = inflate_spring ;
    inflation_parms.l_nlarea = inflate_nlarea ;
    inflation_parms.l_area = inflate_area ;
    inflation_parms.n_averages = inflate_avgs ;
    inflation_parms.l_expand = l_expand ;
    inflation_parms.l_tspring = inflate_tspring ;
    inflation_parms.l_sphere = l_sphere ;
    inflation_parms.l_convex = l_convex ;
#define SCALE_UP 2
    inflation_parms.a = SCALE_UP*DEFAULT_RADIUS ;
    inflation_parms.tol = inflate_tol ;
    inflation_parms.integration_type = INTEGRATE_MOMENTUM ;
    inflation_parms.momentum = 0.9 ;
    inflation_parms.dt = inflate_dt ;

    /* store the inflated positions in the v->c? field so that they can
      be used in the repulsive term.
    */
    /*    inflation_parms.l_repulse_ratio = .1 ;*/
    MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;
    if (l_expand > 0)
    {
      MRISexpandSurface(mris, target_radius/2, &inflation_parms, 0, 1) ;
      l_expand = parms.l_expand = 0 ;
    }
    MRIScenter(mris, mris) ;
    mris->x0 = mris->xctr ;
    mris->y0 = mris->yctr ;
    mris->z0 = mris->zctr ;
    MRISinflateToSphere(mris, &inflation_parms) ;
    if (inflation_parms.l_expand > 0)
    {
      inflation_parms.l_expand = 0 ;
      inflation_parms.niterations += (inflate_iterations*.1) ;
      MRISinflateToSphere(mris, &inflation_parms) ;
    }
    MRISscaleBrain(mris, mris, target_radius/(DEFAULT_RADIUS*SCALE_UP)) ;
    parms.start_t = inflation_parms.start_t ;
    MRISresetNeighborhoodSize(mris, nbrs) ;
  }

  if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
  {
    MRISwrite(mris, "before") ;
  }
  MRISprojectOntoSphere(mris, mris, target_radius) ;
  if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
  {
    MRISwrite(mris, "after") ;
  }
  fprintf(stderr,"surface projected - minimizing metric distortion...\n");
  MRISsetNeighborhoodSize(mris, nbrs) ;
  if (quick)
  {
    if (!load)
    {
#if 0
      parms.n_averages = 32 ;
      parms.tol = .1 ;
      parms.l_parea = parms.l_dist = 0.0 ;
      parms.l_nlarea = 1 ;
#endif
      MRISprintTessellationStats(mris, stderr) ;
      MRISquickSphere(mris, &parms, max_passes) ;
    }
  }
  else
  {
    MRISunfold(mris, &parms, max_passes) ;
  }
  if (remove_negative)
  {
    parms.niterations = 1000 ;
    MRISremoveOverlapWithSmoothing(mris,&parms) ;
  }
  if (!load)
  {
    fprintf(stderr, "writing spherical brain to %s\n", out_fname) ;
    MRISwrite(mris, out_fname) ;
  }

  msec = TimerStop(&then) ;
  fprintf(stderr, "spherical transformation took %2.2f hours\n",
          (float)msec/(1000.0f*60.0f*60.0f));
  exit(0) ;
  return(0) ;  /* for ansi */
}
Esempio n. 2
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);
}
Esempio n. 3
0
/*----------------------------------------------------------------------
  Parameters:

  Description:
  ----------------------------------------------------------------------*/
static int
get_option(int argc, char *argv[])
{
  int  nargs = 0 ;
  char *option ;
  
  option = argv[1] + 1 ;            /* past '-' */
  if (!stricmp(option, "dt"))
    {
    }
  else if (!stricmp(option, "debug_voxel"))
    {
      Gx = atoi(argv[2]) ; Gy = atoi(argv[3]) ; Gz = atoi(argv[4]) ;
      nargs = 3 ;
      printf("debugging voxel (%d, %d, %d)\n", Gx, Gy, Gz) ;
    }
  else if (!stricmp(option, "remove"))
    {
      lta = LTAread(argv[2]) ;
      if (lta == NULL)
	ErrorExit(ERROR_NOFILE, "%s: could not read transform from %s\n", Progname, argv[2]) ;
      printf("removing determinant of transform %s\n", argv[2]) ;
      nargs = 1 ;
    }
  else if (!stricmp(option, "tm3d"))
    {
      tm3dfile = 1;
      printf("The input morph originated from a tm3d (mri_cvs_register file).\n") ;
    }
  else switch (toupper(*option))
    {
    case 'A':
      atlas = 1 ;
      printf("outputing in atlas coords\n") ;
      break ;
    case 'W':
      write_areas = 1 ;
      printf("writing area volumes\n") ;
      break ;
    case 'L':
      use_log = 1 ;
      printf("taking log of jacobian values before saving\n") ;
      break ;
    case 'S':
      sigma = atof(argv[2]) ;
      printf("smoothing jacobian volume with sigma=%2.2f\n", sigma) ;
      nargs = 1 ;
      break ;
    case 'Z':
      zero_mean = 1 ;
      use_log = 1 ;
      printf("making log jacobian zero mean\n") ;
      break ;
    case '?':
    case 'U':
      usage_exit(0) ;
      break ;
    default:
      fprintf(stderr, "unknown option %s\n", argv[1]) ;
      exit(1) ;
      break ;
    }
  
  return(nargs) ;
}
Esempio n. 4
0
/* ----------------------------------------------------------
  Name: regio_read_register()
  Reads a registration file.

  subject -- name of subject as found in the data base
  inplaneres -- in-plane resolution
  betplaneres -- between-plane resolution
  intensity -- for the register program
  R - matrix to convert from xyz in COR space to xyz in Volume space,
      ie, xyzVol = R*xyzCOR
  float2int - if the regfile has a line after the matrix, the string
      is passed to float2int_code(), the result of which is passed
      back as float2int. If there is no extra line, FLT2INT_TKREG
      is returned (indicating that the regfile was created by
      tkregister).
  -------------------------------------------------------------*/
int regio_read_register(char *regfile, char **subject, float *inplaneres,
                        float *betplaneres, float *intensity,  MATRIX **R,
                        int *float2int)
{
  FILE *fp;
  char tmp[1000];
  int r,c,n;
  float val;

  if (!stricmp(FileNameExtension(regfile, tmp), "LTA"))
  {
    LTA *lta ;
    printf("regio_read_register: loading lta\n");
    lta = LTAread(regfile) ;
    if(lta == NULL) return(1) ;
    if(lta->subject[0]==0) strcpy(lta->subject, "subject-unknown"); 
    *subject = (char *) calloc(strlen(lta->subject)+2,sizeof(char));
    strcpy(*subject, lta->subject) ;

    *intensity = lta->fscale ;
    *float2int = FLT2INT_ROUND ;
    *inplaneres  = lta->xforms[0].src.xsize ;
    *betplaneres = lta->xforms[0].src.zsize ;
    *R = TransformLTA2RegDat(lta);
    LTAfree(&lta) ;
    return(0) ;
  }

  fp = fopen(regfile,"r");
  if (fp==NULL)
  {
    perror("regio_read_register()");
    fprintf(stderr,"Could not open %s\n",regfile);
    return(1);
  }

  /* subject name */
  n = fscanf(fp,"%s",tmp);
  if (n != 1)
  {
    perror("regio_read_register()");
    fprintf(stderr,"Error reading subject from %s\n",regfile);
    fclose(fp);
    return(1);
  }
  *subject = (char *) calloc(strlen(tmp)+2,sizeof(char));
  sprintf(*subject,"%s",tmp);

  /* in-plane resolution */
  n = fscanf(fp,"%f",inplaneres);
  if (n != 1)
  {
    perror("regio_read_register()");
    fprintf(stderr,"Error reading inplaneres from %s\n",regfile);
    fclose(fp);
    return(1);
  }

  /* between-plane resolution */
  n = fscanf(fp,"%f",betplaneres);
  if (n != 1)
  {
    perror("regio_read_register()");
    fprintf(stderr,"Error reading betplaneres from %s\n",regfile);
    fclose(fp);
    return(1);
  }

  /* intensity*/
  n = fscanf(fp,"%f",intensity);
  if (n != 1)
  {
    perror("regio_read_register()");
    fprintf(stderr,"Error reading intensity from %s\n",regfile);
    fclose(fp);
    return(1);
  }

  *R = MatrixAlloc(4,4,MATRIX_REAL);
  if (*R == NULL)
  {
    fprintf(stderr,"regio_read_register(): could not alloc R\n");
    fclose(fp);
    return(1);
  }

  /* registration matrix */
  for (r=0;r<4;r++)
  {
    for (c=0;c<4;c++)
    {
      n = fscanf(fp,"%f",&val);
      if (n != 1)
      {
        perror("regio_read_register()");
        fprintf(stderr,"Error reading R[%d][%d] from %s\n",r,c,regfile);
        fclose(fp);
        return(1);
      }
      (*R)->rptr[r+1][c+1] = val;
    }
  }

  /* Get the float2int method string */
  n = fscanf(fp,"%s",&tmp[0]);
  fclose(fp);

  if (n == EOF)
    *float2int = FLT2INT_TKREG;
  else
  {
    *float2int = float2int_code(tmp);
    if ( *float2int == -1 )
    {
      printf("ERROR: regio_read_register(): float2int method %s from file %s,"
             " match not found\n",tmp,regfile);
      return(1);
    }
  }

  return(0);
}
/*----------------------------------------------------------------------
            Parameters:

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

  option = argv[1] + 1 ;            /* past '-' */
  StrUpper(option) ;
  if (!stricmp(option, "DIST") || !stricmp(option, "DISTANCE")) {
    parms.l_dist = atof(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "l_dist = %2.2f\n", parms.l_dist) ;
  } else if (!stricmp(option, "DT")) {
    parms.dt = atof(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "dt = %2.2e\n", parms.dt) ;
  } else if (!stricmp(option, "INVERT")) {
    invert_flag = 1 ;
    fprintf(stderr, "inverting transform before writing...\n") ;
  } else if (!stricmp(option, "crop")) {
    check_crop_flag = 1 ;
    nargs = 1 ;
    fprintf(stderr, "checking for cropping....\n") ;
  } else if (!stricmp(option, "nlevels")) {
    parms.max_levels = atoi(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "nlevels = %d\n", parms.max_levels) ;
  } else if (!stricmp(option, "image_size")) {
    IMAGE_SIZE = atoi(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "setting default image size to %d\n", IMAGE_SIZE) ;
  } else if (!stricmp(option, "TOL")) {
    parms.tol = atof(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "tol = %2.2e\n", parms.tol) ;
  } else if (!stricmp(option, "NUM")) {
    num_xforms = atoi(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "finding a total of %d linear transforms\n", num_xforms) ;
  } else if (!stricmp(option, "SCOUT")) {
    parms.scout_flag = 1 ;
    printf("limitting domain of integration to central slices...\n") ;
  } else if (!stricmp(option, "AREA")) {
    parms.l_area = atof(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "l_area = %2.2f\n", parms.l_area) ;
  } else if (!stricmp(option, "WINDOW")) {
    window_size = atof(argv[2]) ;
    fprintf(stderr, "applying Hanning window (R=%2.1f) to images...\n",
            window_size) ;
    nargs = 1 ;
  } else if (!stricmp(option, "NLAREA")) {
    parms.l_nlarea = atof(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "l_nlarea = %2.2f\n", parms.l_nlarea) ;
  } else if (!stricmp(option, "LEVELS")) {
    parms.levels = atoi(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "levels = %d\n", parms.levels) ;
  } else if (!stricmp(option, "INTENSITY") || !stricmp(option, "CORR")) {
    parms.l_intensity = atof(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "l_intensity = %2.2f\n", parms.l_intensity) ;
  } else if (!stricmp(option, "thresh")) {
    thresh_low = atoi(argv[2]) ;
#if 1
    fprintf(stderr, "setting threshold to %d\n", thresh_low) ;
    nargs = 1 ;
#else
    thresh_hi = atoi(argv[3]) ;
    fprintf(stderr, "thresholds set to %d --> %d\n", thresh_low, thresh_hi) ;
    nargs = 2 ;
#endif
  } else if (!stricmp(option, "reduce")) {
    nreductions = atoi(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "reducing input images %d times before aligning...\n",
            nreductions) ;
  } else if (!stricmp(option, "priors")) {
    l_priors = atof(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "using %2.2f as weight for prior term\n", l_priors) ;
  } else if (!stricmp(option, "voxel")) {
    voxel_coords = 1 ;
    fprintf(stderr, "outputting transform in voxel coordinates\n") ;
  } else if (!stricmp(option, "full_res")) {
    full_res = 1 ;
    fprintf(stderr, "outputting full resolution images\n") ;
  } else if (!stricmp(option, "nopca")) {
    nopca = 1 ;
    fprintf(stderr, "disabling pca\n") ;
  } else if (!stricmp(option, "factor")) {
    parms.factor = atof(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "using time step factor of %2.2f\n",parms.factor) ;
  } else switch (*option) {
    case 'X':
      xform_mean_fname = argv[2] ;
      xform_covariance_fname = argv[3] ;
      printf("reading means (%s) and covariances (%s) of xforms\n",
             xform_mean_fname, xform_covariance_fname) ;
      nargs = 2 ;
      break ;
    case 'D':
      tx = atof(argv[2]) ;
      ty = atof(argv[3]) ;
      tz = atof(argv[4]) ;
      nargs = 3 ;
      break ;
    case 'R':
      rxrot = RADIANS(atof(argv[2])) ;
      ryrot = RADIANS(atof(argv[3])) ;
      rzrot = RADIANS(atof(argv[4])) ;
      nargs = 3 ;
      break ;
    case 'T':
      parms.lta = LTAread(argv[2]) ;
      if (!parms.lta)
        ErrorExit(ERROR_BADFILE, "%s: could not read transform file %s",
                  Progname, argv[2]) ;
      nargs = 1 ;
      fprintf(stderr, "using previously computed transform %s\n", argv[2]) ;
      transform_loaded = 1 ;
      break ;
    case 'B':
      blur_sigma = atof(argv[2]) ;
      nargs = 1 ;
      fprintf(stderr, "blurring input image with sigma=%2.3f\n", blur_sigma);
      break ;
    case 'S':
      parms.sigma = atof(argv[2]) ;
      fprintf(stderr, "using sigma=%2.3f as upper bound on blurring.\n",
              parms.sigma) ;
      nargs = 1 ;
      break ;
    case '?':
    case 'U':
      printf("usage: %s <in volume> <template volume> <output transform>\n",
             argv[0]) ;
      exit(1) ;
      break ;
    case 'V':
      var_fname = argv[2] ;
      fprintf(stderr, "reading variance image from %s...\n", var_fname) ;
      nargs = 1 ;
      break ;
    case 'N':
      parms.niterations = atoi(argv[2]) ;
      nargs = 1 ;
      fprintf(stderr, "niterations = %d\n", parms.niterations) ;
      break ;
    case 'W':
      parms.write_iterations = atoi(argv[2]) ;
      nargs = 1 ;
      fprintf(stderr, "write iterations = %d\n", parms.write_iterations) ;
      Gdiag |= DIAG_WRITE ;
      break ;
    case 'M':
      parms.momentum = atof(argv[2]) ;
      nargs = 1 ;
      fprintf(stderr, "momentum = %2.2f\n", parms.momentum) ;
      break ;
    default:
      fprintf(stderr, "unknown option %s\n", argv[1]) ;
      exit(1) ;
      break ;
    }

  return(nargs) ;
}