#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Plot a given series as a line plot using Matplotlib

Author: Gertjan van den Burg
License: See LICENSE file
Copyright (c) 2020, G.J.J. van den Burg

"""

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


def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-x",
        "--have-x",
        help="Shared x coordinate is stored in the first field.",
        action="store_true",
    )
    parser.add_argument(
        "-c",
        "--consolidate",
        help="Plot in a single plot instead of subplots",
        action="store_true",
    )
    parser.add_argument(
        "-n",
        "--no-scatter",
        help="Disable the scatter plot component",
        action="store_true",
    )
    parser.add_argument(
        "-d",
        "--delimiter",
        help="Delimiter between observations of different dimensions. Default is whitespace",
    )
    parser.add_argument(
        "-t",
        "--transpose",
        help="Transpose the data before plotting",
        action="store_true",
    )
    return parser.parse_args()


def main():
    args = parse_args()
    sep = args.delimiter

    data = []

    for line in sys.stdin:
        if not line.strip():
            continue

        values = line.strip().split(sep)
        row = []
        for value in values:
            if value.strip():
                try:
                    v = float(value)
                except ValueError:
                    v = float('nan')
                row.append(v)
            else:
                row.append(float("nan"))
        data.append(row)

    if args.transpose:
        data = list(map(list, zip(*data)))

    dims = set(map(len, data))
    if not len(dims) == 1:
        raise ValueError("Data is not of consistent dimension.")

    data = np.asarray(data)
    if args.have_x:
        xs = data[:, 0]
        data = data[:, 1:]
    else:
        xs = np.arange(data.shape[0])

    dim = data.shape[1]

    if args.consolidate:
        for d in range(dim):
            if not args.no_scatter:
                plt.scatter(xs, data[:, d])
            plt.plot(xs, data[:, d])
    else:
        fig, axs = plt.subplots(dim, 1, squeeze=False)
        for d in range(dim):
            if not args.no_scatter:
                axs[d, 0].scatter(xs, data[:, d])
            axs[d, 0].plot(xs, data[:, d])

    plt.show()


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        raise SystemExit(1)
