# -*- coding: ascii -*-

###########################################################################
# clive, video extraction utility
# Copyright (C) 2007-2008 Toni Gundogdu
#
# clive 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 of the License, or
# (at your option) any later version.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 0.1.2-1307 USA
###########################################################################

## Contains the program entry point class

import sys
import os
import traceback

try:
    from cStringIO import StringIO
except ImportError:
    import StringIO

from clive.opts import Options
from clive.nomad import Nomad

__all__ = ['Clive']


## The program class
class Clive:

    ## Constructor
    def __init__(self):
        sys.excepthook = self._exc_hook
        self._optparser = Options()
        (self.opts, self.args) = self._optparser.parse()

    ## The entry point
    def main(self):
        self._optparser.show(self._say)
        Nomad().run(self.opts, self.args, self._say)

    def _say(self, text='\n', show_always=0, is_error=0, newline=1):
        if self.opts.enable_verbose or show_always:
            std = ([sys.stdout, sys.stderr][is_error])
            if is_error and not text.startswith('error:'):
                text = 'error: ' + text
            std.write(self._cleanup_text(text, newline))

    def _cleanup_text(self, text, newline):
        text = text.rstrip('\r\n')
        if newline: text += '\n'
        return text

    def _exc_hook(self, type, value, tb):
        if type != EOFError and type != KeyboardInterrupt:
            trace = StringIO()
            traceback.print_exception(type, value, tb, None, trace)
            sys.stderr.write('error: %s\n' % trace.getvalue())
        else:
            print


