#!/usr/bin/env python

"""Display a binary data matrix.
"""

import sys

import argparse

import numpy as np

def main(args):
    # define the data type
    d = np.dtype(args.dtype)
    # read the data from the binary file
    if args.infilename == '-':
        arr = np.fromfile(sys.stdin, dtype=d)
    else:
        with open(args.infilename, 'rb') as fin:
            arr = np.fromfile(fin, dtype=d)
    if args.columns:
        # reshape the array according to the number of columns
        n = len(arr)
        ncols = args.columns
        nrows = n / ncols
        if ncols * nrows != n:
            raise ValueError('ragged row')
        arr = arr.reshape((nrows, ncols))
        # print the array
        lines = []
        for row in arr:
            line = ', '.join([format(x, args.format) for x in row])
            line = '[' + line + ']'
            lines.append(line)
        print '[\n' + ',\n'.join(lines) + ']'
    else:
        # print the array
        lines = [format(x, args.format) for x in arr]
        print '[\n' + ',\n'.join(lines) + ']'

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    """
    parser.add_argument('--commas', action='store_true',
            help='separate elements with commas')
    parser.add_argument('--brackets', action='store_true',
            help='group rows using brackets')
    """
    parser.add_argument('--dtype', default='d',
            help='numpy data type')
    parser.add_argument('--format', default='0.8e',
            help='print using this format string')
    parser.add_argument('--columns', type=int, default=0,
            help='the data matrix has this many columns')
    parser.add_argument('infilename', default='-', nargs='?',
            help='input file')
    main(parser.parse_args())
