#!/usr/bin/env python

""" This script converts old vcs scripts to python scripts
This is version 0. graphic method and template won't be converted
Therefore old script still needed around in order to load all graphic methods needed

Not implemented yet, to do:
xname, xunits, etc....
Transform, Logical mask
"""
version='0.2'
import sys
import vcs
import cdms

## initialize some stats
warnings=0
vcscmd=0
arrays=0
arrays_from_file=0
plots=0
active_plots=0
unimplemented=0
vcs_objects=0
## Continents overlaying (default none)
overlay_continents=''

## Determine input script
src=sys.argv[1]

## Generate output name
outnm=src[:-4]+'.py'

## Generate output name for graphic methods, templates, etc...
outnm_vcs=src[:-4]+'_vcs.scr'
f2=open(outnm_vcs,'w')

# open input script file
fi=open(src,'r')

## Opens output script file
f=open(outnm,'w')
f.write('#/usr/bin/env python\nimport vcs\nimport cdms\nimport MV\nx=vcs.init()\n\n')
f.write('"""Python script autogenerated using vcs2py version '+version+'\n')
f.write('Input VCS script: '+src+'\n"""\n')
f.write('## First load all the necessary template and graphic methods from the old script\nx.scriptrun(\''+outnm_vcs+'\')\n')
f.write("## Individual python code for individual vcs object can be generated by loading the object and saving it to a file\n## e.g: t=x.getboxfill('default')\n## x.scriptobject(t,'myfile.py')\n\n")

## Opens file for graphic methods rewriting

## Ok now let's loop through all lines and figure out commands
ln=fi.readlines()
n=len(ln)

def extract(instring,beg,end=','):
    """ Extract part of a string between 2 characters def, returns None if not existing
    Usage: val = extract(instring,beg,end=',')
    """
    try:
        sp=instring.split(beg)[1]
        sp=sp.split(end)[0]
        if sp[-1]==instring[-1]:
            sp=sp[:-1]
    except:
        sp=None
    return sp
for i in range(n):
    l=ln[i]
    #print l
    iprint=0
    if l[:4]=='Page':
        vcscmd+=1
        val=l[5:].split(')')[0]
        f.write('x.'+val+'()\n\n')
    elif l.split('_')[0] in ['L','Tt','To','Tl','Tf','Tm','Th','C','P',
                                    'Gi','Gfb','Gfi','Gfo','Go','GSp','Gv','GXY','GXy','GYx']:
        # First reconstruct the full name
        nbracket=l.count('(')
        vcs_objects+=1
        j=1
        f2.write(ln[i])
        nbracket-=l.count(')')
        while nbracket>0:
            f2.write(ln[i+j])
            nbracket+=ln[i+j].count('(')
            nbracket-=ln[i+j].count(')')
            j+=1
            
    elif l[:5]=='Sleep':
        vcscmd+=1
        val=l[6:].split(')')[0]
        f.write('import time\ntime.sleep('+val+')\n\n')
    elif l[:4]=='Over':
        vcscmd+=1
        overlay_continents=',continents='
        n=l[19:].split(')')[0]
        overlay_continents+=n
    elif l[:3].lower()=='cgm':
        vcscmd+=1
        args=l[4:].split(')')[0] # get the arguments
        sp=args.split(',')
        cgmfnm=sp[0]
        if len(sp)>1:
            app=sp[1][0]
        else:
            app="'a'"
        f.write("x.cgm('"+cgmfnm+"',"+app+")\n\n")
    elif l[:3].lower()=='run':
        vcscmd+=1
        args=l[4:].split(')')[0] # get the arguments
        sp=args.split(',')
        scrfnm=sp[0]
        f.write("## Warning the following will only load the templates/graphic methods\n")
        f.write("## To excute commands convert script to file and uncoment the following line\n")
        warnings+=1
        print 'Warning: Run script, will not execute any command, you need to convert it first and uncoment the line in the python script'
        pyfnm=scrfnm.replace('.scr','.py')
        f.write("## execfile('"+pyfnm+"')\n")
        f.write("x.scriptrun('"+scrfnm+"')\n\n")
    elif l[:6].lower()=='raster':
        vcscmd+=1
        args=l[7:].split(')')[0] # get the arguments
        sp=args.split(',')
        cgmfnm=sp[0]
        if len(sp)>1:
            app=sp[1][0]
        else:
            app="'a'"
        f.write("x.raster('"+cgmfnm+"',"+app+")\n\n")
    elif l[:3].lower() in['drs','hdf']:
        vcscmd+=1
        warnings+=1
        args=l[4:].split(')')[0] # get the arguments
        sp=args.split(',')
        ncfnm=sp[0]
        ncfnm=ncfnm.replace('.dic','.nc')
        ncfnm=ncfnm.replace('.hdf','.nc')
        if len(sp)>2:
            app=sp[2][0]
            if app=='r':app="'w'"
            if app=='a':app="'r+'"
        else:
            app="'w'"
        array=sp[1]
        print 'WARNING: Output file converted from '+l[:3]+' to NetCDF'
        f.write("f=cdms.open('"+ncfnm+"',"+app+")\n")
        f.write("f.write("+array+","+app+")\n")
        f.write('f.close()\n\n')
    elif l[:6].lower()=='netcdf':
        vcscmd+=1
        args=l[7:].split(')')[0] # get the arguments
        sp=args.split(',')
        ncfnm=sp[0]
        if len(sp)>2:
            app=sp[2][0]
            if app=='r':app="'w'"
            if app=='a':app="'r+'"
        else:
            app="'w'"
        array=sp[1]
        f.write("f=cdms.open('"+ncfnm+"',"+app+")\n")
        f.write("f.write("+array+","+app+")\n")
        f.write('f.close()\n\n')
    elif l[:5].lower()=='clear':
        vcscmd+=1
        f.write('x.clear()\n\n')
    elif l[:5].lower()=='color':
        vcscmd+=1
        cmap=l[6:].split(')')[0]
        f.write("x.setcolormap('"+cmap+"')\n\n")
    elif l[:6].lower()=='canvas':
        vcscmd+=1
        if l[7:-1]=='open':
            f.write('x.open()\n\n')
        elif l[7:-1]=='close':
            f.write('x.close()\n\n')
    elif l[:2]=='A_':
        arrays+=1
        # Acquiring Array data
        # First reconstruct the full name
        j=1
        while l[-2]!=')' and l[-1]!=')':
            l=l[:-1]+ln[i+j]
            j+=1
        l=l.replace('\n','')
        nm=extract(l,'A_','(')
        pnm=nm.replace('.','_') # . are not acceptable in python names
        if pnm!=nm:
            # Now replace in every over possible lines !
            for j in range(i,n):
                ln[j]=ln[j].replace(nm,pnm)
        fnm=extract(l,'File=')
        src=extract(l,'Source=')
        vr=extract(l,'Name=')
        tit=extract(l,'Title=')
        units=extract(l,'Units=')
        xnm=extract(l,'XName=')
        xfirst=extract(l,'xfirst=')
        xlast=extract(l,'xlast=')
        ynm=extract(l,'YName=')
        yfirst=extract(l,'yfirst=')
        ylast=extract(l,'ylast=')
        znm=extract(l,'ZName=')
        zfirst=extract(l,'zfirst=')
        zlast=extract(l,'zlast=')
        tnm=extract(l,'TName=')
        tfirst=extract(l,'tfirst=')
        tlast=extract(l,'tlast=')
        func=extract(l,'Function="','"')
        cmd=''
        
        if not fnm is None:
            arrays_from_file+=1
            cmd+='f = cdms.open('+fnm+')\n'
            cmd+=pnm+' = f('+vr
            if fnm[-5:-1]=='.dic':
                if not tnm is None: tnm=tnm[:-1]+'_'+vr[1:]
                if not znm is None: znm=znm[:-1]+'_'+vr[1:]
                if not ynm is None: ynm=ynm[:-1]+'_'+vr[1:]
                if not xnm is None: xnm=xnm[:-1]+'_'+vr[1:]

        elif not func is None:
            # First of all treats the special commands (mean and sqrt)
            # Mean ?
##             if func[:-1]!=')':
##                 func=func+')'
            imean=func.find('mean(')
            while imean!=-1 :
                tmp=func[imean:]
                tmp=tmp.replace('mean(','cdutil.averager(',1)
                tmp=tmp.split(',')
                tmp2=tmp[1]
                fpar=tmp2.find('\'')
                lpar=tmp2[fpar+1].find('\'')
                tmp3=tmp2[fpar+1:lpar].lower()
                if tmp3=='time':
                    tmp3="axis='t')"
                elif tmp3=='longitude':
                    tmp3="axis='x')"
                elif tmp3=='latitude':
                    tmp3="axis='y')"
                elif tmp3=='level':
                    tmp3="axis='z')"
                else:
                    tmp3="axis='("+tmp2[fpar+1:lpar-1]+")'"+tmp2[lpar:]
                tmp[1]=tmp3
                tmp=','.join(tmp)
                func=func[:imean]+tmp
                imean=func.find('mean(')
            isqrt=func.find('sqrt(')
            while isqrt!=-1:
                warnings+=1
                print 'WARNING FOR ARRAY:'+pnm+'\nsqrt FUNCTION FOUND YOU NEED TO REPLACE AXIS NAME WITH CORRECT VALUE !'
                tmp=func[isqrt:]
                tmp=tmp.replace('sqrt(','MV.xxxx(',1)
                tmp=tmp.split(',')
                if len(tmp)>1:
                    tmp2=tmp[1]
                    fpar=tmp2.find('\'')
                    lpar=tmp2[fpar+1].find('\'')
                    tmp3="axis='("+tmp2[fpar+1:lpar-1].lower()+")'"
                    tmp[1]=tmp3
                else:
                    tmp[0]+=')'
                tmp=','.join(tmp)
                func=func[:isqrt]+tmp
                isqrt=func.find('sqrt(')
            func=func.replace('MV.xxxx','MV.sqrt')
            cmd+=pnm+' = '+func+'\n'+pnm+' = '+pnm+'('
        else:
            raise 'Error array'+nm+' is coming neither from file nor function !'
        # Now does the dimensions needed
        order=''
        if not tnm is None:
            order+='('+tnm[1:-1]+')'
            if not tfirst is None:
                tcmd=tnm[1:-1]+'=('+tfirst+','+tlast+')'
                if cmd[-1]!='(':
                    cmd+=','+tcmd
                else:
                    cmd+=tcmd
        if not znm is None:
            order+='('+znm[1:-1]+')'
            if not zfirst is None:
                zcmd=znm[1:-1]+'=('+zfirst+','+zlast+')'
                if cmd[-1]!='(':
                    cmd+=','+zcmd
                else:
                    cmd+=zcmd
        if not ynm is None:
            order+='('+ynm[1:-1]+')'
            if not yfirst is None:
                ycmd=ynm[1:-1]+'=('+yfirst+','+ylast+')'
                if cmd[-1]!='(':
                    cmd+=','+ycmd
                else:
                    cmd+=ycmd
        if not xnm is None:
            order+='('+xnm[1:-1]+')'
            if not xfirst is None:
                xcmd=xnm[1:-1]+'=('+xfirst+','+xlast+')'
                if cmd[-1]!='(':
                    cmd+=','+xcmd
                else:
                    cmd+=xcmd
        if order!='':
            cmd+=",order='..."+order+"'"
        cmd+=')\n'
        if not fnm is None:
            cmd+='f.close()\n'
        if not src is None:
            cmd+=pnm+'.source = '+src+'\n'
        if not tit is None:
            cmd+=pnm+'.title = '+tit+'\n'
        if not units is None:
            cmd+=pnm+'.units = '+units+'\n'
        
        # Now does the attributes that are overwrittable
        for att in ['source','name','units','crdate','crtime',
                    'comment#1','comment#2','comment#3','comment#4']:
            val=extract(l,att+'="','"')
            Att=att.replace('#','')
            if not val is None:
                cmd+=pnm+'.'+Att+' = "'+val+'"\n'
        cmd+='\n'
        cmd=cmd.replace('"',"'")
        cmd=cmd.replace('(,',"(")
        f.write(cmd)
    elif l[:2]=='D_':
        plots+=1
        # Plotting data
        # First reconstruct the full string
        j=1
        while l[-2]!=')' and l[-1]!=')':
            l=l[:-1]+ln[i+j]
            j+=1
        l=l.replace('\n','')
        off=extract(l,'off=',',')
        if int(off)==0: # Ok it's not off, let's draw it
            cmd=''
            active_plots+=1
        else:
            cmd='## Next line commented, display was "off"\n## '
        type=extract(l,'type='    ,',')
        if type is None: type = 'boxfill'
        tmpl=extract(l,'template=',',')
        if tmpl is None: tmpl='default'
        mthd=extract(l,'graph='   ,',')
        if mthd is None: mthd='default'
        a   =extract(l,'a='       ,',')
        b   =extract(l,'b='       ,',')
        cmd+='x.plot('+a+', '
        if not b is None:
            cmd+=b+' ,'
        cmd+="'"+tmpl+"', '"+type+"', '"+mthd+"'"+overlay_continents+")\n\n"
        f.write(cmd)
f.close()
print 'Successfully converted:',src
print 'Processed:'
print 'VCS Commands:',vcscmd

print 'Arrays:',arrays,':',arrays_from_file,'from file and',arrays-arrays_from_file,'computed'
print 'Plots:',plots
print 'Active plots:',active_plots
print 'Warnings:',warnings
print 'VCS OBJECTS (templates, graphic methods, etc..):',vcs_objects

