#!/usr/bin/env js

var fs = require( 'fs' )
var path = require( 'path' )
var argv = require( 'optimist' )
	.default({ base: '' })
	.alias({ base: 'b' })
	.argv

//var doT = require( 'doT' )
var DIR = path.dirname( path.dirname( process.argv[1] ) )
var doT = require( DIR + '/misc/js/doT.js' )

var readDone = 0
var readAll = 0
var allStarted = false

argv._.forEach( function( val, i ) { readItem( val ) } )
allStarted = true

function readItem( item )
{
	if ( fs.statSync( item ).isDirectory() )
	{
		var dir = item
		fs.readdirSync( dir ).forEach( function( item ){ readItem( path.join( dir, item ) ) } )
	} else
	{
		readFile( item )
	}
}

function readFile( file )
{
	++readAll
	fs.readFile( file, function( err, data )
	{
		if ( err )
		{
			process.stderr.write( 'Error reading file "' + file + '": ' + err + '\n' )
		} else
		{
			var id = path.basename( file, path.extname( file ) )
			if ( argv.base )
				id = path.relative( argv.base, path.dirname( file ) ).replace( /\//g, '.' ) + '.' + id
			var f = doT.compile( data )
			doT.addCached( id, f )
		}
		
		++readDone
		if ( allStarted && readDone == readAll )
			process.stdout.write( doT.exportCached() )
	} )
}

@@ -911,11 +911,21 @@
 %0A%09%09%09
-%09id
+%7B%0A%09%09%09%09var rel
  = p
@@ -993,16 +993,38 @@
 g, '.' )
+%0A%09%09%09%09rel && ( id = rel
  + '.' +
@@ -1026,17 +1026,37 @@
 '.' + id
+ )
 %0A
+%09%09%09%7D%0A%09%09%09try%0A%09%09%09%7B%0A%09
 %09%09%09var f
@@ -1077,17 +1077,19 @@
 ( data )
-%0A
+;%0A%09
 %09%09%09doT.a
@@ -1106,16 +1106,125 @@
 id, f )%0A
+%09%09%09%7D catch( err )%0A%09%09%09%7B%0A%09%09%09%09process.stderr.write( 'Error compiling file %22' + file + '%22: ' + err + '%5Cn' )%0A%09%09%09%7D%0A
 %09%09%7D%0A%09%09%0A%09

fix for relative path