#!/usr/bin/env python3

import os
import sys
import pathlib
from importlib.machinery import SourceFileLoader

def get_test_and_filename( extension ):
    filename = sys.argv[ 1 ].replace( '.py', extension )
    testname = os.path.basename( sys.argv[ 1 ].replace( '.py', '' ) )
    return testname, filename

def convert_to_c( data ):
    testname, filename = get_test_and_filename( '.h' )
    with open( filename, 'w' ) as f:
        f.write( '#pragma once\n' )
        f.write( 'float expected_' + testname +'[] = {' )
        f.write( '{:e}'.format( data[ 0 ] ) )
        for i in data[ 1 : ]:
            f.write( ',{:e}'.format( i ) )
        f.write( '};\n' )

def convert_to_vhdl( data ):
    testname, filename = get_test_and_filename( '.vhd' )
    with open( filename, 'w' ) as f:
        f.write( 'library ieee;\n' )
        f.write( '    use ieee.std_logic_1164.all;\n' )
        f.write( '\n' )
        f.write( 'library work;\n' )
        f.write( '    use work.test_utility.all;\n' )
        f.write( '\n' )
        f.write( 'package ' + testname + '_data is\n' )
        f.write( '    constant expected : real_array( 0 to 1023 ) := (' )
        f.write( '{:e}'.format( data[ 0 ] ) )
        for i in data[ 1 : ]:
            f.write( ',{:e}'.format( i ) )
        f.write( ');\n' )
        f.write( 'end package ' + testname + '_data;\n' )

def convert():
    if ( len( sys.argv ) != 2 ):
        raise( Exception( "Usage: {} expected_data.py" ) )

    cwd = pathlib.Path( os.getcwd() )
    expected_path = cwd.joinpath( sys.argv[ 1 ] )

    expected = SourceFileLoader( 'expected', str( expected_path ) ).load_module()

    convert_to_c( expected.data )
    convert_to_vhdl( expected.data )

def main():
    try:
        convert()
    except Exception as e:
        print( e )


if ( __name__ == '__main__' ):
    main()

