<?php
/**
 * Convert text file with list of tracks to CUE definitions.
 *
 * Usage:

 * ```shell
 * php cue.php FILENAME [START_INDEX]
 * ````
 *
 * Writes new file named FILENAME.cue
 *
 * In the input file each line should be in the format:
 * minutes:seconds performer - title
 *
 * Colon between munutes and seconds and space-dash-space between performer and title are mandatory.
 *
 * Non-well-formed lines are ignored.
 * In the output file there'll be the following block of data for each well-formed line:
 *
 * TRACK ## AUDIO
 *   PERFORMER "performer"
 *   TITLE "title"
 *   INDEX 01 minutes:seconds:00
 *
 * which corresponds to proper CUE format.
 *
 * Note that you MUST add the proper header to the resulting file --- only tracks are being inserted.
 * ## will be replaced by auto incremented number starting from START_INDEX.
 */
$lines = file($argv[1]);

$outfile = fopen($argv[1] . ".cue", "w");
$counter = isset($argv[2]) ? intval($argv[2]) : 1;
foreach ($lines as $line)
{
    $pattern = '/^'
             . '(?<hours>[[:digit:]:]{1,2}:)?'
             . '(?<minutes>[[:digit:]]{2}):'
             . '(?<seconds>[[:digit:]]{2})'
             . '\s+' // whitespace mandatory
             . '(?<performer>[^-]+)' // any char in performer name except dash
             . '\s+-\s+' // space, dash, space separates performer and title
             . '(?<title>.+)$/';
    $data = [];
    $matched = preg_match($pattern, $line, $data);
    print_r($data);
    if (!$matched)
        continue;

    $performer = $data['performer'];
    $title = $data['title'];
    $seconds = intval($data['seconds']);
    $minutes = intval($data['minutes']);

    if (isset($data['hours']))
        $minutes += intval($data['hours']) * 60;

    fprintf($outfile, "  TRACK %02d AUDIO\n", $counter);
    fprintf($outfile, "    PERFORMER \"%s\"\n", $performer);
    fprintf($outfile, "    TITLE \"%s\"\n", $title);
    fprintf($outfile, "    INDEX 01 %02d:%02d:00\n", $minutes, $seconds);
    fprintf($outfile, "\n");
    ++$counter;
}

fclose($outfile);
