#!/usr/bin/python

import os,re,sys,math,string,numpy,postprocessingMath
from optparse import OptionParser, Option

# -----------------------------
class extendableOption(Option):
# -----------------------------
# used for definition of new option parser action 'extend', which enables to take multiple option arguments
# taken from online tutorial http://docs.python.org/library/optparse.html
  
  ACTIONS = Option.ACTIONS + ("extend",)
  STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
  TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
  ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)

  def take_action(self, action, dest, opt, value, values, parser):
    if action == "extend":
      lvalue = value.split(",")
      values.ensure_value(dest, []).extend(lvalue)
    else:
      Option.take_action(self, action, dest, opt, value, values, parser)

def location(idx,res):

  return ( idx  % res[0], \
          (idx // res[0]) % res[1], \
          (idx // res[0] // res[1]) % res[2] )

def index(location,res):

  return ( location[0] % res[0]                    + \
          (location[1] % res[1]) * res[0]          + \
          (location[2] % res[2]) * res[0] * res[1]   )        
# --------------------------------------------------------------------
#                                MAIN
# --------------------------------------------------------------------

parser = OptionParser(option_class=extendableOption, usage='%prog options [file[s]]', description = """
Add column containing debug information
Operates on periodic ordered three-dimensional data sets.

""" + string.replace('$Id:  $','\n','\\n')
)


parser.add_option('--no-shape','-s',    dest='shape', action='store_false', \
                                        help='calcuate mismatch of shape [%default]')
parser.add_option('--no-volume','-v',   dest='volume', action='store_false', \
                                        help='calculate mismatch of volume [%default]')
parser.add_option('-d','--dimension',   dest='dim', type='float', nargs=3, \
                                        help='physical dimension of data set in x (fast) y z (slow) [%default]')
parser.add_option('-r','--resolution',  dest='res', type='int', nargs=3, \
                                        help='resolution of data set in x (fast) y z (slow)')

parser.set_defaults(volume = True)
parser.set_defaults(shape = True)

(options,filenames) = parser.parse_args()

if not options.res or len(options.res) < 3:
  parser.error('improper resolution specification...')
if not options.dim or len(options.dim) < 3:
  parser.error('improper resolution specification...')
  
datainfo = {                                                               # list of requested labels per datatype
             'tensor':     {'len':9,
                            'label':[]},
           }
           
datainfo['tensor']['label'] += 'f'
# ------------------------------------------ setup file handles ---------------------------------------  

files = []
if filenames == []:
  files.append({'name':'STDIN', 'handle':sys.stdin})
else:
  for name in filenames:
    if os.path.exists(name):
      files.append({'name':name, 'handle':open(name)})

# ------------------------------------------ loop over input files ---------------------------------------  

for file in files:
  print file['name']

  content = file['handle'].readlines()
  file['handle'].close()
  
  #  get labels by either read the first row, or - if keyword header is present - the last line of the header

  headerlines = 1
  m = re.search('(\d+)\s*head', content[0].lower())
  if m:
    headerlines = int(m.group(1))
  passOn  = content[1:headerlines]
  headers = content[headerlines].split()
  data    = content[headerlines+1:]
    
  regexp = re.compile('1_\d+_')
  for i,l in enumerate(headers):
    if regexp.match(l):
      headers[i] = l[2:]

  active = {}
  column = {}
  values = {}
  head = []
  for datatype,info in datainfo.items():
    for label in info['label']:
      key = {True :'1_%s',
             False:'%s'   }[info['len']>1]%label
      if key not in headers:
        print 'column %s not found...'%key
      else:
        if datatype not in active: active[datatype] = []
        if datatype not in column: column[datatype] = {}
        active[datatype].append(label)
        column[datatype][label]=headers.index(key)

  defgrad = numpy.array([0.0 for i in range(9*options.res[0]*options.res[1]*options.res[2])]).\
                                            reshape((options.res[0],options.res[1],options.res[2],3,3))

  if options.shape: head += ['shape_mismatch']
  if options.volume: head += ['volume_mismatch']
        
# ------------------------------------------ assemble header ---------------------------------------  

  output = '%i\theader'%(headerlines+1) + '\n' + \
           ''.join(passOn)                 + \
           string.replace('$Id: $','\n','\\n')+ '\t' + \
           ' '.join(sys.argv[1:]) + '\n' + \
           '\t'.join(headers + head) + '\n'                              # build extended header

# ------------------------------------------ read value field ---------------------------------------  

  idx = 0
  for line in data:
    items = line.split()[:len(headers)]
    if len(items) < len(headers):
      continue
    for datatype,labels in active.items():
      for label in labels:
        defgrad[location(idx,options.res)[0]][location(idx,options.res)[1]][location(idx,options.res)[2]]\
            = numpy.reshape(items[column[datatype][label]:column[datatype][label]+9],(3,3))
    idx += 1
  defgrad_av = postprocessingMath.tensor_avg(options.res[0],options.res[1],options.res[2],defgrad)
  centroids = postprocessingMath.deformed_fft(options.res[0],options.res[1],options.res[2],options.dim,defgrad,defgrad_av,1.0)
  nodes = postprocessingMath.mesh(options.res[0],options.res[1],options.res[2],options.dim,defgrad_av,centroids)
# ------------------------------------------ read file --------------------------------------- 
  if options.shape:
    shape_mismatch = postprocessingMath.shape_compare(options.res[0],options.res[1],options.res[2],options.dim,nodes,centroids,defgrad)
  if options.volume:
    volume_mismatch = postprocessingMath.volume_compare(options.res[0],options.res[1],options.res[2],options.dim,nodes,defgrad)
  idx = 0
  for line in data:
    items = line.split()[:len(headers)]
    if len(items) < len(headers):
      continue
    
    output += '\t'.join(items)
       
    for datatype,labels in active.items():
      if options.shape:
        output += '\t%f'%shape_mismatch[location(idx,options.res)[0]][location(idx,options.res)[1]][location(idx,options.res)[2]]
      if options.volume:
        output += '\t%f'%volume_mismatch[location(idx,options.res)[0]][location(idx,options.res)[1]][location(idx,options.res)[2]]
      output += '\n'
      idx += 1
# ------------------------------------------ output result ---------------------------------------  

  if file['name'] == 'STDIN':
    print output
  else:
    file['handle'] = open(file['name']+'_tmp','w')
    try:
      file['handle'].write(output)
      file['handle'].close()
      os.rename(file['name']+'_tmp',file['name'])
    except:
      print 'error during writing',file['name']+'_tmp'