# Copyright INCAA Computers, 2012
# Author: Bert Gooijer <bert.gooijer@incaacomputers.com>
# Licence: GPL v2 or later.
# Website: http://www.ohwr.org

from ptsexcept import *


import sys
import os
import struct
import signal



"""
functions for getting debug information from c library
"""

def redirect_stderr(default_directory):
    
    # redirect stderr(all debug output) to Output.txt
    sys.stderr.flush()
    new_stderr = os.dup(2)
    path = os.path.join(default_directory, './Output.txt')
    opslag = os.open(path, os.O_CREAT | os.O_WRONLY)
    os.dup2(opslag, 2)
    os.close(opslag)
    
    return new_stderr
    
def restore_stderr(new_stderr, default_directory):
    
    # Reopen original stderr
    sys.stderr = os.fdopen(new_stderr, 'w')
    
    # Open Output.txt for display and remove file
    path = os.path.join(default_directory, './Output.txt')
    display = open(path)
    print display.read()
    os.remove(path)
    
def show_stderr(default_directory):
    
    # Open Output.txt for display and empty file
    path = os.path.join(default_directory, './Output.txt')
    display = open(path)
    print display.read()
    os.remove(path)
    opslag = os.open(path, os.O_CREAT | os.O_WRONLY)
    os.dup2(opslag, 2)
    os.close(opslag)


# Register an handler for the timeout
def handler(signum, frame):
    raise Exception("input timeout")

# input with timeout
def timeout_input(message, timeout ):
    # signal.signal(signal.SIGALRM, handler)
    # signal.alarm(timeout)
    try:
        tmp = raw_input(message)
        
    except Exception, exc: 
        tmp = exc
        
    # signal.alarm(0)
    return tmp

def yesnoquestion( message, timeout ):
    
    tmp = timeout_input(message, timeout );
    
    if( isinstance( tmp, str ) ):    
        if ( (tmp.upper() == 'N') or (tmp.upper() == 'NO') ):
            return 0;
        elif ( (tmp.upper() == 'Y') or (tmp.upper() == 'YES') ):
            return 1;
        else:
            return -1;
    else:
        return -1;




import parse

def load_config(filename):
    regs = []

    with open(filename,'r') as file:
    
        for txt in file.readlines():

            parsed = parse.parse('"{:x}","{:b}","{:x}"{}', txt )

            if parsed :
                regs.append([parsed[0], parsed[1]])

    return regs

 