#!/usr/bin/env python

# Copyright (c) 2014 Leif Johnson <leif@leifjohnson.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

'''Convert a C3D file to NPZ (numpy binary) format.'''

from __future__ import print_function

import argparse
import c3d
import climate
import gzip
import numpy as np
import sys

logging = climate.get_logger('c3d2npz')

climate.add_arg('input', default='-', metavar='FILE', nargs=argparse.REMAINDER,
                help='process data from this input FILE')


def convert(filename, args):
    input = sys.stdin
    outname = '-'
    output = sys.stdout
    if filename != '-':
        input = open(filename, 'rb')
        outname = filename.replace('.c3d', '.npz')
        output = gzip.open(outname, 'wb')
    points = []
    analog = []
    for i, (_, p, a) in enumerate(c3d.Reader(input).read_frames()):
        points.append(p)
        analog.append(a)
        if i and not i % 10000:
            logging.info('%s: extracted %d point frames',
                         outname, len(points))
    np.savez(output, points=points, analog=analog)
    logging.info('%s: saved %dx%s points, %dx%s analog',
                 outname,
                 len(points), points[0].shape,
                 len(analog), analog[0].shape if len(analog) else ())
    if filename != '-':
        input.close()
        output.close()


def main(args):
    for filename in args.input:
        convert(filename, args)


if __name__ == '__main__':
    climate.call(main)
