#!/usr/bin/python
# $Id: aparcstats2table,v 1.6 2007/08/10 23:58:35 nicks Exp $
import sys;
import os;
import string;
import tempfile;

# -------------------------------------------------------------------
# Everything between BGINHELP and EDHELP will be printed when the
# program is called with --help.
#

# BEGINHELP

# Converts a cortical stats file created by recon-all and or
# mris_anatomical_stats (eg, ?h.aparc.stats) into a table in which
# each line is a subject and each column is a parcellation. By
# default, the values are the area of the parcellation in mm2. The
# first row is a list of the parcellation names. The first column is
# the subject name.

# The subjedts list can be specified on either of two ways:
#   1. Specify each subject with --s:
#             --s subject1 --s subject2 ...
#   2. Specify all subjects after --subjects. --subjects does not have
#      to be the last argument. Eg:

#             --subject subject1 subject2 ... --hemi lh

# By default, it looks for the ?h.aparc.stats file based on the
# Killiany/Desikan parcellation atlas. This can be changed with
# '--parc parcellation' where parcellation is the parcellation to
# use. An alternative is aparc.a2005s which was developed by
# Christophe Destrieux.

# By default, the area (mm2) of each parcellation is reported. This can
# be changed with '--meas measure', where measure can be area, volume
# (ie, volume of gray matter), thickness, or meancurv.

# Example:
#  aparcstats2table --hemi lh --subjects 004 008 --parc aparc.a2005s \
#     --meas meancurv --t lh.a2005s.meancurv.txt

# lh.a2005s.meancurv.txt will have 3 rows: (1) 'header' with the name
# of each structure, (2) mean curvature for each structure for subject
# 004, (3) mean curvature for each structure for subject 008.

# ENDHELP
# -------------------------------------------------------------------

#---------------------------------------------------------
def print_usage():
  print "USAGE: aparcstats2table";
  print "  --subjects  subject1 <subject2 ...>";
  print "  --s subject1 <--s subject2 ...>";
  print "  --h hemi : lh or rh";
  print "  --parc parcellation : default is aparc (alt aparc.a2005s)";
  print "  --meas measure : default is area (alt volume, thickness, meancurv)";
  print "  ";
  print "  --t tablefile : output file";
  print "  ";
  print "  --help : help";
  print "  --debug ";
  return 0;
#end def print_usage:

#---------------------------------------------------------
def print_help():
  global ProgName;
  printon = 0;
  fp = open(ProgName,'r');
  for line in fp:
    if(printon):
      ind = line.rfind('ENDHELP');
      if(ind == -1):
        sys.stdout.write("%s" % line.replace('# ','',1));
      else:
        sys.exit(1);
      #endif
    else:
      ind = line.rfind('BEGINHELP');
      if(ind != -1):
        printon = 1;
      #endif
    #endif
  #end # while
  return 0;
#end def print_help:

#---------------------------------------------------------
def argnerr(narg,flag):
  print "ERROR: flag %s requires %d arguments" % (flag,narg);
  sys.exit(1);
#end def parse_args(argv)

#---------------------------------------------------------
def parse_args(argv):
  global Version,debug;
  global tablefile, SUBJECTS, nsubjects, hemi, parc, meas;

  del argv[0]; # get past program name (del is like shift)

  while(len(argv) != 0):
    flag = argv[0];
    del argv[0];
    if(debug): print "flag = %s" % flag;

    if(flag == "--s"):
      if(len(argv) < 1): argnerr(1,flag);
      SUBJECTS.insert(nsubjects,argv[0]);del argv[0];
      nsubjects = nsubjects + 1;
    elif(flag == "--subjects"):
      if(len(argv) < 1): argnerr(1,flag);
      while(not isflag(argv[0])):
        SUBJECTS.insert(nsubjects,argv[0]); 
        nsubjects = nsubjects + 1;
        del argv[0];
        if(len(argv) < 1): break;
      #endwhile
    elif(flag == "--t"):
      if(len(argv) < 1): argnerr(1,flag);
      tablefile = argv[0];  del argv[0];
    elif(flag == "--parc"):
      if(len(argv) < 1): argnerr(1,flag);
      parc = argv[0];  del argv[0];
    elif(flag == "--meas"):
      if(len(argv) < 1): argnerr(1,flag);
      meas = argv[0];  del argv[0];
    elif(flag == "--h" or flag == "--hemi"):
      if(len(argv) < 1): argnerr(1,flag);
      hemi = argv[0];  del argv[0];
    elif(flag == "--help"):
      print_usage();
      print "\n%s" % (Version);
      print_help();
      sys.exit(1);
    elif(flag == "--version"):
      print "%s" % (Version)
      sys.exit(1);
    elif(flag == "--debug"):
      debug = 1;
    else:
      print "ERROR: flag %s not recognized" % flag; 
      sys.exit(1);
    #endif
  #endwhile
  return 0;

#end def parse_args(argv)

#--------------------------------------------------
def isflag(arg):
  if(arg[0] == '-' and arg[1] == '-'):
    return 1;
  #end
  return 0;
#end def isflag(arg):


#---------------------------------------------------------
def check_args():
  global tablefile, SUBJECTS, hemi;

  if(len(tablefile) == 0):
    print "ERROR: no tablefile specified";
    sys.exit(1);
  #endif    
  if(len(hemi) == 0):
    print "ERROR: no hemi specified";
    sys.exit(1);
  #endif    
  if(hemi != 'lh' and hemi != 'rh'):
    print "ERROR: hemi = %s, must be lh or rh" % (hemi);
    sys.exit(1);
  #endif    
  if(meas != 'area' and meas != 'volume' and meas != 'thickness' and \
     meas != 'meancurv'):
    print "ERROR: meas = %s, must be area, volume, thickness, or meancurv" % (meas);
    sys.exit(1);
  #endif    
  if(len(SUBJECTS) == 0):
    # Does not work to look in env
    if(os.environ.get('SUBJECTS',0) == 0):
      print "ERROR: SUBJECTS not spec on cmd line and not in env";
      sys.exit(1);
    #endif  
    SUBJECTS = os.environ['SUBJECTS'];
  #endif    
  print "There are %d subjects" %(len(SUBJECTS));
  if(debug): print "%s" % (SUBJECTS);
  return 0;
#end check_args()

#-----------------------------------------------------------
# ----- main -----------------------------------------------
#-----------------------------------------------------------

ProgName = sys.argv[0];
Version = '$Id: aparcstats2table,v 1.6 2007/08/10 23:58:35 nicks Exp $';
tablefile = ();
parc = 'aparc';
hemi = [];
meas = 'area';
debug = 0;

SUBJECTS  = [];
nsubjects = 0;

nargs = len(sys.argv) - 1;
if(nargs == 0):
  print_usage();
  sys.exit(0);
#end
parse_args(sys.argv);
check_args();

print "tablefile  is %s" % (tablefile);

# Get SUBJECTSD_DIR 
if(os.environ.get('SUBJECTS_DIR',0) == 0):
  print "ERROR: SUBJECTS_DIR not defined";
  sys.exit(1);
#endif  
SUBJECTS_DIR = os.environ['SUBJECTS_DIR'];

fptbl = open(tablefile,'w');
# How to check whether this failed or not?

# Loop thru each subjects
nthsubj = 1;
for subject in SUBJECTS:

  statsfile = SUBJECTS_DIR + '/' + subject + '/stats/' + hemi + '.' + parc + '.stats';
  if(not os.path.exists(statsfile)):
    sys.stdout.write('ERROR: cannot find %s' % (statsfile) );
    sys.exit(1);
  #endif
  if(debug): print "%s" % (statsfile);

  # print first line as list of anat structures 
  if(nthsubj == 1):
    # First Co, First Row is hemi 
    fptbl.write('%s.%s.%s ' % (hemi,parc,meas));
    fp = open(statsfile,'r');
    parcid = [];
    for line in fp:
      ind = line.rfind('#');
      if(ind != -1):
        continue;
      else:
        tmp = string.split(line);
        parcid = tmp[0];
        fptbl.write('%s_%s_%s ' % (hemi,parcid,meas) );
      #endif
    #end # line
    fp.close();
    fptbl.write('\n');
  #endif

  # Now go thru each line and print the measure
  fptbl.write('%s' % (subject) );
  fp = open(statsfile,'r');
  nthparc = 0;
  parcid = [];
  for line in fp:
    ind = line.rfind('#');
    if(ind != -1):
      continue;
    else:
      if(debug): print "%s" % line;
      tmp = string.split(line);
      if(meas == 'area'):      val = string.atof(tmp[2]);
      if(meas == 'volume'):    val = string.atof(tmp[3]);
      if(meas == 'thickness'): val = string.atof(tmp[4]);
      if(meas == 'meancurv'):  val = string.atof(tmp[6]);
      if(debug): print "%d %s %g %g" % (nthparc,parcid,val)
      fptbl.write(' %g' % (val) );
      nthparc = nthparc + 1;
    #endif
  #end  for line
  fp.close();
  fptbl.write('\n');
  nthsubj = nthsubj + 1;
#end  for subject

fptbl.close();

sys.stdout.write('aparcstat2table done\n');

sys.exit(0);
#-------------------------------------------------#







