import os
import inspect

# try to import an environment first
Import('env')

# find all .cus & .cpps in the current and backend/ directories
sources = []
directories = ['.', 'backend']
extensions = ['*.cu', '*.cpp']

# finall all backend-specific files
if env['backend'] == 'cuda' or env['backend'] == 'ocelot':
  directories.append(os.path.join('backend','cuda'))
elif env['backend'] == 'omp':
  directories.append(os.path.join('backend','omp'))

for dir in directories:
  for ext in extensions:
    regexp = os.path.join(dir, ext)
    sources.extend(env.Glob(regexp))

# filter test files using a regular expression
if 'tests' in env:
  import re

  pattern = re.compile(env['tests'])

  necessary_sources = set(['testframework.cu'])
  filtered_sources  = []

  for f in sources:
    if str(f) in necessary_sources or pattern.search(f.get_contents()):
      filtered_sources.append(f)

  sources = filtered_sources

if 'single_test' in env:
  filename = env['single_test']+'.cu'
  sources = ['testframework.cu', filename]

# add the directory containing this file to the include path
this_file = inspect.currentframe().f_code.co_filename
this_dir = os.path.dirname(this_file)
env.Append(CPPPATH = [this_dir])

tester = env.Program('tester', sources)

# invoke trivial_tests SConscript
if ('tests' not in env) and ('single_test' not in env) :
  # SConscript('external_libs/SConscript', exports='env')
  SConscript('trivial_tests/Sconscript', exports='env')

