#!/usr/bin/env python

#
# agr2gpt: (xm)grace to gnuplot or pylab translator
# Usage: ./agr2ppt -f grace_file.agr (-pl)
#
# By Julen Larrucea
# http://www.larrucea.eu
#  


import os, sys, argparse

version="0.1"

cwd=os.getcwd()+"/"

parser = argparse.ArgumentParser(description="""%s [options]\n\n Convert .agr (grace) files into gnuplot or pylab \n """)
parser.add_argument('-f','--file_name', help="Name of grace file", required=True)
parser.add_argument('-pl','--pylab', help="Plot using pylab (Mathplotlib)", required=False)
args = vars(parser.parse_args())
inpfile= args['file_name']


if "/" not in inpfile:
 inpfile=cwd+inpfile
print "Input file: "+inpfile

parse_xy="off"
all_data=[]
line_titles=[]
# Parse data from xmgrace file
for line in open(inpfile,"r"):
 # Plotting options
 if '    yaxis  label "' in line:
  ylab=line.rstrip('\n').split()[3:]
  ylab=" ".join(ylab).strip('"')
 if '    xaxis  label "' in line:
  xlab=line.rstrip('\n').split()[3:]
  xlab=" ".join(xlab).strip('"')
 if len(line.split()) > 2 and line.split()[2] == "legend":
  tmp_ti=line.rstrip('\n').split()[3:]
  line_titles.append(" ".join(tmp_ti).strip('"'))
 if len(line.split()) > 4 and line.split()[1]=="world":
  x1,x2,y1,y2=line.split()[2].strip(","),line.split()[4].strip(","),line.split()[3].strip(","),line.split()[5].strip(",")
  print "max x: "+x1+", min x: "+x2
  print "max y: "+y1+", min y: "+y2

 # Get the points for each line
 if parse_xy=="on" and "&" in line:
  parse_xy="off"
  all_data.append(line_data)
 if parse_xy=="on":
  line_data.append([float(line.split()[0]),float(line.split()[1])])
 if "@type xy" in line:
  parse_xy="on"
  line_data=[]

#for i in all_data:
print "ylab: ",ylab
print "xlab: ",xlab
print "line_titles: ",line_titles


# drop raw data to enumerated files
outfiles=[]
for i in range(len(all_data)): #curve
 outdrop=open(inpfile+"."+str(i)+".dat","w")
 outfiles.append(inpfile+"."+str(i)+".dat")
 for j in range(len(all_data[i])): #data pair
  for k in range(len(all_data[i][j])): #data value
   print>>outdrop, all_data[i][j][k],
  print>>outdrop, ""
 outdrop.close()

# create the gnuplot input
outgnu=open(inpfile+".gnuplot","w")
print>>outgnu, "set ylab '", ylab,"'"
print>>outgnu, "set xlab'", xlab,"'"
plotstr="p ["+x1+":"+x2+"] ["+y1+":"+y2+"] "
for i in range(len(outfiles)):
 plotstr=plotstr+" '"+outfiles[i]+"'  u 1:2 title '"+line_titles[i]+"' w l,"
print>>outgnu, plotstr.rstrip(",")
outgnu.close()
# now, you can just run: gnuplot -persist filename.gnuplot


if args['file_name']:
  try:
   from pylab import *
   print "pylab imported"
  except:
   print " ### ERROR: pylab not found. "
   sys.exit() 

if args['pylab']:
  for i in range(len(all_data)):
   plot(zip(*all_data[i])[0],zip(*all_data[i])[1],linewidth=1.0,label=line_titles[i])
  plt.xlabel(xlab)
  plt.ylabel(ylab)
  legend = legend(loc='upper center', shadow=True)
  plt.axis([float(x1),float(x2),float(y1),float(y2)])
  plt.grid(True)
  plt.rcParams.update({'font.size': 22})
  show()   


print "  Done  "

