/* mkcue.cc - make a cue sheet
 * This program is in the public domain.
 */

static char ident[] =
"$Id: mkcue.cc 1724 2004-10-27 06:20:30Z epg $\n"
"$URL: svn+ssh://diplodocus.org/svn/projects/release/mkcue-1/mkcue.cc $";

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "diskid.h"

void
DiskId::ReportError(char *err)
{
    fprintf(stderr, "%s\n", err);
    exit(2);
}

int
main(int argc, char *argv[])
{
    int ch, trackcount;
    DiskId diskid;
    MUSICBRAINZ_CDINFO cdinfo = { 0 };
    int track, minutes, seconds, sectors;

    trackcount = 99;
    while ((ch = getopt(argc, argv, "t:v")) != -1) {
        switch (ch) {
        case 't':
            trackcount = strtol(optarg, NULL, 10);
            if (trackcount < 1 || trackcount > 99) {
                fprintf(stderr, "invalid track-count %s\n", optarg);
                exit(2);
            }
            break;
        case 'V':
            puts(ident);
            exit(0);
        case '?':
            fputs("mkcue [-t track-count] [device]\n", stderr);
            exit(2);
        }
    }
    argv += optind;

    if (argv[0]) {
        diskid.ReadTOC(argv[0], cdinfo);
    } else {
        diskid.ReadTOC(NULL, cdinfo);
    }

    puts("FILE \"dummy.wav\" WAVE");
    puts("  TRACK 01 AUDIO");
    puts("    INDEX 01 00:00:00");

#define min(x, y) ((x) < (y) ? (x) : (y))
    for (track = cdinfo.FirstTrack + 1;
         track <= min(trackcount, cdinfo.LastTrack);
         track++) {
        /* There is frequently (always?) an offset of 150 sectors, so
         * subtract the first track's offset. */
        cdinfo.FrameOffset[track] -= cdinfo.FrameOffset[1];

        minutes = seconds = sectors = 0;
        sectors = cdinfo.FrameOffset[track] % 75;
        if (cdinfo.FrameOffset[track] >= 75) {
            seconds = cdinfo.FrameOffset[track] / 75;
            if (seconds >= 60) {
                minutes = seconds / 60;
                seconds = seconds % 60;
            }
        }

        printf("  TRACK %02d AUDIO\n", track);
        printf("    INDEX 01 %02d:%02d:%02d\n", minutes, seconds, sectors);
    }

    return 0;
}
