import numpy
from netCDF4 import Dataset

from optparse import OptionParser

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

import os.path

parser = OptionParser()
# could add optional arguments here, but none so far
options, args = parser.parse_args()

if(len(args) < 1):
  print "Usage: python plotMISOMIPIceMetrics.py <IceOcean1_result.nc> <IceOcean2_results.nc> ..."
  exit(1)

files = args

sPerYr = 365.*24.*60.*60.
GTPerKg = 1e-12

fieldNames = ['iceVolume', 'iceVAF', 'groundedArea']
titles = ['total ice volume (1000 km^3)', 
          'total ice volume above flotation (1000 km^3)',
          'grounded area (1000 km^2)']
semiLog = [False, False, False]
scales = [1e-12, 1e-12, 1e-9]

for fileName in files:
  print fileName
  ncFile = Dataset(fileName,'r')
  baseName = os.path.basename(fileName)
  label = baseName.split('_')[0]
  
  times = ncFile.variables['time'][:]/sPerYr

  for fIndex in range(len(fieldNames)):
    fieldName = fieldNames[fIndex]
    field = scales[fIndex]*ncFile.variables[fieldName][:]
    plt.figure(fIndex+1)
    if(semiLog[fIndex]):
      plt.semilogy(times, field, label=label)
    else:
      plt.plot(times, field, label=label)
    
for fIndex in range(len(fieldNames)):
  plt.figure(fIndex+1)
  plt.xlabel('time (a)')
  plt.ylabel(titles[fIndex])
  plt.legend()
  plt.draw()
  plt.savefig('%s.png'%fieldNames[fIndex])
  plt.savefig('%s.pdf'%fieldNames[fIndex])

