# MidiWrite.py
# This script writes format 0 midi file.
#
# Midi Record Start = Push Start Button
# Midi Record Stop = Push Stop Button
#

import struct
from buzz import *

timebase=480

midiout=None
time=0
strtime=0
strvalue=0
statrun=0
filestat=0
bpm,tpb,sps,spt,pit,tps=GetMasterInfo()

print "Pybuzz Pattern 2 Midi"

def statfmat():
	global midiout,time,strtime,strvalue,statrun,filestat,bpm,tpb,sps,spt,pit,tps
	
	midiout=None
	time=0
	strtime=0
	strvalue=0
	statrun=0
	filestat=0
	bpm,tpb,sps,spt,pit,tps=GetMasterInfo()

def OnParameter(track,index,value):
	global midiout,time,strtime,strvalue,statrun,filestat
	
	if(index==0):
		if(filestat==0):
			open_init()
			filestat=1
		strtime=time
		time=GetSongPosition()*timebase/tpb
		dtime=time-strtime
		varlen(dtime)
		if(value!=NOTE_OFF):
			if(statrun):
				midiout.write(struct.pack('BB',bn2mn(value),0x7F))
			else:
				midiout.write(struct.pack('BBB',0x90,bn2mn(value),0x7F))
				statrun=1
			strvalue=value
		else:
			midiout.write(struct.pack('BB',bn2mn(strvalue),0x00))
	print "[%02i] %i: %i" %(track,index,value)

def OnStop():
	global midiout,filestat
	
	if(filestat):
		endpos=midiout.tell()
		midiout.seek(18,0)
		midiout.write(struct.pack('>L',endpos-22+4))
		midiout.seek(0,2)
		midiout.write(struct.pack('BBBB',0x7F,0xFF,0x2F,0x00))
		midiout.close()
		statfmat()
		print "CLOSED"

def varlen(v):
	global midiout
	
	if(v<0x80):
		midiout.write(struct.pack('B',v))
	elif(v<0x4000):
		v1=v&0x7F
		v2=v>>7&0x7F|0x80
		midiout.write(struct.pack('BB',v2,v1))
	elif(v<0x200000):
		v1=v&0x7F
		v2=v>>7&0x7F|0x80
		v3=v>>14&0x7F|0x80
		midiout.write(struct.pack('BBB',v3,v2,v1))
	else:
		v1=v&0x7F
		v2=v>>7&0x7F|0x80
		v3=v>>14&0x7F|0x80
		v4=v>>21&0x7F|0x80
		midiout.write(struct.pack('BBBB',v4,v3,v2,v1))

def bn2mn(note):
	note-=1
	return 12*(note/16)+note%16

def open_init():
	global midiout
	
	midiout=open('kazuya.mid','wb')
	midiout.write(struct.pack('>L',0x4D546864))
	midiout.write(struct.pack('>L',0x00000006))
	midiout.write(struct.pack('>H',0x0000))
	midiout.write(struct.pack('>H',0x0001))
	midiout.write(struct.pack('>H',timebase))
	midiout.write(struct.pack('>L',0x4D54726B))
	midiout.write(struct.pack('>L',0x00000000))
	print "OPEN"

SetEventTarget("OnParameter",OnParameter)
SetEventTarget("OnStop",OnStop)

SetPeerCtrlName(0,"Useless")