#!/bin/tcsh -fe

set stat = 1
goto PARSE
RET_PARSE:

tail -n +3 $f > /tmp/FSFILE.1D
set nv = `3dnvals -all /tmp/FSFILE.1D`
set nv = $nv[1]

count -column -digits 1 $v $v R$nv > /tmp/lbl.1D

MAKE_ROI_FILE:
1dcat /tmp/FSFILE.1D'[0]' /tmp/lbl.1D > $f:r.1D.roi

MAKE_DSET: 
ROI2dataset -overwrite -prefix $f:r -of niml -input $f:r.1D.roi

CLEANUP:
   if ($cleanup) then
      \rm -f /tmp/lbl.1D /tmp/FSFILE.1D
   endif
   
goto END

PARSE:
   set f = ''
   set l = 'Unlabeled'
   set v = 1
   set cnt = 1
   set cleanup = 1;		
   set Narg = $#argv
   
   if ("$1" == '' || "$1" == '-h' || "$1" == '-help' || "$2" == '') then
	   goto HELP
   endif

   while ($cnt <= $Narg)
		set donext = 1;
      if ($donext && "$argv[$cnt]" == "-help") then
         goto HELP
      endif
      
      if ($donext && "$argv[$cnt]" == "-prefix") then
         set pLoc = $cnt		
		   if ($pLoc == $Narg) then
				echo "Need a string after -prefix"
            goto END
			else
            @ cnt ++
            set prefix = $argv[$cnt]
            set donext = 0	
         endif	
      endif
      
      if ($donext && "$argv[$cnt]" == "-fs") then
         set pLoc = $cnt		
		   if ($pLoc == $Narg) then
				echo "Need a string after -fs"
            goto END
			else
            @ cnt ++
            set f = $argv[$cnt]
            set donext = 0	
         endif	
      endif

      if ($donext && "$argv[$cnt]" == "-val") then
         set pLoc = $cnt		
		   if ($pLoc == $Narg) then
				echo "Need an integer after -val"
            goto END
			else
            @ cnt ++
            set v = `printf %d $argv[$cnt]`
            set donext = 0	
         endif	
      endif
      
      if ($donext && "$argv[$cnt]" == "-keep_tmp") then
         set cleanup = 0;		
         set donext = 0		
      endif

      if ($donext && "$argv[$cnt]" == "-echo") then
         set echo		
         set donext = 0		
      endif
     
      #ADD NO NEW OPTIONS BELOW THIS LINE
      
      if ($donext == 1) then
         echo "Error: Option or parameter '$argv[$cnt]' not understood"
         goto END
      endif
      
		@ cnt ++
	end
   

   goto RET_PARSE

HELP:
   echo "`basename $0` A script to take a FreeSurfer ascii label file and "
   echo "              turn it to a SUMA dataset and a SUMA ROI"
   echo ""
   echo "Options:"
   echo "   -fs FS_LABEL_FILE: Specify the ascii label file from FreeSurfer"
   echo "   -val VAL: Assign integer VAL to the nodes in FS_LABEL_FILE"
   echo "             Default is 1"
   echo "   -help: This message"
   echo "   -echo: Turn echo for debugging"
   echo "   -keep_tmp: Don't cleanup temp files"
   echo ""
   echo "Example:"
   echo "   `basename $0` -fs lh.FSFILE"
   echo ""
   
   goto END
BEND:
   set stat = 1
   goto END
   
END:
   exit $stat
