#! /usr/bin/env ruby

# quantize.rb: Written by Tadayoshi Funaba 1999-2006
# $Id: quantize.rb,v 1.10 2006-11-10 21:57:06+09 tadf Exp $

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

def usage
  warn 'usage: quantize [-o output] [-u n/d] [input]'
  exit 1
end

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

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

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

n, d = (opt[:u] || '1/32').split('/')
unit = n.to_f / (d || '1').to_f

sq = unless ifile then Sequence.read($stdin) else Sequence.load(ifile) end
qu = Quantize.new(sq.division, unit)

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