#############################################################
------------------------------------------------
 Csurf -- cortical surface program manager
------------------------------------------------
The data base consists of two main directories:

(1) the subjects tree (e.g., /usr/subjects)

  Permanent home of structural MRI data, filtered
  MRI data, and folded, unfolded, and flattened
  surfaces for subjects.  The startup value of
  this must be set with:

    setenv SUBJECTS_DIR <whatever>

  The directory (database) name for each subject
  is typically a first name plus last initial
  (e.g., martys).  The root of the subjects tree
  can be interactively changed with csurf.

(2) functional sessions tree (e.g., /usr/fspace)

  Directory containing individual functional
  sessions.  The startup value of this must be
  set with:

    setenv FUNCTIONALS_DIR <whatever>

  A session is defined as a set of scans taken
  with one subject, in one position, in one RF
  coil.  Individual sessions can be saved
  anywhere.  The name for a session is a date,
  then initials.  The date is in year/month/day
  order so 'ls' will sort a bunch of them
  chronologically (e.g., 000624MS).  The root of
  the sessions tree can be interactively changed
  with csurf.

Each functional session directory (e.g.,
000624MS) is associated with a single subject
directory (e.g., martys).  However, several
different sessions may point to the same
subject.

Csurf generally runs programs from the "scripts"
subdirectory inside the currently selected
session or subject.  A flat file of current
configurations--csurf.dat--is stored there.  It
is read by csurf on entering that session or
subject, and written when you press SAVE or
SAVE/CLOSE on one of the csurf configuration
panels, or when you actually perform an action.
If you remove or move aside the csurf.dat file,
the current configuration of a session or subject
directory will be forgotten, but no data files
will be affected.

The "scripts" directory is also the directory in
which ASCII notes are conventially made.  There
are menu items under File to automatically open
the current subject or session's NOTES file in a
text editor to encourage this practice.

There are two main sets of menu items,
SubjectTools and SessionTools for manipulating
the two main directory trees.  The menu items
within each one are arranged in the order in
which they are normally run.

The general procedure is to first reconstruct a
surface.  Once a surface has been reconstructed,
individual functional sessions can be associated
with it, and statistics can be calculated in 3D
or on the surface, and then rendered.

Log View

As csurf runs command line programs in the
background, it pipes their outputs into a log.
These outputs can be viewed at any time with
Preferences -> View Logs (Alt-l).  There are
three logs--one for medit, one for surfer, and
one for command line programs.  When you quit
csurf, the entire contents of the log is saved
into a file in the current scriptsdir: csurf.log

User Setup

Individual users need at minimum, 4 lines that
look something like this in their .cshrc files:

 setenv CSURF_DIR        /usr/local/FreeSurfer0.8
 setenv SUBJECTS_DIR     ~/subjects
 setenv FUNCTIONALS_DIR  ~/fspace
 source $CSURF_DIR/FreeSurferDefs.csh

Other useful aliases:

 # cd to subj/session scripts dir w/just name
 alias cds 'cd $SUBJECTS_DIR/\!*/scripts; ls'
 alias cdf 'cd $FUNCTIONALS_DIR/\!*/*/scripts; ls'
 alias surfdoc \
  'acroread $CSURF_DIR/docs/FreeSurferManual.pdf'

Per-Vertex File Formats

  The format of some of the per-vertex files has
  changed in more recent distributions of
  FreeSurfer.  There is a new curvature file
  format (*.curv, *.sulc), the area file format
  (*.area) was discontinued (new area files have
  the same format as new curvature).  The value
  file format (e.g., paint output files, *.w) is
  unchanged.  The curvature and area files list
  data for every vertex and contain no vertex
  numbers.  The value files contain a list of
  vertex/value pairs so a subset of vertices may
  be specified.  The byte sizes for the different
  file types are:

  file type             olddist     newdist
  --------------------------------------------
  curv (*.curv,*.sulc)  33{2},..    344{4},..
  area (*.area)         33{4},..    344{4},..
  val (*.w)             23{34},..   23{34},.. 
  --------------------------------------------

Details of file formats (byte sizes in brackets):

  oldcurv
    header:  vertexcnt[3],facecnt[3]
    data:    floatcurv*100[2], ...
  newcurv
    header:  -1[3],vcnt[4],fcnt[4],valspervtx[4]
    data:    floatcurv[4], ...
  oldarea
    header:  vertexcnt[3],facecnt[3]
    data:    floatarea[4], ...
  newarea
    [same as newcurv]
  valfile
    header:  latency[2],vertexcnt[3]
    data:    {vtxnum[3],floatval[4]}, ...
#############################################################

#################################################
#################################################
 This is the default (UCSD) template that appears
 when you select File -> Open Subject NOTES or
 File -> Open Functional NOTES for the first time
 in a subject or functional directory.  This
 template file is stored here:

   $CSURF_DIR/lib/help/csurf/defnotes

 Edit that file to setup site-specific NOTES.
 Also, each user can set up their own default
 NOTES file in:

   ~/.csurfnotes

 The subject- and session-specific (edited by
 user) versions of this file are stored here:

   $session/image/scripts/NOTES
   $subject/scripts/NOTES
#################################################
#################################################


=================================================
Minimal instructions for reconstructing a surface
=================================================
The latest tarball of the UCSD retinotopy-enabled
FreeSurfer (FreeSurfer0.8.tar.gz) is here:

  http://kamares.ucsd.edu/~sereno/csurf/tarballs 

First, decide where you are going to root your
tree of subjects and sessions, and then set these
environment variables to reflect this (the
directories must exist):

  setenv SUBJECTS_DIR /some/place/subjects
  setenv FUNCTIONALS_DIR /some/place/sessions

Now setup your path and start the csurf interface
(you can put the "source ..." line in your .cshrc
to do automatically):

  source \
    /mnt/raid1/sereno/local/etc/FreeSurfer.cshrc
  newdefs
  csurf

To make the highest-quality surface, it is best
to manually align and average two 1x1x1mm MPRAGE
or SPGR scans. To do this, the first step is to
make an new, empty subject (subject "marty" in
the following examples):

  File -> New Subject

Convert the DICOM files to BRIKs, force native
FreeSurfer byte order, make some subdirectories
in the mri/orig subdirectory of the newly made
blank subject, and copy the raw BRIK's into
them:

 cd /raw/s219027
 to3d -prefix spgr1 i*
 forceMSB spgr1+orig.BRIK
 mkdir $SUBJECTS_DIR/marty/mri/orig/spgr1
 cp spgr1+orig.* $SUBJECTS_DIR/marty/mri/orig/spgr1

 cd /raw/s219198
 to3d -prefix spgr2 i*
 forceMSB spgr2+orig.BRIK
 mkdir $SUBJECTS_DIR/marty/mri/orig/spgr2
 cp spgr2+orig.* $SUBJECTS_DIR/marty/mri/orig/spgr2

Now convert the two (or more) scans into the
native COR format and manually align them:

  SubjectTools -> Setup Structural Scans

  [select first scan subdir in list at left]
  Structural Scan Dir
  READ HEADER => check parameters are correct!
  Add "Flip" parameters if scan not coronal:
  -> Thornton sagittal -> coronal: -z y x
  -> fMRI center axial -> coronal: x -z y
  N.B: for fMRI center mp_anat3d scans, add:
    Other Options: -prescale 25

  [select second scan subdir in list at left]
  Structural Scan Dir
  READ HEADER
  Add "Flip" parameters if scan not coronal:
  -> Thornton sagittal -> coronal: -z  y  x
  -> Cent Varian axial -> coronal:  x -z  y
  -> Cent GE axial     -> coronal:  x -z -y

  N.B: for fMRI center mp_anat3d scans, add:
    Other Options: -prescale 25

A single 1x1x1 mm mp_anat3d scan can also be used
if you collect 256 slices (16 minutes) (N.B.:
because mp_anat3d is a volume protocol,
collecting more slices -- even slices outside the
brain -- actually improves the signal in the
central slices).

Finally, start up the manual align:

  CONVERT/AVERAGE 

When buttons turn purple in csurf, something is
going on in the background. If you want to kill
whatever is happening, click the purple button.

CONVERT/AVERAGE will convert the scans to COR
(optionally flipping) and eventually put up the
tkregister application which allows you to flip
back and forth between two 3D scans and align one
(the "MOVEABLE") to the other (the "TARGET").
When you are satisfied, then SAVEREG, and quit
the tkregister application. This will cause csurf
to average the two scans and put the result into
the mri/orig directory (viewable with by picking
the "orig" set of 3D images and hitting the
VOLUME button in csurf). If you only use one
scan, the register step will be skipped.

Now you can start up the 'big button'. This takes
about 4 hours to run on a modern Linux machine
(2GHz). It reconstructs the cortical hemispheres
of each hemisphere, unfolds each one, and then
makes a high quality estimate of the pial surface
and the gray/white matter surface.

  SubjectTools -> Process/Create/Fix/Final

When this finishes, take a look at the surfaces
using the SURFACE button in csurf. If things
don't look right, then edit the segmentation:

  SubjectTools -> Edit Segmentation
  SubjectTools -> Create Surface
  [possibly repeat above two if surface bad...]
  SubjectTools -> Fix/Final

Now you may want to make cuts in order to flatten
part of all of the each hemisphere:

  SubjectTools -> Make Full Surface Cuts

or

  SubjectTools -> Make Occip Surface Cuts

After doing this, then flatten both hemisphere
with:

  SubjectTools -> Flatten Surface

This takes about 4 hours per hemisphere (on the
same 2GHz machine).

==============================================
Minimal instructions for retinotopy analysis
==============================================

The cortical surface is typically reconstructed
from several MPRAGE or SPGR scans taken during a
"structural scan" session (above).

Then, on a number of subsequent "functional scan"
days, we collect an "alignment" scan in the same
plane as the set of "functional" scans (but with
higher resolution). The alignment scan is first
rotated into alignment with the original
structural scans from which the surface was made.
Then the registration matrix is copied (using the
interface) into the functional scan directories,
and touched up by directly comparing the
functional scans to the original high resolution
structural scan.

This makes it possible to collect a large amount
of data on single subjects. Here is an example of
how to collect data on mapping visual areas.
Source code and binaries for the "mapper"
retinotopy stimulus program is available here:

  http://kamares.ucsd.edu/~sereno/stim/IRIX
  http://kamares.ucsd.edu/~sereno/stim/MacOSX
  http://kamares.ucsd.edu/~sereno/stim/Linux
  http://kamares.ucsd.edu/~sereno/stim/src

First start up csurf again:

  newdefs
  csurf

Then make a new blank functional session
directory:

  File -> New Functional

This will query you for a subject name (and a
reconstructed surface) that belongs to the person
from which this functional data was collected. It
has to already exist. For the following example,
the functional session is given a name that sorts
chronologically (year/month/day/initials):

  020930MS

Make subdirectories for each functional scan as
well as the alignment scan in a session:

  cd $FUNCTIONALS_DIR/020930MS/image
  mkdir polar eccen mprage

Copy the raw mprage and functional BRIK's and
HEAD's into those directories and run "flipbrik"
on each functional BRIK like this:

  cp /raw/data/mp_anat3d_01+orig.BRIK mprage
  cp /raw/data/mp_anat3d_01+orig.HEAD mprage
  [don't run flipbrik]

  cp /raw/data/spep_#001+orig.BRIK polar
  cp /raw/data/spep_#001+orig.HEAD polar
  flipbrik \
    polar/spep_#001+orig polar/spep_#001+orig

  cp /raw/data/spep_#002+orig.BRIK eccen
  cp /raw/data/spep_#002+orig.HEAD eccen
  flipbrik \
    eccen/spep_#002+orig eccen/spep_#002+orig

Flipbrik changes the internal ordering of the
data in the AFNI BRIK (and updates the HEAD) so
that x rather than y is the fastest changing
index.

Next, strip off the first three time points
(initial blips-off phase correction acquisition
plus first two non-steady-state TR's):

  cd $FUNCTIONALS_DIR/020930MS/polar
  3dTcat -prefix polar spep_#001+orig'[2..$]'

  cd $FUNCTIONALS_DIR/020930MS/eccen
  3dTcat -prefix eccen spep_#002+orig'[2..$]'

Now open the first panel in the
SessionTools set:

  SessionTools -> Setup Align/Funct Scans

select the alignment scan from the list at the
left at the left and declare the scan to be an
alignment scan by hitting the "Align Scan Dir"
button at the top of the panel.

Now configure the alignment scan:

  read header with READ HEADER button
  enter Block Center Offset
  fix anything that looks incorrect

and then rotate and translate it into alignment
with the original scans the surface was made
from:

  ALIGN=>SUBJ (starts tkregister to align ALIGN
                scan to SUBJECT scan)

When you are done with the manual alignment, hit
SAVEREG on tkregister and quit the tkregister
application.

Now configure all of the functional scans by
selecting each one at the left, and declaring
them to be a "Funct Scan Dir", and filling in the
form:

  READ HEADER
  optionally run AFNI motion correction, 3dvolreg
  (select targ scan, targ TR in scan, hit "ALL")
  select alignment scan from the "Same-Plane
    Structural Dir:" combobox
  enter Block Center Offset
  enter distance to search for data perpendicular
    to each vertex (be reasonable)

Now go back to the Align Scan directory and copy
the transformation matrix into all the functional
directories (automatically accounting for the
difference in voxel size) with:

  COPY ALIGN TO ALL FUNCTS

Be sure to verify that the actual transformation
to be performed by PAINT is a good one by
selecting a functional directory and checking the
alignment with:

  FUNCT=>SUBJ (starts tkregister to align FUNCT
                 scan to SUBJECT scan)

To fix a y-shear in the functional image, rotate
30 deg, shrink (scale-down) y, un-rotate 30 deg,
un-shrink (scale-up) y (shrink/un-shrink x for
x-shear). You can copy your refined registration
to all the other currently configured functionals
with:

  CP TO OTHERS

Now, run the Fourier analysis:

  SessionTools -> Calculate 3D Fourier Stats

  enter the number of stimulus cycles (e.g., 8)
  choose eccen or polar phase encode type
    (presets color scales, analysis scripts)
  do the analysis: FOURIER button
  paint the data on the "orig" surface: PAINT

Optionally calculate field sign:

  SessionTools -> Calculate Visual Fieldsign

Open the rendering panel:

  SessionTools -> View Functional Data

  select scan dir to render from list at left
  select surface or patch from "surface:"
    or "patch:" comboboxes
  hit SURFACE-STATS button

If you redo your registration, you need to
re-paint and re-render everything.  If you want
to redo your registration and then re-paint and
re-render, run:

  SessionTools -> Run Batch Process

select Run All Paint Surfaces and Run All
Rendering Panels, and hit Start.  This will open
all the panels of currently configured scans, run
the PAINT button in each one, and then run the
SURFACE-STATS button in each one. In addition, it
will save bitmaps for any folded or flat views
you have configured on View Functional Data
panels.

The Help -> ... menu items have more detailed
information for all the extra panels. You can
never leave too many ASCII notes in:

  File -> Open Subject NOTES
    (in $subject/scripts/NOTES)

  File -> Open Functional NOTES
    (in $session/image/scripts/NOTES)

:-}

marty

#############################################################
------------------------------------------------
 The File -> New Subject menu creates a new
 blank subject and its standard subdirectories
------------------------------------------------
This is the first step in making a new subject
and must be performed before a new functional
session can be made for this subject.  A new
subject directory and a standard set of
subdirectories is created.  The default location
is the current setting of the environment
variable, SUBJECTS_DIR, but a subject can be made
anywhere.

Finding subjects by name is much easier with
csurf if multiple subjects are stored together in
the same SUBJECTS_DIR on a server.  This is
particularly useful for subjects for which
multiple functional sessions are planned.

The standard subject directory structure is:

 SUBJECTS_DIR (root of a subjects database)
     subjectname  (e.g., firstname+initial)
         scripts      (configs, NOTES file)
         mri          (3D MRI data)
             orig         (origscan w/subdirs)
             T1           (bright-normalized)
             brain        (skull-stripped)
             wm           (white-matter only)
             filled       (rh,lh filled)
             tmp
             transforms
         surf         (surface files)
         bem          (stripskull, EEG/MEG)
         morph        (morph to sphere)
         tmp          (send/goto point, etc)

Once the subject has been made, at least two
T1-weighted 1x1x1mm raw scans should be copied
into separate subdirectories of the mri/orig
directory of that subject.  The subdirectories
you make in there can have any name.  For
example:

  $SUBJECTS_DIR/somesubject/mri/orig/mprage1/*
  $SUBJECTS_DIR/somesubject/mri/orig/mprage2/*

The Setup Struct Scans menu scans the mri/orig
directory to find subdirectories, each of which
should contain a single scan, and averages them.
#############################################################
------------------------------------------------
 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 and press the Structual Scan Dir button.
This configures it as a directory to convert
and possibly average.  At any time, you can
press Ignore Dir to unconfigure a directory.
Ignore Dir doesn't touch anything inside the
directory.

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 the the fields are correct.

Simple Conversion

After configuring one or more directories,
press CONVERT/AVERAGE.  This does a simple
average generating the following images:

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

Auto align with AFNI 3dvolreg

For better alignment of routine images, first go
to Preferences -> Expert Preferences -> Conv.
Then choose "Auto align with AFNI 3dvolreg"
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), and average after registration is done.

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.

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

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

(when "Manual align with tkregister" is set), and
enter the pixel size and slice thickness manually.

High Resolution Surface Reconstruction

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 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

At conversion time, the data set can be flipped.
Caution: this can mirror-image the data set
(sometimes necessary).  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

#############################################################
------------------------------------------------
 HOWTO hand pre-normalize an "orig" dataset
------------------------------------------------
In cases where the automatic normalization
results in an eroded-looking brain surface, you
may have to pre-normalize the "orig" data set by
hand, and then re-run the entire process starting
with Process Volume.

Load the "orig" Data Set

First, start up Medit with the "orig" data set.
You may first want to make a copy of the original
"orig":

  cd $SUBJECTS_DIR/marty/mri
  cp -r orig orig-orig

Medit Piecewise Linear Normalization Panel

Hit F3 in the medit tools window to bring up the
extended Medit panel (F2 goes back to the default
view).  The new subpanel on the right allows you
to test and then apply a piecewise linear ramp of
brightness correction factors (ffrac0-3) at four
control points (lim0-3).  For example, if you
click I/S (inferior/superior direction) and set
lim2 => 145, and ffrac2 => 1.2, this means
multiply the brightness value of pixels at
inferior/superior position 145 (0-255) by 1.2.
Thus, if the pixel value was 134 (view pixel
value in upper border of display window) the new
pixel value will be 134 * 1.2 = 161.

There are 4 control points (lim0-3, 0-255 pixel
coords) that can be applied to one of the 3 main
directions in the image: posterior/anterior,
inferior/superior, or right/left.  The correction
factors are linearly interpolated between the
control points, and remain flat beyond the first
and last control points.

Try Test Normalizations using the Back Buffer

The TEST1 button applies the piecewise linear
ramp to a single slice and puts the result into
the back buffer so that you can use COMPARE to
blink between it and the original image.  If you
change any settings, and hit TEST1 again, it will
redo the test normalization with the new
settings.

To make the eventual effect of the normalization
more obvious, it is best to turn on WMTRUNC (with
the low limit set to 90, which is the default for
mri_wmfilter), which truncated the image to black
below 90.

A <Return> in any of the lim? or frac? entries is
the same as hitting TEST1, so you quickly change
the scale factors or control points in small
steps and immediately see the effects.

For example, to brighten a dim superior sagittal
region, set one control point (e.g., lim3) to the
pixel coordinate of the top of the skull (e.g.,
around 210 -- look in the lower entry of each
pair to the right of the CORONAL, SAGITTAL and
HORIZONTAL buttons for the pixel coordinates).
Now set another control point (e.g., lim2) to the
pixel coordinate just inferior to the dimmed
region (that is, where no correction needs to be
applied, for example, around 180).  Turn on
WMTRUNC, set low=90, and gradually increase
ffrac3 above 1.0, hitting a <Return> each time in
ffrac3 to see the effects.  You can use COMPARE
to see what the truncated original looks like.

Normalize the Entire Data Set (front buffer)

Once you are satisfied with your settings, apply
them to all of the images in the front (editable)
buffer of Medit by clicking ALL.  The images have
not yet been saved, so if you want to go back,
quit without saving.

Save the Normalized Images

Finally, to save the modified images into the
$SUBJECTS_DIR/marty/mri/orig directory, hit
SAVEIMG.  You should now re-run the surface
reconstruction from the beginning, starting with
Process Volume.

Tips

You can apply several ramps in succession in
different directions (e.g., superior/inferior,
left/right), by hitting ALL several times (after
the proper setting of lim0-3 and ffrac0-3 for
each direction have are determined in
succession).

N.B.: since ALL replaces the front (editable)
buffer images with the normalized images, hitting
ALL twice with the same settings will apply that
ramp twice.  This is in contrast to the behavior
of TEST1, which applies the ramp just once and
stores (overwrites) the image into the back
buffer with the result.

N.B.: If you leave the COMPARE button set to the
back buffer (depressed) and change the slice, you
will generally see nothing unless you have
already pressed TEST1 for the other slice.  Also,
If you do one TEST1 in CORONAL and change planes
to, say, SAGITTAL with the COMPARE button
depressed, you will only see the single CORONAL
slice in edge view.  To get back to the front
buffer click COMPARE again (till it's raised).

#############################################################
------------------------------------------------
 The Tools -> Process Volume menu item starts a
 four-part background process to prepare the 3-D
 MRI data to make a surface.
------------------------------------------------
(1) Normalize Intensities

The output files written by this procedure are:

 images: $SUBJECTS_DIR/$name/mri/T1/COR-???

(2) Compute Talairach (uses MINC tools)

 xform: $SUBJECTS_DIR/$name/mri/transforms/
                                 talairach.xfm
(3) Strip Skull

A subtessellated icosahedron is expanded shrunk
to reach the surface of the brain using the
normalized data set.  At each point on the
surface a 'core sample' is used to search for the
first black lamina that corresponds to the inner
surface of the inner table of bone in a
T1-weighted scan, while at the same time,
preserving neighbor relations.  Once this surface
is found, it is used to strip the skull off of
the T1 data set.  The output files written by
this procedure are:

 shrinksurf: $SUBJECTS_DIR/$name/bem/brain.tri
 images: $SUBJECTS_DIR/$name/mri/brain/COR-???

Inspect this output to see that no gyri have
been trimmed.  If they have, open Preferences ->
Expert Preferences => RmSkull tab, reduce fzero
and increase fmax, and re-run.

(4) White Matter Filter

An oriented filter is applied to the stripped
data set to 'floss' and 'spackle' small defects.
Filter coefficients are computed for each 5x5x5
volume in order to determine which plane is most
likely to be parallel ot the cortical surface,
and then a modified median filter is applied.
The output files written by this procedure are:

 images: $SUBJECTS_DIR/$name/mri/wm/COR-???
#############################################################
------------------------------------------------
 The "Edit -> Edit Segmentation" menu item
 starts both medit and surfer so that the
 segmented white matter can be edited to
 correct topological defects
------------------------------------------------

Inspect the surface for topological defects or
'wormholes'.  These typically occur along the
midline near the hippocampus and fornix, along
narrow sulci (e.g., calcarine, central), and
where there is only a very thing sheet of white
matter overlying the ventricle in the fundus of
the calcarine sulcus.

To correct a wormhole, first select a vertex on
it in the surface view with a left-click.  Then
click surfer's SEND button to make the medit
slice view to go to the corresponding point (this
work the other way, too, for medit clicks sent to
surfer with medit's SEND PNT button).

Then edit the 'wm' data set with the middle (edit
to white) and right (edit to black) mouse
buttons. The radius of the editing brush is set
with the 'rad' entry.  The 3Dbrush button toggles
between within-slice brush (default) and 3D
brush.  Use the 3D brush with care because you
are editing pixels you can't see.  Brush radius=0
is 1x1x1 mm (Alt-b returns radius to this);
radius=1 is 3x3x1 mm (or 3x3x3 if 3D button), and
so on (Alt-B increases radius by 1).

For small edits, rad=0 is fine; otherwise, a good
default is rad=1.  Large radii (4-7) are useful
for filling the basal ganglia or ventricles.

When all wormholes have been are corrected,
re-run Create Surfaces (for one or both
hemisphere).

To abandon a segmentation but also save it (e.g.,
to start with a new prenormalized data set):

  cd $SUBJECTS_DIR/<somesubject>/mri
  cp -r wm wm1
  cp -r orig orig1

Hints

If the wormhole is not clearly visible at first
in the initial slice view, change the slice plane
before moving the cursor; it is often possible to
see it more clearly this way.

To see black edits: contrast ($fsquash) = 200
                    midpoint ($fthresh) = 0.01

When selecting vertices on a wormhole, you may
have to try several times until you get a vertex
that has an edge in the wormhole itself.  This is
because (1) the body of the wormhole may be
partly under the surface, and (2) clicking only
selects the vertex nearest the viewer.

Touchup extensive edits in another plane to
neaten the inevitably ragged edges due to the
difficulty of editing the same location in
successive slices.

Detailed Instructions and Typical Problems

(1) fornix and hippocampus

First, find a slice containing an extensive view
of the hippocampus (easiest to find initially
with all3views turned on).  Then in SAGITTAL
view, edit out the hippocampus and the fornix.

Start at the anterior hippocampus, working your
way first posteriorly, then superiorly behind the
thalamus, up toward the lateral ventricle,
connecting up with it, and then anteriorly under
the corpus callosum until the fornix disappears
near the septum.  Repeat for the other
hemisphere.  Brush radius of 1 works well.

(2) calcarine sulcus joins occipital ventricle

There is a very thin white matter sheet between
the posterior extension of the lateral ventricles
and the calcarine.  The reconstructed surface
sometimes protrudes through this into the
ventricle, creating a large sub-calcarine
'wormhole'.  Also, a 3 slice-thick 'baffle' can
be put into the posterior lateral ventricle just
after it closes.

(3) ventromedial anterior temporal gyrus detached

Near the anterior end of temporal lobe, just
before it separates from the rest of the brain in
CORONAL view, there is a medioventrally pointing
parahippocampal gyrus that sometimes gets
detached at its base.  This usually only occurs
in a few slices.

(4) fill basal ganglia

Depending on the pulse sequence, the striatum
(caudate/putamen, globus pallidus, claustrum) may
be partly interpreted as gray matter (which it
mostly is!).  To fill striatum efficiently, use a
larger diameter brush (e.g., 10).

(5) small wormholes across sulci

Locate the wormhole in the data set and widen the
sulcus where it occurs.  It is best to do this
for one or two slices in either way from the
problem slice.  Fix Topology gets most of these.
These can occur across medial occipital sulci in
a brain with a markedly crinkled calcarine
sulcus.

(6) fill escapes down optic nerve

The optic nerve is a strand of white matter that
goes into the brain.  Edit it out in 3 coronal
slices just before it enters the brain.

(7) fill escapes into orbits

There is very little CSF between orbitofrontal
cortex and the orbits, and the white matter fill
may escape into the tops of the orbits, which
sometimes remain in the 'brain' image set even
after stripskull.  This is easy to fix.

(8) small posterior orbitofrontal sulci close

There are two thin anterior-posterior sulci in
medial orbitofrontal cortex than often have to be
opened manually.  This is easiest to see in a
CORONAL plane.  However, it is much faster to
edit these sulci in a HORIZONTAL view.

#############################################################
------------------------------------------------
 The Tools -> Create Surface menu item starts a
 six-part background process to create the left
 and right hemisphere cortical surfaces
------------------------------------------------
(1) Fill White Matter

Start a 3-D region growing process from a
starting point within the white matter in order
to generate the starting point for a surface.
The output files written by this procedure are:

 images: $SUBJECTS_DIR/$name/mri/filled/COR-???

(2) Tessellate White Matter

Connect the surfaces of the filled white matter
voxels into a continuous surface.  The output
files written by this procedure are:

 surface: $SUBJECTS_DIR/$name/surf/rh.orig
 surface: $SUBJECTS_DIR/$name/surf/lh.orig

(3) Smooth Right Hemisphere White Matter
(4) Smooth Left Hemisphere White Matter

The reconstructed white matter surface of the
right and left hemispheres is smoothed.  The
output files written by this procedure are:

 surface: $SUBJECTS_DIR/$name/surf/rh.smoothwm
 surface: $SUBJECTS_DIR/$name/surf/lh.smoothwm

(5) Inflate Right Hemisphere
(6) Inflate Left Hemisphere

Inflate the right and left hemisphere surfaces
while attempting to preserve local angles and
area.  The output files written by this procedure
are:

 surface: $SUBJECTS_DIR/$name/surf/rh.inflated
 surface: $SUBJECTS_DIR/$name/surf/lh.inflated

================================================
Binary format (non-topology-corrected) surfaces
================================================
Binary file format:
    [header]
  3bytes: 16777215
  3bytes: number of vertices
  3bytes: number of faces
    [vertex list--implicit vertex numbering]
  2bytes: x[vertex0]*100
  2bytes: y[vertex0]*100
  2bytes: z[vertex0]*100
  ...
    [face list--vertex numbers of corners]
  3bytes: face1: vertex number 1st corner
  3bytes: face1: vertex number 2nd corner
  3bytes: face1: vertex number 3rd corner
  3bytes: face1: vertex number 4th corner
  ...

================================================
Obtaining ASCII representation of a surface
================================================
writing out ASCII representation
of any surface in FreeSurfer (e.g., rh.orig,
lh.smoothwm, etc).

1) COR coordinate system (lower box in tkmedit)

  0-255  Right -> Left
  0-255  Post -> Ant
  0-255  Inf -> Sup

2) Talairach (higher box with decimal point)

  [standard]

3) Surface coordinate system.  Surface coords
    are written to the log (3 numbers, x,y,z,
    after the "x =" ...)--or to tcl prompt if
    you run tksurfer from the command line--when
    you click a surface point (the surface
    normals are also written out "n=").

  0,0,0 in center of 256x256x256 volume
  x    positive -> Right
  y    positive -> Ant
  z    positive -> Sup


To write out ASCII file of x,y,z of points on any
surface (including topology-corrected):

tksurfer -marty rh smoothwm
% set vrmlsurf /tmp/zz.wrl
% write_vrml 0         ;# 0=points

This will write out a long list of of 3-D
coordinates of each vertex in the surface.

To write out ASCII file that also specifies the
vertices that are the corners of each face:

tksurfer -marty rh smoothwm
% set vrmlsurf /tmp/zz.wrl
% write_vrml 1

This will write out 2 concatenated lists.  The
first are the vertex x,y,z coordinates as
before.  This is followed by a list of vertex
number quadruples.  These numbers are the
implicit vertex numbers (followed by a -1).
write_vrml 1 *doesn't* work with topology
corrected surface currently.

To write out vrml 2.0 format files (the current
version read by plugin like Cortona from
parallelgraphics for windows), do the following
before write_vrml:

% set vrml2flag 1   ;# default is 0 => vers1.0

This only currently works for points.

Examples:

-----------------
VRML 1.0 points:
-----------------
#VRML V1.0 ascii
Coordinate3 {
        point [
12.72 -94.53 -32.12,
12.39 -94.58 -32.13,
11.64 -94.64 -32.22,
11.02 -94.43 -32.13,
...
19.78 -24.83 -29.55,
19.68 -25.31 -29.20,
20.87 -26.00 -28.69
        ]
}

-------------------------------------------------
VRML 1.0 surface (won't work w/topology-correct):
-------------------------------------------------
#VRML V1.0 ascii
Coordinate3 {
        point [
8.23 -97.32 -19.20,
7.70 -97.32 -19.19,
7.24 -97.26 -19.22,
...
15.33 62.33 2.21,
14.67 62.38 2.09,
14.19 62.37 2.08
        ]
}
IndexedFaceSet {
        coordIndex [
0, 1, 6, 5, -1,
0, 21, 22, 1, -1,
0, 5, 29, 21, -1,
...
129668, 129672, 129673, 129669, -1,
129669, 129673, 129674, 129670, -1,
129670, 129674, 129675, 129671
        ]
}

-----------------
VRML 2.0 points:
-----------------
#VRML V2.0 utf8
Collision { collide FALSE
children [ Group { children [ Shape {
appearance Appearance { material DEF _DefMat Material { emissiveColor 1 1 1 } }
geometry PointSet { coord Coordinate {
        point [
8.23 -97.32 -19.20,
7.70 -97.32 -19.19,
7.24 -97.26 -19.22,
...
15.33 62.33 2.21,
14.67 62.38 2.09,
14.19 62.37 2.08
        ]
} } } ] } ] }


-----------------
VRML 2.0 surface
-----------------
 => not currently working

#############################################################
------------------------------------------------
 The Tools -> Fix Topology menu item starts a
 four-part background process to create the left
 and right hemisphere cortical surfaces
------------------------------------------------
(1) Quick Sphere Right Hemisphere Surface
(2) Quick Sphere Left Hemisphere Surface

Inflate each hemisphere to an area-preserving
sphere to identify topological defects.  The
output files are:

 outsurf: $SUBJECTS_DIR/$name/surf/rh.qsphere
 outsurf: $SUBJECTS_DIR/$name/surf/lh.qsphere

(3) Fix Topology Right Sphere'd Surface
(4) Fix Topology Left Sphere'd Surface

Remove defects by finding sphere locations that
have more than one layer (e.g., a "handle" or
"wormhole").  Then, cut out these defects and
re-tessellate them.  The output files are:

 surface: $SUBJECTS_DIR/$name/surf/rh.orig
 surface: $SUBJECTS_DIR/$name/surf/lh.orig

These overwrite the originally reconstructed
surfaces.

(5) Re-Smooth Right Hemisphere White Matter
(6) Re-Smooth Left Hemisphere White Matter

The reconstructed white matter surface of the
right and left hemispheres is smoothed.  The
output files written by this procedure are:

 surface: $SUBJECTS_DIR/$name/surf/rh.smoothwm
 surface: $SUBJECTS_DIR/$name/surf/lh.smoothwm

(7) Re-Inflate Right Hemisphere
(8) Re-Inflate Left Hemisphere

Inflate the right and left hemisphere surfaces
while attempting to preserve local angles and
area.  The output files written by this procedure
are:

 surface: $SUBJECTS_DIR/$name/surf/rh.inflated
 surface: $SUBJECTS_DIR/$name/surf/lh.inflated

#############################################################
------------------------------------------------
 The Tools -> Make Final Surface menu item starts
 a two-part background process to create the
 final left and right hemisphere cortical
 surfaces (after removal of topological defects)
------------------------------------------------
(1) Make Final Right Hemisphere Surfaces
(2) Make Final Left Hemisphere Surfaces

The output files written by this procedure are:

 surface: $SUBJECTS_DIR/$name/surf/rh.white
 surface: $SUBJECTS_DIR/$name/surf/rh.graymid
 surface: $SUBJECTS_DIR/$name/surf/rh.pial

 surface: $SUBJECTS_DIR/$name/surf/lh.white
 surface: $SUBJECTS_DIR/$name/surf/lh.graymid
 surface: $SUBJECTS_DIR/$name/surf/lh.pial




























##############################################

##############################################
#define MAX_WHITE             120
#define MAX_BORDER_WHITE      105
#define MIN_BORDER_WHITE       85
#define MIN_GRAY_AT_WHITE_BORDER  70

#define MAX_GRAY               95
#define MIN_GRAY_AT_CSF_BORDER    40
#define MID_GRAY               ((MAX_GRAY + MIN_GRAY_AT_CSF_BORDER) / 2)
#define MAX_GRAY_AT_CSF_BORDER    75
#define MIN_CSF                10
#define MAX_CSF                40

static  int   max_border_white_set = 0,
  min_border_white_set = 0,
  min_gray_at_white_border_set = 0,
  max_gray_set = 0,
  max_gray_at_csf_border_set = 0,
  min_gray_at_csf_border_set = 0,
  min_csf_set = 0,
  max_csf_set = 0 ;

static  float   max_border_white = MAX_BORDER_WHITE,
                min_border_white = MIN_BORDER_WHITE,
                min_gray_at_white_border = MIN_GRAY_AT_WHITE_BORDER,
                max_gray = MAX_GRAY,
                max_gray_at_csf_border = MAX_GRAY_AT_CSF_BORDER,
                min_gray_at_csf_border = MIN_GRAY_AT_CSF_BORDER,
                min_csf = MIN_CSF,
                max_csf = MAX_CSF ;
##############################################

#############################################################
------------------------------------------------
 The SubjectTools -> Process/Create/Fix/Final
 menu item starts twenty-part background process
 to create a default set of RH and LH surfaces 
------------------------------------------------
Shortcut for:

  Preferences -> Don't Ask Overwrite

  Process Volume
  Create Surface
  Fix Surface Topology
  Make Final Surface

This makes a default set of surfaces for both
hemispheres.  The complete set of output files
written by these procedures for the RH are:

 images: $SUBJECTS_DIR/$name/mri/T1/COR-???
 xform: $SUBJECTS_DIR/$name/mri/transforms/###
 shrinksurf: $SUBJECTS_DIR/$name/bem/brain.tri
 images: $SUBJECTS_DIR/$name/mri/brain/COR-???
 images: $SUBJECTS_DIR/$name/mri/wm/COR-???
 images: $SUBJECTS_DIR/$name/mri/filled/COR-???
 surface: $SUBJECTS_DIR/$name/surf/rh.orig
 surface: $SUBJECTS_DIR/$name/surf/rh.smoothwm
 surface: $SUBJECTS_DIR/$name/surf/rh.inflated
 surface: $SUBJECTS_DIR/$name/surf/rh.qsphere
 surface: $SUBJECTS_DIR/$name/surf/rh.orig
 surface: $SUBJECTS_DIR/$name/surf/rh.smoothwm(2)
 surface: $SUBJECTS_DIR/$name/surf/rh.inflated(2)
 surface: $SUBJECTS_DIR/$name/surf/rh.white
 surface: $SUBJECTS_DIR/$name/surf/rh.graymid
 surface: $SUBJECTS_DIR/$name/surf/rh.pial

A corresponding set of surfaces are made for
the LH.

#############################################################
-------------------------------------------------
 The "Edit -> Make Full/Partial Surface Cuts"
 menu item starts up surfer with a medial view
 of the inflated surface in preparation for
 making relaxation cuts
-------------------------------------------------
HOW TO MAKE CUTS FOR A FULL HEMISPHERE FLATTENING
-------------------------------------------------
(1) make relaxation cuts:
      ==> LEFT-CLICK sequence
      ==> open-line cut with CUTLINE
            [repeat above]
      ==> one standard 5-cut set:
  cut 1: medial, along fundus calcarine
  cut 2: amygdala to temporal pole
  cut 3: ant. corpus callosum to frontal pole
  cut 4: anterior cingulate to dorsal convexity
  cut 5: posterior cingulate to dorsal convexity
      ==> extend past planned midline removal

(2) encircle midline region to remove:
      ==> LEFT-CLICK sequence

(3) make closed-line cut
      ==> CUTAREA button

(4) mark region to fill/save
      ==> single LEFT-CLICK 

(5) fill/save marked region
      ==> FILL button

(6) save patch
      ==> patch: WRITE

The default names for the full cortical surfaces
with the midline removed (following instructions
above) are:

 rh.full.patch.3d
 lh.full.patch.3d

Be sure that the surface is completely cut apart
at the point where the relaxation cuts end at the
midline cut-out.  To be safe, it is a good idea
to click on a few vertices on one side of the cut
and do CUTLINE to remove any stray attachments.
This can be verified with the MESH button (check
for even a single stray edge).

-------------------------------------------------
HOW TO MAKE CUTS FOR OCCIPITAL PATCH FLATTENING
-------------------------------------------------
(1) make calcarine sulcus relaxation cut:
      ==> LEFT-CLICK sequence
      ==> open-line cut with CUTLINE

(2) specify cutting plane
      ==> 3 LEFT CLICK's
      ==> for a patch including most of visual:
   click 1: medial, splenium corpus callosum
   click 2: lateral, intraparietal
   click 3: lateral, anterior inferotemporal

(3) mark region to keep
      ==> 1 LEFT CLICK

(4) make the cut
      ==> CUTPLANE button

(5) optional trim around callosum
      ==> LEFT-CLICK sequence
      ==> open-line cut with CUTLINE
            [repeat if necessary]

(6) save patch
      ==> patch: WRITE

The default names for the occipital patches with
a calcarine relaxation cut are:

 rh.occip.patch.3d
 lh.occip.patch.3d

Be sure to check for stray attachments across
the end of the relaxation cut as above.
#############################################################
------------------------------------------------
 The Tools -> Flatten Surface menu item starts
 a two-part background process to create the
 flattened left and right hemisphere cortical
 surfaces (or surface portions)
------------------------------------------------
(1) Flatten Right Hemisphere Surfaces
(2) Flatten Left Hemisphere Surfaces

The output files written by this procedure are:

 surface: $SUBJECTS_DIR/$name/surf/rh.flat
 surface: $SUBJECTS_DIR/$name/surf/lh.flat
#############################################################
------------------------------------------------
 The Tools -> Sphere Surface menu item starts
 a four-part background process to create the
 spherical left and right hemisphere cortical
 surfaces and then registers them to an average
------------------------------------------------
(1) Sphere Right Hemisphere Surface
(2) Sphere Left Hemisphere Surface

The output files written by this procedure are:

 surface: $SUBJECTS_DIR/$name/surf/rh.sphere
 surface: $SUBJECTS_DIR/$name/surf/lh.sphere

(3) Register Right Hemisphere Surface
(4) Register Sphere Left Hemisphere Surface

 surface: $SUBJECTS_DIR/$name/surf/rh.sphere.reg
 surface: $SUBJECTS_DIR/$name/surf/lh.sphere.reg
#############################################################
------------------------------------------------
 Medit -- display and edit MRI slice data
------------------------------------------------
Medit reads one or more series of images and
displays them in coronal, sagittal, horizontal,
or all 3 planes.  The images in the first (edit)
buffer can be edited and saved.  Images read into
the second buffer cannot be edited.  Edits
applied while viewing the second buffer affect
the first buffer (useful when edit buffer has
segmented white matter and second buffer has
original full T1 images).

Medit can also read in a surface and display the
intersection of the surface with the current
slice.  The interface is described from upper
left to lower right.

CORONAL/SAGITTAL/HORIZONTAL button/slider/field

 button:  switch to this view
 slider:  change coronal slice
 slider field:    enter/view slice number
 talairach field: enter/view coord (MNI software)

When switching planes, the new plane will pass
through the current location.  This is the
location of most recent left-click (default at
startup is center).

To move one slice, use the arrow keys or click in
a slider well to the left or right of a slider.

Display parameters (surface/contrast/midpoint)

The "overlay" checkbutton displays functional
data over an anatomical slice image.  The
contrast and threshold of the overlaid data is
controlled by fthr/fslope/fmid fields at the
lower middle right).  This functionality only
supports real data type (not complex data from
phase-encoded experiments) and is not as
well-developed as AFNI data overlays.  It is
accessed by the VOLUME-STATS button at the top of
the SessionTools -> View Functional Data panel.

The "surface" checkbutton toggles whether or not
the intersection of the currently-read-in surface
with the current slice is displayed.

Higher numbers in "contrast" field increase the
steepness of the sigmoid that is multiplied by
the data before display (default contrast=12.0).
The "midpoint" field sets the data number that
appears at half-max brightness.  The units are
0.0-1.0, so a midpoint setting of 0.35 (default)
means that image data that has a value of 0.35 *
255 = 89 will be displayed at half-max (=128).

To see points that you have edited to black
(actually an image value of 1, not 0), set
contrast and midpoint to:

  contrast = 200
  midpoint = 0.01

New contrast and midpoint settings won't be
visible until you change the slice or plane.

SAVEIMGS button

This button saves edited images (COR files) in
the editable buffer to a COR directory named by
the "outim" field.

The tilde (~) in the "outim" (and "surf") entry
field is an abbreviation of the path of the
current subject directory such as:

  /computer/usr2/subjects/marty

You can substitute an absolute path if you want
to save the images somewhere else.  There is no
edit undo; however, you can quit without saving.
Therefore, it is a good idea to save whenever you
are satified so far.

SEND/GOTO PNT

SEND PNT saves the current 3D location of the
cursor while GOTO PNT moves the display (in the
current slice plane view) to a previously saved
3D location (saved in either medit or surfer).
Note that GOTO PNT in medit goes to a 3D location
while GOTO on the surfer panel requires a search
(see Surfer help for details).

Edit Brush Control (rad, 3Dbrush)

The "rad" field sets the radius of the editing
brush.  The default is a one pixel brush.  At
larger radii, the brush is circular.  A radius of
1 is a useful brush size.  By default, the brush
is 2D, which means that it only affects pixels in
the current slice.  The "3Dbrush" checkbutton
toggles back and forth between a 2D and a 3D
brush.  Use the 3D brush with care since you are
editing slices you cannot see.

Editing (middle/right-click)

  LEFT-CLICK    just select a point
  MIDDLE-CLICK  set to white matter (255)
  RIGHT-CLICK   erase (set intensity to 1)

all3views

The "all3views" checkbutton toggles whether one
view is shown or whether 3 views (coronal,
sagittal, and horizontal) as well as a sagittal
maximum intensity projection is shown.  Clicking
in one of the views when "all3views" is selected
causes the other two views to go to the
corresponding point.  Clicking in the maximum
intensity projection view at the lower right
re-centers the 3 views.

3D/surface File Entries

  surf  -- path to surface
  outim -- path where edited images written
  rgb   -- SGI rgb bitmap

WMTRUNC

This button toggles whether the image is
truncated to zero below "low" and above "high".
The truncation is applied to both the editable
view as well as the second buffer if another
dataset has been loaded.  It is useful for
inspecting the images for small brightness ramps
which are often hard to see (because the human
visual system is so good at autonormalization).
It is typically turned on when using the
ramp-correction utilities of the extended
interface (F3), which allows piecewise linear
test correction ramps to be applied to the image
in the second buffer see if the segmentation is
improved before applying the ramps to the entire
data set (see below).

PLANEFILTER

This only works in the CORONAL plane.  It applies
the anisotropic wormhole filter to one slice
(this search 5x5x5 voxel volumes for planar
structures and performs a median filter in the
direction of greatest planarity).  After it has
run (which takes a few seconds), you can view the
different between the truncated and truncated and
filtered data set by using COMPARE.

Overlay display

The "fthr", "fslope", and "fmid" fields have the
same effect as the fthresh, fslope, and fmid
fields on the surfer tools panel.  The only color
scale available is the real-valued heat scale
(blue-cyan, red-yellow).

2nd imagedir field

By clicking READ, the dataset specified in "2nd
imagedir" is read into the second (non-editable)
buffer.  Successive READ's simply replace the
dataset in the non-editable buffer.  The field by
default expects a COR directory that is relative
to:

  $SUBJECTS_DIR/$subject/mri

You can also put an absolute path to a COR
directory into this field.

HISTOGRAM

Only supported on SGI.

SAGMIRR

This makes a mirror-image of the dataset
around the sagittal midline, which is defined
as the plane in the middle of the stack of
slices that are displayed when SAGITTAL is
clicked.

A more general flipping operator is
available from the tcl prompt (flip_corview_xyz),
which allows you to flip an arbitrary
direction into an arbitrary direction
starting from what is displayed in
CORNONAL view.  Thus:

  flip_corview_xyz  x  z  -y

changes the x-direction currently viewed in
CORONAL view to the x-direction in the new data
set, the y-direction in the current view into the
new z-direction, and the current z-direction (the
direction you move when y ou change CORONAL
slice) into the minus y-direction in the new data
set.  This command checks for degenerate flips.

COMPARE

This toggles between the volumes in the two
buffers.  You can edit in the second buffer view;
remember that in this case, edits are applied to
the editable buffer.

Larger F3 Interface (hand normalize)

Hitting F3 in the medit panel expands it (F2 goes
back to the default view).  The new subpanel on
the right allows you to test and then apply a
piecewise linear ramp of brightness correction
factors (ffrac0-3) at four control points
(lim0-3).  See Help -> Hand Pre-Normalize for
more details on how to use this facility.

------------------------------------------------
 Standalone Commandline and Script Operation
------------------------------------------------
tkmedit can also be run as a standalone program
from the command line (as long as SUBJECTS_DIR
and FUNCTIONALS_DIR are set) from the command
line:

Use: tkmedit name imgdir [surf] [-] [-tcl script]
     tkmedit local [-] [-tcl script]

  name: subjectdir name         (in $SUBJECTS_DIR)
imgdir: orig,T1,brain,wm,filled (in $subject/mri)
  surf: e.g., rh.smoothwm       (in $subject/surf)
  dash: disable editing

The program has an embedded tcl interpreter and
most of its functions (including some not exposed
to the medit tools interface, as well as some
that are now obselete...) can be accessed through
it, either interactively at the tcl prompt, %,
that appears in the terminal from which tkmedit
is started, or offline using a tcl script in a
file whose name follows the -tcl option.  If you
include an "exit" at the end of the tcl script,
tksurfer will quit when the script finishes.  You
can find commands available in the tcl
interpreter using "help" or "info":

  % help
  % info command flip*

Here is an example of a small command line tcl
script that reads in the data on the command
line, and then saves a flipped data set into
a new directory:

flip_corview_xyz -y x z
set abs_imstem /subjects/bill/mri/T1-new/COR-
write_images
exit

If you put the commands above into a file
flip.tcl, you could run it like this:

  tkmedit john T1 -tcl flip.tcl

There is a built-in script (mri2mpg.tcl) to make
3 mpg movies (coronal, sagittal, horizontal)
that can be accessed by typing F12 anywhere in
the medit tools interface.  It asks for slice
limits (min,max) in the three slice planes and
dumps the mpegs in $SUBJECTS_DIR/$name/mpg.

#############################################################
-----------------------------------------------
 Register -- interactively register slice data
-----------------------------------------------
Register reads two series of images, a TARGET set
and a MOVEABLE set, and displays them in coronal,
sagittal, horizontal, planes.  The images in the
the TARGET buffer are fixed while the images in
the MOVEABLE buffer can be modified with a linear
transformation--which included rotation,
translation, and stretching.

The goal of register is to generate a 4x4 linear
transformation matrix (register.dat) that can be
used by other programs to paint 3D statistics
made from the MOVEABLE image set onto a 2D
surface made from the TARGET image set.

Transformations (rotations, translations,
stretchings) are applied to the MOVEABLE data set
relative to its current view.  They will be
immediately visible in other planes or other
slices of the MOVEABLE date set.  Rotations take
place around the last left-clicked point.

The image sets are compared to each other by
pressing the COMPARE button.  Once the
registration is satisfactory, it can be saved
with SAVE REG (asks before overwrite).  To go
back to the original registration, quit without
saving and restart (or use READ REG in the
extended interface).

Alignment Strategies

There are two basic alignment strategies
for functional data.

 Functional Scan => Surf Scan
 Functional Scan => Alignment Scan => Surf Scan

In the first, a single repetition from the
functional data set (typically t=0) is directly
registered to the high-resolution structurals
that were used to reconstruct the cortical
surface.  The difficulty with this is that
the functional contrast is low and reversed
relative to the hi-res T1's.

In the second strategy, a T1-weighted alignment
scan taken in the same plane as the functional
scans is first aligned to the hi-res structural
used to make the surface.  The resulting
transformation matrix is then copied onto the
register.dat file in the functional scan
directory.  A direct Functional => Subject
register can then be run to touch up the
alignment (or add shear--see below).

Aligning Two High-Resolution Data Sets

Register can also be used to manually align two
high resolution data sets prior to averaging.
There are automatic algorithms to do this.
Register can help when the two data sets were
collected on different days (perhaps as Alignment
scans), and the subject's neck, jaw, and scalp
are in a different position.

Display Parameters

The default settings for "contrast" (12.0) and
"midpoint" (0.35) increase contrast between gray
and white matter in images normalized using
mri_normalize.

The "fmov" field sets the brightness of the
MOVEABLE images.  This should be set to be
approximately the same as the TARGET image.

The "masktarg" button masks out the part of the
TARGET images that extend beyond the edge of the
MOVEABLE images volume.  This is typically used
for fine adjustments on data sets collected with
a surface coil where the MOVEABLE functional
images cover only a part of the brain and the
size change during COMPARE is distracting.

Tips

If the data sets are roughly aligned, a good
strategy is to adjust the MOVEABLE in coronal
view, change to sagittal and re-adjust, change to
horizontal and re-adjust, and so on.  Change
planes often.

It may be difficult to guess how to transform the
MOVEABLE data set if it is oriented very
differently than the TARGET data set (e.g., the
TARGET image is coronal but the MOVEABLE image
looks like a sideways horizontal slice).  A
simple strategy here is to transform the MOVEABLE
by rotating 90 degrees around a center point, and
then change to another plane.  If the MOVEABLE
still appears to be in the wrong plane, rotate 90
degrees again and change plane again.  Eventually
you will only need an in-plane rotation to
roughly align the data sets.

To get a shearing transformation, use a rotation
combined with stretching.  For example, rotate 30
deg, stretch vertically, rotate back 30 deg, and
finally, shrink vertically.  Don't stretch until
the data sets are well aligned.

Format of register.dat (8 lines, ASCII)

 arthur   [name in subjects database]
 3.0      [pixel size (mm) of MOVEABLE]
 4.0      [slice thickness (mm) of MOVEABLE]
 0.2      [starting brightness of MOVEABLE]
   [transformation matrix]
 9.9915e-01  2.9973e-02 -4.6041e-02  6.5897e-02
 -5.7313e-03 -7.7659e-01 -6.2997e-01 -3.5452e+01
 5.4680e-02 -6.2928e-01  7.7525e-01 -6.6141e+00
 0.0000e+00  0.0000e+00  0.0000e+00  1.0000e+00

Since the pixel size is included in the file, the
homogeneous 4x4 matrix can be directly used for
data sets with different pixel sizes.

Extended Interface

Several levels of interface are available by
typing the following commands while in the
interface window:

ctrl-F1   micro (just rotate/translate)
ctrl-F2   mini  (default, adds stretching)
ctrl-F3   macro (adds read register.dat, sagittal
                   mirror, savergb, blinktime,
                   and SEND and GOTO PNT)

Standalone Operation

Tkregister can also be run as a standalone program
from anywhere in the directory tree from the
command line:

=================================================
Usage:

  tkregister local
    [mov=cwd  targ=impliedCOR]

  tkregister local <abstargdir>
    [mov=cwd  targ=absCORdir]

  tkregister <absmovdir> <abstargdir>
    [mov=abs  targ=absCORdir]

  tkregister <subj> <movdir> <targdir>
    [mov=relCORdir  targ=relCORdir]

  tkregister -mkdefault
  tkregister -readinfo

    [often run in functional subdir]
    [reldirs in $subject/mri, composite path OK]
    [abstargdirs allow cross-subject reg]

Args:

  local       movdir is cwd
  -mkdefault  make default register.dat in cwd
  -readinfo   COR-.info => register/analyse.dat
  <subject>   in subjects database
  <movdir>    moveable (im,bshort,BRIK,brik,COR)
  <targdir>   target (COR only)

Files:

  targ image   COR images--subj db, sess align
  mov image    EPI,alignCOR,subjCOR--analyse.dat
  register.dat mov: subj,pixsz,slicethick,xform
  analyse.dat  mov: aligndir,imformat,slices,x/ysz
  edit.dat     subj/tmp/edit.dat--SEND/GOTO

Options: (at end,=movdir analyse.dat,req:abs=>abs)

  -movformat <str> (-m) movimg format (rel printf)
  -nslices <n>    (-n) num slices moveable
  -reps <n>       (-e) imgs/slice (BRIK offsets)
  -imres <x> <y>  (-i) xsize,ysize moveable images
  -regdat <file>  (-r) else default=./register.dat
  -fslice1 <mm>   (-1) funct/sess offset

Examples:

  tkregister local (str<=loc;analyse/register.dat)
  tkregister local /fspace/9904TS/mprage (CORtarg)
  tkregister /fsp/9904TS/mprage /sub/me/mri/T1
  tkregister /fsp/9904TS/eccen  /sub/me/mri/T1
  tkregister /fsp/9904TS/eccen  /sub/me/mri/mprage
  tkregister marty orig/im1 orig/im2 (str2<=str1)

#############################################################
------------------------------------------------
 Surfer -- display surface and activation data
------------------------------------------------
The tksurfer program is started either by the
SURFACE button on the main csurf panel, by the
SURAFCE-STATS button on the SessionTools -> View
Functional Data panel, or from the command line
(see below).  It reads a surface file, and
optionally, a curvature file, a patch file, a
label file, and one or more functional data files,
and then renders a view of the surface.  The
surfer tools panel is described from upper left to
lower right.

RUN/EDIT/READENV buttons, script entry

The RUN button executes the tcl script that is
currently specified in the "script:" entry field.
A "#" can be used in that field as an abbreviation
for the standard script directory:

  $CSURF_DIR/lib/tcl

The EDIT button opens the current script (or
creates a new file if the named script doesn't
exist) in a text editor.  READENV re-reads the
setenv environment that tksurfer was started with
(arguments following "env" in surfer log).

Two useful standard scripts for analyzing
complex-valued data are phasemovie.tcl and
offsetmovie.tcl.  The phasemovie.tcl script
colors a small range of phases (default 3%) white
and saves a bitmap for each of 50 steps of
varying the phase of the center of the white
stripe between 0 and 2 Pi.  It leaves the color
scale settings intact underneath the moving white
phase contour.  This is essentially an animation
of the contours in the color phasemap.  It makes
small variations in phase more apparent than
color variation alone does.  The offsetmovie.tcl
script, by contrast, changes the angleoffset
value (thus changing the color map) in 25 steps.
This can be used to find the best color map
setting for color wheel data (color scale w1), or
to find the best delay (angleoffset) for two
condition data analyzed with the fourier method
(color scale ht, with complexval and truncphase
checked).  It is hard to interrupt these scripts
once they have been started.

Surface Data File Entries, READ/WRITE Buttons

  curv  -- curv or sulc file (every vertex)
  patch -- flattened subset of a surface
  label -- vertices and vtx numbers
  fieldsign -- fieldsign and fsmask files
  val   -- value file (maybe vertex subset)
  rgb   -- SGI rgb bitmap (write only)

The formats of these files are as follows (bytes
for each file element in brackets):

 curv (binary, every vertex):
   vnum[3],fnum[3],float*100[2], ...

 area (binary, every vertex):
   vnum[3],fnum[3],float[4], ...

 label file (ASCII, vertex subset):
    #!ascii label , from subject marty <CR>
    <labeled-vtx-count> <CR>
    <vnum> <x> <y> <z> <labelvalue> <CR>
    <vnum> <x> <y> <z> <labelvalue> <CR>
    ...

 fieldsign (binary, every vertex):
   fs (fieldsign): vnum[4],float[4], ...
   fm (fssigmask): vnum[4],float[4], ...

 val (binary, maybe vertex subset):
   latency[2],vnum[3],{vtx[3],float[4]}, ...

 new curv (binary, every vertex):
   -1[3],vnum[4],fnum[4],npervtx[4],float[4],...

 new area (binary, every vertex):
   [same as new curv]

See end of this file for machine-independent
C functions that read/write Linux/IRIX binary
compatible FreeSurfer files that contain 4-byte
float, 4-byte ints, 3-byte ints, and 2-byte ints
in MSB order (most significant byte first).  This
version of tksurfer cannot read the new curvature
file format (same as new area format).  The
program, calcvert, can convert back and forth
between these different formats.

In all the READ/WRITE entry fields, a tilde (~)
can be used as an abbreviation of the path of the
current subject directory such as:

  /computer/usr2/subjects/marty

An asterisk (*) can be used as an abbreviation of
the current functional session directory such as:

  /computer/usr3/sessions/040115MS/image

One possible action is to read in the "sulc" file
instead of the "curv" file (e.g., substitute
"rh.sulc" for "rh.curv", click READ, and then
click REDRAW).  The sulc data is the summed
perpendicular movement of each vertex during
inflation.  It is used to drive morphing, and is
closer to sulcus-vs-gyrus than curvature, which
is a strictly local measure of the one vertex in
relation to its immediate neighbors
(concave-vs-convex).

To generate a label file, first outline a region
with LEFT-CLICKS and use CUTAREA and FILL to
select it.  Then select a name for the label file
and WRITE it.

Fieldsign and fieldsign mask files are
automatically generated using the SessionTools ->
Calculate Visual Fieldsign panel.

Value files (*.w files) are generated as the
output of clicking PAINT on several different
panels.  They may be real or complex.

The PUSH button to the left of the "val" field
can be used to read in complex data.  First read
the imaginary file with READ, and possibly SMOOTH
it (val).  PUSH is used to move the imaginary
data to the second position on the data stack.
Then the real data file is read in with another
READ on a different file name.  These actions are
performed by the standard scripts that read
complex data such as polar-views.tcl.

When WRITE'ing an rgb file, make sure that the
surfer display window is completely onscreen,
cleanly redrawn, and not occluded by any other
window.  The mouse cursor is ignored.

ROTATE/TRANSLATE/SCALE Sliders

  ROTATE
    horizontal slider -- rotate around vertical
    vertical slider -- rotate around horizontal
    yrot field -- rotate around y axis (deg)
    xrot field -- rotate around x axis (deg)
    zrot field -- rotate around z axis (deg)

  TRANSLATE
    horizontal slider -- translate left-right 
    vertical slider   -- translate up-down
    x field -- translate in x axis
    y field -- translate in y axis

  SCALE
    vertical slider -- scale larger-smaller
    % field -- scale in percent

REDRAW/RESTORE/SEND/GOTO

The REDRAW button manually redraws the screen,
while RESTORE then REDRAW reestablishes the
original, lateral viewing orientation (it is easy
to get lost after several non-orthogonal
rotations).

SEND saves the coordinates of a surface point.
It also automatically causes an open medit tools
display to GOTO that point, (but only if the
xhost list is empty, which is a security
feature).

GOTO finds the nearest (Euclidian distance)
surface point to the last point that was saved by
a SEND or SEND PNT in surfer tools, medit tools,
or tkregister.

Note that the GOTO operation is not equivalent
for surface (2D) and volume (3D) data sets.  Any
surface point can always be located (to within a
voxel) in a volume data set; however, a point
selected in a volume often lies outside of the
corresponding cortical surface, so a search must
be performed.  This can lead to counterintuitive
results.  For example, assume you are displaying
the right hemisphere surface.  If a volume point
is accidentally selected in the opposite (left)
hemisphere of a 3D data set, and you GOTO that
point on the surface the nearest (Euclidean)
surface point will typically lie somewhere along
the midline, and will not even be visible in
lateral view.

Background Color

If "none" is selected, the curvature data set is
not displayed.  The default is "curv".  When only
curvature is displayed, it is represented using
red and green.  When curvature is displayed under
activations ("overlay" checked), curvature is
represented as two shades of gray.

Color Scale (ColScl) for Functional Data

  w1 -- color wheel (eccen or polar versions)
  ht -- heat scale (brown/white or red/blue)
  BRw -- blue/red/white (real data only)
  fs -- fieldsign ($hemi.fs, $hemi.fm only)

For much more detail on the behavior of these
different color scales, see SessionTools -> View
Functional Data.

MESH and CM Buttons

MESH toggles between viewing and not viewing the
vertices and edges of each polygon in the
surface.  The mesh is too dense to resolve unless
the brain is first SCALE'ed up.  The r/g/b fields
can set the color of the mesh (bug: mesh color
setting is ignored if brain extends beyond
viewing window; however, viewing window can be
enlarged).  The CM button displays a 1 cm gray
scale bar at the lower right and a color scale
bar (the color scale bar does not work right for
the "w1" color scale; use the program "wheel"
instead).

Functional Display Parameters

Left Checkboxes and "fthresh:" Entry Field

 truncphase -- only display positive values
 revphase   -- reverse time axis (complex data)
 invphase   -- reverse positive, negative values 
 overlay    -- display functional data (gray curv)
 complexval -- complex-valued data (usu. autoset)

 fthresh -- hard stat thresh (stat values under
              this value display underlying gray
              curvature instead)

Right Column Entry Fields

 fslope -- contrast (steepness sigmoid, or double
             sigmoid steepness w/2-ended scales)
 fmid   -- set where sigmoid changes fastest (use
              this to set effective threshold
              but avoid truncation edges)
 cslope -- contrast of R/G curvature colorscale
 cmid   -- midpoint of R/G curvature colorscale
 anglecycles -- complex: eccen=1.0, polar=2.2
 angleoffset -- complex: 0-1 => phase angle 0-2pi

For more detail on the meaning of these fields as
a function of different color scales, see
SessionTools -> View Functional Data.

Surface Cut/Fill Operations

  CUTAREA  -- closed-line cut using most recent
                list of LEFT-CLICK'd points
  FILL     -- fill region selected by single
                LEFT-CLICK, then delete unfilled
  CUTPLANE -- 3 LEFT-CLICK's define plane, 4th
                indicates which side to keep  
  CUTLINE  -- open-line cut using most recent
                list of LEFT-CLICK'd points
  FILL ROI -- fill region with min stat value
  UNDO CUT -- undo most recent cut
  RECONNECTALL -- undo all cuts

Once an operation has been performed, the list of
selected points is cleared in preparation for the
next operation.

Data and Curvature Smoothing

The SMOOTH button performs the requested number
of nearest-neighbor smoothing steps on either the
curvature ("curv") or the data on the top of the
value stack ("val").  The approximate mapping
from smoothing steps to full-width-at-half-max
filter result is:

  10 steps => 3.2 mm FWHM
  20 steps => 4.5 mm FWHM

See Help -> View Functional Data for more
detail on smoothing.

------------------------------------------------
 Standalone Commandline and Script Operation
------------------------------------------------
tksurfer can also be run as a standalone program
from the command line (as long as SUBJECTS_DIR and
FUNCTIONALS_DIR are set) from the command line:

Usage: tksurfer -{name} {hemi} {surf} [-tcl script]
       tksurfer -help, -h

   name:  dirname in current SUBJECTS_DIR
   hemi:  lh,rh
   surf:  orig,smoothwm,inflated,sphere,...

The program has an embedded tcl interpreter and
most of its functions (including some not exposed
to the surfer tools interface, as well as some
that are now obselete...) can be accessed through
it, either interactively at the tcl prompt, %,
that appears in the terminal from which tksurfer
is started, or offline using a tcl script in a
file whose name follows the -tcl option.  If you
include an "exit" at the end of the tcl script,
tksurfer will quit when the script finishes.  You
can find commands available in the tcl interpreter
using "help":

  % help

which also lists settable variables (tcl variables
linked to C variables).  Set the value of a
variable like this:

  % set cslope 5.0

To find the current value, omit the value

  % set cslope
  3.0

You can also search for commands by pattern
matching:

  % info command rotate*
  rotate_brain_x rotate_brain_y rotate_brain_z

Commands have some minimal error checking/usage:

  % rotate_brain_y
  Wrong # args: rotate_brain_y <deg>

Unix commands can be executed directly from the
tcl prompt (but to get csh-style globbing, you
have to do it explicitly):

  % cd /tmp
  % ls -al
  % eval ls -al [glob *.rgb]

Here is an example of a small command line tcl
script that reads in a surface, and then saves 90
bitmap images of the brain, each one rotated 4
degrees around the vertical axis from the
previous image (i.e., a rotating brain movie).

open_window
make_lateral_view
read_binary_curv
set cslope 5.0
set i 0
while {$i < 90} {
  redraw
  set rgb /tmp/brain-[format "%03d" $i].rgb
  save_rgb
  incr i
  rotate_brain_y 4
}
exit

You could either paste the script into the
tcl prompt or put the commands in a file,
rotbrain.tcl, run it like this:

  tksurfer -john rh smoothwm -tcl rotbrain.tcl

You could also execute the script from the surfer
tools interface by typing its full pathname (or
using "#" as an abbreviation for the standard
script directory if you have put the script there)
into the "script:" entry field, and clicking RUN.

------------------------------------------------
 C-code for machine-independent MSB read/write
------------------------------------------------
/* machine-indep read/write float/int/2,3byte */

short swapShort(short s);
int swapInt(int i);
float swapFloat(float f);

int fread2(int *v, FILE *fp); /* ret: n read = 1 */
int fread3(int *v, FILE *fp); /* ret: n read = 1 */
int freadInt(FILE *fp);       /* ret: int value */
float freadFloat(FILE *fp);   /* ret: float value */

int fwrite2(int v, FILE *fp);
int fwrite3(int v, FILE *fp);
int fwriteInt(int v, FILE *fp);
int fwriteFloat(float f, FILE *fp);

short swapShort(short s)
{
  SWAP_SHORT ss;
  char       c;

  /* first swap bytes in word */
  ss.s = s;
  c = ss.buf[0];
  ss.buf[0] = ss.buf[1] ;
  ss.buf[1] = c;

  return(ss.s);
}

int swapInt(int i)
{
  SWAP_LONG  sl;
  short      s;

  /* first swap bytes in each word */
  sl.i = i;
  sl.s[0] = swapShort(sl.s[0]);
  sl.s[1] = swapShort(sl.s[1]);

  /* now swap words */
  s = sl.s[0];
  sl.s[0] = sl.s[1];
  sl.s[1] = s;

  return(sl.i);
}

float swapFloat(float f)
{
  SWAP_LONG  sl;
  short      s;

  /* first swap bytes in each word */
  sl.f = f;
  sl.s[0] = swapShort(sl.s[0]);
  sl.s[1] = swapShort(sl.s[1]);

  /* now swap words */
  s = sl.s[0];
  sl.s[0] = sl.s[1];
  sl.s[1] = s;

  return(sl.f);
}

int fread2(int *v, FILE *fp)
{
  short s;
  int   ret ;

  ret = fread(&s,2,1,fp);
#ifdef Linux
  s = swapShort(s) ;
#endif
  *v = s;
  return(ret) ;
}

int fread3(int *v, FILE *fp)
{
  unsigned int i = 0;
  int  ret;

  ret = fread(&i,3,1,fp);
#ifdef Linux
  i = (unsigned int)swapInt(i);
#endif
  *v = ((i>>8) & 0xffffff);
  return(ret);
}

int freadInt(FILE *fp)
{
  int  i, nread ;
                                                                                
  nread = fread(&i,sizeof(int),1,fp);
#ifdef Linux
  i = swapInt(i) ;
#endif
  return(i) ;
}

float freadFloat(FILE *fp)
{
  float f;
  int ret;

  ret = fread(&f,4,1,fp);
#ifdef Linux
  f = swapFloat(f);
#endif
  return(f);
}

int fwrite2(int v, FILE *fp)
{
  short s;

  if (v > 0x7fff)    /* don't let it overflow */
    v = 0x7fff;
  else if (v < -0x7fff)
    v = -0x7fff;
  s = (short)v;
#ifdef Linux
  s = swapShort(s) ;
#endif
  return(fwrite(&s,2,1,fp));
}

int fwrite3(int v, FILE *fp)
{
  unsigned int i = (unsigned int)(v<<8);
#ifdef Linux
  i = (unsigned int)swapInt(i);
#endif
  return(fwrite(&i,3,1,fp));
}

int fwriteInt(int v, FILE *fp)
{
#ifdef Linux
  v = swapInt(v);
#endif
  return(fwrite(&v,sizeof(int),1,fp));
}

int fwriteFloat(float f, FILE *fp)
{
#ifdef Linux
  f = swapFloat(f);
#endif
  return(fwrite(&f,sizeof(float),1,fp));
}

#############################################################
------------------------------------------------
 The File -> New Functional menu creates a new
 blank functional session directory and its
 standard subdirectories
------------------------------------------------
This is the first step in making a new session.
A new functional session directory and a standard
set of subdirectories in it is created.  The
default location for the new session is the
current setting of the environment variable,
FUNCTIONALS_DIR, but a functional session can be
made anywhere.

Finding sessions by date or initials is much
easier with the csurf interface if multiple
sessions are stored in the same FUNCTIONALS_DIR.

The standard functional session directory
structure is:

 FUNCTIONALS_DIR (root of a sessions database)
    sessionname    (year+month+day+initials)
       image          (images)
          scripts        (configs, NOTES file)
          rgb            (saved SGI rgb bitmaps)
          mpg            (saved mpeg movies)
          mprage         (alignment scan)
          functscan1     (functional scan1)
          functscan2     (functional scan2)
          ...

When the functional session is made, it prompts
you to find a subject somewhere that contains the
surface for this functional.  The subject must
exist somewhere.  This linkage is saved in a
file, "name", inside the session directory
containing only the SUBJECTS_DIR directory name
of the subject (e.g., johns).

Once the functional session has been made, a
subdirectory for each functional scan should be
made in the image subdirectory.  Then, the
individual scans for that session should be
copied into the separate subdirectories.

You can give the scan subdirectories any name
besides the names of the standard subdirectories
but it is extremely helpful to number them so
they sort in the order in which were acquired.
Also, it helps to add an informative suffix to
each name (e.g., the name of the stimulus
program), since the directory names are what are
used to select scans in the interface.  For
example:

  $FUNCTIONALS_DIR/somesession/image/1-smfaces/*
  $FUNCTIONALS_DIR/somesession/image/2-bigfaces/*
  $FUNCTIONALS_DIR/somesession/image/3-words/*
  ...

The alignment scan (in directory "mprage" above,
but can be any name) is a T1-weighted scan taken
in the same plane as the functional scans.
Typically, it has thinner slices, smaller
in-plane pixels, and more coverage than the
functional scan.

The alignment scan is used to align the
functional data with the scans in the subjects
database that were used to make the surfaces for
this subject.  This procedure generates a
transformation matrix that allows statistical
measures calculated from the functional scans to
be painted onto the cortical surface.

There can be more than one alignment scan.  You
choose for each functional can which alignment
scan should be associated with it.

#############################################################
------------------------------------------------
 The SessionsTools -> View All Scandirs menu
 provides a quick way to browse the entire set of
 scan dirs in the current functional dir.
------------------------------------------------
Choosing View All Scandirs makes a popup that
contains all the previously configured scandirs
in the current FUNCTIONALS_DIR.  This may take a
few seconds.

The scandirs are sorted by subject (with a note
if the subject was not found in the current
SUBJECTS_DIR).  The sessions for each subject are
then arranged alphabetically.

Quick scandir access

Double-clicking a scandir opens the View
Functional Data panel for the session that
contains it, and renders activations onto the
currently selected surface.

If a surfer tools panel is already open, you have
to do two double-clicks on a new scandir to close
the currently rendering (and its surfer tools)
and to open a new one.

Double-clicking a session just opens the the View
Functional Data panel without rendering
anything.

Suppress render panel (multiple Surfer Tools)

To suppress the opening of the View Functional
Data panel, select "no panel" at the top of the
popup.  This also allows you to view more than
one scandir at a time.  Instead of closing the
current rendering and its surfer tools, a new
surfer tools panel will be generated (in the same
screen position) for each subsequent scandir.
#############################################################
------------------------------------------------
 The SessionsTools->Make Scandirs,Find/Copy Raw
 menu names and creates scan directories, makes
 raw scan links in them, strips initial TRs, and
 copies stripped scans into the new scan
 directories with meaningful, unique names.
------------------------------------------------

Getting Started

This panel is designed to be the first panel
accessed after running File -> New Functional.
It requires a virgin session directory tree
containing no scan directories.   If scan
directories have already been created (even if
they are empty), you won't even be able to open
this panel.   First manually remove existing scan
directories (the panel ignores the "rgb",
"scripts", and "tmp" directories in a newly-made
session).

Click the Find Raw Scans button at the top of the
panel to begin.  Click SETUP NEW SCANDIR one or
more times to create blank scan configuration
lines.  DELETE LAST SETUP deletes the most
recently added line, whether or not you have
altered it.

Create Scan Directories and Find Raw Scans

The scan directory name is the main text label
used in the rest of the interface for each scan,
and so it helps to choose informative names and
use them consistently.  One good name for a scan
is the name of the stimulus program that was
used.

By default, the first scan directory is the
alignment scan directory, and it is auto-named
"alignscan".  Directories after that are given
default prefixes: "1-", "2-", etc.  You can
change the names of the proposed scan directories
to whatever you like, but the names must be
unique (the default number prefixes guarantee
this, even if the stimulus exactly repeats --
e.g., "1-polar", "2-polar", etc).

For each new scan directory, click the FIND
button to locate a single raw alignment or
functional scan.  Subsequent FIND button clicks
start the directory browser in the parent
directory of the most recently selected Raw
Scan.

Once you are satisfied with the mapping between
scan directory names and raw scan names, click
MAKE SCANDIRS at the top of the panel.  If all
the fields are complete, the name list is unique,
and the raw scans all exist, the new scan
directories should appear on the left of this
panel (if not, fix things and click MAKE SCANDIRS
again).  Links to the raw scans will be made in
each of the scan directories.  If you want to
redo this stage, remove the just-created scan
directories (which will contain only links to raw
scans).

Strip Initial TRs and Copy/Rename Raw Scans

When the MAKE SCANDIRS button is clicked
successfully, default unique scan names will be
inserted into the right-most column (New Scan
Names).  These names must be unique because they
are used as the prefix for saved bitmaps, which
all reside in the same rgb directory.  These
names can be adjusted if necessary.  You may also
want to reset the number of repetitions ("rmTRs")
to strip off the begining of the functional
scans.  The defaults are to strip 0 for the first
(alignment) scan and strip 2 initial repetitions
off of subsequent functional scans.

Finally, click STRIP/COPY-RAW at the upper
right.  After checking the list of new names for
completeness and uniqueness, this strips TRs and
copies the raw functional scans into each scan
directory.

The STRIP/COPY-RAW function currently only works
with AFNI BRIKS. For now, if the fastest changing
index in the scan is not in the right/left
direction, the internal data order of the BRIK
will be flipped into this order and the HEAD is
updated to reflect this change (because some
later analysis steps do not yet read the AFNI
HEAD file).

#############################################################
------------------------------------------------
 The SessionsTools -> Setup Align/Funct Scans
 menu sets up the basic image parameters for
 functional and alignement scans in preparation
 for statistical analysis and rendering.
------------------------------------------------
On the left of this panel is a list of the
subdirectories in the current session.  On the
right are a set of pages--one for each scan
directory--that correspond to each functional
scan directory.  The first time you bring up this
panel, all the pages on the right of the panel
will be blank--no matter which scan directory is
selected, no parameters appear on the right.

The configure a particular directory, select it
from the list on the left (it should be marked
green) and then hit one of the buttons at the top
center of the panel to declare it to be either a
"Funct Scan Dir" or an "Align Scan Dir".

A "Funct Scan Dir" should contain one functional
scan, with multiple images/timepoints for each
slice.  An "Align Scan Dir" should contain a
T1-weighted scan taken in the same plane as the
functional scans, with one image per slice,
typically at a higher resolution than the
functional scans.

To save the current configuration of all of the
scan directories in the current session, hit Save
or Save/Close at the bottom of the panel.  You
can move between directories without losing any
configuration information as long as you do not
exit the panel.  Hitting Cancel will exit the
panel and leave the configuration in whatever
state it was when you first opened the panel.

The bottom buttons only affect the configuration
of the scan directories.  This information is
stored in an ASCII file:

  csurf.dat

which is located in the funct scripts directory:

  $FUNCTIONALS_DIR/$session/image/scripts

The Save/Close and Save buttons do not affect any
of the data files in the scan directories.

Configure and Convert the Alignment Scan

Once a directory has been declared to be an
"Align Scan Dir", the first step is to read the
header of an example file.  All the files within
the current scan directory will be present in
the "Image File:" combo box.  Select one of the
files (e.g., alignscan+orig.BRIK).  Then click
"READ HEADER" to attempt to read the parameters
from this file.  Verify that all the fields have
been filled in correctly.  Any fields that say
"-unset-" need to be set manually.

If the format of the scan is *not* an AFNI
BRIK or a bshort, you may be able to convert
it to a FreeSurfer native 1-byte COR format
by clicking the CONVERT=>COR button.  If this
doesn't work, try to convert to an AFNI brik
and read it directly.  CONVERT=>COR has not been
extensively tested.

Now click the INIT button near the bottom of the
panel to create an initial default transformation
matrix (the identity matrix).  This is equivalent
to assuming that the Align scan and the Subject
scan used to make the surface are already aligned
(they often *not* be aligned).  A panel will
say this was done automatically if you forget
when you hit the "Align=>Subj" button

Register the Alignment Scan

Now use the "Align=>Subj" button starts up the
registration program (tkregister) with the scans
used to make the surface for this subject as the
TARGET scan, and the alignment scans in the
currently selected directory as the MOVEABLE
scan.

The sole purpose of the tkregister application is
to generate a transformation matrix that maps the
alignment scan onto the scans used to make the
subject's surface.  The only file that tkregister
affects is:

  register.dat

one of which is located in each scan dir:

  $FUNCTIONALS_DIR/$session/image/$scan

See the "Register" Help menu item for tips on
how to register data sets.

Once the data sets have been aligned to your
satisfaction, hit the SAVEREG button on the
tkregister application to save it (it will backup
the previous registration matrix to the file
register.dat~).  Then quit the tkregister
application (using same now-purple button you
started it with).

Configure the Functional Scans

Now select each functional scan in the listbox at
the left and configure each one as a "Funct Scan
Dir".  Fill in any missing or "-unset-"
parameters.

Siemens UCSD mosaic note: although READ HEADER
can identify some of the parameters in a Siemens
mosaic scan, tkregister can't read a mosaic
directly.  First convert it a BRIK with thor.

Don't run the FUNCT=>SUBJ register button yet,
but be sure to open the combox box labeled
"Same-Plane Structural Dir:" at the bottom of the
panel to and select the alignment scan to be
associated with this functional scan.  This makes
it possible for there to be more than one
alignment scan.

Viewing Functional Scans

If the functional scan is a bona fide *.BRIK
file, you can view it with AFNI by typing
Alt-a in the panel (or using the AFNI button).
This will start AFNI in the currently selected
functional scan directory.

Optional 3D Volume Registration using AFNI

The AFNI tool, 3dvolreg, can be used for motion
correction using the buttons in the line labeled
"Volreg:".  The combo box labeled "Targ:" picks
the target scan.  It can be the current scan
(default) or any other scan currently configured
as a functional scan.  The field "TR:" picks the
target TR (default 10).  Clicking "CURR" aligns
all the other TR's in the current functional scan
with the target TR.  Clicking "ALL" aligns all
the TR's in every currently configured functional
scan to the target TR.

The volume-registered BRIK's are then written
back into the respective scan directories with a
"-vreg" infix.  For example:

 infile:  scandir1/scanname1+orig.BRIK
 outfile: scandir1/scanname1-vreg+orig.BRIK

 infile:  scandir2/scanname2+orig.BRIK
 outfile: scandir2/scanname2-vreg+orig.BRIK

The original BRIK's will be untouched.  The name
of the new volume-register BRIK's will be
inserted into the "Image Name Format" field in
the Setup Align/Funct scans panels.  Note that
this operation doubles the size of the functional
data in each affected scandir.

This program will only run on a bona fide *.BRIK
as an input.  To go back to the original
non-motion corrected data (or to re-run the
3dvolreg program), re-select a non-vreg'd "Image
File:" and READ HEADER.

Copy Alignment Registration to Functionals

Go back to the previously configured alignment
directory and use the "Copy Align To All Functs"
button to copy the alignscan-to-subjectscan
transformation matrix into each configured
functional scan directory.  This copies the
transformation, taking into account the fact that
the slice thickness and inplane resolution
typically differs between the alignment and
functional scans).

Block Center Offset

If the alignment scan and the functional scans
have different block centers, enter them in this
field.  This is used to modify the register.dat
file when it is copied between the alignment scan
and the functional scans.

Verify/Touch-up Functional Scan Registration

Select the first functional scan at the left.
Now register the functional scan directly to the
surface reconstruction scan using the FUNCT=>SUBJ
register button, which starts tkregister again.
Since the functional and alignment scans were
collected in the same plane, the rotation of the
functional scan will be correct.

Currently, however, the offset between the first
slice in the functional and alignment scans is
not accounted for.  To correct this, use only the
TRANSLATE buttons from tkregister.  Since the
scan has already been rotated, there will be an
x, y, and z component to the translation.  Change
planes and translate until the functional scan is
aligned.

Non-Rigid Transformations

Some of the lower-bandwidth, higher
signal-to-noise scans have additional shearing
(rhomboidal) distortion.  To correct shear you
have to use a combination of a rotation and a
scaling--a rotation alone won't work.  For
example, to correct a shear in which the left
side of the image is too high and right side to
low, do something like this:

  1) choose a rotation point near the center
  2) rotate 30 degrees to the right
  3) scale 95% in the vertical direction
  4) rotate 30 degrees to the left
  5) scale 105% in the vertical direction

Apply shear/scaling with discretion, only after
completely exhausting attempts to align the
images using translation and rotation.

Copy Registration Between Functionals

After finishing with one functional, you can copy
the final functional alignment transformation
matrix between functional scans using the CP PREV
button.  Select one scan, then a second, then hit
the button.  It will ask you to verify that you
are copying the registration matrix from the
first to the second scan.  To copy the current
functional registration to all the other
functionals, use the CP TO OTHERS button.

Vtx Normal Search Operation (for Paint)

During the PAINT process (in several different
later panels), a 3D statistic is associated with
each vertex on the surface by finding which voxel
the vertex lies within.  By entering different
values into the "mn:" (minumum) and "mx:"
(maxium) fields, a search will be performed
between those limits in increments of "step:"
size.  Possible operations (radio buttons at
right) on the set of statistics recovered in the
search are: "mx" (find largest absolute-valued
statistic along the vertex normal), "av"
(find average statistic), or "mn" find minimum
absolute-valued statistic.  There is an identical
set of controls on the Import 3D Stats panel.

Common Layout of SessionTools Panels

Most of the rest of the SessionTools panels are
arranged in a similar way.

 (1) center-top buttons that configure the
     current directory as a directory of a
     certain kind or tell the program to ignore a
     directory by Unset-ing it (a previously
     configured, then Unset directory, recovers
     its sets when re-configured)

 (2) settable parameters in the main part
     of the panel

 (3) action buttons at the top right with bold
     lettering that read the parameters you have
     set and actually perform computations that
     affect data files.  Those buttons turn
     purple during computations.

Some panels have smaller actions button in the
main body of the panels, mostly for (trying to!)
read headers.

#############################################################
------------------------------------------------
 The SessionsTools -> Combine 3D Raw Images
 menu averages/concatenates raw funct data
------------------------------------------------
The basic layout of this panel (scan directories
to the left, common action button at the top,
pages of parameters to the right) is similar to
the other SessionTools panels.  For more details,
see Help -> Setup Align/Funct.

This panel creates a new scan directory that
will contain averaged scans.

Configuration Buttons--Make Avg Dir, Unset Dir

First carefully choose a name for the average
directory in the entry to the right of the Make
Avg Dir button.  Clicking Make Avg Dir creates
that directory.  If the directory already exists,
it will be re-used rather than re-created.

To ignore an existing raw avg/concat directory,
use Unset Dir.  The files the unset directory
will not be altered and any saved parameters will
re-appear if you Make Avg Dir with that directory
name again.

Operation

Selected scans can either be averaged, time point
by time point, or concatenated.

Choosing Scans to Combine

A list of currently available functional scans
can be found in the "Select to Add" dropdown
combobox.  Selecting one of them will add it to
the "Dirs to Average" list.  To delete (or
re-order) directories from that list, select it
in the list and use the Delete or Backspace key.

Action Button--COMBINE

This button performs averages or concatenates the
3D time series data sets and writes the result
into the current raw average directory as a set
of bshort files (each bshort file has all the
time points for one slice) for averaging, and
AFNI briks for concatenation.  The registration
matrix from the first scan is copied into the raw
avg/concat directory and by convention, the first
scan in the average is used to name the output
files:

 infiles (several x-y-z-t images):

   scandir1/scanname1[-vreg]+orig.BRIK
   scandir2/scanname2[-vreg]+orig.BRIK

 outfiles (one x-y-z-t image):

   avgdir/scanname1[-vreg]+orig_000.bshort
   avgdir/scanname1[-vreg]+orig_000.hdr
   avgdir/scanname1[-vreg]+orig_001.bshort
   avgdir/scanname1[-vreg]+orig_001.hdr
   [etc]
            (or if concat)

   avgdir/scanname1[-vreg]+orig.BRIK

If the scans have been volume-registered, those
will automatically be used.  Otherwise, the
original raw scans are used.  The averaging is
done in 3D without any additional registration.
Note that the register.dat files are ignored.

If the operation is concatenation, an AFNI
boundary file, runs.1D, is automatically created
(units are TRs).  If the time series is analyzed
using deconvolution, this file is consulted to
prevent stimulus events at the end of one run
from accounting for variance at the beginning of
the next run.  If motion correction has been
run on the individual scans, a concatenated
motion.1D file will also be generated.

You may want at this point, to go back to
SessionTools -> Setup Align/Funct Scans to touch
up the FUNCT=>SUBJ registration for the averaged
scan, and finally to COPY the touched-up
registration matrix into each of the component
directories.

#############################################################
------------------------------------------------
 The SessionsTools -> Calculate 3D Fourier Stats
 sets up and calculates Fourier-based statistics
 on 3D volume data sets
------------------------------------------------
This panel runs FFT's on the time course at each
voxel when you click FOURIER.  Normally, you then
click PAINT.

The Image Name Format

This is automatically entered from the Setup
Functional panel.

Stimulus Program Notes

An arbitrary length string of ASCII characters
for informational purposes.

Stim Cycles Per Scan

This is the most important parameter on the
panel.  To analyze a polar angle mapping stimulus
(rotating wedge) with 8 cycles, enter 8.  You
would also enter 8 if there were 8 ON blocks and
8 OFF blocks.  This number does *not* have to be
a power of two.

TR

The TR can be entered but is not currently used
(it could be used to correct for interleaving
delays).

Smoothing Steps

In-plane nearest neighbor smoothing steps
(typically 0).

Low-Freq Window

This is the number of bins immediately below the
stimulus frequency to ignore when calculating the
significance of the periodic activation at the
stimulus frequency relative to the activation at
other frequencies.

Omit Freq

This is the frequency (cycles per scan) of an
additional periodic nuisance signal to discard
when calculating signal-to-noise (e.g., a
periodic activation due to a regularly performed
task during a phase-encoded mapping experiment).
To disable, set to -1 (default).

Mean Delay

This is only relevant to the calculation of the
F-statistic.  For this calculation, response
phases are broken into two 180 degree halves.
This parameter controls where the two halves are
situated.  Later on, in the View FUnctional Dat
panel, this delay can be interactively controlled
with angle_offset for FOurier analyzed data.
However, it is set in this panel if F-statistics
are read in (as opposed to the real and imaginary
Fourier components).  The see F-statistics with a
difference delay, you have to re-run FOURIER.

Phase Encode Type

The radio button chosen merely gives default
values to the color map, the parameter settings,
and the tcl scripts used when the View Functional
Data panel is opened to render surface images.
All of the values can be overridden there.

Truncphase

If Truncphase is checked, some phase angles will
be set to zero during the PAINT operation which
associates 3D statistics with each surface
vertex.

[TODO: explain default settings]

Action Button--FOURIER

When FOURIER is run, the panel will check whether
the number of repetitions in the corresponding
Setup Functional panels are powers of 2.  FOURIER
will not run unless this is the case (typically
64, 128, 256, or 512 repetitions).

Action Button--PAINT

This button samples the Fourier analyzed data
onto the surface specified in "Surface for
Sampling 3D Data".  The result is four files
(whose names appear schematically in the bottom
two entries), two for each hemisphere, which
consist of the real and imaginary components of
the Fourier transform.

View 3D Stats, Raw Images

On IRIX, use Alt-v to start up the (unsupported)
tkanalyse 3D statistics and raw images viewer for
the currently selected scan directory.

#############################################################
------------------------------------------------
 The SessionsTools -> Calc 3D Rand Block Stats
 sets up and runs deconvolution on 3D volume
 data set using AFNI 3dDeconvolve (by Doug Ward)
------------------------------------------------
This panel configures files and runs Doug Ward's
3dDeconvolve on functional time-series BRIKs.
Normally, you then use SessionTools -> Import 3D
Stats to extract the output files and PAINT
them.  It requires that the 1D paradigm files
have been previously generated and placed within
the paradigm dir (see below).

The Image Name Format

This will typically be a concatenated,
motion-corrected time-series BRIK.  This is
automatically entered from the Setup Functional
panel.

Paradigm Dir

Directory containing the single-condition 1D
files specifying the paradigm.  This can be
anywhere (e.g., a central paradigm depository).
However, since these files are small, and since a
central paradigm store may get out of sync with
an already-performed expt, it is a better idea to
save a copy of the paradigm files that were
actually used inside each scan directory.  The
directory specified here can either be absolute
(starts with "/") or relative (doesn't start with
"/" and is assumed to be inside the current
scandir).  A relative path is preferred since
using an absolute path to the paradigm dir may
break if the functional session is moved into a
different FUNCTIONALS_DIR.  The standard name
is "stim1Ds".

Paradigm Files

These are single column (n x 1) files, one for
each condition.  The filename should be a short
(8 chars or less) word followed by a .1D suffix
(e.g., face.1D, house.1D, scramble.1D).  The
filename stem (e.g., face, house, scramble) will
be used in the interface and the resulting saved
bitmaps as the condition name.  The file should
contain a 1 when its named condition is present
and a zero when it is not.  The baseline
condition is defined by the presence of a 0 in
all of the condition files.  There is no 1D file
for the off-condition.  Except for the
off-condition case, for a given TR, there should
be a 1 in exactly one paradigm file.  Here is an
example of a portion of a paradigm file:

0
0
1
1
1

Note that the concatenation process (COMBINE on
the SessionTools -> Combine 3D Raw Images panel)
*does not* concatenate the files in the stim1Ds
directory.  A stim1Ds directory has to be
manually created in the concatenated scandir
(which is itself created on clicking COMBINE) and
the 1D files from each condition have to be
assembled manually in there.

TR (sec)

Repetition time between successive images of
the same slice in seconds.

Maximum Lag (-maxlag)

The maximum lag (in TRs) to allow when solving
for the hemodynamic response function for a
each trial type.

Polynomial Fit Order (-polort)

This specifies the order of the polynomial used
to fit the low frequency drift in the signal.
The default is 2.

Motion Params File (-dfile)

This should contain a 6-parameters-per-timestep
estimate of motion artifact.  This is typically
generated by 3dvolreg after motion correction is
run in the Setup Functional panel.

Scans, Total TRs

The number of scans that were concatenated to
generate the input file named at the top, and the
total number of TRs that it contains.

Paradigm Panel

When "READ 1Ds" is clicked, the individual
condition paradigm files are each read and
assembled into a paradigm matrix, where each
column comes from one 1D file.  The stems of the
paradigm filenames are substituted for 1's and
"----" is substituted the 0's in the 1D file.
This verifies that the 1D file all have the same
length.

Condition Differences

To add a subtraction, select a block type from
the "Condition A:" and  "Condition B:" dropdown
menus and then click "ADD SUBTRACTION" which
should add it to the Subtractions list below.  To
omit a subtraction, use Backspace.

Action Button--DECONVOLVE

When DECONVOLVE is clicked, 3dDeconvolve will be
run according to the mode radio buttons just
above the paradigm window (test/F/t-stats).  The
output stats file will be written into the
current scan directory.  If Test is selected, the
parameters are checked for completeness and the
design matrix is tested for singularity.

Stats Output File

The output stats BRIK name appears here after
DECONVOLVE has been run.  This takes a while
for a concatenated scan.  Correct settings for
rendering will depend on the paradigm.  For the
blue/red scale, try starting with:

  smooth:   20
  thresh:   0.0
  contrast: 0.1
  midpoint: 25
#############################################################
------------------------------------------------
 The SessionsTools -> Combine 3D Phase Stats
 menu averages fourier-analyzed 3D stats
------------------------------------------------
This panel creates a new scan directory that will
contain averaged 3D fourier-based statistics.

Configure Buttons--Make CombineDir, Unset Dir

First carefully choose a name for the average
directory in the entry to the right of the Make
CombineDir button.  Clicking Make CombineDir
creates that directory.  If the directory already
exists, it will be re-used rather than
re-created.

To ignore an existing 3D phase average directory,
use Unset Dir.  The files in the unset directory
will not be altered and any saved parameters will
re-appear if you click Make CombineDir with that
directory name again.

The 3D stats files are combined voxel-by-voxel,
which ignores the funct=>struct transformation
matrix (register.dat).  The transformation matrix
for the combined file is copied from the *first*
stats set in the combine list.  This
transformation matrix gets used when the combined
file is PAINT'ed.  Be sure to re-COMBINE in order
to redo this copy operation if you go back and
touch up the transformation matrix from the
firstan input stat set (adjustments to later stat
sets in the list are ignored) and you want the
that modified transformation matrix to be used
for the PAINT in this panel.

Choosing Stat Files to Average

A list of currently available fourier-analyzed
functional scans can be found in the "Select to
Add" dropdown combobox.  Selecting one of them
will add it to the "ScansToCombine" list.  To
delete (or re-order) a directory from that list,
select it in the list and then use the Delete or
Backspace key.

Reversing Phase of Stat Files

If scans to be combined do not have the same
phase direction (e.g., clockwise vs. counter-
clockwise direction of the moving sector in a
polar angle mapping experiment), the phase of one
or more scans can be reversed by selecting the
scan to be reversed, and then typing Return (or
double-clicking).  "Reversing the phase" means
taking the negative of the phase angle calculated
for each voxel.  This is equivalent to reversing
the direction of time in the time domain.

Combine Operations

Now select a combine operation.  The operation
'phaseaverage' calculates the voxel-by-voxel
vector average of the the complex-valued data
(separately average real and imaginary
components).  The operation 'phasecancel'
calculates the voxel-by-voxel angular average
and then separately averages the amplitudes
(separately average phase and amplitude
components).  In the first case, if two vectors
with large amplitude have very different angles,
the amplitude of their vector average will be
small; in the second case, it will be large.
Thus, the 'phaseaverage' operation more strongly
penalizes voxels with inconsistent phase in the
component scans.  Currently, the 'phasecancel'
operation can only combine two scans.

Offset

The measured response phase consists of a
stimulus phase plus a hemodynamic delay phase.
If scans are combined with opposite directions of
phase, the hemodynamic delay phase can be
subtracted out.  However, if the operation
'phaseaverage' is used, this will reduce the
amplitude of the vector average (there is no
effect of a hemodynamic delay on the
'phasecancel' operation and no effect of a
non-zero offset in this panel).  To avoid this
reduction in amplitude, an estimated average
hemodynamic delay (in units 0.0 to 1.0, where 1.0
equals one full stimulus cycle) can be applied
prior to the 'phaseaverage' operation.

Action Button--COMBINE

This button performs the 3D phase average of
the fourier-analyzed data sets that you have
selected and writes the result into the current
sig average directory as a new set of 3D files.

Action Button--PAINT

This button samples the combined data onto the
surface specified in "Surface for Sampling 3D
Data" in the Fourier panel.  The result is four
new files, two for each hemisphere, which consist
of the real and imaginary components of the
combined Fourier statistics (*.w files) which can
be directly displayed on the surface with View
Functional Data panel.  Note that this button
generates files for both hemispheres, regardless
of which hemisphere is currently selected.

Input and Output Files

 infiles (Fourier-analyzed files--complex data):

   -----------------------------------------
   session1/scandir1/scanname1_r_%03d.bfloat 
   session1/scandir1/scanname1_i_%03d.bfloat 
   -----------------------------------------
   session1/scandir2/scanname1_r_%03d.bfloat 
   session1/scandir2/scanname1_i_%03d.bfloat 
   -----------------------------------------
   ...


 outfiles (3D files--complex data):

   ---------------------------------------------
   currentsession/sigavg/scanname1_r_%03d.bfloat 
   currentsession/sigavg/scanname1_i_%03d.bfloat 
   ---------------------------------------------

 outfiles (paint files--complex data):

   ----------------------------------------
   currentsession/sigavg/scanname1_r-rh.w
   currentsession/sigavg/scanname1_i-lh.w
   ----------------------------------------
   currentsession/sigavg/scanname1_r-lh.w
   currentsession/sigavg/scanname1_i-lh.w
   ----------------------------------------

#############################################################
------------------------------------------------
 The SessionsTools -> Combine Surface Stats
 menu averages already-painted surface stats
------------------------------------------------
This panel creates a new scan directory that
will contain averaged surface-based statistics
(possibly cross-session).

Configure Buttons--Make SurfAvg Dir, Unset Dir

First carefully choose a name for the average
directory in the entry to the right of the Make
Avg Dir button.  Clicking Make SurfAvg Dir
creates that directory.  If the directory already
exists, it will be re-used rather than
re-created.

To ignore an existing surface average directory,
use Unset Dir.  The files in the unset directory
will not be altered and any saved parameters will
re-appear if you click Make SurfAvg Dir with that
directory name again.

Choosing Stat Files to Average

Choosing the pre-painted stats to average is a
three-part process.

First select a session from which a scan will be
chosen, by selecting a session using the
"Functional Sessions to Choose From" dropdown
combo box at the top.  This allows you to average
scans across different sessions, as long as they
are in the current Functional Sessions directory
($FUNCTIONALS_DIR).  The statistics to average
must have been painted using a single subject's
surface (the same version of it!).  If you want
to select a scan from the currently open session,
you have to hit 'Enter' in the combo box.

Second, once you have selected a session, the
dropdown combo box on the next line at the left
("Select Both", meaning both hemispheres) will
now contain the individual scan directories in
that session.  Select one scan directory.  If the
scan directory contains pre-painted data, the
dropdown combo box immediately to the right
("Vertex List Prefix") will be updated.

Finally, select one of the pre-painted vertex
list prefixes in the "Vertex List Prefix"
dropdown combo box to the right.  If the paint
file is from a retinotopy session, the real and
imaginary infixes will be automatically stripped
(you only need to select either the real or
imaginary file).

Once you have selected one of the paint files,
the full path to it will be added to the central
"Fullpath Vertex Lists to Combine" panel.  To
delete (or re-order) directories from that list,
select one in the list and use the Delete or
Backspace key.

Reversing Phase of Stat Files

If scans to be combined do not have the same
phase direction (e.g., clockwise vs. counter-
clockwise direction of the moving sector in a
polar angle mapping experiment), the phase of one
or more scans can be reversed by selecting the
scan to be reversed, and then typing Return (or
double-clicking).  "Reversing the phase" means
taking the negative of the phase angle calculated
for each voxel.  This is equivalent to reversing
the direction of time in the time domain.

Combine Operations

Now select a combine operation.  The operation
'realaverage' simply averages two real-valued
data sets (e.g., F-stats).  The other three
operations average complex data sets and differ
only in how they setup the default color scale
options in the View Functional Data panel.  For
complex data sets, you can introduce a phase
offset for each data set that differs from zero
(see below).

Use Script, New Script checkbox

If the "Use Script" checkbox is selected, a
editable combine script will be created (IRIX
only, using binary: surfcombine).  Checking "New
Script" overwrites/re-generates a fresh version
of this file if it already exists.

Action Button--SURFCOMBINE

This button performs a surface-based average of
the pre-painted stats data sets that you have
selected and writes the result into the current
surf average directory as a new set of painted
files (*.w files) which can be directly displayed
on the surface with View Functional Data panel.
Note that this button operates on the files for
both hemispheres, regardless of which hemisphere
is currently selected.

When you click the SURFCOMBINE button with "Use
Script" *un*-checked, the selected paintfiles are
combined (using binary: rcxcombine).

When you click the SURFCOMBINE button with "Use
Script" checked (currently IRIX only), a small
text file with a *.scom suffix is created and
opened using the default text editor.  This file
will be used by the surfcombine program to do the
averaging after you click "OK" on the alert
panel.

You can edit the file in the editor before it
is used.  For example, you can use non-zero
angle_offsets for each file (OK to have a
different angle offset for each file) or the
phase can be reversed for one or more input
files.  Do this by changing the default arguments
of the transform_angles command:

  transform_angles <revphaseflag> <angle_offset>
                     default=0     default=0.0

The commands that can be placed in the *.scom
file and their arguments are:
  ---------------------------------------------
  setdir <directory_path>
  read_real    <stem-hemi.w>
  read_complex <stem_r-hemi.w> <stem_i-hemi.w>
  average_real    <number_of_files_to_average>
  average_complex <number_of_files_to_average>
  smooth_real    <steps>
  smooth_complex <steps>
  transform_angles <revphaseflag> <angle_offset>
  write_real <stem-hemi.w>
  write_complex <stem_r-hemi.w> <stem_i-hemi.w>
  ---------------------------------------------

Input and Output Files

 infiles (paint files--complex data example):

   ----------------------------------
   session1/scandir1/scanname1_r-rh.w
   session1/scandir1/scanname1_i-rh.w
   session1/scandir1/scanname1_r-lh.w
   session1/scandir1/scanname1_i-lh.w
   ----------------------------------
   session2/scandir1/scanname1_r-rh.w
   session2/scandir1/scanname1_i-rh.w
   session2/scandir1/scanname1_r-lh.w
   session2/scandir1/scanname1_i-lh.w
   ----------------------------------

 outfiles (paint files--complex data example):

   ----------------------------------------
   currentsession/surfavg/scanname1_r-rh.w
   currentsession/surfavg/scanname1_i-lh.w
   ----------------------------------------
   currentsession/surfavg/scanname1_r-lh.w
   currentsession/surfavg/scanname1_i-lh.w
   ----------------------------------------

#############################################################
------------------------------------------------
 The SessionsTools -> Calculate Visual Field Sign
 sets up two Fourier-analyzed data sets in order
 to calculate the visual field sign (mirror vs.
 non-mirror image representation)
------------------------------------------------
This panel calculates the visual field sign using
two Fourier-analyzed data sets--one for in which
eccentricity was mapping and the other in which
polar angle was mapped.

The gradients in retinal eccentricity and polar
angle with respect to cortical x and y are
computed.  These two gradients are vector
quantities whose norms have units deg/mm (the
reciprocal of magnification factor). They are
computed by fitting a plane to the r (or theta)
values of the current vertex and its immediate
neighbors using least squares.  The clockwise
angle between them (the fieldsign angle) is then
measured to determine whether the local
representation of the visual field at that vertex
was non-mirror-image (angle near Pi/2) or
mirror-image (angle near -Pi/2). Finally, the
intensity of the field sign coloring was adjusted
using the average significance from the
eccentricity and polar angle data sets.

Input Files

There are eight Fourier-analyzed, painted
input files for this operation:

 $FUNCTIONALS_DIR/sess1/image/eccen/ecc_r-rh.w
 $FUNCTIONALS_DIR/sess1/image/eccen/ecc_i-rh.w
 $FUNCTIONALS_DIR/sess1/image/polar/pol_r-rh.w
 $FUNCTIONALS_DIR/sess1/image/polar/pol_i-rh.w

 $FUNCTIONALS_DIR/sess1/image/eccen/ecc_r-lh.w
 $FUNCTIONALS_DIR/sess1/image/eccen/ecc_i-lh.w
 $FUNCTIONALS_DIR/sess1/image/polar/pol_r-lh.w
 $FUNCTIONALS_DIR/sess1/image/polar/pol_i-lh.w

Eccentricity and Polar Angle Scan comboboxes

Select an eccentricity functional scan in the
"Scan Directory" combo box.  A *.w file must
appear in the "Vertex List Prefix" combo box
immediately to the right.  Do the same for a
polar angle functional scan.

Smoothing Steps

Since the fieldsign calculation involves
gradients (derivatives), the data needs to be
heavily smoothed to reduce noise (default: 50
steps)

Action Button--FIELDSIGN

This generates four files, two for each
hemisphere.  The fieldsign itself is stored in
{rh,lh}.fs while the fieldsign significance mask
is in {rh,lh}.fm.

 $FUNCTIONALS_DIR/sess1/image/fs/rh.fs
 $FUNCTIONALS_DIR/sess1/image/fs/rh.fm

 $FUNCTIONALS_DIR/sess1/image/fs/lh.fs
 $FUNCTIONALS_DIR/sess1/image/fs/lh.fm

#############################################################
------------------------------------------------
 The SessionsTools -> Import 3D Stats sets up
 to import statistical data set that have already
 been analyzed with AFNI (or SPM)
------------------------------------------------

Select Input Data Set

First select the input data set to extract and
convert.  The interface will crudely guess at the
StatType using the input file suffix:

  <stem>.img         => SPM
  <stem>.BRIK/HEAD   => AFNI-SINGLE
  <stem>.BRIK/HEAD   => AFNI-MULTI (BRICK_LABS)
  <stem>_%03d.bfloat => BFLOAT

After checking the configuration, then press
EXTRACT/CONVERT.  If this works without error,
press PAINT.

SPM Format

The SPM extraction requires that matlab
be installed (to extract the transformation
matrix) and has not been updated in a long time.
For now, convert to BRIK and use AFNI import.

AFNI BRIK Format

The tools for extracting and converting AFNI
files analyzed with 3dDeconvolve have been more
thoroughly tested.

If a BRIK contains no labels (BRICK_LABS field
in *.HEAD file) or only a single default label
('#0~), it will be treated as an AFNI-SINGLE
import, which allows the extraction of a single
subbrik ("Briks to Skip" selects which subbrik
to extract, if there are more than one).

An extra sub-panel appears when a BRIK containing
multiple labels is selected.  After pressing
the READ HEADER button in the sub-panel, you
should then be able to choose which sub-briks
to extract, which sub-briks to use as maskfiles,
and what the mask threshold should be.  You can
also run clustering and set the cluster radius
and volume.

Paint

Pressing PAINT, paints all the extracted
3D files onto the chosen cortical surface,
using the current vertex normal operation (same
operations as on Setup Align/Funct Scans panel,
for explanation, see Help for that panel).
You can then view all of the painted files later
on in the rendering panel:

  SessionTools -> View Functional Data

where there is a set of radiobuttons near the top
of the panel that allow the rendering of multiple
extracted sub-briks from a single scan directory.
The options are:

 one  -- render selected (single) vertex file
 last -- render all vertexfiles from last extract
 all  -- render all vertexfiles (except complex)

When the multiple-render options are clicked, 
the selected vertex file changes to "-multiple-".
The stems of the output rgb files in that case
are the same as the stems of the sub-briks.

BFLOAT

The bfloat format is a slice-based format with a
minimal header that is used internally by
FreeSurfer programs, and that can be easily be
generated by an external C program.  The filename
format for each slice file and header file is:

  <stem>_%03d.bfloat
  <stem>_%03d.hdr

The slice numbering is zero-based.  The first
slice is therefore:

  <stem>_000.bfloat
  <stem>_000.hdr

The bfloat file is a headerless string of floats
with x as the inner loop (x is the R->L direction
in tkregister when a default (identity matrix)
register.dat is loaded).  The hdr file is an
ASCII file that contains 4 strings:

  <xsize> <ysize> <numtimepoints> <other>

For example:

  64 64 1 0

Note that for binary compatibility across all
platforms, the bfloat files are stored in
SGI/Sun/Mac byte order.  All the FreeSurfer
programs automatically swap bytes on read and
write on Linux.  For this reason, if bfloat files
are generated by a simple C program in Linux
using fwrite(), you should swap the bytes as the
last step.  For example, you could run AFNI 4swap
on each bfloat after generating it.  The hdr
files are ASCII and therefore don't need to be
swapped.

#############################################################
------------------------------------------------
 The SessionsTools -> View Functional Data sets
 up to paint 3D statistics onto high resolution
 3D data sets (medit) or onto different views
 of the cortical surface (surfer)
------------------------------------------------
The basic layout of this panel (scan directories
to the left, common action button at the top,
pages of parameters to the right) is similar to
the other SessionTools panels.  For more details,
see Help -> Setup Align/Funct.

First select a scan directory at the left and
click "Render Stats Dir" at the top to get a new
page of parameters.  Each field in the page is
described from top to bottom.

Painted Vertex List Prefix (VtxList Pref)

This is the stem for files that are generated
when you hit the PAINT button on functional
analysis panels.  The full files (for the right
hemisphere) may have the following forms:

 <stem>-rh.w      real data (e.g., corr)
 <stem>f-rh.w     signed F-stats exponents
 <stem>_r-rh.w    real comp of Fourier
 <stem>_i-rh.w    imaginary comp Fourier

These files contain lists of vertex-number/value
pairs.  These values can be rendered onto any
transformation of a surface (folded, unfolded,
flattened patch, etc) that has the same number of
vertices.

When you select one of the stems that has an
infix (e.g., _r, _i, f), the infix is
automatically stripped off (the polar, eccen
and twocond scripts use this stem to read two
files).

The set of radiobuttons directly to the right 
of the Painted VtxList Pref selector allow the
the rendering of multiple extracted sub-briks
from a single scan directory.  The options are:

 one  -- render selected (single) vertex file
 last -- render all vertexfiles from last extract
 all  -- render all vertexfiles (except complex)

When the multiple-render options are clicked, 
the selected vertex file changes to "-multiple-".
The stems of the output rgb files in that case
are the same as the stems of the sub-briks.

Saved Images Prefix

This is the name of the stem of the bitmap(s)
that will be generated when SURFACE-STATS or
VOLUME-STATS is run.

Stat Color Scales

There are four color scales available from csurf,
some of which have more than one behavior.  Other
less common color scales are available from the
large version of the surfer tools panel.

  Colwheel (w1)

  This color scale was originally designed for
  phase-encoded data (e.g., retinotopic
  mapping).  The hue represents the phase and the
  saturation represents the strength of the
  response.

  With integral anglecycles (1,2,3), the scale is
  red(early)->blu(intermed)->grn(late) wrapping
  around at red.  This is used for eccentricity
  data or two-condition data.  With anglecycles=1
  each phase has a unique color.  To compensate
  for hemodynamic delay, angleoffset should be
  decreased (-0.1 same as 0.9).  To convert
  angleoffset into seconds, multiply it by the
  time for one cycle.

  With anglecycles set to a non-integral number,
  there is only one red->blu->grn cycle.  In this
  mode, phase values below red are clamped to red
  and phase values above green clamped to green,
  each fading to gray.  To completely remove half
  of the phases opposite to the red->blu->grn,
  use truncphase (oldcsurf only).  Truncphase has
  no effect with integral anglecycles.  For
  non-integral angleoffsets between 1 and 2,
  there is an additional 1/6 of a cycle offset
  not seen with angleoffsets between 2 and 3 (the
  normal usage).  Thus, these pairs will color
  phases (in the first cycle) equivalently:

                   anglecycles   angleoffset
                   -----------   -----------
    integral          1.0           0.0
    non-integral      1.0001        0.1666

    integral          2.0           0.0
    non-integral      2.0001        0.0

  To see strongly activated regions, set
  fmid to 1.5, fslope to 1.5, and fthresh to
  0.3.  If the absolute threshold (fthresh) is
  kept low, fmid can be used to adjust the
  effective threshold without introducing
  artifactual edges.

  It is difficult to represent the full range of
  exact values of phase using color alone.  A
  more fine-grained representation can be
  obtained by running the phasemovie.tcl script
  from Surfer Tools.  This steps through each
  phase (total number of steps adjustable),
  drawing a white contour line for a small range
  of phases (width of range adjustable).  With
  invphase and revphase off, the white phase
  marker progresses from regions responding best
  to the beginning of each stimulus cycle toward
  regions responding to the end of the cycle.

  Mapping stimuli that start horizontal

  For a counter-clockwise rotating polar angle
  stimulus that starts at the right (zero deg),
  the default settings for Phase/Rev,Offset in
  the View Functional Data panel are (ignoring
  hemodynamic delays):

  Phase/Rev,Offset: [ ] "RH" 0.0   [x] "LH" 0.5

  Note that the offset for the right hemisphere
  is zero when the stimulus starts in the right
  hemifield, which is counterintuitive, but,
  unfortunately now conventional.

  These settings result in brain regions
  representing the contralateral upper field
  being colored red, brain regions representing
  the contralateral lower field colored green,
  and the brain regions representing the
  contralateral horizontal meridian colored blue,
  in *both* hemispheres.

  Adjust settings if the stimulus is different.
  For example, for a clockwise rotating polar
  angle stimulus that also starts right, reverse
  the opposite hemisphere:

  Phase/Rev,Offset: [x] "RH" 0.0   [ ] "LH" 0.5

  For a counter-clockwise rotating stimulus that
  starts on the left, use RH offset=0.5 and LH
  offset=0.0, and so on.

  Mapping stimuli that start vertical

  For a clockwise rotating polar angle stimulus
  that starts at the *top* (e.g., a stimulus that
  first enters the top right hemifield or the top
  right side of the face), you have to add a
  quarter cycle to the values above.  Since one
  hemisphere is reversed, the quarter cycles make
  the angle offsets the same for both hemispheres
  (again assuming no hemodynamic delay).

  Phase/Rev,Offset: [x]"RH" 0.75  [ ]"LH" 0.75

  If a clockwise stimulus starts at the bottom,
  then the offsets should both be set to 0.25

  To get an interactive, screen-dump-able
  representation of how the color wheel code
  colors each phaseangle or how significance
  and phase angle interact, use the included
  program, wheel:

    wheel <0-3> [opts]

  and adjust rendering parameters with F1-12.
 
  Pseudocode for non-integral anglecycles:
    find amplitude from real/imaginary
    trunc amplitude to zero below fthresh
    run non-trunc'd amplitude through sigmoid
    find phase from real/imag in -0.5 to 0.5
    if reverse => take negative of phase angle
    if inverse => add 0.5 to phase angle
    subtract angle_offset from phase angle
    fmod/add-1-to-neg => phase back in 0-1
    [truncphase currently broken -- don't use]
    if truncphase => zero outside 0.25 to 0.75
    subtract 0.5 from phase angle
    multiply phase angle by anglecycles
    if less than -1/3 => red
    if less than 0    => red to blue
    if less than 1/3  => blue to green
    greater than 1/3  => green
    fade ipsilateral colors (def: fadef=0.7)
    fade into two background grays

  Heatscale (ht)

  The heat color scale here represents the
  significance of the response and has two main
  behaviors.

  With fourier-analyzed (complex) data, the heat
  scale runs from dark brown to white and
  displays any brain region significantly
  activated in a periodic fashion (i.e., all
  phases).  Truncphase can be used to truncate
  half of the phases and angleoffset controls the
  exact half that are truncated.  The angleoffset
  for two condition expt with 20s ON and 20s OFF
  should be something like 0.1 (this is in units
  of one cycle: 0.1 * 40 sec = 4 sec delay).

  The heat color scale can also be used to
  display F-statistics.  The analysis performed
  by the Fourier panel generates a third file,
  <stem>f-$hemi.w.  This will be read in if (1)
  the Complex button is *un*-set, and (2) the
  twocond tcl scripts are used in place of the
  polar or eccen tcl scripts.  Unlike the first
  heat scale, this one is calculated for a single
  delay, settable when FOURIER is run in the
  Fourier panel (changing this delay does *not*
  affect the color wheel and complex heat scale
  statistics).  Foci activted by ON-first are
  red->yellow while foci activated by OFF-second
  are blue->lightblue.  This scale can be
  truncated with truncphase and reversed with
  invphase (surfer tools).  The values of fthresh
  and fmid represent negative powers of ten of
  p-values.  Foci visible with fmid set to 4.0
  are strongly significant.  The scale bar values
  are:

    threshold        = fthresh
    full red/blue    = fthresh + fmid
    full yellow/cyan = fthresh + fmid + 1/fslope

  One strategy to set the F-stats delay is to run
  an angle offset movie using the complex heat
  scale with truncphase ON, using a tcl script
  (scripts: offsetmovie.tcl) and then enter a
  reasonable angleoffset (generally not more than
  plus or minus a quarter of a full cycle) that
  best captures all of the ON activations into
  the delay field of the Fourier panel, re-run
  Fourier, and re-render using the F-stats
  (non-complex) heat scale.

  Blue/Red->white (BRw)

  Two-condition statistic color scale for real,
  signed data.  Red positively correlated; blue
  negatively correlated (reversible with
  revphaseflag).  As significance increases,
  scale goes to white for both positive and
  negative correlations.  Not affected by
  angleoffset, anglecycles, invphase (N.B. this
  scale will give spurious results if it is used
  to display complex data).

  Fieldsign (fs)

  This binary color scale is designed for field
  sign data only.  Yellow is mirror-image field
  sign and blue is non-mirror-image fieldsign.
  Reversible with revphaseflag.

Smoothing Steps on Surface

Controls how many nearest-neighbor smoothing
steps are done before display.  These are
performed on the finer mesh of the surface, not
on the coarser mesh of the functional scan.  To
see the effects interactively, use the surfer
tools SMOOTH button with the radio button set to
'val' (operates on data currently on the top of
the value stack).

An empirically derived correspondence between
the number of smoothing steps and the average
full-width-at-half-max filter result starting
with a single non-zero vertex is:

  steps   FWHM (mm)
 --------------------
   10      3.20
   20      4.49
   30      5.36
   50      6.99
   70      8.31
  100     10.15
  230     ~1.5 cm
  400     ~2 cm
  900     ~3 cm
 --------------------

A power function fit to this empirical map
(r^2 = 0.9987) is:

  fwhm = 0.9921 * steps^0.5018

Statistical Threshold (fthesh)

This is a hard thresh.  The meaning of the
value depends on the current scale.

Statistical Contrast (fslope)

Controls the steepness of a sigmoid (or a double
sigmoid in the case of two-ended color scales).
Larger values make the color scale change more
rapidly for a given change in a statistic.

Statistical Midpoint (fmid)

Sets the location of the fastest changing part of
the sigmoid (or of a double sigmoid for two-ended
scales).  This is typically used to set the
effective threshold.

PhaseReverse (revphase), Offset (angleoffset)

The phase can be reversed, and an offset can be
added to it independently for the two
hemispheres.  The Offsets (angleoffset) are only
relevant for complex-valued color scales
(colwheel, heatscale w/complex on).

Color Wheel Cycles

Integral values for the color wheel cycles cause
the color wheel of phases to wrap around one or
more times while non-integral values cause there
to be one cycle through the color wheel with
phases off its ends clamped to the ending color
(see 'Colwheel' above).

Complex

Indicates that the statistical data is
complex-valued (use colwheel and heatscale).  To
see F-stats, select heatscale, *un*select
Complex, and select twocond scripts.

Truncphase

Truncate one half of the phases of the response
to zero.  Color-scale-dependent behavior (see
above).

mm, ColBar

Turn the millimeter and color scales on or off.

Bri

Turn on brighter render (more top light, overall
brighter curvature background, reduce light/dark
gray curvature contrast).

Curv

Turn on curvature background (off->uniform gray).

Views

These buttons select which views will have a
bitmap saved for them when SURFACE-STATS is
clicked.  The 'cust' view (custom) is a special
case.  Clicking it will expose an additional 12
fields than can be used to define a custom view
for each hemisphere.  If this is done for the
current scan dir, the next scan dir that is
defined as a "Render Stats Dir" will
automatically start with the current 'cust'
values. The transformations listed are applied
left to right.

3D and Flat Tcl Scripts

These tcl scripts control the startup of the
surfer tools.  These scripts are found in
FreeSurfer/lib/tcl/*.tcl.  For retinotopy, use
eccen, polar, and fs.  For phase analysis of two
condition, use eccen or twocond.  For real-valued
data read in from external programs (e.g.,
correlation coefficients), use real.

To convert (old) fmid to p:

  plot(fmid, -log10(1-fcdf(fmid.^2,sdf,ndf))

where sdf and ndf are signal and noise degrees
of freedom.
#############################################################
------------------------------------------------
 SessionsTools -> Run Batch Process runs
 through each SessionTools panel that is
 currently configured and presses the action
 buttons at the top right to re-perform the
 actions of the panel.
------------------------------------------------
Once an initial analysis of the data has been
performed, it is often necessary to re-run parts
of the analysis.  The Run Batch Process panel
automates this.

On the first pass through the analysis, each
panel is manually configured and action buttons
are pressed to generate data files.

The Batch Process panel is used to redo all or
parts of the analysis.

Examples

1) If motion correction is redone (e.g., using
   a different TR), all actions on all the
   subsequent panels need to be redone.  In this
   case, select all the boxes in the BATCH
   PROCESS panel.

2) If the FUNCT=>STRUCT registration is touched
   up, select Paint Surface, Calculate Surface
   Stats and Run Rendering Panels.

3) To use a different delay in the Fourier panel
   (affect F-stats), select Fourier and all
   following boxes

The Batch Process panel actually opens the
individual panels and presses the button, so you
can see the individual steps that are performed.
To skip a directory, Unset it (the previously
saved configuration will be retrieved if you
re-declare the directory).

The Batch Process Panel Saves Bitmaps

The one difference between running actions using
Batch Process and actually clicking the buttons
is that on the View Functional Data panel, the
bitmaps you have configured (Views: radio buttons
near the bottom of the panel) will actually be
saved into the <session>/image/rgb directory.

Run Each Panel Manually the First Time

It is currently not possible to run Batch process
initially because some files and directories
needed for configuring subsequent actions won't
yet exist the first time through the analysis.

#############################################################
#############################################################
------------------------------------------------
 Csurf -- cortical surface program manager
------------------------------------------------
The data base consists of two main directories:

(1) the subjects tree (e.g., /usr/subjects)

  Permanent home of structural MRI data, filtered
  MRI data, and folded, unfolded, and flattened
  surfaces for subjects.  The startup value of
  this must be set with:

    setenv SUBJECTS_DIR <whatever>

  The directory (database) name for each subject
  is typically a first name plus last initial
  (e.g., martys).  The root of the subjects tree
  can be interactively changed with csurf.

(2) functional sessions tree (e.g., /usr/fspace)

  Directory containing individual functional
  sessions.  The startup value of this must be
  set with:

    setenv FUNCTIONALS_DIR <whatever>

  A session is defined as a set of scans taken
  with one subject, in one position, in one RF
  coil.  Individual sessions can be saved
  anywhere.  The name for a session is a date,
  then initials.  The date is in year/month/day
  order so 'ls' will sort a bunch of them
  chronologically (e.g., 000624MS).  The root of
  the sessions tree can be interactively changed
  with csurf.

Each functional session directory (e.g.,
000624MS) is associated with a single subject
directory (e.g., martys).  However, several
different sessions may point to the same
subject.

Csurf generally runs programs from the "scripts"
subdirectory inside the currently selected
session or subject.  A flat file of current
configurations--csurf.dat--is stored there.  It
is read by csurf on entering that session or
subject, and written when you press SAVE or
SAVE/CLOSE on one of the csurf configuration
panels, or when you actually perform an action.
If you remove or move aside the csurf.dat file,
the current configuration of a session or subject
directory will be forgotten, but no data files
will be affected.

The "scripts" directory is also the directory in
which ASCII notes are conventially made.  There
are menu items under File to automatically open
the current subject or session's NOTES file in a
text editor to encourage this practice.

There are two main sets of menu items,
SubjectTools and SessionTools for manipulating
the two main directory trees.  The menu items
within each one are arranged in the order in
which they are normally run.

The general procedure is to first reconstruct a
surface.  Once a surface has been reconstructed,
individual functional sessions can be associated
with it, and statistics can be calculated in 3D
or on the surface, and then rendered.

Log View

As csurf runs command line programs in the
background, it pipes their outputs into a log.
These outputs can be viewed at any time with
Preferences -> View Logs (Alt-l).  There are
three logs--one for medit, one for surfer, and
one for command line programs.  When you quit
csurf, the entire contents of the log is saved
into a file in the current scriptsdir: csurf.log

User Setup

Individual users need at minimum, 4 lines that
look something like this in their .cshrc files:

 setenv CSURF_DIR        /usr/local/FreeSurfer0.8
 setenv SUBJECTS_DIR     ~/subjects
 setenv FUNCTIONALS_DIR  ~/fspace
 source $CSURF_DIR/FreeSurferDefs.csh

Other useful aliases:

 # cd to subj/session scripts dir w/just name
 alias cds 'cd $SUBJECTS_DIR/\!*/scripts; ls'
 alias cdf 'cd $FUNCTIONALS_DIR/\!*/*/scripts; ls'
 alias surfdoc \
  'acroread $CSURF_DIR/docs/FreeSurferManual.pdf'

Per-Vertex File Formats

  The format of some of the per-vertex files has
  changed in more recent distributions of
  FreeSurfer.  There is a new curvature file
  format (*.curv, *.sulc), the area file format
  (*.area) was discontinued (new area files have
  the same format as new curvature).  The value
  file format (e.g., paint output files, *.w) is
  unchanged.  The curvature and area files list
  data for every vertex and contain no vertex
  numbers.  The value files contain a list of
  vertex/value pairs so a subset of vertices may
  be specified.  The byte sizes for the different
  file types are:

  file type             olddist     newdist
  --------------------------------------------
  curv (*.curv,*.sulc)  33{2},..    344{4},..
  area (*.area)         33{4},..    344{4},..
  val (*.w)             23{34},..   23{34},.. 
  --------------------------------------------

Details of file formats (byte sizes in brackets):

  oldcurv
    header:  vertexcnt[3],facecnt[3]
    data:    floatcurv*100[2], ...
  newcurv
    header:  -1[3],vcnt[4],fcnt[4],valspervtx[4]
    data:    floatcurv[4], ...
  oldarea
    header:  vertexcnt[3],facecnt[3]
    data:    floatarea[4], ...
  newarea
    [same as newcurv]
  valfile
    header:  latency[2],vertexcnt[3]
    data:    {vtxnum[3],floatval[4]}, ...
#############################################################

#################################################
#################################################
 This is the default (UCSD) template that appears
 when you select File -> Open Subject NOTES or
 File -> Open Functional NOTES for the first time
 in a subject or functional directory.  This
 template file is stored here:

   $CSURF_DIR/lib/help/csurf/defnotes

 Edit that file to setup site-specific NOTES.
 Also, each user can set up their own default
 NOTES file in:

   ~/.csurfnotes

 The subject- and session-specific (edited by
 user) versions of this file are stored here:

   $session/image/scripts/NOTES
   $subject/scripts/NOTES
#################################################
#################################################


=================================================
Minimal instructions for reconstructing a surface
=================================================
The latest tarball of the UCSD retinotopy-enabled
FreeSurfer (FreeSurfer0.8.tar.gz) is here:

  http://kamares.ucsd.edu/~sereno/csurf/tarballs 

First, decide where you are going to root your
tree of subjects and sessions, and then set these
environment variables to reflect this (the
directories must exist):

  setenv SUBJECTS_DIR /some/place/subjects
  setenv FUNCTIONALS_DIR /some/place/sessions

Now setup your path and start the csurf interface
(you can put the "source ..." line in your .cshrc
to do automatically):

  source \
    /mnt/raid1/sereno/local/etc/FreeSurfer.cshrc
  newdefs
  csurf

To make the highest-quality surface, it is best
to manually align and average two 1x1x1mm MPRAGE
or SPGR scans. To do this, the first step is to
make an new, empty subject (subject "marty" in
the following examples):

  File -> New Subject

Convert the DICOM files to BRIKs, force native
FreeSurfer byte order, make some subdirectories
in the mri/orig subdirectory of the newly made
blank subject, and copy the raw BRIK's into
them:

 cd /raw/s219027
 to3d -prefix spgr1 i*
 forceMSB spgr1+orig.BRIK
 mkdir $SUBJECTS_DIR/marty/mri/orig/spgr1
 cp spgr1+orig.* $SUBJECTS_DIR/marty/mri/orig/spgr1

 cd /raw/s219198
 to3d -prefix spgr2 i*
 forceMSB spgr2+orig.BRIK
 mkdir $SUBJECTS_DIR/marty/mri/orig/spgr2
 cp spgr2+orig.* $SUBJECTS_DIR/marty/mri/orig/spgr2

Now convert the two (or more) scans into the
native COR format and manually align them:

  SubjectTools -> Setup Structural Scans

  [select first scan subdir in list at left]
  Structural Scan Dir
  READ HEADER => check parameters are correct!
  Add "Flip" parameters if scan not coronal:
  -> Thornton sagittal -> coronal: -z y x
  -> fMRI center axial -> coronal: x -z y
  N.B: for fMRI center mp_anat3d scans, add:
    Other Options: -prescale 25

  [select second scan subdir in list at left]
  Structural Scan Dir
  READ HEADER
  Add "Flip" parameters if scan not coronal:
  -> Thornton sagittal -> coronal: -z  y  x
  -> Cent Varian axial -> coronal:  x -z  y
  -> Cent GE axial     -> coronal:  x -z -y

  N.B: for fMRI center mp_anat3d scans, add:
    Other Options: -prescale 25

A single 1x1x1 mm mp_anat3d scan can also be used
if you collect 256 slices (16 minutes) (N.B.:
because mp_anat3d is a volume protocol,
collecting more slices -- even slices outside the
brain -- actually improves the signal in the
central slices).

Finally, start up the manual align:

  CONVERT/AVERAGE 

When buttons turn purple in csurf, something is
going on in the background. If you want to kill
whatever is happening, click the purple button.

CONVERT/AVERAGE will convert the scans to COR
(optionally flipping) and eventually put up the
tkregister application which allows you to flip
back and forth between two 3D scans and align one
(the "MOVEABLE") to the other (the "TARGET").
When you are satisfied, then SAVEREG, and quit
the tkregister application. This will cause csurf
to average the two scans and put the result into
the mri/orig directory (viewable with by picking
the "orig" set of 3D images and hitting the
VOLUME button in csurf). If you only use one
scan, the register step will be skipped.

Now you can start up the 'big button'. This takes
about 4 hours to run on a modern Linux machine
(2GHz). It reconstructs the cortical hemispheres
of each hemisphere, unfolds each one, and then
makes a high quality estimate of the pial surface
and the gray/white matter surface.

  SubjectTools -> Process/Create/Fix/Final

When this finishes, take a look at the surfaces
using the SURFACE button in csurf. If things
don't look right, then edit the segmentation:

  SubjectTools -> Edit Segmentation
  SubjectTools -> Create Surface
  [possibly repeat above two if surface bad...]
  SubjectTools -> Fix/Final

Now you may want to make cuts in order to flatten
part of all of the each hemisphere:

  SubjectTools -> Make Full Surface Cuts

or

  SubjectTools -> Make Occip Surface Cuts

After doing this, then flatten both hemisphere
with:

  SubjectTools -> Flatten Surface

This takes about 4 hours per hemisphere (on the
same 2GHz machine).

==============================================
Minimal instructions for retinotopy analysis
==============================================

The cortical surface is typically reconstructed
from several MPRAGE or SPGR scans taken during a
"structural scan" session (above).

Then, on a number of subsequent "functional scan"
days, we collect an "alignment" scan in the same
plane as the set of "functional" scans (but with
higher resolution). The alignment scan is first
rotated into alignment with the original
structural scans from which the surface was made.
Then the registration matrix is copied (using the
interface) into the functional scan directories,
and touched up by directly comparing the
functional scans to the original high resolution
structural scan.

This makes it possible to collect a large amount
of data on single subjects. Here is an example of
how to collect data on mapping visual areas.
Source code and binaries for the "mapper"
retinotopy stimulus program is available here:

  http://kamares.ucsd.edu/~sereno/stim/IRIX
  http://kamares.ucsd.edu/~sereno/stim/MacOSX
  http://kamares.ucsd.edu/~sereno/stim/Linux
  http://kamares.ucsd.edu/~sereno/stim/src

First start up csurf again:

  newdefs
  csurf

Then make a new blank functional session
directory:

  File -> New Functional

This will query you for a subject name (and a
reconstructed surface) that belongs to the person
from which this functional data was collected. It
has to already exist. For the following example,
the functional session is given a name that sorts
chronologically (year/month/day/initials):

  020930MS

Make subdirectories for each functional scan as
well as the alignment scan in a session:

  cd $FUNCTIONALS_DIR/020930MS/image
  mkdir polar eccen mprage

Copy the raw mprage and functional BRIK's and
HEAD's into those directories and run "flipbrik"
on each functional BRIK like this:

  cp /raw/data/mp_anat3d_01+orig.BRIK mprage
  cp /raw/data/mp_anat3d_01+orig.HEAD mprage
  [don't run flipbrik]

  cp /raw/data/spep_#001+orig.BRIK polar
  cp /raw/data/spep_#001+orig.HEAD polar
  flipbrik \
    polar/spep_#001+orig polar/spep_#001+orig

  cp /raw/data/spep_#002+orig.BRIK eccen
  cp /raw/data/spep_#002+orig.HEAD eccen
  flipbrik \
    eccen/spep_#002+orig eccen/spep_#002+orig

Flipbrik changes the internal ordering of the
data in the AFNI BRIK (and updates the HEAD) so
that x rather than y is the fastest changing
index.

Next, strip off the first three time points
(initial blips-off phase correction acquisition
plus first two non-steady-state TR's):

  cd $FUNCTIONALS_DIR/020930MS/polar
  3dTcat -prefix polar spep_#001+orig'[2..$]'

  cd $FUNCTIONALS_DIR/020930MS/eccen
  3dTcat -prefix eccen spep_#002+orig'[2..$]'

Now open the first panel in the
SessionTools set:

  SessionTools -> Setup Align/Funct Scans

select the alignment scan from the list at the
left at the left and declare the scan to be an
alignment scan by hitting the "Align Scan Dir"
button at the top of the panel.

Now configure the alignment scan:

  read header with READ HEADER button
  enter Block Center Offset
  fix anything that looks incorrect

and then rotate and translate it into alignment
with the original scans the surface was made
from:

  ALIGN=>SUBJ (starts tkregister to align ALIGN
                scan to SUBJECT scan)

When you are done with the manual alignment, hit
SAVEREG on tkregister and quit the tkregister
application.

Now configure all of the functional scans by
selecting each one at the left, and declaring
them to be a "Funct Scan Dir", and filling in the
form:

  READ HEADER
  optionally run AFNI motion correction, 3dvolreg
  (select targ scan, targ TR in scan, hit "ALL")
  select alignment scan from the "Same-Plane
    Structural Dir:" combobox
  enter Block Center Offset
  enter distance to search for data perpendicular
    to each vertex (be reasonable)

Now go back to the Align Scan directory and copy
the transformation matrix into all the functional
directories (automatically accounting for the
difference in voxel size) with:

  COPY ALIGN TO ALL FUNCTS

Be sure to verify that the actual transformation
to be performed by PAINT is a good one by
selecting a functional directory and checking the
alignment with:

  FUNCT=>SUBJ (starts tkregister to align FUNCT
                 scan to SUBJECT scan)

To fix a y-shear in the functional image, rotate
30 deg, shrink (scale-down) y, un-rotate 30 deg,
un-shrink (scale-up) y (shrink/un-shrink x for
x-shear). You can copy your refined registration
to all the other currently configured functionals
with:

  CP TO OTHERS

Now, run the Fourier analysis:

  SessionTools -> Calculate 3D Fourier Stats

  enter the number of stimulus cycles (e.g., 8)
  choose eccen or polar phase encode type
    (presets color scales, analysis scripts)
  do the analysis: FOURIER button
  paint the data on the "orig" surface: PAINT

Optionally calculate field sign:

  SessionTools -> Calculate Visual Fieldsign

Open the rendering panel:

  SessionTools -> View Functional Data

  select scan dir to render from list at left
  select surface or patch from "surface:"
    or "patch:" comboboxes
  hit SURFACE-STATS button

If you redo your registration, you need to
re-paint and re-render everything.  If you want
to redo your registration and then re-paint and
re-render, run:

  SessionTools -> Run Batch Process

select Run All Paint Surfaces and Run All
Rendering Panels, and hit Start.  This will open
all the panels of currently configured scans, run
the PAINT button in each one, and then run the
SURFACE-STATS button in each one. In addition, it
will save bitmaps for any folded or flat views
you have configured on View Functional Data
panels.

The Help -> ... menu items have more detailed
information for all the extra panels. You can
never leave too many ASCII notes in:

  File -> Open Subject NOTES
    (in $subject/scripts/NOTES)

  File -> Open Functional NOTES
    (in $session/image/scripts/NOTES)

:-}

marty

#############################################################
------------------------------------------------
 The File -> New Subject menu creates a new
 blank subject and its standard subdirectories
------------------------------------------------
This is the first step in making a new subject
and must be performed before a new functional
session can be made for this subject.  A new
subject directory and a standard set of
subdirectories is created.  The default location
is the current setting of the environment
variable, SUBJECTS_DIR, but a subject can be made
anywhere.

Finding subjects by name is much easier with
csurf if multiple subjects are stored together in
the same SUBJECTS_DIR on a server.  This is
particularly useful for subjects for which
multiple functional sessions are planned.

The standard subject directory structure is:

 SUBJECTS_DIR (root of a subjects database)
     subjectname  (e.g., firstname+initial)
         scripts      (configs, NOTES file)
         mri          (3D MRI data)
             orig         (origscan w/subdirs)
             T1           (bright-normalized)
             brain        (skull-stripped)
             wm           (white-matter only)
             filled       (rh,lh filled)
             tmp
             transforms
         surf         (surface files)
         bem          (stripskull, EEG/MEG)
         morph        (morph to sphere)
         tmp          (send/goto point, etc)

Once the subject has been made, at least two
T1-weighted 1x1x1mm raw scans should be copied
into separate subdirectories of the mri/orig
directory of that subject.  The subdirectories
you make in there can have any name.  For
example:

  $SUBJECTS_DIR/somesubject/mri/orig/mprage1/*
  $SUBJECTS_DIR/somesubject/mri/orig/mprage2/*

The Setup Struct Scans menu scans the mri/orig
directory to find subdirectories, each of which
should contain a single scan, and averages them.
#############################################################
------------------------------------------------
 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 and press the Structual Scan Dir button.
This configures it as a directory to convert
and possibly average.  At any time, you can
press Ignore Dir to unconfigure a directory.
Ignore Dir doesn't touch anything inside the
directory.

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 the the fields are correct.

Simple Conversion

After configuring one or more directories,
press CONVERT/AVERAGE.  This does a simple
average generating the following images:

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

Auto align with AFNI 3dvolreg

For better alignment of routine images, first go
to Preferences -> Expert Preferences -> Conv.
Then choose "Auto align with AFNI 3dvolreg"
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), and average after registration is done.

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.

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

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

(when "Manual align with tkregister" is set), and
enter the pixel size and slice thickness manually.

High Resolution Surface Reconstruction

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 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

At conversion time, the data set can be flipped.
Caution: this can mirror-image the data set
(sometimes necessary).  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

#############################################################
------------------------------------------------
 HOWTO hand pre-normalize an "orig" dataset
------------------------------------------------
In cases where the automatic normalization
results in an eroded-looking brain surface, you
may have to pre-normalize the "orig" data set by
hand, and then re-run the entire process starting
with Process Volume.

Load the "orig" Data Set

First, start up Medit with the "orig" data set.
You may first want to make a copy of the original
"orig":

  cd $SUBJECTS_DIR/marty/mri
  cp -r orig orig-orig

Medit Piecewise Linear Normalization Panel

Hit F3 in the medit tools window to bring up the
extended Medit panel (F2 goes back to the default
view).  The new subpanel on the right allows you
to test and then apply a piecewise linear ramp of
brightness correction factors (ffrac0-3) at four
control points (lim0-3).  For example, if you
click I/S (inferior/superior direction) and set
lim2 => 145, and ffrac2 => 1.2, this means
multiply the brightness value of pixels at
inferior/superior position 145 (0-255) by 1.2.
Thus, if the pixel value was 134 (view pixel
value in upper border of display window) the new
pixel value will be 134 * 1.2 = 161.

There are 4 control points (lim0-3, 0-255 pixel
coords) that can be applied to one of the 3 main
directions in the image: posterior/anterior,
inferior/superior, or right/left.  The correction
factors are linearly interpolated between the
control points, and remain flat beyond the first
and last control points.

Try Test Normalizations using the Back Buffer

The TEST1 button applies the piecewise linear
ramp to a single slice and puts the result into
the back buffer so that you can use COMPARE to
blink between it and the original image.  If you
change any settings, and hit TEST1 again, it will
redo the test normalization with the new
settings.

To make the eventual effect of the normalization
more obvious, it is best to turn on WMTRUNC (with
the low limit set to 90, which is the default for
mri_wmfilter), which truncated the image to black
below 90.

A <Return> in any of the lim? or frac? entries is
the same as hitting TEST1, so you quickly change
the scale factors or control points in small
steps and immediately see the effects.

For example, to brighten a dim superior sagittal
region, set one control point (e.g., lim3) to the
pixel coordinate of the top of the skull (e.g.,
around 210 -- look in the lower entry of each
pair to the right of the CORONAL, SAGITTAL and
HORIZONTAL buttons for the pixel coordinates).
Now set another control point (e.g., lim2) to the
pixel coordinate just inferior to the dimmed
region (that is, where no correction needs to be
applied, for example, around 180).  Turn on
WMTRUNC, set low=90, and gradually increase
ffrac3 above 1.0, hitting a <Return> each time in
ffrac3 to see the effects.  You can use COMPARE
to see what the truncated original looks like.

Normalize the Entire Data Set (front buffer)

Once you are satisfied with your settings, apply
them to all of the images in the front (editable)
buffer of Medit by clicking ALL.  The images have
not yet been saved, so if you want to go back,
quit without saving.

Save the Normalized Images

Finally, to save the modified images into the
$SUBJECTS_DIR/marty/mri/orig directory, hit
SAVEIMG.  You should now re-run the surface
reconstruction from the beginning, starting with
Process Volume.

Tips

You can apply several ramps in succession in
different directions (e.g., superior/inferior,
left/right), by hitting ALL several times (after
the proper setting of lim0-3 and ffrac0-3 for
each direction have are determined in
succession).

N.B.: since ALL replaces the front (editable)
buffer images with the normalized images, hitting
ALL twice with the same settings will apply that
ramp twice.  This is in contrast to the behavior
of TEST1, which applies the ramp just once and
stores (overwrites) the image into the back
buffer with the result.

N.B.: If you leave the COMPARE button set to the
back buffer (depressed) and change the slice, you
will generally see nothing unless you have
already pressed TEST1 for the other slice.  Also,
If you do one TEST1 in CORONAL and change planes
to, say, SAGITTAL with the COMPARE button
depressed, you will only see the single CORONAL
slice in edge view.  To get back to the front
buffer click COMPARE again (till it's raised).

#############################################################
------------------------------------------------
 The Tools -> Process Volume menu item starts a
 four-part background process to prepare the 3-D
 MRI data to make a surface.
------------------------------------------------
(1) Normalize Intensities

The output files written by this procedure are:

 images: $SUBJECTS_DIR/$name/mri/T1/COR-???

(2) Compute Talairach (uses MINC tools)

 xform: $SUBJECTS_DIR/$name/mri/transforms/
                                 talairach.xfm
(3) Strip Skull

A subtessellated icosahedron is expanded shrunk
to reach the surface of the brain using the
normalized data set.  At each point on the
surface a 'core sample' is used to search for the
first black lamina that corresponds to the inner
surface of the inner table of bone in a
T1-weighted scan, while at the same time,
preserving neighbor relations.  Once this surface
is found, it is used to strip the skull off of
the T1 data set.  The output files written by
this procedure are:

 shrinksurf: $SUBJECTS_DIR/$name/bem/brain.tri
 images: $SUBJECTS_DIR/$name/mri/brain/COR-???

Inspect this output to see that no gyri have
been trimmed.  If they have, open Preferences ->
Expert Preferences => RmSkull tab, reduce fzero
and increase fmax, and re-run.

(4) White Matter Filter

An oriented filter is applied to the stripped
data set to 'floss' and 'spackle' small defects.
Filter coefficients are computed for each 5x5x5
volume in order to determine which plane is most
likely to be parallel ot the cortical surface,
and then a modified median filter is applied.
The output files written by this procedure are:

 images: $SUBJECTS_DIR/$name/mri/wm/COR-???
#############################################################
------------------------------------------------
 The "Edit -> Edit Segmentation" menu item
 starts both medit and surfer so that the
 segmented white matter can be edited to
 correct topological defects
------------------------------------------------

Inspect the surface for topological defects or
'wormholes'.  These typically occur along the
midline near the hippocampus and fornix, along
narrow sulci (e.g., calcarine, central), and
where there is only a very thing sheet of white
matter overlying the ventricle in the fundus of
the calcarine sulcus.

To correct a wormhole, first select a vertex on
it in the surface view with a left-click.  Then
click surfer's SEND button to make the medit
slice view to go to the corresponding point (this
work the other way, too, for medit clicks sent to
surfer with medit's SEND PNT button).

Then edit the 'wm' data set with the middle (edit
to white) and right (edit to black) mouse
buttons. The radius of the editing brush is set
with the 'rad' entry.  The 3Dbrush button toggles
between within-slice brush (default) and 3D
brush.  Use the 3D brush with care because you
are editing pixels you can't see.  Brush radius=0
is 1x1x1 mm (Alt-b returns radius to this);
radius=1 is 3x3x1 mm (or 3x3x3 if 3D button), and
so on (Alt-B increases radius by 1).

For small edits, rad=0 is fine; otherwise, a good
default is rad=1.  Large radii (4-7) are useful
for filling the basal ganglia or ventricles.

When all wormholes have been are corrected,
re-run Create Surfaces (for one or both
hemisphere).

To abandon a segmentation but also save it (e.g.,
to start with a new prenormalized data set):

  cd $SUBJECTS_DIR/<somesubject>/mri
  cp -r wm wm1
  cp -r orig orig1

Hints

If the wormhole is not clearly visible at first
in the initial slice view, change the slice plane
before moving the cursor; it is often possible to
see it more clearly this way.

To see black edits: contrast ($fsquash) = 200
                    midpoint ($fthresh) = 0.01

When selecting vertices on a wormhole, you may
have to try several times until you get a vertex
that has an edge in the wormhole itself.  This is
because (1) the body of the wormhole may be
partly under the surface, and (2) clicking only
selects the vertex nearest the viewer.

Touchup extensive edits in another plane to
neaten the inevitably ragged edges due to the
difficulty of editing the same location in
successive slices.

Detailed Instructions and Typical Problems

(1) fornix and hippocampus

First, find a slice containing an extensive view
of the hippocampus (easiest to find initially
with all3views turned on).  Then in SAGITTAL
view, edit out the hippocampus and the fornix.

Start at the anterior hippocampus, working your
way first posteriorly, then superiorly behind the
thalamus, up toward the lateral ventricle,
connecting up with it, and then anteriorly under
the corpus callosum until the fornix disappears
near the septum.  Repeat for the other
hemisphere.  Brush radius of 1 works well.

(2) calcarine sulcus joins occipital ventricle

There is a very thin white matter sheet between
the posterior extension of the lateral ventricles
and the calcarine.  The reconstructed surface
sometimes protrudes through this into the
ventricle, creating a large sub-calcarine
'wormhole'.  Also, a 3 slice-thick 'baffle' can
be put into the posterior lateral ventricle just
after it closes.

(3) ventromedial anterior temporal gyrus detached

Near the anterior end of temporal lobe, just
before it separates from the rest of the brain in
CORONAL view, there is a medioventrally pointing
parahippocampal gyrus that sometimes gets
detached at its base.  This usually only occurs
in a few slices.

(4) fill basal ganglia

Depending on the pulse sequence, the striatum
(caudate/putamen, globus pallidus, claustrum) may
be partly interpreted as gray matter (which it
mostly is!).  To fill striatum efficiently, use a
larger diameter brush (e.g., 10).

(5) small wormholes across sulci

Locate the wormhole in the data set and widen the
sulcus where it occurs.  It is best to do this
for one or two slices in either way from the
problem slice.  Fix Topology gets most of these.
These can occur across medial occipital sulci in
a brain with a markedly crinkled calcarine
sulcus.

(6) fill escapes down optic nerve

The optic nerve is a strand of white matter that
goes into the brain.  Edit it out in 3 coronal
slices just before it enters the brain.

(7) fill escapes into orbits

There is very little CSF between orbitofrontal
cortex and the orbits, and the white matter fill
may escape into the tops of the orbits, which
sometimes remain in the 'brain' image set even
after stripskull.  This is easy to fix.

(8) small posterior orbitofrontal sulci close

There are two thin anterior-posterior sulci in
medial orbitofrontal cortex than often have to be
opened manually.  This is easiest to see in a
CORONAL plane.  However, it is much faster to
edit these sulci in a HORIZONTAL view.

#############################################################
------------------------------------------------
 The Tools -> Create Surface menu item starts a
 six-part background process to create the left
 and right hemisphere cortical surfaces
------------------------------------------------
(1) Fill White Matter

Start a 3-D region growing process from a
starting point within the white matter in order
to generate the starting point for a surface.
The output files written by this procedure are:

 images: $SUBJECTS_DIR/$name/mri/filled/COR-???

(2) Tessellate White Matter

Connect the surfaces of the filled white matter
voxels into a continuous surface.  The output
files written by this procedure are:

 surface: $SUBJECTS_DIR/$name/surf/rh.orig
 surface: $SUBJECTS_DIR/$name/surf/lh.orig

(3) Smooth Right Hemisphere White Matter
(4) Smooth Left Hemisphere White Matter

The reconstructed white matter surface of the
right and left hemispheres is smoothed.  The
output files written by this procedure are:

 surface: $SUBJECTS_DIR/$name/surf/rh.smoothwm
 surface: $SUBJECTS_DIR/$name/surf/lh.smoothwm

(5) Inflate Right Hemisphere
(6) Inflate Left Hemisphere

Inflate the right and left hemisphere surfaces
while attempting to preserve local angles and
area.  The output files written by this procedure
are:

 surface: $SUBJECTS_DIR/$name/surf/rh.inflated
 surface: $SUBJECTS_DIR/$name/surf/lh.inflated

================================================
Binary format (non-topology-corrected) surfaces
================================================
Binary file format:
    [header]
  3bytes: 16777215
  3bytes: number of vertices
  3bytes: number of faces
    [vertex list--implicit vertex numbering]
  2bytes: x[vertex0]*100
  2bytes: y[vertex0]*100
  2bytes: z[vertex0]*100
  ...
    [face list--vertex numbers of corners]
  3bytes: face1: vertex number 1st corner
  3bytes: face1: vertex number 2nd corner
  3bytes: face1: vertex number 3rd corner
  3bytes: face1: vertex number 4th corner
  ...

================================================
Obtaining ASCII representation of a surface
================================================
writing out ASCII representation
of any surface in FreeSurfer (e.g., rh.orig,
lh.smoothwm, etc).

1) COR coordinate system (lower box in tkmedit)

  0-255  Right -> Left
  0-255  Post -> Ant
  0-255  Inf -> Sup

2) Talairach (higher box with decimal point)

  [standard]

3) Surface coordinate system.  Surface coords
    are written to the log (3 numbers, x,y,z,
    after the "x =" ...)--or to tcl prompt if
    you run tksurfer from the command line--when
    you click a surface point (the surface
    normals are also written out "n=").

  0,0,0 in center of 256x256x256 volume
  x    positive -> Right
  y    positive -> Ant
  z    positive -> Sup


To write out ASCII file of x,y,z of points on any
surface (including topology-corrected):

tksurfer -marty rh smoothwm
% set vrmlsurf /tmp/zz.wrl
% write_vrml 0         ;# 0=points

This will write out a long list of of 3-D
coordinates of each vertex in the surface.

To write out ASCII file that also specifies the
vertices that are the corners of each face:

tksurfer -marty rh smoothwm
% set vrmlsurf /tmp/zz.wrl
% write_vrml 1

This will write out 2 concatenated lists.  The
first are the vertex x,y,z coordinates as
before.  This is followed by a list of vertex
number quadruples.  These numbers are the
implicit vertex numbers (followed by a -1).
write_vrml 1 *doesn't* work with topology
corrected surface currently.

To write out vrml 2.0 format files (the current
version read by plugin like Cortona from
parallelgraphics for windows), do the following
before write_vrml:

% set vrml2flag 1   ;# default is 0 => vers1.0

This only currently works for points.

Examples:

-----------------
VRML 1.0 points:
-----------------
#VRML V1.0 ascii
Coordinate3 {
        point [
12.72 -94.53 -32.12,
12.39 -94.58 -32.13,
11.64 -94.64 -32.22,
11.02 -94.43 -32.13,
...
19.78 -24.83 -29.55,
19.68 -25.31 -29.20,
20.87 -26.00 -28.69
        ]
}

-------------------------------------------------
VRML 1.0 surface (won't work w/topology-correct):
-------------------------------------------------
#VRML V1.0 ascii
Coordinate3 {
        point [
8.23 -97.32 -19.20,
7.70 -97.32 -19.19,
7.24 -97.26 -19.22,
...
15.33 62.33 2.21,
14.67 62.38 2.09,
14.19 62.37 2.08
        ]
}
IndexedFaceSet {
        coordIndex [
0, 1, 6, 5, -1,
0, 21, 22, 1, -1,
0, 5, 29, 21, -1,
...
129668, 129672, 129673, 129669, -1,
129669, 129673, 129674, 129670, -1,
129670, 129674, 129675, 129671
        ]
}

-----------------
VRML 2.0 points:
-----------------
#VRML V2.0 utf8
Collision { collide FALSE
children [ Group { children [ Shape {
appearance Appearance { material DEF _DefMat Material { emissiveColor 1 1 1 } }
geometry PointSet { coord Coordinate {
        point [
8.23 -97.32 -19.20,
7.70 -97.32 -19.19,
7.24 -97.26 -19.22,
...
15.33 62.33 2.21,
14.67 62.38 2.09,
14.19 62.37 2.08
        ]
} } } ] } ] }


-----------------
VRML 2.0 surface
-----------------
 => not currently working

#############################################################
------------------------------------------------
 The Tools -> Fix Topology menu item starts a
 four-part background process to create the left
 and right hemisphere cortical surfaces
------------------------------------------------
(1) Quick Sphere Right Hemisphere Surface
(2) Quick Sphere Left Hemisphere Surface

Inflate each hemisphere to an area-preserving
sphere to identify topological defects.  The
output files are:

 outsurf: $SUBJECTS_DIR/$name/surf/rh.qsphere
 outsurf: $SUBJECTS_DIR/$name/surf/lh.qsphere

(3) Fix Topology Right Sphere'd Surface
(4) Fix Topology Left Sphere'd Surface

Remove defects by finding sphere locations that
have more than one layer (e.g., a "handle" or
"wormhole").  Then, cut out these defects and
re-tessellate them.  The output files are:

 surface: $SUBJECTS_DIR/$name/surf/rh.orig
 surface: $SUBJECTS_DIR/$name/surf/lh.orig

These overwrite the originally reconstructed
surfaces.

(5) Re-Smooth Right Hemisphere White Matter
(6) Re-Smooth Left Hemisphere White Matter

The reconstructed white matter surface of the
right and left hemispheres is smoothed.  The
output files written by this procedure are:

 surface: $SUBJECTS_DIR/$name/surf/rh.smoothwm
 surface: $SUBJECTS_DIR/$name/surf/lh.smoothwm

(7) Re-Inflate Right Hemisphere
(8) Re-Inflate Left Hemisphere

Inflate the right and left hemisphere surfaces
while attempting to preserve local angles and
area.  The output files written by this procedure
are:

 surface: $SUBJECTS_DIR/$name/surf/rh.inflated
 surface: $SUBJECTS_DIR/$name/surf/lh.inflated

#############################################################
------------------------------------------------
 The Tools -> Make Final Surface menu item starts
 a two-part background process to create the
 final left and right hemisphere cortical
 surfaces (after removal of topological defects)
------------------------------------------------
(1) Make Final Right Hemisphere Surfaces
(2) Make Final Left Hemisphere Surfaces

The output files written by this procedure are:

 surface: $SUBJECTS_DIR/$name/surf/rh.white
 surface: $SUBJECTS_DIR/$name/surf/rh.graymid
 surface: $SUBJECTS_DIR/$name/surf/rh.pial

 surface: $SUBJECTS_DIR/$name/surf/lh.white
 surface: $SUBJECTS_DIR/$name/surf/lh.graymid
 surface: $SUBJECTS_DIR/$name/surf/lh.pial




























##############################################

##############################################
#define MAX_WHITE             120
#define MAX_BORDER_WHITE      105
#define MIN_BORDER_WHITE       85
#define MIN_GRAY_AT_WHITE_BORDER  70

#define MAX_GRAY               95
#define MIN_GRAY_AT_CSF_BORDER    40
#define MID_GRAY               ((MAX_GRAY + MIN_GRAY_AT_CSF_BORDER) / 2)
#define MAX_GRAY_AT_CSF_BORDER    75
#define MIN_CSF                10
#define MAX_CSF                40

static  int   max_border_white_set = 0,
  min_border_white_set = 0,
  min_gray_at_white_border_set = 0,
  max_gray_set = 0,
  max_gray_at_csf_border_set = 0,
  min_gray_at_csf_border_set = 0,
  min_csf_set = 0,
  max_csf_set = 0 ;

static  float   max_border_white = MAX_BORDER_WHITE,
                min_border_white = MIN_BORDER_WHITE,
                min_gray_at_white_border = MIN_GRAY_AT_WHITE_BORDER,
                max_gray = MAX_GRAY,
                max_gray_at_csf_border = MAX_GRAY_AT_CSF_BORDER,
                min_gray_at_csf_border = MIN_GRAY_AT_CSF_BORDER,
                min_csf = MIN_CSF,
                max_csf = MAX_CSF ;
##############################################

#############################################################
------------------------------------------------
 The SubjectTools -> Process/Create/Fix/Final
 menu item starts twenty-part background process
 to create a default set of RH and LH surfaces 
------------------------------------------------
Shortcut for:

  Preferences -> Don't Ask Overwrite

  Process Volume
  Create Surface
  Fix Surface Topology
  Make Final Surface

This makes a default set of surfaces for both
hemispheres.  The complete set of output files
written by these procedures for the RH are:

 images: $SUBJECTS_DIR/$name/mri/T1/COR-???
 xform: $SUBJECTS_DIR/$name/mri/transforms/###
 shrinksurf: $SUBJECTS_DIR/$name/bem/brain.tri
 images: $SUBJECTS_DIR/$name/mri/brain/COR-???
 images: $SUBJECTS_DIR/$name/mri/wm/COR-???
 images: $SUBJECTS_DIR/$name/mri/filled/COR-???
 surface: $SUBJECTS_DIR/$name/surf/rh.orig
 surface: $SUBJECTS_DIR/$name/surf/rh.smoothwm
 surface: $SUBJECTS_DIR/$name/surf/rh.inflated
 surface: $SUBJECTS_DIR/$name/surf/rh.qsphere
 surface: $SUBJECTS_DIR/$name/surf/rh.orig
 surface: $SUBJECTS_DIR/$name/surf/rh.smoothwm(2)
 surface: $SUBJECTS_DIR/$name/surf/rh.inflated(2)
 surface: $SUBJECTS_DIR/$name/surf/rh.white
 surface: $SUBJECTS_DIR/$name/surf/rh.graymid
 surface: $SUBJECTS_DIR/$name/surf/rh.pial

A corresponding set of surfaces are made for
the LH.

#############################################################
------------------------------------------------
 SubjectsTools -> Back Compat Curv/3d
 SubjectsTools -> Undo Back Compat Curv
 SubjectsTools -> Forward Compat 3d
 SubjectsTools -> Undo Forward Compat 3d
------------------------------------------------
Current MGH freesurfer has updated the
data formats for curvature and sulcus files
({rh,lh}.{curv,sulc}: 2-byte => 4-byte) and
3D files (directories containing COR files ->
single-file *.mgz files).  These menu items
support basic forward and backward compatibility
between the old and new formats.

Back Compat Curv/3d

If a subject's surface has been reconstructed
using new freesurfer and you want to view it
with this older distribution, copy the subject
into a $SUBJECTS_DIR, select the subject, and use
"Back Compat Curv/3d" to generate the new format
curvature files and 3d files.

For 3d files, the new format files (*.mgz
files) are left in place and old format files
(directories containing single-byte, single
slice COR- files) are regenerated alongside them
(FreeSurfer0.8 will ignore the mgz files).

For curvature files, new format (4 byte) files
are moved aside to {rh,lh}.{curv,sulc}FLOAT and
old style (2 byte) files are generated from the
4 bytes files.  Re-run OK.

Undo Back Compat Curv

To restore the new format curvature and
sulcus files, this menu item moves the
old format curvature and sulcus files to
{rh,lh}.{curv,sulc}OLD and restores the
new format files to their original names:
{rh,lh}.{curv,sulc}.  The 3d files are not
touched.  Re-run OK.

Forward Compat 3d

Current MGH freesurfer has a bug that prevents
it from reading COR format files (faulty path
manipulation relating to COR-.info file).
To work around this bug, click this menu item
for a subject before operating on it with MGH
freesurfer.

New format *.mgz files are generated from
COR file directories, and then the COR file
directories are moved aside to <dir>COR to
prevent new freesurfer from finding them (and
failing before it looks for *.mgz files).

The following files are generated and renamed:

Generated:

  orig/COR-*    =>  orig.mgz
  T1/COR-*      =>  T1.mgz
  brain/COR-*   =>  brain.mgz
  wm/COR-*      =>  wm.mgz
  filled/COR-*  =>  filled.mgz

Renamed/Moved-aside:

  orig/COR-*    =>  origCOR/COR-*
  T1/COR-*      =>  T1COR/COR-*
  brain/COR-*   =>  brainCOR/COR-*
  wm/COR-*      =>  wmCOR/COR-*
  filled/COR-*  =>  filledCOR/COR-*

Re-run OK (asks choice of whether to write
over *.mgz file -- e.g., if COR files have been
re-made and need to be re-exported).

Undo Forward Compat 3d

To undo the renaming of the COR file directories
(so UCSD freesurfer will once again automatically
find the files), use this menu item.  The *.mgz
generated by a previous "Forward Compat 3d"
will not be touched.  Re-run OK.

#############################################################
-------------------------------------------------
 The "Edit -> Make Full/Partial Surface Cuts"
 menu item starts up surfer with a medial view
 of the inflated surface in preparation for
 making relaxation cuts
-------------------------------------------------
HOW TO MAKE CUTS FOR A FULL HEMISPHERE FLATTENING
-------------------------------------------------
(1) make relaxation cuts:
      ==> LEFT-CLICK sequence
      ==> open-line cut with CUTLINE
            [repeat above]
      ==> one standard 5-cut set:
  cut 1: medial, along fundus calcarine
  cut 2: amygdala to temporal pole
  cut 3: ant. corpus callosum to frontal pole
  cut 4: anterior cingulate to dorsal convexity
  cut 5: posterior cingulate to dorsal convexity
      ==> extend past planned midline removal

(2) encircle midline region to remove:
      ==> LEFT-CLICK sequence

(3) make closed-line cut
      ==> CUTAREA button

(4) mark region to fill/save
      ==> single LEFT-CLICK 

(5) fill/save marked region
      ==> FILL button

(6) save patch
      ==> patch: WRITE

The default names for the full cortical surfaces
with the midline removed (following instructions
above) are:

 rh.full.patch.3d
 lh.full.patch.3d

Be sure that the surface is completely cut apart
at the point where the relaxation cuts end at the
midline cut-out.  To be safe, it is a good idea
to click on a few vertices on one side of the cut
and do CUTLINE to remove any stray attachments.
This can be verified with the MESH button (check
for even a single stray edge).

-------------------------------------------------
HOW TO MAKE CUTS FOR OCCIPITAL PATCH FLATTENING
-------------------------------------------------
(1) make calcarine sulcus relaxation cut:
      ==> LEFT-CLICK sequence
      ==> open-line cut with CUTLINE

(2) specify cutting plane
      ==> 3 LEFT CLICK's
      ==> for a patch including most of visual:
   click 1: medial, splenium corpus callosum
   click 2: lateral, intraparietal
   click 3: lateral, anterior inferotemporal

(3) mark region to keep
      ==> 1 LEFT CLICK

(4) make the cut
      ==> CUTPLANE button

(5) optional trim around callosum
      ==> LEFT-CLICK sequence
      ==> open-line cut with CUTLINE
            [repeat if necessary]

(6) save patch
      ==> patch: WRITE

The default names for the occipital patches with
a calcarine relaxation cut are:

 rh.occip.patch.3d
 lh.occip.patch.3d

Be sure to check for stray attachments across
the end of the relaxation cut as above.
#############################################################
------------------------------------------------
 The Tools -> Flatten Surface menu item starts
 a two-part background process to create the
 flattened left and right hemisphere cortical
 surfaces (or surface portions)
------------------------------------------------
(1) Flatten Right Hemisphere Surfaces
(2) Flatten Left Hemisphere Surfaces

The output files written by this procedure are:

 surface: $SUBJECTS_DIR/$name/surf/rh.flat
 surface: $SUBJECTS_DIR/$name/surf/lh.flat
#############################################################
------------------------------------------------
 The Tools -> Sphere Surface menu item starts
 a four-part background process to create the
 spherical left and right hemisphere cortical
 surfaces and then registers them to an average
------------------------------------------------
(1) Sphere Right Hemisphere Surface
(2) Sphere Left Hemisphere Surface

The output files written by this procedure are:

 surface: $SUBJECTS_DIR/$name/surf/rh.sphere
 surface: $SUBJECTS_DIR/$name/surf/lh.sphere

(3) Register Right Hemisphere Surface
(4) Register Sphere Left Hemisphere Surface

 surface: $SUBJECTS_DIR/$name/surf/rh.sphere.reg
 surface: $SUBJECTS_DIR/$name/surf/lh.sphere.reg
#############################################################
------------------------------------------------
 Medit -- display and edit MRI slice data
------------------------------------------------
Medit reads one or more series of images and
displays them in coronal, sagittal, horizontal,
or all 3 planes.  The images in the first (edit)
buffer can be edited and saved.  Images read into
the second buffer cannot be edited.  Edits
applied while viewing the second buffer affect
the first buffer (useful when edit buffer has
segmented white matter and second buffer has
original full T1 images).

Medit can also read in a surface and display the
intersection of the surface with the current
slice.  The interface is described from upper
left to lower right.

CORONAL/SAGITTAL/HORIZONTAL button/slider/field

 button:  switch to this view
 slider:  change coronal slice
 slider field:    enter/view slice number
 talairach field: enter/view coord (MNI software)

When switching planes, the new plane will pass
through the current location.  This is the
location of most recent left-click (default at
startup is center).

To move one slice, use the arrow keys or click in
a slider well to the left or right of a slider.

Display parameters (surface/contrast/midpoint)

The "overlay" checkbutton displays functional
data over an anatomical slice image.  The
contrast and threshold of the overlaid data is
controlled by fthr/fslope/fmid fields at the
lower middle right).  This functionality only
supports real data type (not complex data from
phase-encoded experiments) and is not as
well-developed as AFNI data overlays.  It is
accessed by the VOLUME-STATS button at the top of
the SessionTools -> View Functional Data panel.

The "surface" checkbutton toggles whether or not
the intersection of the currently-read-in surface
with the current slice is displayed.

Higher numbers in "contrast" field increase the
steepness of the sigmoid that is multiplied by
the data before display (default contrast=12.0).
The "midpoint" field sets the data number that
appears at half-max brightness.  The units are
0.0-1.0, so a midpoint setting of 0.35 (default)
means that image data that has a value of 0.35 *
255 = 89 will be displayed at half-max (=128).

To see points that you have edited to black
(actually an image value of 1, not 0), set
contrast and midpoint to:

  contrast = 200
  midpoint = 0.01

New contrast and midpoint settings won't be
visible until you change the slice or plane.

SAVEIMGS button

This button saves edited images (COR files) in
the editable buffer to a COR directory named by
the "outim" field.

The tilde (~) in the "outim" (and "surf") entry
field is an abbreviation of the path of the
current subject directory such as:

  /computer/usr2/subjects/marty

You can substitute an absolute path if you want
to save the images somewhere else.  There is no
edit undo; however, you can quit without saving.
Therefore, it is a good idea to save whenever you
are satified so far.

SEND/GOTO PNT

SEND PNT saves the current 3D location of the
cursor while GOTO PNT moves the display (in the
current slice plane view) to a previously saved
3D location (saved in either medit or surfer).
Note that GOTO PNT in medit goes to a 3D location
while GOTO on the surfer panel requires a search
(see Surfer help for details).

Edit Brush Control (rad, 3Dbrush)

The "rad" field sets the radius of the editing
brush.  The default is a one pixel brush.  At
larger radii, the brush is circular.  A radius of
1 is a useful brush size.  By default, the brush
is 2D, which means that it only affects pixels in
the current slice.  The "3Dbrush" checkbutton
toggles back and forth between a 2D and a 3D
brush.  Use the 3D brush with care since you are
editing slices you cannot see.

Editing (middle/right-click)

  LEFT-CLICK    just select a point
  MIDDLE-CLICK  set to white matter (255)
  RIGHT-CLICK   erase (set intensity to 1)

all3views

The "all3views" checkbutton toggles whether one
view is shown or whether 3 views (coronal,
sagittal, and horizontal) as well as a sagittal
maximum intensity projection is shown.  Clicking
in one of the views when "all3views" is selected
causes the other two views to go to the
corresponding point.  Clicking in the maximum
intensity projection view at the lower right
re-centers the 3 views.

3D/surface File Entries

  surf  -- path to surface
  outim -- path where edited images written
  rgb   -- SGI rgb bitmap

WMTRUNC

This button toggles whether the image is
truncated to zero below "low" and above "high".
The truncation is applied to both the editable
view as well as the second buffer if another
dataset has been loaded.  It is useful for
inspecting the images for small brightness ramps
which are often hard to see (because the human
visual system is so good at autonormalization).
It is typically turned on when using the
ramp-correction utilities of the extended
interface (F3), which allows piecewise linear
test correction ramps to be applied to the image
in the second buffer see if the segmentation is
improved before applying the ramps to the entire
data set (see below).

PLANEFILTER

This only works in the CORONAL plane.  It applies
the anisotropic wormhole filter to one slice
(this search 5x5x5 voxel volumes for planar
structures and performs a median filter in the
direction of greatest planarity).  After it has
run (which takes a few seconds), you can view the
different between the truncated and truncated and
filtered data set by using COMPARE.

Overlay display

The "fthr", "fslope", and "fmid" fields have the
same effect as the fthresh, fslope, and fmid
fields on the surfer tools panel.  The only color
scale available is the real-valued heat scale
(blue-cyan, red-yellow).

2nd imagedir field

By clicking READ, the dataset specified in "2nd
imagedir" is read into the second (non-editable)
buffer.  Successive READ's simply replace the
dataset in the non-editable buffer.  The field by
default expects a COR directory that is relative
to:

  $SUBJECTS_DIR/$subject/mri

You can also put an absolute path to a COR
directory into this field.

HISTOGRAM

Only supported on SGI.

SAGMIRR

This makes a mirror-image of the dataset
around the sagittal midline, which is defined
as the plane in the middle of the stack of
slices that are displayed when SAGITTAL is
clicked.

A more general flipping operator is
available from the tcl prompt (flip_corview_xyz),
which allows you to flip an arbitrary
direction into an arbitrary direction
starting from what is displayed in
CORNONAL view.  Thus:

  flip_corview_xyz  x  z  -y

changes the x-direction currently viewed in
CORONAL view to the x-direction in the new data
set, the y-direction in the current view into the
new z-direction, and the current z-direction (the
direction you move when y ou change CORONAL
slice) into the minus y-direction in the new data
set.  This command checks for degenerate flips.

COMPARE

This toggles between the volumes in the two
buffers.  You can edit in the second buffer view;
remember that in this case, edits are applied to
the editable buffer.

Larger F3 Interface (hand normalize)

Hitting F3 in the medit panel expands it (F2 goes
back to the default view).  The new subpanel on
the right allows you to test and then apply a
piecewise linear ramp of brightness correction
factors (ffrac0-3) at four control points
(lim0-3).  See Help -> Hand Pre-Normalize for
more details on how to use this facility.

------------------------------------------------
 Standalone Commandline and Script Operation
------------------------------------------------
tkmedit can also be run as a standalone program
from the command line (as long as SUBJECTS_DIR
and FUNCTIONALS_DIR are set) from the command
line:

Use: tkmedit name imgdir [surf] [-] [-tcl script]
     tkmedit local [-] [-tcl script]

  name: subjectdir name         (in $SUBJECTS_DIR)
imgdir: orig,T1,brain,wm,filled (in $subject/mri)
  surf: e.g., rh.smoothwm       (in $subject/surf)
  dash: disable editing

The program has an embedded tcl interpreter and
most of its functions (including some not exposed
to the medit tools interface, as well as some
that are now obselete...) can be accessed through
it, either interactively at the tcl prompt, %,
that appears in the terminal from which tkmedit
is started, or offline using a tcl script in a
file whose name follows the -tcl option.  If you
include an "exit" at the end of the tcl script,
tksurfer will quit when the script finishes.  You
can find commands available in the tcl
interpreter using "help" or "info":

  % help
  % info command flip*

Here is an example of a small command line tcl
script that reads in the data on the command
line, and then saves a flipped data set into
a new directory:

flip_corview_xyz -y x z
set abs_imstem /subjects/bill/mri/T1-new/COR-
write_images
exit

If you put the commands above into a file
flip.tcl, you could run it like this:

  tkmedit john T1 -tcl flip.tcl

There is a built-in script (mri2mpg.tcl) to make
3 mpg movies (coronal, sagittal, horizontal)
that can be accessed by typing F12 anywhere in
the medit tools interface.  It asks for slice
limits (min,max) in the three slice planes and
dumps the mpegs in $SUBJECTS_DIR/$name/mpg.

#############################################################
-----------------------------------------------
 Register -- interactively register slice data
-----------------------------------------------
Register reads two series of images, a TARGET set
and a MOVEABLE set, and displays them in coronal,
sagittal, horizontal, planes.  The images in the
the TARGET buffer are fixed while the images in
the MOVEABLE buffer can be modified with a linear
transformation--which included rotation,
translation, and stretching.

The goal of register is to generate a 4x4 linear
transformation matrix (register.dat) that can be
used by other programs to paint 3D statistics
made from the MOVEABLE image set onto a 2D
surface made from the TARGET image set.

Transformations (rotations, translations,
stretchings) are applied to the MOVEABLE data set
relative to its current view.  They will be
immediately visible in other planes or other
slices of the MOVEABLE date set.  Rotations take
place around the last left-clicked point.

The image sets are compared to each other by
pressing the COMPARE button.  Once the
registration is satisfactory, it can be saved
with SAVE REG (asks before overwrite).  To go
back to the original registration, quit without
saving and restart (or use READ REG in the
extended interface).

Alignment Strategies

There are two basic alignment strategies
for functional data.

 Functional Scan => Surf Scan
 Functional Scan => Alignment Scan => Surf Scan

In the first, a single repetition from the
functional data set (typically t=0) is directly
registered to the high-resolution structurals
that were used to reconstruct the cortical
surface.  The difficulty with this is that
the functional contrast is low and reversed
relative to the hi-res T1's.

In the second strategy, a T1-weighted alignment
scan taken in the same plane as the functional
scans is first aligned to the hi-res structural
used to make the surface.  The resulting
transformation matrix is then copied onto the
register.dat file in the functional scan
directory.  A direct Functional => Subject
register can then be run to touch up the
alignment (or add shear--see below).

Aligning Two High-Resolution Data Sets

Register can also be used to manually align two
high resolution data sets prior to averaging.
There are automatic algorithms to do this.
Register can help when the two data sets were
collected on different days (perhaps as Alignment
scans), and the subject's neck, jaw, and scalp
are in a different position.

Display Parameters

The default settings for "contrast" (12.0) and
"midpoint" (0.35) increase contrast between gray
and white matter in images normalized using
mri_normalize.

The "fmov" field sets the brightness of the
MOVEABLE images.  This should be set to be
approximately the same as the TARGET image.

The "masktarg" button masks out the part of the
TARGET images that extend beyond the edge of the
MOVEABLE images volume.  This is typically used
for fine adjustments on data sets collected with
a surface coil where the MOVEABLE functional
images cover only a part of the brain and the
size change during COMPARE is distracting.

Tips

If the data sets are roughly aligned, a good
strategy is to adjust the MOVEABLE in coronal
view, change to sagittal and re-adjust, change to
horizontal and re-adjust, and so on.  Change
planes often.

It may be difficult to guess how to transform the
MOVEABLE data set if it is oriented very
differently than the TARGET data set (e.g., the
TARGET image is coronal but the MOVEABLE image
looks like a sideways horizontal slice).  A
simple strategy here is to transform the MOVEABLE
by rotating 90 degrees around a center point, and
then change to another plane.  If the MOVEABLE
still appears to be in the wrong plane, rotate 90
degrees again and change plane again.  Eventually
you will only need an in-plane rotation to
roughly align the data sets.

To get a shearing transformation, use a rotation
combined with stretching.  For example, rotate 30
deg, stretch vertically, rotate back 30 deg, and
finally, shrink vertically.  Don't stretch until
the data sets are well aligned.

Format of register.dat (8 lines, ASCII)

 arthur   [name in subjects database]
 3.0      [pixel size (mm) of MOVEABLE]
 4.0      [slice thickness (mm) of MOVEABLE]
 0.2      [starting brightness of MOVEABLE]
   [transformation matrix]
 9.9915e-01  2.9973e-02 -4.6041e-02  6.5897e-02
 -5.7313e-03 -7.7659e-01 -6.2997e-01 -3.5452e+01
 5.4680e-02 -6.2928e-01  7.7525e-01 -6.6141e+00
 0.0000e+00  0.0000e+00  0.0000e+00  1.0000e+00

Since the pixel size is included in the file, the
homogeneous 4x4 matrix can be directly used for
data sets with different pixel sizes.

Extended Interface

Several levels of interface are available by
typing the following commands while in the
interface window:

ctrl-F1   micro (just rotate/translate)
ctrl-F2   mini  (default, adds stretching)
ctrl-F3   macro (adds read register.dat, sagittal
                   mirror, savergb, blinktime,
                   and SEND and GOTO PNT)

Standalone Operation

Tkregister can also be run as a standalone program
from anywhere in the directory tree from the
command line:

=================================================
Usage:

  tkregister local
    [mov=cwd  targ=impliedCOR]

  tkregister local <abstargdir>
    [mov=cwd  targ=absCORdir]

  tkregister <absmovdir> <abstargdir>
    [mov=abs  targ=absCORdir]

  tkregister <subj> <movdir> <targdir>
    [mov=relCORdir  targ=relCORdir]

  tkregister -mkdefault
  tkregister -readinfo

    [often run in functional subdir]
    [reldirs in $subject/mri, composite path OK]
    [abstargdirs allow cross-subject reg]

Args:

  local       movdir is cwd
  -mkdefault  make default register.dat in cwd
  -readinfo   COR-.info => register/analyse.dat
  <subject>   in subjects database
  <movdir>    moveable (im,bshort,BRIK,brik,COR)
  <targdir>   target (COR only)

Files:

  targ image   COR images--subj db, sess align
  mov image    EPI,alignCOR,subjCOR--analyse.dat
  register.dat mov: subj,pixsz,slicethick,xform
  analyse.dat  mov: aligndir,imformat,slices,x/ysz
  edit.dat     subj/tmp/edit.dat--SEND/GOTO

Options: (at end,=movdir analyse.dat,req:abs=>abs)

  -movformat <str> (-m) movimg format (rel printf)
  -nslices <n>    (-n) num slices moveable
  -reps <n>       (-e) imgs/slice (BRIK offsets)
  -imres <x> <y>  (-i) xsize,ysize moveable images
  -regdat <file>  (-r) else default=./register.dat
  -fslice1 <mm>   (-1) funct/sess offset

Examples:

  tkregister local (str<=loc;analyse/register.dat)
  tkregister local /fspace/9904TS/mprage (CORtarg)
  tkregister /fsp/9904TS/mprage /sub/me/mri/T1
  tkregister /fsp/9904TS/eccen  /sub/me/mri/T1
  tkregister /fsp/9904TS/eccen  /sub/me/mri/mprage
  tkregister marty orig/im1 orig/im2 (str2<=str1)

#############################################################
------------------------------------------------
 Surfer -- display surface and activation data
------------------------------------------------
The tksurfer program is started either by the
SURFACE button on the main csurf panel, by the
SURAFCE-STATS button on the SessionTools -> View
Functional Data panel, or from the command line
(see below).  It reads a surface file, and
optionally, a curvature file, a patch file, a
label file, and one or more functional data files,
and then renders a view of the surface.  The
surfer tools panel is described from upper left to
lower right.

RUN/EDIT/READENV buttons, script entry

The RUN button executes the tcl script that is
currently specified in the "script:" entry field.
A "#" can be used in that field as an abbreviation
for the standard script directory:

  $CSURF_DIR/lib/tcl

The EDIT button opens the current script (or
creates a new file if the named script doesn't
exist) in a text editor.  READENV re-reads the
setenv environment that tksurfer was started with
(arguments following "env" in surfer log).

Two useful standard scripts for analyzing
complex-valued data are phasemovie.tcl and
offsetmovie.tcl.  The phasemovie.tcl script
colors a small range of phases (default 3%) white
and saves a bitmap for each of 50 steps of
varying the phase of the center of the white
stripe between 0 and 2 Pi.  It leaves the color
scale settings intact underneath the moving white
phase contour.  This is essentially an animation
of the contours in the color phasemap.  It makes
small variations in phase more apparent than
color variation alone does.  The offsetmovie.tcl
script, by contrast, changes the angleoffset
value (thus changing the color map) in 25 steps.
This can be used to find the best color map
setting for color wheel data (color scale w1), or
to find the best delay (angleoffset) for two
condition data analyzed with the fourier method
(color scale ht, with complexval and truncphase
checked).  It is hard to interrupt these scripts
once they have been started.

Surface Data File Entries, READ/WRITE Buttons

  curv  -- curv or sulc file (every vertex)
  patch -- flattened subset of a surface
  label -- vertices and vtx numbers
  fieldsign -- fieldsign and fsmask files
  val   -- value file (maybe vertex subset)
  rgb   -- SGI rgb bitmap (write only)

The formats of these files are as follows (bytes
for each file element in brackets):

 curv (binary, every vertex):
   vnum[3],fnum[3],float*100[2], ...

 area (binary, every vertex):
   vnum[3],fnum[3],float[4], ...

 label file (ASCII, vertex subset):
    #!ascii label , from subject marty <CR>
    <labeled-vtx-count> <CR>
    <vnum> <x> <y> <z> <labelvalue> <CR>
    <vnum> <x> <y> <z> <labelvalue> <CR>
    ...

 fieldsign (binary, every vertex):
   fs (fieldsign): vnum[4],float[4], ...
   fm (fssigmask): vnum[4],float[4], ...

 val (binary, maybe vertex subset):
   latency[2],vnum[3],{vtx[3],float[4]}, ...

 new curv (binary, every vertex):
   -1[3],vnum[4],fnum[4],npervtx[4],float[4],...

 new area (binary, every vertex):
   [same as new curv]

See end of this file for machine-independent
C functions that read/write Linux/IRIX binary
compatible FreeSurfer files that contain 4-byte
float, 4-byte ints, 3-byte ints, and 2-byte ints
in MSB order (most significant byte first).  This
version of tksurfer cannot read the new curvature
file format (same as new area format).  The
program, calcvert, can convert back and forth
between these different formats.

In all the READ/WRITE entry fields, a tilde (~)
can be used as an abbreviation of the path of the
current subject directory such as:

  /computer/usr2/subjects/marty

An asterisk (*) can be used as an abbreviation of
the current functional session directory such as:

  /computer/usr3/sessions/040115MS/image

One possible action is to read in the "sulc" file
instead of the "curv" file (e.g., substitute
"rh.sulc" for "rh.curv", click READ, and then
click REDRAW).  The sulc data is the summed
perpendicular movement of each vertex during
inflation.  It is used to drive morphing, and is
closer to sulcus-vs-gyrus than curvature, which
is a strictly local measure of the one vertex in
relation to its immediate neighbors
(concave-vs-convex).

To generate a label file, first outline a region
with LEFT-CLICKS and use CUTAREA and FILL to
select it.  Then select a name for the label file
and WRITE it.

Fieldsign and fieldsign mask files are
automatically generated using the SessionTools ->
Calculate Visual Fieldsign panel.

Value files (*.w files) are generated as the
output of clicking PAINT on several different
panels.  They may be real or complex.

The PUSH button to the left of the "val" field
can be used to read in complex data.  First read
the imaginary file with READ, and possibly SMOOTH
it (val).  PUSH is used to move the imaginary
data to the second position on the data stack.
Then the real data file is read in with another
READ on a different file name.  These actions are
performed by the standard scripts that read
complex data such as polar-views.tcl.

When WRITE'ing an rgb file, make sure that the
surfer display window is completely onscreen,
cleanly redrawn, and not occluded by any other
window.  The mouse cursor is ignored.

ROTATE/TRANSLATE/SCALE Sliders

  ROTATE
    horizontal slider -- rotate around vertical
    vertical slider -- rotate around horizontal
    yrot field -- rotate around y axis (deg)
    xrot field -- rotate around x axis (deg)
    zrot field -- rotate around z axis (deg)

  TRANSLATE
    horizontal slider -- translate left-right 
    vertical slider   -- translate up-down
    x field -- translate in x axis
    y field -- translate in y axis

  SCALE
    vertical slider -- scale larger-smaller
    % field -- scale in percent

REDRAW/RESTORE/SEND/GOTO

The REDRAW button manually redraws the screen,
while RESTORE then REDRAW reestablishes the
original, lateral viewing orientation (it is easy
to get lost after several non-orthogonal
rotations).

SEND saves the coordinates of a surface point.
It also automatically causes an open medit tools
display to GOTO that point, (but only if the
xhost list is empty, which is a security
feature).

GOTO finds the nearest (Euclidian distance)
surface point to the last point that was saved by
a SEND or SEND PNT in surfer tools, medit tools,
or tkregister.

Note that the GOTO operation is not equivalent
for surface (2D) and volume (3D) data sets.  Any
surface point can always be located (to within a
voxel) in a volume data set; however, a point
selected in a volume often lies outside of the
corresponding cortical surface, so a search must
be performed.  This can lead to counterintuitive
results.  For example, assume you are displaying
the right hemisphere surface.  If a volume point
is accidentally selected in the opposite (left)
hemisphere of a 3D data set, and you GOTO that
point on the surface the nearest (Euclidean)
surface point will typically lie somewhere along
the midline, and will not even be visible in
lateral view.

Background Color

If "none" is selected, the curvature data set is
not displayed.  The default is "curv".  When only
curvature is displayed, it is represented using
red and green.  When curvature is displayed under
activations ("overlay" checked), curvature is
represented as two shades of gray.

Color Scale (ColScl) for Functional Data

  w1 -- color wheel (eccen or polar versions)
  ht -- heat scale (brown/white or red/blue)
  BRw -- blue/red/white (real data only)
  fs -- fieldsign ($hemi.fs, $hemi.fm only)

For much more detail on the behavior of these
different color scales, see SessionTools -> View
Functional Data.

MESH and CM Buttons

MESH toggles between viewing and not viewing the
vertices and edges of each polygon in the
surface.  The mesh is too dense to resolve unless
the brain is first SCALE'ed up.  The r/g/b fields
can set the color of the mesh (bug: mesh color
setting is ignored if brain extends beyond
viewing window; however, viewing window can be
enlarged).  The CM button displays a 1 cm gray
scale bar at the lower right and a color scale
bar (the color scale bar does not work right for
the "w1" color scale; use the program "wheel"
instead).

Functional Display Parameters

Left Checkboxes and "fthresh:" Entry Field

 truncphase -- only display positive values
 revphase   -- reverse time axis (complex data)
 invphase   -- reverse positive, negative values 
 overlay    -- display functional data (gray curv)
 complexval -- complex-valued data (usu. autoset)

 fthresh -- hard stat thresh (stat values under
              this value display underlying gray
              curvature instead)

Right Column Entry Fields

 fslope -- contrast (steepness sigmoid, or double
             sigmoid steepness w/2-ended scales)
 fmid   -- set where sigmoid changes fastest (use
              this to set effective threshold
              but avoid truncation edges)
 cslope -- contrast of R/G curvature colorscale
 cmid   -- midpoint of R/G curvature colorscale
 anglecycles -- complex: eccen=1.0, polar=2.2
 angleoffset -- complex: 0-1 => phase angle 0-2pi

For more detail on the meaning of these fields as
a function of different color scales, see
SessionTools -> View Functional Data.

Surface Cut/Fill Operations

  CUTAREA  -- closed-line cut using most recent
                list of LEFT-CLICK'd points
  FILL     -- fill region selected by single
                LEFT-CLICK, then delete unfilled
  CUTPLANE -- 3 LEFT-CLICK's define plane, 4th
                indicates which side to keep  
  CUTLINE  -- open-line cut using most recent
                list of LEFT-CLICK'd points
  FILL ROI -- fill region with min stat value
  UNDO CUT -- undo most recent cut
  RECONNECTALL -- undo all cuts

Once an operation has been performed, the list of
selected points is cleared in preparation for the
next operation.

Data and Curvature Smoothing

The SMOOTH button performs the requested number
of nearest-neighbor smoothing steps on either the
curvature ("curv") or the data on the top of the
value stack ("val").  The approximate mapping
from smoothing steps to full-width-at-half-max
filter result is:

  10 steps => 3.2 mm FWHM
  20 steps => 4.5 mm FWHM

See Help -> View Functional Data for more
detail on smoothing.

------------------------------------------------
 Standalone Commandline and Script Operation
------------------------------------------------
tksurfer can also be run as a standalone program
from the command line (as long as SUBJECTS_DIR and
FUNCTIONALS_DIR are set) from the command line:

Usage: tksurfer -{name} {hemi} {surf} [-tcl script]
       tksurfer -help, -h

   name:  dirname in current SUBJECTS_DIR
   hemi:  lh,rh
   surf:  orig,smoothwm,inflated,sphere,...

The program has an embedded tcl interpreter and
most of its functions (including some not exposed
to the surfer tools interface, as well as some
that are now obselete...) can be accessed through
it, either interactively at the tcl prompt, %,
that appears in the terminal from which tksurfer
is started, or offline using a tcl script in a
file whose name follows the -tcl option.  If you
include an "exit" at the end of the tcl script,
tksurfer will quit when the script finishes.  You
can find commands available in the tcl interpreter
using "help":

  % help

which also lists settable variables (tcl variables
linked to C variables).  Set the value of a
variable like this:

  % set cslope 5.0

To find the current value, omit the value

  % set cslope
  3.0

You can also search for commands by pattern
matching:

  % info command rotate*
  rotate_brain_x rotate_brain_y rotate_brain_z

Commands have some minimal error checking/usage:

  % rotate_brain_y
  Wrong # args: rotate_brain_y <deg>

Unix commands can be executed directly from the
tcl prompt (but to get csh-style globbing, you
have to do it explicitly):

  % cd /tmp
  % ls -al
  % eval ls -al [glob *.rgb]

Here is an example of a small command line tcl
script that reads in a surface, and then saves 90
bitmap images of the brain, each one rotated 4
degrees around the vertical axis from the
previous image (i.e., a rotating brain movie).

open_window
make_lateral_view
read_binary_curv
set cslope 5.0
set i 0
while {$i < 90} {
  redraw
  set rgb /tmp/brain-[format "%03d" $i].rgb
  save_rgb
  incr i
  rotate_brain_y 4
}
exit

You could either paste the script into the
tcl prompt or put the commands in a file,
rotbrain.tcl, run it like this:

  tksurfer -john rh smoothwm -tcl rotbrain.tcl

You could also execute the script from the surfer
tools interface by typing its full pathname (or
using "#" as an abbreviation for the standard
script directory if you have put the script there)
into the "script:" entry field, and clicking RUN.

------------------------------------------------
 C-code for machine-independent MSB read/write
------------------------------------------------
/* machine-indep read/write float/int/2,3byte */

short swapShort(short s);
int swapInt(int i);
float swapFloat(float f);

int fread2(int *v, FILE *fp); /* ret: n read = 1 */
int fread3(int *v, FILE *fp); /* ret: n read = 1 */
int freadInt(FILE *fp);       /* ret: int value */
float freadFloat(FILE *fp);   /* ret: float value */

int fwrite2(int v, FILE *fp);
int fwrite3(int v, FILE *fp);
int fwriteInt(int v, FILE *fp);
int fwriteFloat(float f, FILE *fp);

short swapShort(short s)
{
  SWAP_SHORT ss;
  char       c;

  /* first swap bytes in word */
  ss.s = s;
  c = ss.buf[0];
  ss.buf[0] = ss.buf[1] ;
  ss.buf[1] = c;

  return(ss.s);
}

int swapInt(int i)
{
  SWAP_LONG  sl;
  short      s;

  /* first swap bytes in each word */
  sl.i = i;
  sl.s[0] = swapShort(sl.s[0]);
  sl.s[1] = swapShort(sl.s[1]);

  /* now swap words */
  s = sl.s[0];
  sl.s[0] = sl.s[1];
  sl.s[1] = s;

  return(sl.i);
}

float swapFloat(float f)
{
  SWAP_LONG  sl;
  short      s;

  /* first swap bytes in each word */
  sl.f = f;
  sl.s[0] = swapShort(sl.s[0]);
  sl.s[1] = swapShort(sl.s[1]);

  /* now swap words */
  s = sl.s[0];
  sl.s[0] = sl.s[1];
  sl.s[1] = s;

  return(sl.f);
}

int fread2(int *v, FILE *fp)
{
  short s;
  int   ret ;

  ret = fread(&s,2,1,fp);
#ifdef Linux
  s = swapShort(s) ;
#endif
  *v = s;
  return(ret) ;
}

int fread3(int *v, FILE *fp)
{
  unsigned int i = 0;
  int  ret;

  ret = fread(&i,3,1,fp);
#ifdef Linux
  i = (unsigned int)swapInt(i);
#endif
  *v = ((i>>8) & 0xffffff);
  return(ret);
}

int freadInt(FILE *fp)
{
  int  i, nread ;
                                                                                
  nread = fread(&i,sizeof(int),1,fp);
#ifdef Linux
  i = swapInt(i) ;
#endif
  return(i) ;
}

float freadFloat(FILE *fp)
{
  float f;
  int ret;

  ret = fread(&f,4,1,fp);
#ifdef Linux
  f = swapFloat(f);
#endif
  return(f);
}

int fwrite2(int v, FILE *fp)
{
  short s;

  if (v > 0x7fff)    /* don't let it overflow */
    v = 0x7fff;
  else if (v < -0x7fff)
    v = -0x7fff;
  s = (short)v;
#ifdef Linux
  s = swapShort(s) ;
#endif
  return(fwrite(&s,2,1,fp));
}

int fwrite3(int v, FILE *fp)
{
  unsigned int i = (unsigned int)(v<<8);
#ifdef Linux
  i = (unsigned int)swapInt(i);
#endif
  return(fwrite(&i,3,1,fp));
}

int fwriteInt(int v, FILE *fp)
{
#ifdef Linux
  v = swapInt(v);
#endif
  return(fwrite(&v,sizeof(int),1,fp));
}

int fwriteFloat(float f, FILE *fp)
{
#ifdef Linux
  f = swapFloat(f);
#endif
  return(fwrite(&f,sizeof(float),1,fp));
}

#############################################################
------------------------------------------------
 The File -> New Functional menu creates a new
 blank functional session directory and its
 standard subdirectories
------------------------------------------------
This is the first step in making a new session.
A new functional session directory and a standard
set of subdirectories in it is created.  The
default location for the new session is the
current setting of the environment variable,
FUNCTIONALS_DIR, but a functional session can be
made anywhere.

Finding sessions by date or initials is much
easier with the csurf interface if multiple
sessions are stored in the same FUNCTIONALS_DIR.

The standard functional session directory
structure is:

 FUNCTIONALS_DIR (root of a sessions database)
    sessionname    (year+month+day+initials)
       image          (images)
          scripts        (configs, NOTES file)
          rgb            (saved SGI rgb bitmaps)
          mpg            (saved mpeg movies)
          mprage         (alignment scan)
          functscan1     (functional scan1)
          functscan2     (functional scan2)
          ...

When the functional session is made, it prompts
you to find a subject somewhere that contains the
surface for this functional.  The subject must
exist somewhere.  This linkage is saved in a
file, "name", inside the session directory
containing only the SUBJECTS_DIR directory name
of the subject (e.g., johns).

Once the functional session has been made, a
subdirectory for each functional scan should be
made in the image subdirectory.  Then, the
individual scans for that session should be
copied into the separate subdirectories.

You can give the scan subdirectories any name
besides the names of the standard subdirectories
but it is extremely helpful to number them so
they sort in the order in which were acquired.
Also, it helps to add an informative suffix to
each name (e.g., the name of the stimulus
program), since the directory names are what are
used to select scans in the interface.  For
example:

  $FUNCTIONALS_DIR/somesession/image/1-smfaces/*
  $FUNCTIONALS_DIR/somesession/image/2-bigfaces/*
  $FUNCTIONALS_DIR/somesession/image/3-words/*
  ...

The alignment scan (in directory "mprage" above,
but can be any name) is a T1-weighted scan taken
in the same plane as the functional scans.
Typically, it has thinner slices, smaller
in-plane pixels, and more coverage than the
functional scan.

The alignment scan is used to align the
functional data with the scans in the subjects
database that were used to make the surfaces for
this subject.  This procedure generates a
transformation matrix that allows statistical
measures calculated from the functional scans to
be painted onto the cortical surface.

There can be more than one alignment scan.  You
choose for each functional can which alignment
scan should be associated with it.

#############################################################
------------------------------------------------
 The SessionsTools -> View All Scandirs menu
 provides a quick way to browse the entire set of
 scan dirs in the current functional dir.
------------------------------------------------
Choosing View All Scandirs makes a popup that
contains all the previously configured scandirs
in the current FUNCTIONALS_DIR.  This may take a
few seconds.

The scandirs are sorted by subject (with a note
if the subject was not found in the current
SUBJECTS_DIR).  The sessions for each subject are
then arranged alphabetically.

Quick scandir access

Double-clicking a scandir opens the View
Functional Data panel for the session that
contains it, and renders activations onto the
currently selected surface.

If a surfer tools panel is already open, you have
to do two double-clicks on a new scandir to close
the currently rendering (and its surfer tools)
and to open a new one.

Double-clicking a session just opens the the View
Functional Data panel without rendering
anything.

Suppress render panel (multiple Surfer Tools)

To suppress the opening of the View Functional
Data panel, select "no panel" at the top of the
popup.  This also allows you to view more than
one scandir at a time.  Instead of closing the
current rendering and its surfer tools, a new
surfer tools panel will be generated (in the same
screen position) for each subsequent scandir.
#############################################################
------------------------------------------------
 The SessionsTools->Make Scandirs,Find/Copy Raw
 menu names and creates scan directories, makes
 raw scan links in them, strips initial TRs, and
 copies stripped scans into the new scan
 directories with meaningful, unique names.
------------------------------------------------

Getting Started

This panel is designed to be the first panel
accessed after running File -> New Functional.
It requires a virgin session directory tree
containing no scan directories.   If scan
directories have already been created (even if
they are empty), you won't even be able to open
this panel.   First manually remove existing scan
directories (the panel ignores the "rgb",
"scripts", and "tmp" directories in a newly-made
session).

Click the Find Raw Scans button at the top of the
panel to begin.  Click SETUP NEW SCANDIR one or
more times to create blank scan configuration
lines.  DELETE LAST SETUP deletes the most
recently added line, whether or not you have
altered it.

Create Scan Directories and Find Raw Scans

The scan directory name is the main text label
used in the rest of the interface for each scan,
and so it helps to choose informative names and
use them consistently.  One good name for a scan
is the name of the stimulus program that was
used.

By default, the first scan directory is the
alignment scan directory, and it is auto-named
"alignscan".  Directories after that are given
default prefixes: "1-", "2-", etc.  You can
change the names of the proposed scan directories
to whatever you like, but the names must be
unique (the default number prefixes guarantee
this, even if the stimulus exactly repeats --
e.g., "1-polar", "2-polar", etc).

For each new scan directory, click the FIND
button to locate a single raw alignment or
functional scan.  Subsequent FIND button clicks
start the directory browser in the parent
directory of the most recently selected Raw
Scan.

Once you are satisfied with the mapping between
scan directory names and raw scan names, click
MAKE SCANDIRS at the top of the panel.  If all
the fields are complete, the name list is unique,
and the raw scans all exist, the new scan
directories should appear on the left of this
panel (if not, fix things and click MAKE SCANDIRS
again).  Links to the raw scans will be made in
each of the scan directories.  If you want to
redo this stage, remove the just-created scan
directories (which will contain only links to raw
scans).

Strip Initial TRs and Copy/Rename Raw Scans

When the MAKE SCANDIRS button is clicked
successfully, default unique scan names will be
inserted into the right-most column (New Scan
Names).  These names must be unique because they
are used as the prefix for saved bitmaps, which
all reside in the same rgb directory.  These
names can be adjusted if necessary.  You may also
want to reset the number of repetitions ("rmTRs")
to strip off the begining of the functional
scans.  The defaults are to strip 0 for the first
(alignment) scan and strip 2 initial repetitions
off of subsequent functional scans.

Finally, click STRIP/COPY-RAW at the upper
right.  After checking the list of new names for
completeness and uniqueness, this strips TRs and
copies the raw functional scans into each scan
directory.

The STRIP/COPY-RAW function currently only works
with AFNI BRIKS. For now, if the fastest changing
index in the scan is not in the right/left
direction, the internal data order of the BRIK
will be flipped into this order and the HEAD is
updated to reflect this change (because some
later analysis steps do not yet read the AFNI
HEAD file).

#############################################################
------------------------------------------------
 The SessionsTools -> Setup Align/Funct Scans
 menu sets up the basic image parameters for
 functional and alignement scans in preparation
 for statistical analysis and rendering.
------------------------------------------------
On the left of this panel is a list of the
subdirectories in the current session.  On the
right are a set of pages--one for each scan
directory--that correspond to each functional
scan directory.  The first time you bring up this
panel, all the pages on the right of the panel
will be blank--no matter which scan directory is
selected, no parameters appear on the right.

The configure a particular directory, select it
from the list on the left (it should be marked
green) and then hit one of the buttons at the top
center of the panel to declare it to be either a
"Funct Scan Dir" or an "Align Scan Dir".

A "Funct Scan Dir" should contain one functional
scan, with multiple images/timepoints for each
slice.  An "Align Scan Dir" should contain a
T1-weighted scan taken in the same plane as the
functional scans, with one image per slice,
typically at a higher resolution than the
functional scans.

To save the current configuration of all of the
scan directories in the current session, hit Save
or Save/Close at the bottom of the panel.  You
can move between directories without losing any
configuration information as long as you do not
exit the panel.  Hitting Cancel will exit the
panel and leave the configuration in whatever
state it was when you first opened the panel.

The bottom buttons only affect the configuration
of the scan directories.  This information is
stored in an ASCII file:

  csurf.dat

which is located in the funct scripts directory:

  $FUNCTIONALS_DIR/$session/image/scripts

The Save/Close and Save buttons do not affect any
of the data files in the scan directories.

Configure and Convert the Alignment Scan

Once a directory has been declared to be an
"Align Scan Dir", the first step is to read the
header of an example file.  All the files within
the current scan directory will be present in
the "Image File:" combo box.  Select one of the
files (e.g., alignscan+orig.BRIK).  Then click
"READ HEADER" to attempt to read the parameters
from this file.  Verify that all the fields have
been filled in correctly.  Any fields that say
"-unset-" need to be set manually.

If the format of the scan is *not* an AFNI
BRIK or a bshort, you may be able to convert
it to a FreeSurfer native 1-byte COR format
by clicking the CONVERT=>COR button.  If this
doesn't work, try to convert to an AFNI brik
and read it directly.  CONVERT=>COR has not been
extensively tested.

Now click the INIT button near the bottom of the
panel to create an initial default transformation
matrix (the identity matrix).  This is equivalent
to assuming that the Align scan and the Subject
scan used to make the surface are already aligned
(they often *not* be aligned).  A panel will
say this was done automatically if you forget
when you hit the "Align=>Subj" button

Register the Alignment Scan

Now use the "Align=>Subj" button starts up the
registration program (tkregister) with the scans
used to make the surface for this subject as the
TARGET scan, and the alignment scans in the
currently selected directory as the MOVEABLE
scan.

The sole purpose of the tkregister application is
to generate a transformation matrix that maps the
alignment scan onto the scans used to make the
subject's surface.  The only file that tkregister
affects is:

  register.dat

one of which is located in each scan dir:

  $FUNCTIONALS_DIR/$session/image/$scan

See the "Register" Help menu item for tips on
how to register data sets.

Once the data sets have been aligned to your
satisfaction, hit the SAVEREG button on the
tkregister application to save it (it will backup
the previous registration matrix to the file
register.dat~).  Then quit the tkregister
application (using same now-purple button you
started it with).

Configure the Functional Scans

Now select each functional scan in the listbox at
the left and configure each one as a "Funct Scan
Dir".  Fill in any missing or "-unset-"
parameters.

Siemens UCSD mosaic note: although READ HEADER
can identify some of the parameters in a Siemens
mosaic scan, tkregister can't read a mosaic
directly.  First convert it a BRIK with thor.

Don't run the FUNCT=>SUBJ register button yet,
but be sure to open the combox box labeled
"Same-Plane Structural Dir:" at the bottom of the
panel to and select the alignment scan to be
associated with this functional scan.  This makes
it possible for there to be more than one
alignment scan.

Viewing Functional Scans

If the functional scan is a bona fide *.BRIK
file, you can view it with AFNI by typing
Alt-a in the panel (or using the AFNI button).
This will start AFNI in the currently selected
functional scan directory.

Optional 3D Volume Registration using AFNI

The AFNI tool, 3dvolreg, can be used for motion
correction using the buttons in the line labeled
"Volreg:".  The combo box labeled "Targ:" picks
the target scan.  It can be the current scan
(default) or any other scan currently configured
as a functional scan.  The field "TR:" picks the
target TR (default 10).  Clicking "CURR" aligns
all the other TR's in the current functional scan
with the target TR.  Clicking "ALL" aligns all
the TR's in every currently configured functional
scan to the target TR.

The volume-registered BRIK's are then written
back into the respective scan directories with a
"-vreg" infix.  For example:

 infile:  scandir1/scanname1+orig.BRIK
 outfile: scandir1/scanname1-vreg+orig.BRIK

 infile:  scandir2/scanname2+orig.BRIK
 outfile: scandir2/scanname2-vreg+orig.BRIK

The original BRIK's will be untouched.  The name
of the new volume-register BRIK's will be
inserted into the "Image Name Format" field in
the Setup Align/Funct scans panels.  Note that
this operation doubles the size of the functional
data in each affected scandir.

This program will only run on a bona fide *.BRIK
as an input.  To go back to the original
non-motion corrected data (or to re-run the
3dvolreg program), re-select a non-vreg'd "Image
File:" and READ HEADER.

Copy Alignment Registration to Functionals

Go back to the previously configured alignment
directory and use the "Copy Align To All Functs"
button to copy the alignscan-to-subjectscan
transformation matrix into each configured
functional scan directory.  This copies the
transformation, taking into account the fact that
the slice thickness and inplane resolution
typically differs between the alignment and
functional scans).

Block Center Offset

If the alignment scan and the functional scans
have different block centers, enter them in this
field.  This is used to modify the register.dat
file when it is copied between the alignment scan
and the functional scans.

Verify/Touch-up Functional Scan Registration

Select the first functional scan at the left.
Now register the functional scan directly to the
surface reconstruction scan using the FUNCT=>SUBJ
register button, which starts tkregister again.
Since the functional and alignment scans were
collected in the same plane, the rotation of the
functional scan will be correct.

Currently, however, the offset between the first
slice in the functional and alignment scans is
not accounted for.  To correct this, use only the
TRANSLATE buttons from tkregister.  Since the
scan has already been rotated, there will be an
x, y, and z component to the translation.  Change
planes and translate until the functional scan is
aligned.

Non-Rigid Transformations

Some of the lower-bandwidth, higher
signal-to-noise scans have additional shearing
(rhomboidal) distortion.  To correct shear you
have to use a combination of a rotation and a
scaling--a rotation alone won't work.  For
example, to correct a shear in which the left
side of the image is too high and right side to
low, do something like this:

  1) choose a rotation point near the center
  2) rotate 30 degrees to the right
  3) scale 95% in the vertical direction
  4) rotate 30 degrees to the left
  5) scale 105% in the vertical direction

Apply shear/scaling with discretion, only after
completely exhausting attempts to align the
images using translation and rotation.

Copy Registration Between Functionals

After finishing with one functional, you can copy
the final functional alignment transformation
matrix between functional scans using the CP PREV
button.  Select one scan, then a second, then hit
the button.  It will ask you to verify that you
are copying the registration matrix from the
first to the second scan.  To copy the current
functional registration to all the other
functionals, use the CP TO OTHERS button.

Vtx Normal Search Operation (for Paint)

During the PAINT process (in several different
later panels), a 3D statistic is associated with
each vertex on the surface by finding which voxel
the vertex lies within.  By entering different
values into the "mn:" (minumum) and "mx:"
(maxium) fields, a search will be performed
between those limits in increments of "step:"
size.  Possible operations (radio buttons at
right) on the set of statistics recovered in the
search are: "mx" (find largest absolute-valued
statistic along the vertex normal), "av"
(find average statistic), or "mn" find minimum
absolute-valued statistic.  There is an identical
set of controls on the Import 3D Stats panel.

Common Layout of SessionTools Panels

Most of the rest of the SessionTools panels are
arranged in a similar way.

 (1) center-top buttons that configure the
     current directory as a directory of a
     certain kind or tell the program to ignore a
     directory by Unset-ing it (a previously
     configured, then Unset directory, recovers
     its sets when re-configured)

 (2) settable parameters in the main part
     of the panel

 (3) action buttons at the top right with bold
     lettering that read the parameters you have
     set and actually perform computations that
     affect data files.  Those buttons turn
     purple during computations.

Some panels have smaller actions button in the
main body of the panels, mostly for (trying to!)
read headers.

#############################################################
------------------------------------------------
 The SessionsTools -> Combine 3D Raw Images
 menu averages/concatenates raw funct data
------------------------------------------------
The basic layout of this panel (scan directories
to the left, common action button at the top,
pages of parameters to the right) is similar to
the other SessionTools panels.  For more details,
see Help -> Setup Align/Funct.

This panel creates a new scan directory that
will contain averaged scans.

Configuration Buttons--Make Avg Dir, Unset Dir

First carefully choose a name for the average
directory in the entry to the right of the Make
Avg Dir button.  Clicking Make Avg Dir creates
that directory.  If the directory already exists,
it will be re-used rather than re-created.

To ignore an existing raw avg/concat directory,
use Unset Dir.  The files the unset directory
will not be altered and any saved parameters will
re-appear if you Make Avg Dir with that directory
name again.

Operation

Selected scans can either be averaged, time point
by time point, or concatenated.

Choosing Scans to Combine

A list of currently available functional scans
can be found in the "Select to Add" dropdown
combobox.  Selecting one of them will add it to
the "Dirs to Average" list.  To delete (or
re-order) directories from that list, select it
in the list and use the Delete or Backspace key.

Action Button--COMBINE

This button performs averages or concatenates the
3D time series data sets and writes the result
into the current raw average directory as a set
of bshort files (each bshort file has all the
time points for one slice) for averaging, and
AFNI briks for concatenation.  The registration
matrix from the first scan is copied into the raw
avg/concat directory and by convention, the first
scan in the average is used to name the output
files:

 infiles (several x-y-z-t images):

   scandir1/scanname1[-vreg]+orig.BRIK
   scandir2/scanname2[-vreg]+orig.BRIK

 outfiles (one x-y-z-t image):

   avgdir/scanname1[-vreg]+orig_000.bshort
   avgdir/scanname1[-vreg]+orig_000.hdr
   avgdir/scanname1[-vreg]+orig_001.bshort
   avgdir/scanname1[-vreg]+orig_001.hdr
   [etc]
            (or if concat)

   avgdir/scanname1[-vreg]+orig.BRIK

If the scans have been volume-registered, those
will automatically be used.  Otherwise, the
original raw scans are used.  The averaging is
done in 3D without any additional registration.
Note that register.dat files are ignored.

Other Files Generated by "Concatenate"

If the COMBINE operation is concatenate, an AFNI
boundary file, runs.1D, is automatically created
(units are TRs).  If the time series is analyzed
using deconvolution, this file is consulted to
prevent stimulus events at the end of one run
from accounting for variance at the beginning
of the next run.

If motion correction has been run on the
individual scans, a concatenated motion.1D file
will also automatically be generated.

Finally, if paradigm files are present in a
paradigm subdirectories (default: stim1Ds/)
of each scan to be
concatenated, the paradigm files for each
condition will be separately concatentated and placed in a paradigm
directory in the new concatenated scandir.
For the automatic concatenation of paradigm 1D
files to work correctly, the paradigm files in
the stim1Ds subdir in each of the scan dirs to
be concantentated *must* be named as follows:

  scan1
    face1.1D
    house1.1D
  scan2
    face2.1D
    house2.1D
  ...

That is, the condition name stem (up to the
number before the .1D suffix) much be exactly
the same across all scans to be concatentated.
The stem must be immediately followed by a single
numeral before the .1D suffix.

The list of conditions (1D files) to concatenate
is taken from the first directory in the list.
That is, each successive scan should have
the same set of conditions in it.  It's OK if
numerals are the same across scans (e.g., same
randomization in those scans).  The concatenated
paradigm file will be given a name that has the
numeral position replaced by a 'C'.

Touch up

If you averaged the data, at this point you
may want to go back to SessionTools -> Setup
Align/Funct Scans to touch up the FUNCT=>SUBJ
registration for the averaged scan.

#############################################################
------------------------------------------------
 The SessionsTools -> Calculate 3D Fourier Stats
 sets up and calculates Fourier-based statistics
 on 3D volume data sets
------------------------------------------------
This panel runs FFT's on the time course at each
voxel when you click FOURIER.  Normally, you then
click PAINT.

The Image Name Format

This is automatically entered from the Setup
Functional panel.

Stimulus Program Notes

An arbitrary length string of ASCII characters
for informational purposes.

Stim Cycles Per Scan

This is the most important parameter on the
panel.  To analyze a polar angle mapping stimulus
(rotating wedge) with 8 cycles, enter 8.  You
would also enter 8 if there were 8 ON blocks and
8 OFF blocks.  This number does *not* have to be
a power of two.

TR

The TR can be entered but is not currently used
(it could be used to correct for interleaving
delays).

Smoothing Steps

In-plane nearest neighbor smoothing steps
(typically 0).

Low-Freq Window

This is the number of bins immediately below the
stimulus frequency to ignore when calculating the
significance of the periodic activation at the
stimulus frequency relative to the activation at
other frequencies.

Omit Freq

This is the frequency (cycles per scan) of an
additional periodic nuisance signal to discard
when calculating signal-to-noise (e.g., a
periodic activation due to a regularly performed
task during a phase-encoded mapping experiment).
To disable, set to -1 (default).

Mean Delay

This is only relevant to the calculation of the
F-statistic.  For this calculation, response
phases are broken into two 180 degree halves.
This parameter controls where the two halves are
situated.  Later on, in the View FUnctional Dat
panel, this delay can be interactively controlled
with angle_offset for FOurier analyzed data.
However, it is set in this panel if F-statistics
are read in (as opposed to the real and imaginary
Fourier components).  The see F-statistics with a
difference delay, you have to re-run FOURIER.

Phase Encode Type

The radio button chosen merely gives default
values to the color map, the parameter settings,
and the tcl scripts used when the View Functional
Data panel is opened to render surface images.
All of the values can be overridden there.

Truncphase

If Truncphase is checked, some phase angles will
be set to zero during the PAINT operation which
associates 3D statistics with each surface
vertex.

[TODO: explain default settings]

Action Button--FOURIER

When FOURIER is run, the panel will check whether
the number of repetitions in the corresponding
Setup Functional panels are powers of 2.  FOURIER
will not run unless this is the case (typically
64, 128, 256, or 512 repetitions).

Action Button--PAINT

This button samples the Fourier analyzed data
onto the surface specified in "Surface for
Sampling 3D Data".  The result is four files
(whose names appear schematically in the bottom
two entries), two for each hemisphere, which
consist of the real and imaginary components of
the Fourier transform.

View 3D Stats, Raw Images

On IRIX, use Alt-v to start up the (unsupported)
tkanalyse 3D statistics and raw images viewer for
the currently selected scan directory.

#############################################################
------------------------------------------------
 The SessionsTools -> Calc 3D Rand Block Stats
 sets up and runs deconvolution on 3D volume
 data set using AFNI 3dDeconvolve (by Doug Ward)
------------------------------------------------
This panel configures files and runs Doug Ward's
3dDeconvolve on functional time-series BRIKs.
Normally, you then use SessionTools -> Import 3D
Stats to extract the output files and PAINT them.
It requires that single-column 1D paradigm files
have been previously generated and placed within
each paradigm dir (see below).

The Image Name Format

This will typically be a concatenated,
motion-corrected time-series BRIK.  This is
automatically entered from the Setup Functional
panel.

Paradigm Dir

Directory containing the single-condition 1D
files specifying the paradigm.  This can be
anywhere (e.g., a central paradigm depository).
However, since these files are small, and since
a central paradigm store may get out of sync
with an already-performed expt, it is a better
idea to save a copy of the paradigm files that
were actually used inside each scan directory.
The directory specified here can either be
absolute (starts with "/") or relative (doesn't
start with "/" and is assumed to be inside the
current scandir).  A relative path is preferred
since using an absolute path to the paradigm
dir may break if the functional session is moved
into a different FUNCTIONALS_DIR.  The standard
name is "stim1Ds".

Paradigm Files

These are single column (n x 1) files, one
for each condition.  The filename should be a
short (8 chars or less) word followed by a .1D
suffix (e.g., face.1D, house.1D, scramble.1D).
(see below on naming rules for files that are
going to be auto-concatentated).

The files should end in unix-style newline
characters, \n.  If they don't -- e.g., output
from export to "space-separated" from Excel has
DOS carriage returns (\r), not unix newlines
(\n) -- fix them by using, for example, tr:

  tr '\r' '\n' < condfiles.prn > condfiles.txt

That would convert DOS carriage returns to unix
newlines (you will need a different tr command
is you have more than one invisible end-of-line
character).  To see explicitly what is in a text
file, use

  od -cv textfile

This will print out the actual bytes in the
file 16 to a line, with spaces between each byte
(N.B.: space characters also show up as spaces
[separated by spaces]).  There should only be
numbers (0 and 1) and newlines (\n) (and possibly
spaces or tabs (\t) in the paradigm file.  Spaces
and tabs will be ignored.  Any other characters
will cause csurf or 3dDeconvolve errors.

The filename stem (e.g., face, house, scramble)
will be used in the interface and the resulting
saved bitmaps as the condition name.  Inside
the file, there should be a 1 when its named
condition is present and a 0 when it is not
(an error panel will come up if something other
than 0 or 1 is found).

The baseline condition is defined by the presence
of a 0 in all of the condition files.  Thus,
there is no 1D file for the off-condition.
Except for the off-condition case, for a given
TR, there should be a 1 in exactly one paradigm
file.  Here is an example of a portion of a
paradigm file:

====== cut here ==========================
0
0
1
1
1
...
====== cut here ==========================

If the scandir was generated by concatenating
raw data files from separate runs (COMBINE
on the SessionTools -> Combine 3D Raw Images
panel) prior to opening this panel, the COMBINE
concatentation process should already have
automatically generated the following files:

 concat'd BRIK/HEAD raw data file
 concat'd motion.1D file (if runs volreg'd)
 boundsfile: run1.1D (so HDRs don't cross runs)
 a stim1Ds subdirectory
 concat'd paradigm files put in stim1Ds/

N.B.: for the automatic concatenation of paradigm
1D files to work correctly, the paradigm files
in the stim1Ds subdir in each of the scan dirs
to be concantentated *must* be named as follows:

  scan1
    face1.1D
    house1.1D
  scan2
    face2.1D
    house2.1D
  ...

That is, the condition name stem (up to the
number before the .1D suffix) much be exactly
the same across all scans to be concatentated.
The stem must be immediately followed by a single
numeral before the .1D suffix.

The list of conditions (1D files) to concatenate 
is taken from the first directory in the list.
That is, each successive scan should have 
the same set of conditions in it.  It's OK if
numerals are the same across scans (e.g., same
randomization in those scans).  The concatenated
paradigm file will be given a name that has the
numeral position replaced by a 'C'.

TR (sec)

Repetition time between successive images of
the same slice in seconds.

Maximum Lag (-maxlag)

The maximum lag (in TRs) to allow when solving
for the hemodynamic response function for a
each trial type.

Polynomial Fit Order (-polort)

This specifies the order of the polynomial used
to fit the low frequency drift in the signal.
The default is 2.

Motion Params File (-dfile)

This should contain a 6-parameters-per-timestep
estimate of motion artifact.  This is typically
generated by 3dvolreg after motion correction is
run in the Setup Functional panel.

Scans, Total TRs

The number of scans that were concatenated to
generate the input file named at the top, and the
total number of TRs that it contains.

Paradigm Panel

When "READ 1Ds" is clicked, the individual
condition paradigm files are each read and
assembled into a paradigm matrix, where each
column comes from one 1D file.  The stems of the
paradigm filenames are substituted for 1's and
"----" is substituted the 0's in the 1D file.
This step verifies that the 1D files all have
the same length.

Condition Differences

To add a subtraction, select a block type from
the "Condition A:" and  "Condition B:" dropdown
menus and then click "ADD SUBTRACTION" which
should add it to the Subtractions list below.  To
omit a subtraction, use Backspace.

Action Button--DECONVOLVE

When DECONVOLVE is clicked, 3dDeconvolve will be
run according to the mode radio buttons just
above the paradigm window (test/F/t-stats).  The
output stats file will be written into the
current scan directory.  If Test is selected, the
parameters are checked for completeness and the
design matrix is tested for singularity.

Stats Output File

The output stats BRIK name appears here after
DECONVOLVE has been run.  This takes a while
for a concatenated scan.  Correct settings for
rendering will depend on the paradigm.  For the
blue/red scale, try starting with:

  smooth:   10
  thresh:   0.0
  contrast: 0.15
  midpoint: 7
#############################################################
------------------------------------------------
 The SessionsTools -> Combine 3D Phase Stats
 menu averages fourier-analyzed 3D stats
------------------------------------------------
This panel creates a new scan directory that will
contain averaged 3D fourier-based statistics.

Configure Buttons--Make CombineDir, Unset Dir

First carefully choose a name for the average
directory in the entry to the right of the Make
CombineDir button.  Clicking Make CombineDir
creates that directory.  If the directory already
exists, it will be re-used rather than
re-created.

To ignore an existing 3D phase average directory,
use Unset Dir.  The files in the unset directory
will not be altered and any saved parameters will
re-appear if you click Make CombineDir with that
directory name again.

The 3D stats files are combined voxel-by-voxel,
which ignores the funct=>struct transformation
matrix (register.dat).  The transformation matrix
for the combined file is copied from the *first*
stats set in the combine list.  This
transformation matrix gets used when the combined
file is PAINT'ed.  Be sure to re-COMBINE in order
to redo this copy operation if you go back and
touch up the transformation matrix from the
firstan input stat set (adjustments to later stat
sets in the list are ignored) and you want the
that modified transformation matrix to be used
for the PAINT in this panel.

Choosing Stat Files to Average

A list of currently available fourier-analyzed
functional scans can be found in the "Select to
Add" dropdown combobox.  Selecting one of them
will add it to the "ScansToCombine" list.  To
delete (or re-order) a directory from that list,
select it in the list and then use the Delete or
Backspace key.

Reversing Phase of Stat Files

If scans to be combined do not have the same
phase direction (e.g., clockwise vs. counter-
clockwise direction of the moving sector in a
polar angle mapping experiment), the phase of one
or more scans can be reversed by selecting the
scan to be reversed, and then typing Return (or
double-clicking).  "Reversing the phase" means
taking the negative of the phase angle calculated
for each voxel.  This is equivalent to reversing
the direction of time in the time domain.

Combine Operations

Now select a combine operation.  The operation
'phaseaverage' calculates the voxel-by-voxel
vector average of the the complex-valued data
(separately average real and imaginary
components).  The operation 'phasecancel'
calculates the voxel-by-voxel angular average
and then separately averages the amplitudes
(separately average phase and amplitude
components).  In the first case, if two vectors
with large amplitude have very different angles,
the amplitude of their vector average will be
small; in the second case, it will be large.
Thus, the 'phaseaverage' operation more strongly
penalizes voxels with inconsistent phase in the
component scans.  Currently, the 'phasecancel'
operation can only combine two scans.

Offset

The measured response phase consists of a
stimulus phase plus a hemodynamic delay phase.
If scans are combined with opposite directions of
phase, the hemodynamic delay phase can be
subtracted out.  However, if the operation
'phaseaverage' is used, this will reduce the
amplitude of the vector average (there is no
effect of a hemodynamic delay on the
'phasecancel' operation and no effect of a
non-zero offset in this panel).  To avoid this
reduction in amplitude, an estimated average
hemodynamic delay (in units 0.0 to 1.0, where 1.0
equals one full stimulus cycle) can be applied
prior to the 'phaseaverage' operation.

Action Button--COMBINE

This button performs the 3D phase average of
the fourier-analyzed data sets that you have
selected and writes the result into the current
sig average directory as a new set of 3D files.

Action Button--PAINT

This button samples the combined data onto the
surface specified in "Surface for Sampling 3D
Data" in the Fourier panel.  The result is four
new files, two for each hemisphere, which consist
of the real and imaginary components of the
combined Fourier statistics (*.w files) which can
be directly displayed on the surface with View
Functional Data panel.  Note that this button
generates files for both hemispheres, regardless
of which hemisphere is currently selected.

Input and Output Files

 infiles (Fourier-analyzed files--complex data):

   -----------------------------------------
   session1/scandir1/scanname1_r_%03d.bfloat 
   session1/scandir1/scanname1_i_%03d.bfloat 
   -----------------------------------------
   session1/scandir2/scanname1_r_%03d.bfloat 
   session1/scandir2/scanname1_i_%03d.bfloat 
   -----------------------------------------
   ...


 outfiles (3D files--complex data):

   ---------------------------------------------
   currentsession/sigavg/scanname1_r_%03d.bfloat 
   currentsession/sigavg/scanname1_i_%03d.bfloat 
   ---------------------------------------------

 outfiles (paint files--complex data):

   ----------------------------------------
   currentsession/sigavg/scanname1_r-rh.w
   currentsession/sigavg/scanname1_i-lh.w
   ----------------------------------------
   currentsession/sigavg/scanname1_r-lh.w
   currentsession/sigavg/scanname1_i-lh.w
   ----------------------------------------

#############################################################
------------------------------------------------
 The SessionsTools -> Combine Surface Stats
 menu averages already-painted surface stats
------------------------------------------------
This panel creates a new scan directory that
will contain averaged surface-based statistics
(possibly cross-session).

Configure Buttons--Make SurfAvg Dir, Unset Dir

First carefully choose a name for the average
directory in the entry to the right of the Make
Avg Dir button.  Clicking Make SurfAvg Dir
creates that directory.  If the directory already
exists, it will be re-used rather than
re-created.

To ignore an existing surface average directory,
use Unset Dir.  The files in the unset directory
will not be altered and any saved parameters will
re-appear if you click Make SurfAvg Dir with that
directory name again.

Choosing Stat Files to Average

Choosing the pre-painted stats to average is a
three-part process.

First select a session from which a scan will be
chosen, by selecting a session using the
"Functional Sessions to Choose From" dropdown
combo box at the top.  This allows you to average
scans across different sessions, as long as they
are in the current Functional Sessions directory
($FUNCTIONALS_DIR).  The statistics to average
must have been painted using a single subject's
surface (the same version of it!).  If you want
to select a scan from the currently open session,
you have to hit 'Enter' in the combo box.

Second, once you have selected a session, the
dropdown combo box on the next line at the left
("Select Both", meaning both hemispheres) will
now contain the individual scan directories in
that session.  Select one scan directory.  If the
scan directory contains pre-painted data, the
dropdown combo box immediately to the right
("Vertex List Prefix") will be updated.

Finally, select one of the pre-painted vertex
list prefixes in the "Vertex List Prefix"
dropdown combo box to the right.  If the paint
file is from a retinotopy session, the real and
imaginary infixes will be automatically stripped
(you only need to select either the real or
imaginary file).

Once you have selected one of the paint files,
the full path to it will be added to the central
"Fullpath Vertex Lists to Combine" panel.  To
delete (or re-order) directories from that list,
select one in the list and use the Delete or
Backspace key.

Reversing Phase of Stat Files

If scans to be combined do not have the same
phase direction (e.g., clockwise vs. counter-
clockwise direction of the moving sector in a
polar angle mapping experiment), the phase of one
or more scans can be reversed by selecting the
scan to be reversed, and then typing Return (or
double-clicking).  "Reversing the phase" means
taking the negative of the phase angle calculated
for each voxel.  This is equivalent to reversing
the direction of time in the time domain.

Combine Operations

Now select a combine operation.  The operation
'realaverage' simply averages two real-valued
data sets (e.g., F-stats).  The other three
operations average complex data sets and differ
only in how they setup the default color scale
options in the View Functional Data panel.  For
complex data sets, you can introduce a phase
offset for each data set that differs from zero
(see below).

Use Script, New Script checkbox

If the "Use Script" checkbox is selected, a
editable combine script will be created (IRIX
only, using binary: surfcombine).  Checking "New
Script" overwrites/re-generates a fresh version
of this file if it already exists.

Action Button--SURFCOMBINE

This button performs a surface-based average of
the pre-painted stats data sets that you have
selected and writes the result into the current
surf average directory as a new set of painted
files (*.w files) which can be directly displayed
on the surface with View Functional Data panel.
Note that this button operates on the files for
both hemispheres, regardless of which hemisphere
is currently selected.

When you click the SURFCOMBINE button with "Use
Script" *un*-checked, the selected paintfiles are
combined (using binary: rcxcombine).

When you click the SURFCOMBINE button with "Use
Script" checked (currently IRIX only), a small
text file with a *.scom suffix is created and
opened using the default text editor.  This file
will be used by the surfcombine program to do the
averaging after you click "OK" on the alert
panel.

You can edit the file in the editor before it
is used.  For example, you can use non-zero
angle_offsets for each file (OK to have a
different angle offset for each file) or the
phase can be reversed for one or more input
files.  Do this by changing the default arguments
of the transform_angles command:

  transform_angles <revphaseflag> <angle_offset>
                     default=0     default=0.0

The commands that can be placed in the *.scom
file and their arguments are:
  ---------------------------------------------
  setdir <directory_path>
  read_real    <stem-hemi.w>
  read_complex <stem_r-hemi.w> <stem_i-hemi.w>
  average_real    <number_of_files_to_average>
  average_complex <number_of_files_to_average>
  smooth_real    <steps>
  smooth_complex <steps>
  transform_angles <revphaseflag> <angle_offset>
  write_real <stem-hemi.w>
  write_complex <stem_r-hemi.w> <stem_i-hemi.w>
  ---------------------------------------------

Input and Output Files

 infiles (paint files--complex data example):

   ----------------------------------
   session1/scandir1/scanname1_r-rh.w
   session1/scandir1/scanname1_i-rh.w
   session1/scandir1/scanname1_r-lh.w
   session1/scandir1/scanname1_i-lh.w
   ----------------------------------
   session2/scandir1/scanname1_r-rh.w
   session2/scandir1/scanname1_i-rh.w
   session2/scandir1/scanname1_r-lh.w
   session2/scandir1/scanname1_i-lh.w
   ----------------------------------

 outfiles (paint files--complex data example):

   ----------------------------------------
   currentsession/surfavg/scanname1_r-rh.w
   currentsession/surfavg/scanname1_i-lh.w
   ----------------------------------------
   currentsession/surfavg/scanname1_r-lh.w
   currentsession/surfavg/scanname1_i-lh.w
   ----------------------------------------

#############################################################
------------------------------------------------
 The SessionsTools -> Calculate Visual Field Sign
 sets up two Fourier-analyzed data sets in order
 to calculate the visual field sign (mirror vs.
 non-mirror image representation)
------------------------------------------------
This panel calculates the visual field sign using
two Fourier-analyzed data sets--one for in which
eccentricity was mapping and the other in which
polar angle was mapped.

The gradients in retinal eccentricity and polar
angle with respect to cortical x and y are
computed.  These two gradients are vector
quantities whose norms have units deg/mm (the
reciprocal of magnification factor). They are
computed by fitting a plane to the r (or theta)
values of the current vertex and its immediate
neighbors using least squares.  The clockwise
angle between them (the fieldsign angle) is then
measured to determine whether the local
representation of the visual field at that vertex
was non-mirror-image (angle near Pi/2) or
mirror-image (angle near -Pi/2). Finally, the
intensity of the field sign coloring was adjusted
using the average significance from the
eccentricity and polar angle data sets.

Input Files

There are eight Fourier-analyzed, painted
input files for this operation:

 $FUNCTIONALS_DIR/sess1/image/eccen/ecc_r-rh.w
 $FUNCTIONALS_DIR/sess1/image/eccen/ecc_i-rh.w
 $FUNCTIONALS_DIR/sess1/image/polar/pol_r-rh.w
 $FUNCTIONALS_DIR/sess1/image/polar/pol_i-rh.w

 $FUNCTIONALS_DIR/sess1/image/eccen/ecc_r-lh.w
 $FUNCTIONALS_DIR/sess1/image/eccen/ecc_i-lh.w
 $FUNCTIONALS_DIR/sess1/image/polar/pol_r-lh.w
 $FUNCTIONALS_DIR/sess1/image/polar/pol_i-lh.w

Eccentricity and Polar Angle Scan comboboxes

Select an eccentricity functional scan in the
"Scan Directory" combo box.  A *.w file must
appear in the "Vertex List Prefix" combo box
immediately to the right.  Do the same for a
polar angle functional scan.

Smoothing Steps

Since the fieldsign calculation involves
gradients (derivatives), the data needs to be
heavily smoothed to reduce noise (default: 50
steps)

Action Button--FIELDSIGN

This generates four files, two for each
hemisphere.  The fieldsign itself is stored in
{rh,lh}.fs while the fieldsign significance mask
is in {rh,lh}.fm.

 $FUNCTIONALS_DIR/sess1/image/fs/rh.fs
 $FUNCTIONALS_DIR/sess1/image/fs/rh.fm

 $FUNCTIONALS_DIR/sess1/image/fs/lh.fs
 $FUNCTIONALS_DIR/sess1/image/fs/lh.fm

#############################################################
------------------------------------------------
 The SessionsTools -> Import 3D Stats sets up
 to import statistical data set that have already
 been analyzed with AFNI (or SPM)
------------------------------------------------

Select Input Data Set

First select the input data set to extract and
convert.  The interface will crudely guess at the
StatType using the input file suffix:

  <stem>.img         => SPM
  <stem>.BRIK/HEAD   => AFNI-SINGLE
  <stem>.BRIK/HEAD   => AFNI-MULTI (BRICK_LABS)
  <stem>_%03d.bfloat => BFLOAT

After checking the configuration, then press
EXTRACT/CONVERT.  If this works without error,
press PAINT.

SPM Format

The SPM extraction requires that matlab
be installed (to extract the transformation
matrix) and has not been updated in a long time.
For now, convert to BRIK and use AFNI import.

AFNI BRIK Format

The tools for extracting and converting AFNI
files analyzed with 3dDeconvolve have been more
thoroughly tested.

If a BRIK contains no labels (BRICK_LABS field
in *.HEAD file) or only a single default label
('#0~), it will be treated as an AFNI-SINGLE
import, which allows the extraction of a single
subbrik ("Briks to Skip" selects which subbrik
to extract, if there are more than one).

An extra sub-panel appears when a BRIK containing
multiple labels is selected.  After pressing
the READ HEADER button in the sub-panel, you
should then be able to choose which sub-briks
to extract, which sub-briks to use as maskfiles,
and what the mask threshold should be.  You can
also run clustering and set the cluster radius
and volume.

Paint

Pressing PAINT, paints all the extracted
3D files onto the chosen cortical surface,
using the current vertex normal operation (same
operations as on Setup Align/Funct Scans panel,
for explanation, see Help for that panel).
You can then view all of the painted files later
on in the rendering panel:

  SessionTools -> View Functional Data

where there is a set of radiobuttons near the top
of the panel that allow the rendering of multiple
extracted sub-briks from a single scan directory.
The options are:

 one  -- render selected (single) vertex file
 last -- render all vertexfiles from last extract
 all  -- render all vertexfiles (except complex)

When the multiple-render options are clicked, 
the selected vertex file changes to "-multiple-".
The stems of the output rgb files in that case
are the same as the stems of the sub-briks.

BFLOAT

The bfloat format is a slice-based format with a
minimal header that is used internally by
FreeSurfer programs, and that can be easily be
generated by an external C program.  The filename
format for each slice file and header file is:

  <stem>_%03d.bfloat
  <stem>_%03d.hdr

The slice numbering is zero-based.  The first
slice is therefore:

  <stem>_000.bfloat
  <stem>_000.hdr

The bfloat file is a headerless string of floats
with x as the inner loop (x is the R->L direction
in tkregister when a default (identity matrix)
register.dat is loaded).  The hdr file is an
ASCII file that contains 4 strings:

  <xsize> <ysize> <numtimepoints> <other>

For example:

  64 64 1 0

Note that for binary compatibility across all
platforms, the bfloat files are stored in
SGI/Sun/Mac byte order.  All the FreeSurfer
programs automatically swap bytes on read and
write on Linux.  For this reason, if bfloat files
are generated by a simple C program in Linux
using fwrite(), you should swap the bytes as the
last step.  For example, you could run AFNI 4swap
on each bfloat after generating it.  The hdr
files are ASCII and therefore don't need to be
swapped.

#############################################################
------------------------------------------------
 The SessionsTools -> View Functional Data sets
 up to paint 3D statistics onto high resolution
 3D data sets (medit) or onto different views
 of the cortical surface (surfer)
------------------------------------------------
The basic layout of this panel (scan directories
to the left, common action button at the top,
pages of parameters to the right) is similar to
the other SessionTools panels.  For more details,
see Help -> Setup Align/Funct.

First select a scan directory at the left and
click "Render Stats Dir" at the top to get a new
page of parameters.  Each field in the page is
described from top to bottom.

Painted Vertex List Prefix (VtxList Pref)

This is the stem for files that are generated
when you hit the PAINT button on functional
analysis panels.  The full files (for the right
hemisphere) may have the following forms:

 <stem>-rh.w      real data (e.g., corr)
 <stem>f-rh.w     signed F-stats exponents
 <stem>_r-rh.w    real comp of Fourier
 <stem>_i-rh.w    imaginary comp Fourier

These files contain lists of vertex-number/value
pairs.  These values can be rendered onto any
transformation of a surface (folded, unfolded,
flattened patch, etc) that has the same number of
vertices.

When you select one of the stems that has an
infix (e.g., _r, _i, f), the infix is
automatically stripped off (the polar, eccen
and twocond scripts use this stem to read two
files).

The set of radiobuttons directly to the right 
of the Painted VtxList Pref selector allow the
the rendering of multiple extracted sub-briks
from a single scan directory.  The options are:

 one  -- render selected (single) vertex file
 last -- render all vertexfiles from last extract
 all  -- render all vertexfiles (except complex)

When the multiple-render options are clicked, 
the selected vertex file changes to "-multiple-".
The stems of the output rgb files in that case
are the same as the stems of the sub-briks.

Saved Images Prefix

This is the name of the stem of the bitmap(s)
that will be generated when SURFACE-STATS or
VOLUME-STATS is run.

Stat Color Scales

There are four color scales available from csurf,
some of which have more than one behavior.  Other
less common color scales are available from the
large version of the surfer tools panel.

  Colwheel (w1)

  This color scale was originally designed for
  phase-encoded data (e.g., retinotopic
  mapping).  The hue represents the phase and the
  saturation represents the strength of the
  response.

  With integral anglecycles (1,2,3), the scale is
  red(early)->blu(intermed)->grn(late) wrapping
  around at red.  This is used for eccentricity
  data or two-condition data.  With anglecycles=1
  each phase has a unique color.  To compensate
  for hemodynamic delay, angleoffset should be
  decreased (-0.1 same as 0.9).  To convert
  angleoffset into seconds, multiply it by the
  time for one cycle.

  With anglecycles set to a non-integral number,
  there is only one red->blu->grn cycle.  In this
  mode, phase values below red are clamped to red
  and phase values above green clamped to green,
  each fading to gray.  To completely remove half
  of the phases opposite to the red->blu->grn,
  use truncphase (oldcsurf only).  Truncphase has
  no effect with integral anglecycles.  For
  non-integral angleoffsets between 1 and 2,
  there is an additional 1/6 of a cycle offset
  not seen with angleoffsets between 2 and 3 (the
  normal usage).  Thus, these pairs will color
  phases (in the first cycle) equivalently:

                   anglecycles   angleoffset
                   -----------   -----------
    integral          1.0           0.0
    non-integral      1.0001        0.1666

    integral          2.0           0.0
    non-integral      2.0001        0.0

  To see strongly activated regions, set
  fmid to 1.5, fslope to 1.5, and fthresh to
  0.3.  If the absolute threshold (fthresh) is
  kept low, fmid can be used to adjust the
  effective threshold without introducing
  artifactual edges.

  It is difficult to represent the full range of
  exact values of phase using color alone.  A
  more fine-grained representation can be
  obtained by running the phasemovie.tcl script
  from Surfer Tools.  This steps through each
  phase (total number of steps adjustable),
  drawing a white contour line for a small range
  of phases (width of range adjustable).  With
  invphase and revphase off, the white phase
  marker progresses from regions responding best
  to the beginning of each stimulus cycle toward
  regions responding to the end of the cycle.

  Mapping stimuli that start horizontal

  For a counter-clockwise rotating polar angle
  stimulus that starts at the right (zero deg),
  the default settings for Phase/Rev,Offset in
  the View Functional Data panel are (ignoring
  hemodynamic delays):

  Phase/Rev,Offset: [ ] "RH" 0.0   [x] "LH" 0.5

  Note that the offset for the right hemisphere
  is zero when the stimulus starts in the right
  hemifield, which is counterintuitive, but,
  unfortunately now conventional.

  These settings result in brain regions
  representing the contralateral upper field
  being colored red, brain regions representing
  the contralateral lower field colored green,
  and the brain regions representing the
  contralateral horizontal meridian colored blue,
  in *both* hemispheres.

  Adjust settings if the stimulus is different.
  For example, for a clockwise rotating polar
  angle stimulus that also starts right, reverse
  the opposite hemisphere:

  Phase/Rev,Offset: [x] "RH" 0.0   [ ] "LH" 0.5

  For a counter-clockwise rotating stimulus that
  starts on the left, use RH offset=0.5 and LH
  offset=0.0, and so on.

  Mapping stimuli that start vertical

  For a clockwise rotating polar angle stimulus
  that starts at the *top* (e.g., a stimulus that
  first enters the top right hemifield or the top
  right side of the face), you have to add a
  quarter cycle to the values above.  Since one
  hemisphere is reversed, the quarter cycles make
  the angle offsets the same for both hemispheres
  (again assuming no hemodynamic delay).

  Phase/Rev,Offset: [x]"RH" 0.75  [ ]"LH" 0.75

  If a clockwise stimulus starts at the bottom,
  then the offsets should both be set to 0.25

  To get an interactive, screen-dump-able
  representation of how the color wheel code
  colors each phaseangle or how significance
  and phase angle interact, use the included
  program, wheel:

    wheel <0-3> [opts]

  and adjust rendering parameters with F1-12.
 
  Pseudocode for non-integral anglecycles:
    find amplitude from real/imaginary
    trunc amplitude to zero below fthresh
    run non-trunc'd amplitude through sigmoid
    find phase from real/imag in -0.5 to 0.5
    if reverse => take negative of phase angle
    if inverse => add 0.5 to phase angle
    subtract angle_offset from phase angle
    fmod/add-1-to-neg => phase back in 0-1
    [truncphase currently broken -- don't use]
    if truncphase => zero outside 0.25 to 0.75
    subtract 0.5 from phase angle
    multiply phase angle by anglecycles
    if less than -1/3 => red
    if less than 0    => red to blue
    if less than 1/3  => blue to green
    greater than 1/3  => green
    fade ipsilateral colors (def: fadef=0.7)
    fade into two background grays

  Heatscale (ht)

  The heat color scale here represents the
  significance of the response and has two main
  behaviors.

  With fourier-analyzed (complex) data, the heat
  scale runs from dark brown to white and
  displays any brain region significantly
  activated in a periodic fashion (i.e., all
  phases).  Truncphase can be used to truncate
  half of the phases and angleoffset controls the
  exact half that are truncated.  The angleoffset
  for two condition expt with 20s ON and 20s OFF
  should be something like 0.1 (this is in units
  of one cycle: 0.1 * 40 sec = 4 sec delay).

  The heat color scale can also be used to
  display F-statistics.  The analysis performed
  by the Fourier panel generates a third file,
  <stem>f-$hemi.w.  This will be read in if (1)
  the Complex button is *un*-set, and (2) the
  twocond tcl scripts are used in place of the
  polar or eccen tcl scripts.  Unlike the first
  heat scale, this one is calculated for a single
  delay, settable when FOURIER is run in the
  Fourier panel (changing this delay does *not*
  affect the color wheel and complex heat scale
  statistics).  Foci activted by ON-first are
  red->yellow while foci activated by OFF-second
  are blue->lightblue.  This scale can be
  truncated with truncphase and reversed with
  invphase (surfer tools).  The values of fthresh
  and fmid represent negative powers of ten of
  p-values.  Foci visible with fmid set to 4.0
  are strongly significant.  The scale bar values
  are:

    threshold        = fthresh
    full red/blue    = fthresh + fmid
    full yellow/cyan = fthresh + fmid + 1/fslope

  One strategy to set the F-stats delay is to run
  an angle offset movie using the complex heat
  scale with truncphase ON, using a tcl script
  (scripts: offsetmovie.tcl) and then enter a
  reasonable angleoffset (generally not more than
  plus or minus a quarter of a full cycle) that
  best captures all of the ON activations into
  the delay field of the Fourier panel, re-run
  Fourier, and re-render using the F-stats
  (non-complex) heat scale.

  Blue/Red->white (BRw)

  Two-condition statistic color scale for real,
  signed data.  Red positively correlated; blue
  negatively correlated (reversible with
  revphaseflag).  As significance increases,
  scale goes to white for both positive and
  negative correlations.  Not affected by
  angleoffset, anglecycles, invphase (N.B. this
  scale will give spurious results if it is used
  to display complex data).

  Fieldsign (fs)

  This binary color scale is designed for field
  sign data only.  Yellow is mirror-image field
  sign and blue is non-mirror-image fieldsign.
  Reversible with revphaseflag.

Smoothing Steps on Surface

Controls how many nearest-neighbor smoothing
steps are done before display.  These are
performed on the finer mesh of the surface, not
on the coarser mesh of the functional scan.  To
see the effects interactively, use the surfer
tools SMOOTH button with the radio button set to
'val' (operates on data currently on the top of
the value stack).

An empirically derived correspondence between
the number of smoothing steps and the average
full-width-at-half-max filter result starting
with a single non-zero vertex is:

  steps   FWHM (mm)
 --------------------
   10      3.20
   20      4.49
   30      5.36
   50      6.99
   70      8.31
  100     10.15
  230     ~1.5 cm
  400     ~2 cm
  900     ~3 cm
 --------------------

A power function fit to this empirical map
(r^2 = 0.9987) is:

  fwhm = 0.9921 * steps^0.5018

Statistical Threshold (fthesh)

This is a hard thresh.  The meaning of the
value depends on the current scale.

Statistical Contrast (fslope)

Controls the steepness of a sigmoid (or a double
sigmoid in the case of two-ended color scales).
Larger values make the color scale change more
rapidly for a given change in a statistic.

Statistical Midpoint (fmid)

Sets the location of the fastest changing part of
the sigmoid (or of a double sigmoid for two-ended
scales).  This is typically used to set the
effective threshold.

PhaseReverse (revphase), Offset (angleoffset)

The phase can be reversed, and an offset can be
added to it independently for the two
hemispheres.  The Offsets (angleoffset) are only
relevant for complex-valued color scales
(colwheel, heatscale w/complex on).

Color Wheel Cycles

Integral values for the color wheel cycles cause
the color wheel of phases to wrap around one or
more times while non-integral values cause there
to be one cycle through the color wheel with
phases off its ends clamped to the ending color
(see 'Colwheel' above).

Complex

Indicates that the statistical data is
complex-valued (use colwheel and heatscale).  To
see F-stats, select heatscale, *un*select
Complex, and select twocond scripts.

Truncphase

Truncate one half of the phases of the response
to zero.  Color-scale-dependent behavior (see
above).

mm, ColBar

Turn the millimeter and color scales on or off.

Bri

Turn on brighter render (more top light, overall
brighter curvature background, reduce light/dark
gray curvature contrast).

Curv

Turn on curvature background (off->uniform gray).

Views

These buttons select which views will have a
bitmap saved for them when SURFACE-STATS is
clicked.  The 'cust' view (custom) is a special
case.  Clicking it will expose an additional 12
fields than can be used to define a custom view
for each hemisphere.  If this is done for the
current scan dir, the next scan dir that is
defined as a "Render Stats Dir" will
automatically start with the current 'cust'
values. The transformations listed are applied
left to right.

3D and Flat Tcl Scripts

These tcl scripts control the startup of the
surfer tools.  These scripts are found in
FreeSurfer/lib/tcl/*.tcl.  For retinotopy, use
eccen, polar, and fs.  For phase analysis of two
condition, use eccen or twocond.  For real-valued
data read in from external programs (e.g.,
correlation coefficients), use real.

To convert (old) fmid to p:

  plot(fmid, -log10(1-fcdf(fmid.^2,sdf,ndf))

where sdf and ndf are signal and noise degrees
of freedom.
#############################################################
------------------------------------------------
 SessionsTools -> Run Batch Process runs
 through each SessionTools panel that is
 currently configured and presses the action
 buttons at the top right to re-perform the
 actions of the panel.
------------------------------------------------
Once an initial analysis of the data has been
performed, it is often necessary to re-run parts
of the analysis.  The Run Batch Process panel
automates this.

On the first pass through the analysis, each
panel is manually configured and action buttons
are pressed to generate data files.

The Batch Process panel is used to redo all or
parts of the analysis.

Examples

1) If motion correction is redone (e.g., using
   a different TR), all actions on all the
   subsequent panels need to be redone.  In this
   case, select all the boxes in the BATCH
   PROCESS panel.

2) If the FUNCT=>STRUCT registration is touched
   up, select Paint Surface, Calculate Surface
   Stats and Run Rendering Panels.

3) To use a different delay in the Fourier panel
   (affect F-stats), select Fourier and all
   following boxes

The Batch Process panel actually opens the
individual panels and presses the button, so you
can see the individual steps that are performed.
To skip a directory, Unset it (the previously
saved configuration will be retrieved if you
re-declare the directory).

The Batch Process Panel Saves Bitmaps

The one difference between running actions using
Batch Process and actually clicking the buttons
is that on the View Functional Data panel, the
bitmaps you have configured (Views: radio buttons
near the bottom of the panel) will actually be
saved into the <session>/image/rgb directory.

Run Each Panel Manually the First Time

It is currently not possible to run Batch process
initially because some files and directories
needed for configuring subsequent actions won't
yet exist the first time through the analysis.

#############################################################
