#! /usr/bin/env python

# Copyright (C) 2010
# Glimmer-CISM contributors - see AUTHORS file for list of contributors
#
# This file is part of Glimmer-CISM.
#
# Glimmer-CISM is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or (at
# your option) any later version.
#
# Glimmer-CISM is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Glimmer-CISM.  If not, see <http://www.gnu.org/licenses/>.
#
# Glimmer-CISM is hosted on BerliOS.de:
# https://developer.berlios.de/projects/glimmer-cism/

"""Plot variable at single location."""

import PyGC,numpy
import matplotlib.pyplot
from mpl_toolkits.axes_grid.anchored_artists import AnchoredText

# creating option parser
parser = PyGC.GCOptParser()
parser.width=15.
parser.spot()
parser.time()
parser.region1d()
parser.plot()
opts = PyGC.GCOptions(parser,-1)

mspots = len(opts.options.ij)>1
mfiles = opts.nfiles>1
mtimes = opts.ntimes>1

haveMulti=0
for m in [mspots,mfiles,mtimes]:
    if m:
        haveMulti+=1
if haveMulti>1:
    raise RuntimeError, 'Can only have one of multiple spots, times or files'
nplots = max(len(opts.options.ij),opts.nfiles,opts.ntimes)
naxes = opts.nvars

infile = opts.gcfile()
time = opts.times(infile)
spot = opts.options.ij[0]

fig = matplotlib.pyplot.figure(figsize=opts.plotsize)

# create axes
totalheight=0.8
if nplots > 1:
    # make room for legend
    totalheight = totalheight - 0.075
plotwidth = 0.9/naxes
sep = 0.05
axprops = {}
axes = []
for i in range(1,naxes+1):
    axes.append( fig.add_axes([1-i*plotwidth,0.9-totalheight,plotwidth-sep,totalheight]))
    var = opts.vars(infile,i-1)
    if not var.is3d:
        raise RuntimeError, 'variable %s is not three dimensional'%opts.options.vars[i-1]
    axes[i-1].set_xlabel('%s [%s]'%(var.long_name,var.units))
    if i==1:
        axprops['sharey'] = axes[0]
    if i!=naxes:
        axes[i-1].get_yaxis().set_visible(False)
    else:
        if 'level' in var.var.dimensions:
            axes[i-1].set_ylabel('elevation [m]')
        else:
            axes[i-1].set_ylabel('depth [m]')

if nplots>1:
    COLS='bgrcnyk'
else:
    COLS='k'

for i in range(0,nplots):
    if mfiles:
        infile = opts.gcfile(i)
        time = opts.times(infile)
        label = infile.title
    elif mtimes:
        time = opts.times(infile,i)
        label = '%.2fka'%infile.time(time)
    else:
        spot = opts.options.ij[i]
        label = str(spot)

    for j in range(0,opts.nvars):
        var = opts.vars(infile,j)
        if 'level' in var.var.dimensions:
            ldata = (1-numpy.array(infile.file.variables['level']))*infile.getvar('thk').getSpotIJ(spot,time)
            lname = infile.file.variables['level'].long_name
        elif 'lithoz' in var.var.dimensions:
            ldata = numpy.array(infile.file.variables['lithoz'])
            lname = infile.file.variables['lithoz'].long_name
        data = var.getSpotIJ(spot,time,None)
        axes[j].plot(data,ldata,color=COLS[i],label=label)

handles, labels = axes[-1].get_legend_handles_labels()
if nplots > 1:
    matplotlib.pyplot.figlegend(handles,labels,'lower center',ncol=2, mode="expand")

if opts.options.output==None:
    matplotlib.pyplot.show()
else:
    matplotlib.pyplot.savefig(opts.options.output)
