#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Command Line Untrending
-----------------------

There is also the option of using **Untrendy** from the command line if you
don't want to bother with all the Python stuff. If you have a whitespace
separated ASCII file containing your light curve, you can de-trend it by
running:

::

    untrend /path/to/data.txt

The code will assume that your file has 2 or 3 columns with time, flux and
(optionally) uncertainties for each observation. Then, the de-trended light
curve will be written to standard out in the same format. Alternatively, the
same program can read the data right from standard in:

::

    cat /path/to/data.txt | untrend

This gives you the option of doing something crazy and then piping it all
UNIX-like. Personally, I would just use Python.

"""

from __future__ import print_function, absolute_import, unicode_literals

import sys
import numpy as np
import untrendy

if __name__ == "__main__":
    if "-h" in sys.argv or "--help" in sys.argv:
        print(__doc__.strip())
        sys.exit(0)

    # Read in data.
    if len(sys.argv) == 2:
        fn = sys.argv[1]
        with open(fn) as f:
            data = np.loadtxt(f)

    else:
        with sys.stdin as f:
            data = np.loadtxt(f)

    # Parse the columns.
    if data.shape[1] == 2:
        t, f = zip(*data)
        ferr = None
        title_fmt = "# {0:10s}    {1:10s}"
        fmt = "{0:10.8e}    {1:10.8e}"
    elif data.shape[1] == 3:
        t, f, ferr = zip(*data)
        title_fmt = "# {0:10s}    {1:10s}    {2:10s}"
        fmt = "{0:10.8e}    {1:10.8e}    {2:10.8e}"
    else:
        print("The light curve data file must contain 2 or 3 columns.")
        sys.exit(2)

    # De-trend the data.
    f, ferr = untrendy.untrend(t, f, ferr)

    # Output the results.
    print(title_fmt.format("time", "flux", "flux_err"))
    for row in zip(t, f, ferr):
        print(fmt.format(*row))
