#! /usr/bin/env ruby

# velcomp.rb: Written by Tadayoshi Funaba 2005,2006
# $Id: velcomp.rb,v 1.3 2006-11-10 21:57:06+09 tadf Exp $

require 'smf'
require 'smf/toy/velcomp'
require 'gopt'
include  SMF

def usage
  warn 'usage: velcomp [-o output] [-g gain] [-t thresh] [-r ratio] [input]'
  exit 1
end

usage unless opt = Gopt.gopt('o:g:t:r:')
usage unless $*.size >= 0 && $*.size <= 1

ifile = $*.shift
ifile = nil if ifile == '-'

ofile = opt[:o] if opt[:o]
ofile ||= File.basename(ifile, '.mid') + '-velcomp.mid' if ifile
ofile = nil if ofile == '-'

g = (opt[:g] || '0').to_f
t = (opt[:t] || '80').to_f
r = (opt[:r] || '0.9').to_f

sq = unless ifile then Sequence.read($stdin) else Sequence.load(ifile) end
vc = VelComp.new
vc.gain = g
vc.thresh = t
vc.ratio = r

sq.each do |tr|
  tr.pop
  tr.each do |ev|
    case ev
    when NoteOn
      vc.velcomp(ev)
    end
  end
end
unless ofile then sq.write($stdout) else sq.save(ofile) end
