# This scripts is doing...
# Patrick Kuehl, date
import time
from pylab import *
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
import numpy.ma as ma
from matplotlib.colors import LogNorm
from scipy.optimize import leastsq
from matplotlib import dates
import time
import datetime as date
from datetime import datetime
from datetime import timedelta
import os
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning) 
from matplotlib.backends.backend_pdf import PdfPages
from spacepy import pycdf

########
# working scripts including data can be found on /home/pacifix/kuehl/work/data/IMP_GME/
########

####################################################################################################
## run   
#####    . /home/pacifix/kuehl/software/cdf_lib/cdf36_4-dist/bin/definitions.B
## before starting scripts

####################################################################################################


h=open("data/all_years.dat","w")
h.write("#year mon day hour minute int1 int2 int3\n")
for year in range(1974,2002):
  print year
  #os.system("mkdir data/%i" %year)
  fname1="i8_h0_gme_%i0101_v01.cdf"%year
  fname2="i8_h0_gme_%i0701_v01.cdf"%year
  fname3="i8_h0_gme_%i0101_v02.cdf"%year
  fname4="i8_h0_gme_%i0701_v02.cdf"%year
  g=open("data/%i.dat"%year,"w")
  g.write("#year mon day hour minute int1 int2 int3\n")
  for fname in [fname1,fname2,fname3,fname4]:
    try:

      cdf=pycdf.CDF("data/%i/%s" %(year,fname))
      #print cdf.keys()
      #print cdf["Proton_DIntn_Engy"][...]



      f=open("energies.bins","w")
      for ene in cdf["Proton_DIntn_Engy"][...][-3:]:
        f.write("%4.4f "%ene)
      f.close()

      ints= cdf["Proton_DIntn"][...]
      epochs= cdf["Epoch"][...]


      
      
      for q in range(len(epochs)):
        year= epochs[q].year
        mon= epochs[q].month
        day= epochs[q].day
        hour= epochs[q].hour
        minu= epochs[q].minute
        myints= ints[q][-3:]

        g.write("%i %i %i %i %i %4.4e %4.4e %4.4e \n" %(year,mon,day,hour,minu, myints[0],myints[1],myints[2]))
        h.write("%i %i %i %i %i %4.4e %4.4e %4.4e \n" %(year,mon,day,hour,minu, myints[0],myints[1],myints[2]))
      cdf.close()
    except:
      print "bad file: %i %s"%(year,fname)
  g.close()
h.close()

