import math
import os
import glob, re

plot = []
plotSeparate = False
plotType='dpdx'
show_plot = True
var='press'
var='vel'
resultFolder  = 'prod'
stringToFind  = 'ref1'
stringToFind2 = ''       
stringToFind3 = ''
minlevel=0
maxlevel=10

plotError=False
if plotType == 'error': 
  plotError=True
  files = ['*_Errdpdx*.res' ]
  ind=1
  figname='channel_dpdx_error_'+stringToFind
  tempfile=stringToFind
  if stringToFind2 != '':
    figname=figname+'_'+stringToFind2
    tempfile=tempfile+'_'+stringToFind2
  tempfile=tempfile+'_err.res'
  tFile=open( tempfile,'w')
  # Strings enclosing the level
  strBefore='level'
  strAfter ='ref'
elif plotType == 'dpdx':
  files = ['*_probePr*.res' ]
  ind=2
  figname='channel_probePress'
elif plotType == 'press':
  files = ['*_dpdx*.res' ]
  ind=4
  figname='channel_dpdx'
else:
  print 'unknown plot type chosen. Abort'
  stop


folders = []
# Set up the list of simulation folders in the results directory
for dirname, dirnames, filenames in os.walk(resultFolder):
  isSimDir = False
  # if I find tracking as subdirectory, mark as a simulation directory
  if 'tracking' in dirnames:
    if ( stringToFind in dirname ) and ( stringToFind2 in dirname ) and ( stringToFind3 in dirname ):
        print 'dirnames', dirname
        isSimDir = True
  # if it was marked as a simulation directory, append it to the folder list
  if isSimDir:
    includeInAnalysis = False
    level = re.search(r"(?<=level)[0-9]*?(?=ref)", dirname).group(0)
    if int(level) >= minlevel and int(level) <= maxlevel:
      print 'level is', level
      folders.append(dirname)
      includeInAnalysis = True
    if plotError and includeInAnalysis:
      # If error has to be extracted, copy last line of file to temporary file
      # get the explicit file from the wildcard form
      filelist=glob.glob(dirname+'/tracking/'+files[0])
      # Run over all the files in the list (should be just one)
      # Extract the level from the dirname: what is between level and refine
      for filename in filelist:
        level = re.search(r"(?<=level)[0-9]*?(?=ref)", filename).group(0)
        print 'cur filename', filename, 'found level', level
        with open(filename) as myfile:
          string=(list(myfile)[-1])
          print 'writing string to file'+level+'. '+string
          tFile.write(level+'.   '+string)
    print 'Found simulation folders:'
    print folders

if plotError:
  tFile.close()
  ylogscale=True
  startPlt=True
  endPlt=True
  print 'Plotting temporarily generated error file'
  ## xy plot 
  plot.append(dict(kind = 'xy',
              data=[tempfile], format='eps', ylogscale=True,
              figname=figname, ls='-', legend_loc=9,
              row=[1,-1],col=[1,3], startplot = startPlt, endplot = endPlt,
              label  = 'dpdx error' ))
else:
  # directory loop
  for iFolder in range(len(folders)):
    if plotSeparate:
      startPlt=True
      endPlt=True
    else:
      if iFolder == 0:
        startPlt = True
      else:
        startPlt = False
      if iFolder == len(folders)-1:
        endPlt = True
      else:
        endPlt = False
    level = re.search(r"(?<=level)[0-9]*?(?=ref)", folders[iFolder]).group(0)
    #intp  = re.search(r"(?<=intp)[a-z]*?(?=scl)", folders[iFolder]).group(0)
    #print 'intp', intp

    label = str(folders[iFolder]) #'level '+str(level)+ ' '
    label = label.replace( '/', '-')
    label = label.replace( '.', '-')
    label = label.replace( '_', '-')
    print 'label for current plot', label
    print 'acting on folder', folders[iFolder], files[0]
    ## xy plot 
    plot.append(dict(kind = 'xy',
                data=[folders[iFolder]+'/tracking/'+files[0]], format='eps',
                figname=figname, ls='-', legend_loc=1,
                row=[1,-1],col=[1,ind], startplot = startPlt, endplot = endPlt,
                xlabel = 'channel length', ylabel = 'Pressure',
                label  =  label ))
#    if iFolder == len(folders)-1:
#      startPlt = False
#      plot.append(dict(kind = 'xy',
#                  data=[folders[iFolder]+'/tracking/'+files[0]], format='eps',
#                  figname=figname, ls='-', legend_loc=1,
#                  row=[1,-1],col=[1,ind+1], startplot = startPlt, endplot = endPlt,
#                  xlabel = 'channel length', ylabel = 'Pressure',
#                  label  = 'ref'))



