#include "IZ_midi.h"

char* IZ_MIDIGetNoteName(unsigned char midi_note) {
	static const char* pitch_names[] = {
		"C",
		"C#",
		"D",
		"D#",
		"E",
		"F",
		"F#",
		"G",
		"G#",
		"A",
		"A#",
		"B"
	};

	const unsigned char pitch_class = midi_note % 12;
	const unsigned char octave = midi_note / 12;
	static char note_name[8];
	sprintf(note_name, "%s%u", pitch_names[pitch_class], octave);
	return note_name;
}

unsigned char IZ_MIDIGetNoteFromName(const char* name) {
	char name_copy[8];
	IZ_strlwr(name_copy, name, 8);

	unsigned char octave;
	const char base_pitch_name[] = "c d ef g a b";

	if (strlen(name_copy) == 2) {
		octave = name_copy[1] - '0';
		unsigned char pitch_index;
		for (pitch_index = 0; pitch_index < 12; pitch_index += 1) {
			if (base_pitch_name[pitch_index] == name_copy[0]) {
				return (octave * 12) + pitch_index;
			}
		}
		return 255u; // invalid note value
	}

	unsigned char pitch_class;
	octave = name_copy[2] - '0';
	if (strstr(name_copy, "c#") || strstr(name_copy, "db")) {
		pitch_class = 1;
	} else if (strstr(name_copy, "d#") || strstr(name_copy, "eb")) {
		pitch_class = 3;
	} else if (strstr(name_copy, "f#") || strstr(name_copy, "gb")) {
		pitch_class = 6;
	} else if (strstr(name_copy, "g#") || strstr(name_copy, "ab")) {
		pitch_class = 8;
	} else if (strstr(name_copy, "a#") || strstr(name_copy, "bb")) {
		pitch_class = 10;
	} else {
		return 255u;
	}

	return (octave * 12) + pitch_class;
}
