#! /bin/csh -f

### marty sereno: mri2jpgs (v04)
# Mar2015: -no_detach: avoid async bg proc

set jpgdir = zzJPG
set tmpafni = TmpAfniCommand.$$
if ($#argv != 2) then
  echo ""
  echo "use: mri2jpgs <stem>+orig.BRIK <sliceplane>"
  echo ""
  echo " converts one structural scan in AFNI BRIK format to a set of jpgs"
  echo " pick sliceplane with cor, sag, axi, or all3"
  echo ""
  echo " (1) convert scan to AFNI BRIK"
  echo " (2) cd into zzAFNI subdirectory (or wherever a BRIK is)"
  echo " (3) run mri2jpgs -> jpgs to $jpgdir/<scan#>/<plane>/*.jpg (in currdir)"
  echo ""
  exit
endif
onintr cleanup

### check
set inbrik = $argv[1]
set planearg = $argv[2]
if ($planearg != "cor" && $planearg != "sag" && $planearg != "axi" && \
    $planearg != "all3") then
  echo "mri2jpgs: ### sliceplane must be one of: cor, sag, axi, or all3"
  exit
endif
set planelist = "$planearg"
if ($planearg == "all3") set planelist = "cor sag axi"
if (! -e $inbrik) then
  echo "mri2jpgs: ### infile $inbrik not found"
  exit
endif
if ($inbrik !~ *+orig.BRIK && $inbrik !~ *+tlrc.BRIK) then
  echo "mri2jpgs: ### input file must end in +orig.BRIK or +tlrc.BRIK"
  exit
endif
set foundspgr = `3dinfo $inbrik | grep -i -c spgr`
if (! $foundspgr) then
  echo ""
  echo "mri2jpgs: ### $inbrik doesn't look like a struct scan  ...go anyway?"
  echo "(y|N <ret>)"
  set resp = $<
  if ($resp != "y" && $resp != "Y" && $resp != "yes") then
    echo "  ...quitting"
    exit
  endif
endif
if ($inbrik =~ *+orig.BRIK) set stem = `basename $inbrik +orig.BRIK`
if ($inbrik =~ *+tlrc.BRIK) set stem = `basename $inbrik +tlrc.BRIK`

### go
foreach plane ($planelist)
  set jpgdir2 = $jpgdir/$stem/$plane
  if (-e $jpgdir2) echo "mri2jpgs: dir: $jpgdir2 already exists  ...using it"
  if ($plane == "cor") set imagetype = coronalimage
  if ($plane == "sag") set imagetype = sagittalimage
  if ($plane == "axi") set imagetype = axialimage
  cat << EOF > $tmpafni
  afni -no_detach \
    -com 'SET_XHAIRS OFF'                 \
    -com 'SET_ANATOMY $stem'              \
    -com 'OPEN_WINDOW $imagetype'         \
    -com 'SAVE_ALLJPEG $imagetype $plane' \
    -com 'QUIT'
EOF
  csh $tmpafni
  # move into subdir
  if (! -e $jpgdir2) mkdir -p $jpgdir2
  mv $plane.*.jpg $jpgdir2
end

### cleanup
cleanup:
if (-e $tmpafni) rm $tmpafni

