#!/usr/bin/env python3

# print-MIDI-file.py : utility script to inspect the contents of a MIDI file

import argparse

# https://mido.readthedocs.io/en/latest/index.html
import mido

parser = argparse.ArgumentParser(description = "Read a MIDI file with mido and display all the messages.")
parser.add_argument('input', help='MIDI files to process.')
args = parser.parse_args()

mid = mido.MidiFile(args.input)
print(f"Opened MIDI file type {mid.type} from {args.input}")

print("Track list:")
for i, track in enumerate(mid.tracks):
    print(f'  Track {i} name: {track.name}')

print("Resolution: %d ticks per beat." % (mid.ticks_per_beat))

# assume a default 120 BPM tempo until overridden by a tempo MetaMessage
midi_tempo = 500000

for track in mid.tracks:
    print()
    print(f"Contents of track '{track.name}':")
    for msg in track:
        if msg.is_meta:
            print(repr(msg))

            if msg.type == 'set_tempo':
                print("--> Found tempo of %d usec/beat, %f BPM." % (msg.tempo, mido.tempo2bpm(msg.tempo)))
                midi_tempo = msg.tempo

        else:
            print("%s (%f seconds)" % (repr(msg), mido.tick2second(msg.time, mid.ticks_per_beat, midi_tempo)))
