#! /usr/bin/env ruby

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

require 'smf'
require 'smf/divert'
require 'gopt'
include  SMF

def usage
  warn 'usage: merge [-o output] [input]'
  exit 1
end

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

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

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

sq = unless ifile then Sequence.read($stdin) else Sequence.load(ifile) end
nsq = Sequence.new(0, sq.division, sq.tc)
eot = []
sq.each do |tr|
  tr.divert(nsq) do |ev|
    case ev
    when EndOfTrack; eot << ev; nil
    else; 0
    end
  end
end
nsq[0] << eot.max unless eot.empty?
unless ofile then nsq.write($stdout) else nsq.save(ofile) end
