#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 21 11:00:29 2017

@author: Neo


11 Jan 2018, N. Liu : set the zero-formal-uncertainty to 0.999999



Retrieve the estimates of daily offset of nutation in longitude and
nutation in obliquity as well as their formal uncertainties from .nut
file which is generated by the program getpar.

NOTE: These Nutation angles are wrt to Wahr1980 expension, NOT IAU2000A.


   .nut file contains estimates of daily offset of nutation in longitude and
nutation in obliquity as well as their formal uncertainties. .nut file contains
also database names and time-tags.

   File contains lines of two types:
1) Comment. The first character is #. Header comment contain the full name of
   the spool file.

2) Estimates.

   Field   Format Units     Meaning
   1-8     A8     --        record type identifier:  NUT_LOC:
   11-20   A10    --        database name with leading dollar sign
   23-25   I3     --        database version number
   37-46   F10.5  years     time tag
   53-59   I6     --        the number of used observations
   64-74   F11.3  mas       estimate of nutation in longitude
   79-88   F10.1  muas      formal uncertainty of nutation in longitude
   94-104  F11.3  mas       estimate of nutation in obliquity
   109-118 F10.1  muas      formal uncertainty of nutation in obliquity

"""

import numpy as np
import sys
import matplotlib.pyplot as plt


__all__ = {"zero_err", "read_nut"}


# ------------------------------  FUNCTIONS  ---------------------------
def zero_err(err):
    '''set zero-error to 0.999999
    '''

    return np.where(err == 0, 0.999999, err)


def read_nut(datafile):
    '''Retri__all__ = {"zero_err", "read_eob"}eve the result from .nut file.

    Parameters
    ----------
    datafile : string
        name of data file

    Returns
    ----------
    dbname : array, string
        database name with leading dollar sign
    tag : array, float
        time flag, year
    obsnum : array, int
        number of observations used
    P : array, float
        nutation in longitude, mas
    P_err : array, float
        formal uncertainty of P, mas
    E : array, float
        nutation on obliquity, mas
    E_err : array, float
        formal uncertainty of E, mas
    '''

    dbname = np.genfromtxt(datafile, dtype=str, usecols=(1,))
    tag = np.genfromtxt(datafile, usecols=(4,))
    obsnum = np.genfromtxt(datafile, dtype=int, usecols=(6,))
    P, P_err, E, E_err = np.genfromtxt(datafile,
                                       usecols=np.arange(8, 16, 2),
                                       missing_values='*'*8,
                                       filling_values=0.,
                                       unpack=True)

    # Avoid zero-error, 0.0 -> 0.999999
    P_err = zero_err(P_err)
    E_err = zero_err(E_err)

    # uas -> mas
    P_err, E_err = P_err / 1000.0, E_err / 1000.0

    return dbname, tag, obsnum, P, P_err, E, E_err


# # Retrieve estimates.
# if len(sys.argv) == 1:
#     datafile = 'result/test.nut'
# else:
#     datafile = sys.argv[1]
# dbname, tag, obsnum, P, P_err, E, E_err = read_nut(datafile)

# # Plot it.
# fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True)
# ax0.errorbar(tag, P, yerr=P_err, fmt='.')
# ax0.set_title("Nutation longitude")
# ax0.set_ylim([-200, 200])
# ax1.errorbar(tag, E, yerr=E_err, fmt='.')
# ax1.set_title("Nutation obliquity")
# ax1.set_ylim([-200, 200])
# plt.savefig("figures/nut.eps")
# plt.show()
# ------------------------------ END -----------------------------------
