"""
.. module:: skrf.io.metas
========================================
metas (:mod:`skrf.io.metas`)
========================================

Functions for reading and writing file formats defined by METAS

https://www.metas.ch/vnatools

.. autosummary::
   :toctree: generated/


"""
from numpy import array, hstack, savetxt

from ..mathFunctions import complex2Scalar
from ..network import average
from ..networkSet import NetworkSet


def ns_2_sdatcv(ns, fname, polar=False):
    """
    Write a sdatcv from a skrf.NetworkSet.

    Parameters
    ----------
    ns : :class:`~skrf.networkset.NetworkSet`
        `NetworkSet`
    fname : string
        filename to save
    polar : boolean, optional
        Average the mag/phase components individually. Default is False.

    """

    ntwk = ns[0]
    nports = ntwk.nports
    freq_hz = ntwk.f.reshape(-1, 1)

    # make the header and columns information
    top = '\n'.join(['SDATCV',
                   'Ports',
                   '\t'.join(['%i\t'%(k+1) for k in range(nports)])])

    # port impedance info
    z0ri = complex2Scalar(ntwk.z0[0])
    zcol ='\t'.join(['Zr[%i]re\tZr[%i]im'%(k+1, k+1) \
        for k in range(nports)])
    zvals = '\t'.join([str(k) for k in z0ri])
    zhead = '\n'.join([zcol,zvals])

    # s and cov matrix info
    shead = '\t'.join(['S[%i,%i]%s'%(m+1, n+1, k) \
        for m,n in ntwk.port_tuples for k in ['re','im'] ])

    cvhead = '\t'.join(['CV[%i,%i]'%(n+1, m+1) \
        for m in range(2*nports**2) for n in range(2*nports**2)])

    datahead = '\t'.join(['Freq', shead, cvhead])

    header = '\n'.join([top, zhead, datahead])

    # calculate covariance matrix
    cv = ns.cov()

    # calculate mean s value,  everything so we have a 2D matrix
    mean_ntwk = average(ns, polar=polar)
    s_mean_flat = NetworkSet([mean_ntwk]).scalar_mat().squeeze()
    cv_flat = array([k.flatten('F') for k in cv])

    data = hstack([freq_hz, s_mean_flat, cv_flat])
    savetxt(fname, data, delimiter='\t', header=header, comments='')
