#!/usr/bin/env python
# -*- python -*-
#
# Copyright 2002 Free Software Foundation, Inc.
# 
# This file is part of GNU Radio
# 
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
# 
# GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING.  If not, write to
# the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
# 

#
# Run the ATSC receiver on samples and check output for errors.
#

# usage: run_rx [options] -f input_samples -o output_stream
#    -f <input_samples>    source file for input samples
#    -o <transport_stream> destination file for transport stream
#    -s 20                 input sample rate is 20MS/s
#    -s 2x                 input sample rate is 21.52MS/s (2 * ATSC_SYMBOL_RATE)
#    -h, --help            help msg
#    -v, --verbose         verbose
#    -l, --log             enable RX logging
#    -L, --lms             enable LMS equalizer, else NOP equalizer
#    -g, --gui             enable RX GUI
#
#    --loop-filter-tap=<float>
#    --loop-timing-rate=<float>


import os, os.path, math, sys, getopt, string
import mpeg_packet_error_rate


# set srcdir to the directory that contains Makefile.am

try:
    srcdir = os.environ['srcdir']
except KeyError, e:
    srcdir = "."
srcdir = srcdir + '/'


def system_chk (cmd):
    r = os.system (cmd)
    if (r != 0):
        # print "FAILED (%d): %s" % (r >> 8, cmd)
        if ((r & 0xff) != 0) :          # killed by signal
            sys.exit (127)
        else :
            sys.exit (r >> 8)
    return 0


def usage ():
    sys.stderr.write ("usage: %s [options] -f input_samples -o output_stream\n" % sys.argv[0])
    sys.stderr.write (
'''    -f <input_samples> source file for input samples
    -o <output_stream> destination file for transport stream
    -s 20              input sample rate is 20MS/s
    -s 2x              input sample rate is 21.52MS/s (2 * ATSC_SYMBOL_RATE)
    -h, --help         this message
    -v, --verbose      verbose
    -l, --logging      enable RX logging
    -L, --lms          enable LMS equalizer, else NOP equalizer
    -g, --gui          enable RX GUI
    -S skip_count      packets to skip when computing error rate

    --20               input sample rate is 20MS/s
    --2x               input sample rate is 21.52MS/s (2 * ATSC_SYMBOL_RATE)

    --loop-filter-tap=<float>
    --loop-timing-rate=<float>

''')
    sys.exit (1)

#
# parse command line args
#

atsc_rx_FLAGS = ''
verbose_p = 0
time_CMD = ''
skip_count = 0

try:
    opts, args = getopt.getopt(sys.argv[1:],
                               "hvlLgTs:f:o:S:",
                               ["help", "verbose", "logging", "lms", "gui",
                                "time", "loop-filter-tap=", "loop-timing-rate=",
                                "20", "2x"])
except getopt.GetoptError:
    # print help information and exit:
    usage ()

input_samples = None
output_ts = None
s_option = ''

for o, a in opts:
    if o == "-f":
        input_samples = a
    if o == "-o":
        output_ts = a
    if o in ("-h", "--help"):
        usage ()
    if o in ("-v", "--verbose"):
        verbose_p = 1
    if o in ("-l", "--logging"):
        atsc_rx_FLAGS += '-l '
    if o in ("-L", "--lms"):
        atsc_rx_FLAGS += '-L '
    if o in ("-g", "--gui"):
        atsc_rx_FLAGS += '-g '
    if o in ("-T", "--time"): 
        time_CMD = 'time '
    if o == "-S":
        skip_count = a
    if o == '--loop-filter-tap':
        atsc_rx_FLAGS += '-F ' + a + ' '
    if o == '--loop-timing-rate':
        atsc_rx_FLAGS += '-R ' + a + ' '
    if o == '--20':
        s_option = ' -s 20'
    if o == '--2x':
        s_option = ' -s 2x'
    if o == '-s':
        if a == '20':
            s_option = ' -s 20'
        elif a == '2x':
            s_option = ' -s 2x'
        else:
            usage ()

atsc_rx_FLAGS += s_option


if len (args) != 0 or not input_samples or not output_ts:
    usage ()

#
# construct filenames for intermediate files
#

dst_dir = "."           # destination directory for output and intermediates

transport_error_flags = os.path.join (dst_dir, output_ts + ".error_flags")

#
# do the work
#

sys.stderr.write ("@@@\n@@@ Running Receiver\n@@@\n")
system_chk (time_CMD + ("./atsc_rx %s -f %s -o %s"
                        % (atsc_rx_FLAGS, input_samples, output_ts)))

#
# --- check transport error flags
#

error_rate = mpeg_packet_error_rate.error_rate (output_ts, skip_count)


r = 0
sys.exit (r >> 8)                       # return result code

