// cell build – Compile all .cm and .ce files to bytecode

var io = use('io')
var js = use('js')
var time = use('time')

var build_root = '.cell/build'

log.console("Building scripts...")

var now = time.number()

// Find and compile all .cm and .ce files from root
var files = io.globfs(['**/*.cm', '**/*.ce', '!**/*.git', '!**/*.cell', '!**/subprojects'], '')

var compiled_count = 0
var error_count = 0

for (var file of files) {
  var src = io.slurp(file)
  var fullpath = io.realdir(file) + "/" + file
  var outpath = build_root + fullpath
  io.mkdir(outpath.substring(0, outpath.lastIndexOf('/')))
  var mod_name = file
    .replace(/\.(cm|ce)$/, '')
    .replace(/[\/\-.]/g, '_')
    
  var src_content = io.slurp(file)
    
  var wrapped = '(function ' + mod_name + '(arg){' + src_content + '})'
  try {
    var compiled = js.compile(file, wrapped)
    var blob = js.compile_blob(compiled)
    io.slurpwrite(outpath, blob)
    compiled_count++
  } catch(e) {
    log.error(e)
    error_count++
  }
}

log.console("Build complete: " + compiled_count + " files compiled in " + (time.number()-now) + " seconds")
if (error_count > 0) {
  log.console("  " + error_count + " errors")
}

$_.stop()
