-------------------------------------------
 tkmedit -- display and edit MRI slice data
-------------------------------------------
The tkmedit program  is started either by the
VOLUME botton on the main csurf panel, by the
VOLUME-STATS button on the SessionTools -> View
Functional Data panel, or from the command line
(see below).

It reads one or more series of images and
displays them in the coronal, sagittal, or
horizontal plane, or in all 3 planes at once
along with a sagittal maximum intensity
projection.  Images must be in one of two
formats:

  (1) COR dir: 256 (or 512) 1-byte 256x256
      (or 512x512) coronal slices images

  (2) 256^3 or 512^3 .mgh/.mgz format

Images in the first (edit) buffer can be edited
and saved (in same format as read).  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 orig/T1 images which have more
content and context, which makes edits easier).

There is a 4-step undo (alt/cmd-z) and a 1-step
redo (alt/cmd-Z).  Alternate image window
shortcuts for undo and redo are ctrl-left-click
and shift-ctrl-left-click).

Up to two surfaces from the same hemisphere can
be read and the intersection of the surfaces with
the current slice displayed in yellow (first) and
green (second).

A real- or complex-valued stats overlay can be
displayed using the same color scales as
tksurfer.

If a scan directory contains rawdata, hand-made
ROIs or MGH 3D segmentation ROIs can be used to
extract raw timecourses for further analysis.

Context-dependent help

Every interface element (button, tick, entry,
bold label title) has a R-click help panel, which
are also all gathered in the csurf -> Help -> All
Help Contents panel.  For any button or tickbox
with multiple hotkey functions (some up to 5),
R-click help also brings up a button bar with
verbosely named buttons to control each alternate
function.

Workaround for MGH tkmedit (which req's pixwidth=0.0)

MGH tkmedit currently requires that the
voxelsize/spacing fields in the *.mgz header
(spacingX,Y,Z, in mm) all be 0.0.  If any are
non-zero (e.g., they will be 0.5 in a hi-res
512^3, 0.5mm^3 voxel data set generated by
brik2cor here), MGH tkmedit will return the
following error:

  MRIresample(): source matrix has zero determinant

As a workaround, verify that the spacing fields
are non-zero, and them reset them to 0.0 with:

  calcimg -spacing <file>.mgz            # read
  calcimg -setspacing 0.0 <file>.mgz   # change

This saves aside the original dataset for safety.

Running tksurfer from a bash/tcsh shell script

N.B.: on MacOS 10.11+, the environment variable
DYLD_LIBRARY_PATH is *not* passed into a shell
script, which will prevent tkmedit from seeing
the csurf X11 tcl/tk libraries.  To use tkmedit
in a MacOS 10.11+ shell script, include the
following line before the first call to tkmedit:

csh/tcsh:
  setenv DYLD_LIBRARY_PATH $CSURF_LIBRARY_PATH

sh/bash:
  export DYLD_LIBRARY_PATH=$CSURF_LIBRARY_PATH

-------------------------------------------
Volume Image Window Clicks
-------------------------------------------

(1) Left-Click: Select point

  On change plane, this click determines which
  other-plane slice will be shown.  For example,
  in CORONAL view, to view a SAGITTAL slice
  through the hippocampus, first click the
  hippocampus in CORONAL view, then click
  SAGITTAL.  This also prints data about this
  point to the log.

(2) Middle-Click: Edit to white

  Used to fill in missing part of the white
  matter -- N.B.: this always edits the main
  buffer even when viewing the second buffer.

(3) Right-Click: Edit to black

  Used to cut away parts of image that aren't
  white matter -- N.B.: this always edits the
  main buffer even when viewing the second
  buffer.

(4) Shift-Left-Click: Edit to targval if im/(im2) in bounds

  If image pix is within bounds (set by two
  entries right of TRUNC), it is edited to the
  target value (set by entry to right of PF).
  Middle clicking lower right "la" tickbox uses
  im2 (instead of the editable image) for the
  bounds test (but edits still go to im).
  Finally, when using im2 bounds, a second set of
  bounds can block the im edit to preserve
  structure.  R-click on TRUNC or the entries to
  make a popup with all the parameters.

(5) Shift-Middle-Click: Print histogram of 3D region

  First set "rad:" to pick the radius of a the
  sampling sphere.  If gnuplot is installed, a
  shift-middle-click on a selected vertex prints
  a very lightly smoothed histogram.

(6) Shift-Right-Click: Dump single voxel timecourse

  If a timecourse overlay has been loaded with
  -rawdata (and -regdat), this will dump clicked
  voxel timecourse to the bottom of the slice
  viewer.  Additional shift-right-clicks in this
  slice overlay additional voxel timecourses.
  Left-click to clear.

(7) Double-Middle-Click: Report pixval

  A pop-up reports the value of the underlay pixel.
  If an MGH segmentation have has been loaded, the
  label name, idnum and rgb values are also reported.

(8) Ctrl-Left-Click: Undo last edit

  Undoes most recent edit (click or click-drag in
  image window).  Cmd-z in image window is
  equivalent.

(9) Ctrl-Right-Double-Click: This help

[no longer needed: use "no double-clk" tickbox on
F4 tkmedit interface ($blockdoubleclickflag)].

-------------------------------------------
 Keyboard shortcuts -- for both image,tk windows
-------------------------------------------
Single key

  # interface size (see also far left "i" button)
  F1 -- basic interface     (Mac=fn-F1)
  F2 -- overlay interface   (Mac=fn-F2)
  F3 -- normalize interface (Mac=fn-F3)
  F4 -- electrode interface (Mac=fn-F4)
  F5 -- thin horiz interface (Mac=fn-F5)

  # move slice
  R/L arrow   -- slice up/down
  up/dn arrow -- slice up/down

  # cursor
  k  -- one-time switch to large cursor
  K  -- toggle cursor visibility
  O  -- toggle open center cursor

  # fmid control
  i  -- fmid down (more permissive)
  I  -- fmid up (less permissive)

  # resize image window (only works in img win)
  1  -- 1 underlay pix -> 1 screen pix
  2  -- 1 underlay pix -> 2x2 screen pix
  3  -- 1 underlay pix -> 3x3 screen pix
  4  -- 1 underlay pix -> 4x4 screen pix

Modifier + key (LinuxMod="Alt", MacMod="Cmd")

  # cursor
  Mod-k  -- one-time switch to lg cursor
  Mod-K  -- toggle cursor visibility
  Mod-O  -- toggle open center cursor

  # edit brush
  Mod-b  -- return to single pix brush
  Mod-B  -- increase brush radius (wraps)
  Mod-l  -- go back to last brush size
  
  # underlay contrast
  Mod-asterisk -- contrast up (times)
  Mod-slash    -- contrast down (divide)

  # underlay brightness
  Mod-plus   -- brightness up
  Mod-minus  -- brigthness down

  # underlay back to default contr/bright
  Mod-equals  -- contr=>12,midpt=>0.35

  # COMPARE button
  Mod-0 [zero] *or* Mod-singlequote

  # SEND/GOTO
  Mod-f  -- SEND (forward) point
  Mod-g  -- GOTO point

  # surface
  Mod-d  -- toggle surface visibility

  # maximum intensity projection
  Mod-p  -- toggle max intens proj

  # stat overlay
  Mod-o  -- toggle stats visibility

  # fmid control
  Mod-i  -- fmid down (more permissive)
  Mod-I  -- fmid up (less permissive)

  # SAVE IMG
  Mod-e  -- save (edit) images
-------------------------------------------


F1 Interface (default)

The default F1 interface is described from upper
left to lower right.

CORONAL/SAGITTAL/HORIZONTAL button/slider/field

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

When switching planes, the new plane will pass
through the current cursor 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.

A non-default middle-click on the CORONAL button
pops up a panel to allow performing one of 48
different possible 3D transposes on the data
(using tcl/C function flip_corview_xyz -- see
below for details).

Display parameters (overlay/surf/contrast/midpnt)

The "overlay" checkbutton toggles display of
functional data over an anatomical slice image.
Overlay data is controlled by fthr/fslope/fmid
fields at the lower middle right (not the
immediately adjacent "contrast" and "midpoint"
fields).  Load an overlay using the VOLUME-STATS
button at the top of the SessionTools -> View
Functional Data panel.  Look in log to see
additional options given to tkmedit.

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

The "contr" and "midpt" fields control the
(editable) underlay.  Higher "contr" increases
the steepness of the sigmoid multiplying the data
before display (default=12.0).  The "midpt" field
sets the mri data number that appears at half-max
brightness, in units of 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 to an image value of 1, not 0), set
contrast and midpoint to:

  contrast = 200
  midpoint = 0.01

FILL/ROI controls

The FILL button does a 3D region-growing fill
down of 4 different kinds of overlay data, in
order of precedence:

  last-clicked 3D annotation region
  stat mask > $sfthresh
  overlay data > $fthresh
  struct data between WMTRUNC limits

If the entry immediately to the right is not 0.0,
the fill will be limited to a maximum spherical
radius (mm).  Also, edits to black (e.g.,
temporary) are respected.

A shift-left-click on the FILL button reports the
volume of the currently filled region.

The "roi" tick toggles visibility (in white) of
the ROI (occludes overlay data) while the "m"
tick toggles using the ROI (where it equals 0) as
a mask for the overlay data.

"SAVE IMGS" button

This button saves edited images (COR files or
.mgh/.mgh file) in the editable buffer back to
the file and format that was read in at tkmedit
startup.

N.B.: SAVE IMGS ignores any change you might have
made to the image name in "im:" field (SAVE IMGS
uses the filename read in at startup -- that is,
it always overwrites the input file).

By contrast, the "W" (write) button on the "im:"
line respects any change made to the filename on
that line, so this can be used for "Save As..."
(the "im:" field is *not* visible in F2/overlay
view, but is visible in F1 and F3/F4 view).

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

  /machine1/usr2/subjects/marty

You can substitute an absolute path if you want
to save the images somewhere else.  Save whenever
you are satified so far.

SEND PNT, 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
for nearest surface point (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.

When "all3views" is selected, an additional
checkbutton, "z", appears which toggles a 2x zoom
of the central portion of each of the 3 images.
This makes subcortical structures (and functional
overlays on them) easier to see.  The zoomed view
cannot be panned.  If "all3" is unclicked, the "z"
button disappears.

3D/surface File Entries

Slightly different interface lines are visible
with different interface sizes.  Also, clicking
val{n,s} and msk{n,s} toggles between the "n"
(native) and "s" (upsampled) entries.

  surf	-- read surface ("cpx" affects overlay)
  im	-- read/write editable 3D images
  roin	-- read and register native ROI
  roiup	-- read/write upsampled ROI, to get timecourse
  valn	-- read and register native res overlay data
  valup	-- read/write upsampled overlay data
  mskn	-- read and register native res mask
  mskup	-- read/write upsampled mask
  rgb	-- write tiff bitmap (or SGI rgb)

The "surf" entry specifies the surface to read
("R").  The intersection of the surface with the
current slice is drawn in yellow.  Ticking the
"2" checkbutton before reading a surface causes a
second surface to be read and displayed in green.
Visibility of surfaces is toggled by the lower
left "surface" checkbutton.

The "im" entry reads and write images to and from
the editable buffer.  Note that the "R" button on
the "im" entry can read another dataset into the
editable buffer, destroying any edits that
haven't been saved (with either SAVE IMGS, or
equivalently with the "W").

The "roi{n,up}" two-state entry (toggle by
clicking the bold label) reads and writes an AFNI
ROI/label file with voxel value of 1 or 64 to
indicate where the filled/connected label is.
Can be either in native/rawdata resolution or
upsampled and registered to the 256^3/1mm^3
underlay resolution.  This can be used to extract
rawdata time courses ("T") or mask overlay data
("m").  If an MGH 3D segmentation has been
loaded, a region idnum can be typed into this
entry to extract timecourses.

The "val{n,up}" two-state entry (toggle by
clicking the bold label) reads and writes real or
complex overlay activations in either
native/rawdata resolution or upsampled and
registered to the 256^3/1mm^3 underlay
resolution.

The "msk{n,up}" two-state entry (toggle by
clicking the bold label) reads native/rawdata or
upsampled and registered stat masks.

The "rgb" entry writes the current view into a
tiff (or an SGI rgb file if the unlabeled
checkbox to the right of the entry is unchecked).

WMTRUNC

This button toggles whether the image is
truncated to zero below the low and high limits
in the entries to the right.  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 visual system is so good at
autonormalization).

TRUNC is typically turned on when using the ramp
or spherical correction utilities of the extended
interface (F3).  These allows piecewise linear
test correction ramps or variable radius
spherical field corrections to be applied to the
image in the second buffer.  Generally, it is
good to check if the rough segmentation is
improved before applying the corrections to the
entire data set (see below).

The two entries also have an overloaded use to
set bounds and pixel value targets for pixel
range-dependent editing (shift-right-click in
image window - see R-click help for the two TRUNC
entries).

PF, PFGAU (anisotropic plane filters)

The PF and the PFGAU apply truncating or
anisotropic Gaussian 'wormhole' filters to the
image in the editable buffer.  The output is
either saved into the second bufer for
comparison, or into the editable buffer for
saving.  See the R-click help for the PF and
PFGAU buttons for more details.

The entries also has an overloaded use to set the
target value for pixel range-dependent editing
(shift-right-click in image window - see R-click
help for the PF entry).

Second Comparison Image Set (im2:)

By clicking the adjoining "R", the dataset
specified in "im2" is read into the second
(non-editable) buffer.  Successive "R's" simply
replace the dataset in the non-editable buffer.
The field expects a COR directory or .mgz file
that is relative to:

  $SUBJECTS_DIR/$subject/mri

You can also put an absolute (or tilde
abbreviated) path to a COR directory or an
.mgz file into this field.

Finally, an 3D MGH segmentation file (byte or
int) can be read using the same dropdown and "R"
button.  In this case, it will be used to
construct a transparent overly for the main
(editable) buffer using the idnum->colors map
found in:

  $CSURF_DIR/lib/lut/FreeSurferColorLut.txt

The label ransparency can be adjusted using the
"tran:" entry on the large F4 tkmedit interface.
(the "no double-clk" tick immediately below
disables double click pop-ups for fast editing).

Generalized Transpose of 3D Image Data

A general flipping operator (the C/tcl function
flip_corview_xyz) is accessible from a pop-up
after a middle-click on the CORONAL button.  This
allows you to rearrange the axes of a data set,
starting from whatever 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.

Not that there are 48 different 3D transposes for
viewing a 3D data set: 6 cube face views x 4
rotations of each face x 2 mirror-images (so it
is easy to get lost).

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 now invisible first editable buffer.

Alternate clicks allow swapping the contents of
the editable and im2 buffers (C/tcl function,
swap_imim2), and copying im2 edits to the
editable buffer (C/tcl funct, im2wmedits_to_im).


F2 Interface (add overlay display)

You can toggle between different interface sizes
using either F1 to F5 (add "fn" key on Mac), or
from a small pop-up available from the far left
"i" button.

Use F2 (Mac: fn-F2) in the tkmedit panel to add a
small overlay control panel to the right.  The F2
panel is automatically displayed if an overlay has
been loaded from csurf.  Use F1 to get back to the
default panel.

The "fthresh", "fslope", and "fmid" fields (on
the main panel) have the same effect as the
fthresh, fslope, and fmid fields on the tksurfer
panel.  See the R-click help for the tickbox
immediately left of "mskn:", which enables
masking of the overlay by a stat file (this
doubles each of the entries above).

The SMOOTHSTATS button performs a convolution
with a 3D Gaussian with settable kernel width
(unlabeled left field) and FWHM in mm.  If
"overlay" is unclicked, the SMOOTHSTATS button
changes to SMOOTHSTRUCT so that 3D smoothing can
be applied to the structural data.

Next are radio buttons for 6 different color
scales.  The first three are for complex-valued
stats: w1=Wheel1, h=Heat, and b=BiRedGreen.  The
last three are for real valued stats:
BR=BlueRedWhite, BRy=BlueRedCyanYellow, and
lt=LookUpTable.  The next line of widgets allows
editing, reading, and writing color look up
tables (suffix: .lut).

Complex-valued data are controlled with the same
truncate, reverse, angle cycles and offset, and
ipsilateral fade/yellow controls as in tksurfer.

Run Tcl Script

At the bottom right is an entry to edit (click
ED) and run (click GO) a tcl tkmedit tcl script,
such as phasemovie.tcl or mri2mpg.tcl.  Use a "#"
as an abbreviation for the standard tcl scripts
directory (or an absolute path like /tmp/zz.tcl).

Logging Interface Actions as Tcl Commands

Clicking the "tcl:" label near bottom right of
the tkmedit interface turns on the logging of
all interface actions as tcl commands to the
file, tkmedit.log, in:

  $FUNCTIONALS_DIR/<session>/image/scripts

These can be used to record actions to make a
command line tcl script to automate tkmedit
actions.  The "tcl:" label turns bold during 
logging.  To finish logging, click the label
again.  Or you can startup tkmedit from csurf
with the log already on by selecting:

  Preferences -> Log tkmedit actions as tcl cmds

Note that in both cases, any previous log of tcl
commands in tkmedit.log in this session's script 
dir is overwritten so each log starts fresh.


F3 Interface (rm overlay, add hand normalize)

Clicking F3 (Mac: fn-F3) in the medit panel
expands it (F1 goes back to the default view or
F2 back to the default plus overlay 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.


F4 Interface (add SURFPAINT, electrode align)

This panel contains controls for interactive
electrode positioning (less well supported), and
display of curvature, fieldsign, and annotation
files along the cortical ribbon of a slice.


F5 Interface (long thin minimal horizontal)

This long thin panel is designed to take up as
little screen space as possible while editing a
complex surface (e.g., cerebellum) where a large
surface view as well as a large slice view is
required.

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

Use: [edit MRI, optional img2/surf/stats]

 tkmedit subj COR/mgz [surfname] [-tcl script] [opts..]
 tkmedit CORdir/mgzfile
 tkmedit -help,-h   => more verbose help

   subjname:  subject name     (in $SUBJECTS_DIR)
   CORdir:    orig, T1, ...    (in $subject/mri)
      *or*
   mgzfile:   orig.mgz, T1.mgz, ...
   surfname:  ?h.smoothwm, ?h.inflated, ...

   {256,512}^3 byte-img or .mgz/.mgh byte/short/int/float
   overlay activations upsampled to {256,512}^3

 Examples:

   [display SUBJECTS_DIR CORdir volume, from any dir]
   tkmedit martys09 orig

   [display SUBJECTS_DIR .mgz volume, from any dir]
   tkmedit martys09 orig.mgz

   [display local .mgz volume]
   cd $SUBJECTS_DIR/martys09/mri
   tkmedit orig.mgz

   [read/reg/upsamp/overlay native res complex stats]
   cd /usr0/sessions/120101MS/image/scripts
   tkmedit martys09 orig rh.orig \
     -scandir ecc1 \
     -real pol1-vreg+orig_r+orig.BRIK \
     -imag pol1-vreg+orig_i+orig.BRIK \
     -regdat register.dat \
     -rawdata ecc1-vreg+orig.BRIK \
     -colscale 0 \
     -angle_cycles 1.0  \
     -angle_offset 0.75  \
     -fslope 1.5 \
     -fmid 1.1

Type "tkmedit -h" to get a verbose list of
options, tcl commands, and more examples.

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 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 on the command
line.  If you include an "exit" at the end of the
tcl script, tksurfer will quit when the script
finishes.  You can find commands available from
inside the tcl interpreter using "help" or "info"
(info accepts wildcards):

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

As noted above, you can record the tcl commands
for all interface actions by clicking the "tcl:"
label at the lower right.
