#! /usr/bin/env ruby

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

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

def usage
  warn 'usage: groove [-o output] [-a amount] groove [input]'
  exit 1
end

usage unless opt = Gopt.gopt('o:a:')
usage unless $*.size >= 1 && $*.size <= 2

pat   = $*.shift

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

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

amount = (opt[:a] || '0.5').to_f

sq = unless ifile then Sequence.read($stdin) else Sequence.load(ifile) end

sp = IO.read(pat).scan(/\S+/).collect{|x| x.to_f}
gr = Groove.new(sq.division, sp)
gr.amount = amount

sq.each do |tr|
  tr.pop
  tr.each do |ev|
    case ev
    when NoteOff, NoteOn
      gr.groove(ev)
    end
  end
end
unless ofile then sq.write($stdout) else sq.save(ofile) end
