------------------------------------------------
 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));
}

