#! python

import os
import sys
import signal
from gmisclib import die
from gmisclib import makemake as M
from gmisclib import g2_select

signal.signal(signal.SIGHUP, signal.SIG_IGN)
M.maketemp(dir=os.path.join(os.environ['HOME'], 'tmp'))
M.setlog('LOG')
M.log("#" + M.date())
M.log(' '.join(sys.argv))

# Do format conversions on the audio signal, before other processing.
# This will also resample the speech signal to a standard rate, if desired.
# Resampling is done with the -resample flag.
#
# This script is designed to take advantage of a Beowulf cluster,
# if available.  (Using qmake.)    To run with qmake, set the
# -qmake NNN flag, where NNN is the number of processors in the cluster.
#
# The input to this script is in two pieces.   One is a database that
# lists the data files, either in FIAT format or a=v format.   Specify
# the name of the database with the -db FFF or the -dbav FFF flags, as
# appropriate.
# Note that pathnames in the database should either be absolute or relative
# to the directory where the database sits.  Pathnames are stored in two
# columns, "d" and "f" and the full pathname of the input audio data
# is "$d/$f.wav".
# The other part of the input is a directory tree of audio files.

# The output of this script is a directory tree one level deeper,
# where audio file $d/$f.wav is expanded into a directory
# $d/$f, containing raw.wav, raw.dat.
# raw.wav is just a link to the original audio (or the original data, resampled),
# raw.dat is the audio converted into the "GPK ASCII Image" format (see speechresearch/gpkio),

B = M.path_to('g_audioprep.py')
CODE = B
CLUSTERSIZE = None
Rewrite = None
Selector = 'True'
DB = 'DB.fiat'
DBD = '.'
misc = []
Resample = None
WAV = 'wav'
Channel = None
Harmless = False

arglist = sys.argv[1:]
while arglist and arglist[0].startswith('-'):
	arg = arglist.pop(0)
	if arg == '':
		break
	elif arg == '--':
		break
	elif arg == '-channel':
		Channel = arglist.pop(0)
		# You can specify a channel here, or if it
		# begins with '@', then it specifies a variable
		# to look up in the header of the metadata file.
		# That variable then specifies the audio channel.
	elif arg == '-rewrite':
		Rewrite = M.makefile
	elif arg == '-harmless':
		CODE = ''
	elif arg == '-debug':
		M.set_debug()
	elif arg == '-resample':
		Resample = arglist.pop(0)
	elif arg == '-wav':
		WAV = arglist.pop(0)
	elif arg == '-j':
		CLUSTERSIZE = arglist.pop(0)
	elif arg == '-qmake':
		M.set_make_prog('qmake', '-V', '-cwd', '--')
	elif arg == '-db':
		DB = arglist.pop(0)
		DBD = os.path.dirname(DB)
	elif arg == '-dbav':
		DB = arglist.pop(0)
		DBD = os.path.dirname(DB)
		M.DB_format = 'avio'
	elif arg in ['-k', '-t']:
		misc.append(arg)
	elif arg == '-s':
		Selector = arglist.pop(0)	# Selecting a subset of the data.
	else:
		die.die("Unrecognized arg: %s" % arg)

if CLUSTERSIZE is None:
	M.makeflags.extend(['-j', M.ncpu()])
else:
	M.makeflags.extend(["-j", CLUSTERSIZE])

M.var('B', M.quote(B))
M.var('CODE', M.quote(CODE))

if Rewrite:
	M.var('REWRITE', M.quote(Rewrite))

M.var('WAV', M.quote(WAV))

all1 = []
all2 = []
metaheader, metadata = M.read(DB)
for d in g2_select.filter_iter(Selector, metadata):
	all1.append(os.path.join(DBD, d['d'], d['f'], 'raw.dat'))
	all2.append(os.path.join(DBD, d['d'], d['f'], 'raw.wav'))
M.rule('all : %s' % (' '.join(all1)))
M.rule('all : %s' % (' '.join(all2)))

if Resample is not None:
	M.var('resample', M.quote(Resample))
	M.rule("%/raw.wav : %.$(WAV) $(REWRITE)",
			"mkdir -p $* && sox $*.$(WAV) -r $(resample) $@ polyphase"
		)

else:
	M.rule("%/raw.wav : %.$(WAV)",
			"mkdir -p $* && cd $* && ln -s ../$(notdir $*).$(WAV) raw.wav"
		)

if Channel is None:
	M.var('Channel', '')
elif Channel.startswith('@') and Channel[1:] in metaheader:
	M.var('Channel', '-c %s' % metaheader[Channel[1:]])
else:
	M.var('Channel', '-c %s' % Channel)

M.rule("%/raw.dat : %/raw.wav $(CODE) $(REWRITE)",
		"mkdir -p $* && $(B) $(Channel) $*/raw.wav $@"
	)

M.finish()
