
var gMidiToI1Params;
{
#include "../omino_adobe_script_suite/src/shared/ominoDialogMaker.jsx"
#include "midi_reader.jsx"
 
 

function layerByName(layers,name)
{
    var i;
    for(i = 0; i < layers.length; i++)
    {
        var layer = layers[i];
        if(layer.name == name)
            return layer;
    }
    return null;
}



function newLayer(doc,baseName)
{
	var n = 0;
	var result = null;
	while(result == null)
	{
		n++;
		var aName = "" + baseName + n;
		var existingLayer = layerByName(doc.layers,aName);
		if(existingLayer == null)
		{
			result = doc.layers.add();
			result.name = aName;
		}
	}
	return result;
}



function addP(points,x,y)
{
	var p = points.add();
	p.anchor = [x,y];
	p.leftDirection = p.anchor;
	p.rightDirection = p.anchor;
}


function go()
{
	
	// setting up a dialog is easy. you can add entries for basic types of
	// string and number, and checkbox and radio buttons, and the 
	// dialog is presented reasonably, with very little work.
	
	var omd = newOminoDialog("Midi File To Illustrator 1");

//	omd.boxedText(5,"This script reads a MIDI file, and generates \n"
//		+ "control text for it, matching note-on velocities to \n"
//		+ "letters a-z.");
	omd.number("width per beat","width",12);
	omd.number("height per Channel","height",32);
	omd.openFile("midi file","midiFileName","","Choose a MIDI File",".mid");
 
	// when we "run" the dialog, we get back a result variable.
	// if you hit CANCEL, then the result is null.
	// if you hit OK, then the values are populated into the result.
	
	// note: you can kill photoshop by running the dialog from ExtendScript toolkit, then halting
	// the script with the dialog still up.
	
	omd.set(gMidiToI1Params);
	var result = omd.run();
	
	if(result == null)
		alert("Cancelled\nYou clicked \"cancel\".");
	else
	{
		gMidiToI1Params = result;

		midiFile = new MidiFile(result.midiFileName);
		var layer = newLayer(app.documents[0],"midi");
		
//		var ch = midiFile.channels[16];
		var x = 0;
		var y = 0;
		for(var i in midiFile.channels)
		{

			var ch = midiFile.channels[i];
			var notes = ch.notes;
			var lastBeats = -100;
			var points;

			for(var i = 0; i < notes.length; i++)
			{
				var note = notes[i];
				if(note.vel == 0)
					continue;
				
				var beats = note.beats;
				if(beats - lastBeats > 2)
				{
					var pathItem = layer.pathItems.add();
					pathItem.closed = false;
					points = pathItem.pathPoints; // brand new, empty
				}

				
				var cx = x + result.width * note.beats;
				var kk = 12;
				var cy = y + (note.pitch % kk) * result.height / 12;

				addP(points,cx,cy);
				lastBeats = beats;
			}
			y += result.height;
		}
		
	}
}

go();
}