#!/bin/bash

makemkvcon info disc:0 > temp/info.txt

wait $!

awk 'function flush_print_maybe() {
         if (matching){
                 LC2 = length(buf)
                 if (LC2 > LC1){
                        LC1 = LC2
                        t = n
                        title = buf
                 }
                 printf("Grep Match = %d lines = %d\n%s\n", t, LC1, title)
                 n++
         }
         buf = ""
     }
     /Title / { flush_print_maybe(); matching = 1 }
     /^$/  { flush_print_maybe(); matching = 0 }
     matching { buf = (buf == "" ? $0 : buf ORS $0) }
     END   { flush_print_maybe() }' temp/info.txt | grep -A 1 'Grep' | tail -2 > temp/info2.txt

wait $!

TITLE=$(egrep -o '[0-9]+' temp/info2.txt | tail -1)
echo $TITLE

makemkvcon mkv --progress=-same disc:0 $TITLE mkvs
