-------------------------------------------
 The SubjectTools -> Setup Structural Scans menu
 sets up to convert and average raw data sets
 in preparation for surface reconstruction.
-------------------------------------------
When this panel opens, it scans $subject/mri/orig
for subdirectories and makes of list of them at
the left of the panel.  If there are no subdirs,
the list will be blank.

Select an mri/orig subdir containing a single
scan (typically an AFNI BRIK containing short or
float data) and press the Structual Scan Dir
button.  This configures it as a directory to
convert and possibly average.  At any time, you
can press Unset Dir to ignore a directory.  Unset
Dir doesn't touch anything inside the directory.

To first convert a nifti file to a BRIK, use AFNI
utility 3dcopy:

  3dcopy somefile.nii somefile+orig

The AFNI button can be used to view a selected
input data set (if it is a BRIK).

Now, select a scan or scan file in the combo box
labeled "Image File:", and press READ HEADER.
This should fill in all the fields below.  Verify
that the fields are correct.

CONVERT/AVERAGE

First go to Preferences -> Expert Preferences ->
Conv and verify that "Auto align with AFNI
3dvolreg (-heptic)" is clicked, then OK/Save.

After configuring one or more directories,
press CONVERT/AVERAGE.  This will generate the
following images:

 images: $SUBJECTS_DIR/$name/mri/orig/COR-???
 header: $SUBJECTS_DIR/$name/mri/orig/COR-.info

If the checkbutton at the bottom of the panel
"Generate .mgz output" is clicked, the output
format will instead be:

 images:  $SUBJECTS_DIR/$name/mri/orig.mgz

Back at the Setup Structural Scans panel, after
several scans have been configured, pressing
CONVERT/AVERAGE will first align each scan and
average it before finally converting it to CORdir
or .mgz format.

Headerless data

To read headerless data sets or data sets for
which the header is not recognized, set the Scan
Type to:

  noheadbrik   => headerless 2-byte xyz images
  noheader     => headerless 2-byte xy images
  ignoreheader => read x*y*2 bytes from file end

For slice formats, the "Image Name Format:" field
accepts C-style formats (e.g., zz_%03d.im).

In these cases, the pixel size and slice
thickness has to be entered manually.

High Resolution Surface Reconstruction

Same as above but on the "Other Options:" line,
add "-hires" in order to cause brik2cor to
generate a subsampled-to-0.5mm^3 CORdir (COR-001
to COR-512) or .mgz file.

To read the .mgz output of this step in MGH
tkmedit, add another option, "-zeropixwidth",
which sets the pixel width to 0.0.  This is a
workaround to an MGH tkmedit bug that incorrectly
reads the direction cosines in .mgz files and
quits with a zero determinant (will eventually be
fixed).  No need to add this option for csurf
tkmedit.

The command line program calcimg can be used to
read or reset the pixel width field in .mgz
files:

 calcimg -spacing <im.mgz>            => read
 calcimg -setspacing <1.0> <im.mgz>   => to 1mm

Other useful parameters that can be added to
"Other Options:" is "-prescale <divisor>".  This
will divide the value of each pixel by the
divisor to better scale it into the range of
0-255.  There is also "-floatfac <factor>".
Finally, to stop resampling to 1x1x1mm, use
"-noresamp".  This is useful for post-mortem
reconstructions with sub-1-mm voxels.

=========================
 brik2cor command line
=========================
Use: [convert/resamp brik to 256^3/1mm^3
          or 512^3/0.5mm^3 bytecube]

 brik2cor <in:brik> <out:CORdir/mgzfile> [opts..]

Options: (usu. just -prescale/-p if input *.BRIK)

  -xysize <x> <y>
     (-xy) pix cnt input slices (def:256x256)
  -xfov <mm>
     (-f) slice xFOV (def:256)
  -nslices <n>
     (-z) number input slices (def:160)
  -thick <mm>
     (-t) slice thickness (def:1.0)
  -ori <inner1> <2> <3>
     (-d) inp loop ord: 0=RL,1=LR,2=PA,3=AP,4=IS,5=SI
  -briktype <n>
     (-b) 1=short or 3=float (def:1=short)
  -swap
     (-s) swap shorts (def:no)
  -floatfac <f>
     (-c) multiply (usu. short) brikdata by (def:1.0)
  -prescale <f>
     (-p) divide by before trunc=>byte (def:3.0)
  -offset <int>
     (-o) add after prescale (def:0.0)
  -invert
     (-i) invert image contrast (def:no)
  -nneigh
     (-n) nearest neigh resample (def:trilinear)
  -hires 
     (-h) sample to 512^3 (def:256^3)
  -noresamp
     (-m) ignore HEAD pixsize, set->1.0 (hires->0.5)
  -zeropixwidth
     (-w) mgz outheader spacXYZ->0 MGH tkmedit bug
  -ignorehead
     (-r) requires: xysize/xfov/nslices/thick/[ori]

 Notes:

 outformat by suff: .mgz, else COR (does mkdir)
 reads AFNI BRIK (float or short, auto-detect)
 read barebrik w/opts: xysize/fov/nslices/thick
 order: => [swap] => [prescale] => [offset] =>
         trunc2byte => [inv] => interp
 can't convert non-square in-plane pix

Examples:

 brik2cor zz+orig.BRIK zz -p 4.5

 brik2cor zz+orig.BRIK zz \
    -p 4.5 \
    -r \
    -xy 280 320 \
    -f 224 \
    -z 208 \
    -t 0.8 \
    -d 3 4 1

======================================
Manual import (e.g., PD for skullstrip)
======================================

Example of how a proton density scan could be
manually importing and subsampled to hi-res:

 cd /rawdata
 3dcopy sMA0419-01.nii PD+orig
 brik2cor PD+orig.BRIK PD.mgz -hires -prescale 1.0

==========================
Rarely-used, older options
==========================

Manual Register Before Average

For manual alignment (e.g., for very different
images, partial images) go to Preferences ->
Expert Preferences -> Conv.  Then choose "Manual
align with tkregister" and OK/Save.  Back at the
Setup Structural Scans panel, after several scans
have been configured, pressing CONVERT/AVERAGE
will convert each scan to COR format, flip it if
necessary (see below), start Register possibly
multiple times, and finally, average after
registration is done.

The first Register will start with the first
configured scan as the TARGET and the second scan
as the MOVEABLE.  After manually registering and
saving the matrix (SAVE REG), quit that register
(double-click register interface at upper left).
If there is a third scan, this will start another
Register set up to align the third scan with the
first.

When the last Register is quit, the registered
scans will then be averaged (*don't* click the
purple QuitCONVERT/AVE button or you will kill
the averaging before it finishes--that button
will turn gray again when the averaging is
done).

If the mid-sagittal plane of the first (TARGET)
scan is badly skewed, click "Adjust Target
Scan..." before CONVERT/AVERAGE.  This will bring
up the first scan as both the MOVEABLE and TARGET
allowing you to adjust it before doing any
alignments between scans.

Higher Res Surface Recon by faking 1x1x1mm data

To reconstruct a less-than-1x1x1mm scan as
if it was a 1x1x1mm scan (in order obtain a
higher resolution surface with more vertices and
smaller faces), start with an AFNI brik (or other
x-y-z data brik), READ HEADER, and then use the
following roundabout method to fool FreeSurfer
into thinking the scan is actually 1x1x1mm.
This example is for a 240x320 inplane 0.75mm
x 0.75mm x 0.75mm sagittal Siemens MPRAGE with
208 slices/partitions:

     Scan Type: noheadbrik   [was brik]
   Slice Count: 208          [leave as is]
  Image X Size: 240          [leave as is]
  Image Y Size: 320          [leave as is]
 In Plane (mm): 1.0          [leave as is]
Thickness (mm): 1.0          [leave as is]
 Other Options: -fov 256 -t 1.0 ... [e.g.,-p 2.5]
          Flip: x=>-z  y=>y z=>x

After the surface has been reconstructed, to
use it for standard functional overlays, first
duplicate the subject (to preserve the high
resolution data).  Then resample the 3D data to
1x1x1 by running CONVERT/AVERAGE the standard way
(*without* resetting Scan Type to noheadbrik,
and after removing the -fov and -t entires from
Other Options).  Delete the copied directories
of the other processing stages (T1, brain, wm,
filled) and move the "orig" data set to the
"T1" directory, which is the Target scan for
tkregister when you click Align=>Struct in Setup
Functional Scan Parameters for an Align scan.
Finally, rescale the surfaces to match.  Here is
how to do that with a tcl script. First make a
file TmpTclScript.tcl:

open_window
read_binary_curv
make_lateral_view
set cslope 3.0
redraw
really_scale_brain 0.75 0.75 0.75
redraw
set outsurf $insurf
write_binary_surface
exit              

Then run the tmp tcl script on all 12 surfaces
(example in csh):

#! /bin/csh -f
set name = marty
set tmpscript = TmpTclScript.tcl
foreach hemi ( lh rh )
  foreach surf ( orig smoothwm inflated \
                 white graymid pial )
    tksurfer -${name} $hemi $surf -tcl $tmpscript
  end
end

The supplied script, scalesurfaces, can do
this for all surfaces of a subject.  Remember,
this permanently alters the surface, so you will
typically want to run it on a copy.

The new (copied) subject will now have a higher
resolution surface aligned with a 1x1x1mm
Target scan.  Note that the effective width
of the smoothing kernel for a given number of
Smoothing Steps (in View Functional Data) will
now be reduced.

Input and Output Files (in $SUBUECTS_DIR)


   [for two AFNI BRIKs]

 raw images1:   $name/mri/orig/mp1/scan1+orig.BRIK
 raw images2:   $name/mri/orig/mp2/scan2+orig.BRIK

 output images: $name/mri/orig.mgz
 

   [for two old format Siemens input subdirs]
 
 raw images1:   $name/mri/orig/scan1/165-2-10.ima
 input images1: $name/mri/orig/scan1/COR-???
 input header1: $name/mri/orig/scan1/COR-.info
 input xform1:  $name/mri/orig/scan1/register.dat

 raw images1:   $name/mri/orig/scan1/165-3-171.ima
 input images2: $name/mri/orig/scan2/COR-???
 input header2: $name/mri/orig/scan2/COR-.info
 input xform2:  $name/mri/orig/scan2/register.dat

 output images: $name/mri/orig/COR-???
 output header: $name/mri/orig/COR-.info


If you redo a manual register average, it will
start with the previously saved transformation
matrix.  To redo a manual register average from
scatch, go into each of the raw scan directories
and remove (or move aside) the register.dat
file.

Flipping

N.B.: the following is now rarely required with
AFNI BRIK input since brik2cor properly reads the
ORIENT_SPECIFIC field from a (properly
configured) HEAD file.

At conversion time, the data set can be flipped.
Be cautious since this can mirror-image the data
set (but this is sometimes necessary).  Also,
since there are a large number of possible flips
of a 3D data set (48), it is easy to get
confused.  The data cube can be viewed from 6
different faces times 4 rotations of each face
times 2 enantiomers (non-mirror-image and
mirror-image) = 48.

Typically, this is done after the data set has
already been converted once without any flipping.
Set the view to CORONAL first.  The 3 directions
are defined in the CORONAL view as:

  x => left   -> right
  y => bottom -> top
  z => near   -> far

Then determine which direction you would like
the current x (left-right) to be flipped to.
You can use a negative sign.  For example,
to left right mirror-image a data set, set
the fields like this:

  x => -x
  y => y
  z => z

This should be done for each page/directory.

To flip a sagittal acquired right->left to
coronal, use:

  x => -z
  y => y
  z => x

Data sets can also be interactively flipped by running
tkmedit on the command line and typing:

  flip <[-]{x,y,z}> <[-]{x,y,z}> <[-]{x,y,z}>

at the tcl prompt.

Some flips we have used:

  -> Siemens sagittal -> coronal: -z  y  x
  -> Varian mp axial  -> coronal:  x -z  y
  -> GE FSPGR axial   -> coronal:  x -z -y

