#! /usr/bin/env python
# encoding: utf-8

import os

FRAGMENT_VLA='''int main (int argc, char **argv) {
	char a[argc];
	a[sizeof( a ) - 1] = 0;
	int N;
	return a[0];
}'''

FRAGMENT_ALLOCA_H='''#include <alloca.h>
int main (void) {
	int foo=10;
	int * array = alloca(foo);
}'''

FRAGMENT_STDLIB_H='''#include <malloc.h>
#include <stdlib.h>
int main (void) {
	int foo=10;
	int * array = alloca(foo);
}'''

def options(opt):
	pass

def configure(conf):
	if not conf.path.find_dir('opus') or not conf.path.find_dir('opus/src'):
		conf.fatal('Can\'t find opus submodule. Run `git submodule update --init --recursive`.')
		return

	# Check for C99 variable-size arrays, or alloca() as fallback
	if conf.check_cc(fragment=FRAGMENT_VLA, msg = 'Checking for C99 VLA support', mandatory = False):
		conf.define('VAR_ARRAYS', 1)
	elif conf.check_cc(fragment=FRAGMENT_ALLOCA_H, msg = 'Checking for alloca in alloca.h header', mandatory = False):
		conf.define('USE_ALLOCA', 1)
		conf.define('HAVE_ALLOCA_H', 1)
	elif conf.check_cc(fragmenmt=FRAGMENT_STDLIB_H, msg = 'Checking for alloca.h in stdlib.h', mandatory = False):
		conf.define('USE_ALLOCA', 1)

	# TODO: ARM/x86 intrinsics detection
	# TODO: maybe call autotools/cmake/meson instead?

def build(bld):
	sources = bld.path.ant_glob([
		'opus/src/*.c',
		'opus/celt/*.c',
		'opus/silk/*.c',
		'opus/silk/float/*.c'
	], excl = [
		'opus/src/repacketizer_demo.c',
		'opus/src/opus_demo.c',
		'opus/src/opus_compare.c',
		'opus/celt/opus_custom_demo.c'
	])
	includes = ['opus/include/', 'opus/celt/', 'opus/silk/', 'opus/silk/float/']
	defines = ['OPUS_BUILD', 'FLOAT_APPROX', 'PACKAGE_VERSION="1.4.0"', 'CUSTOM_MODES']

	bld.stlib(
		source = sources,
		target = 'opus',
		features = 'c',
		includes = includes,
		defines = defines,
		export_includes = ['opus/include/']
	)
