/****************************************************************************
	This program reads any number of track times (in mins and secs) 
      and allocates them to a CD with maximum time 74 minutes.
	The list of times is terminated by end of file.
	e.g. three tracks with times 2:30, 1:52 and 4:15:

	2:30
	1:52
	4:15
	
	It prints a track list of selected tracks and the total time for the CD:

	Track 1 ( 2:30 )
	Track 2 ( 1:52 )
	Track 3 ( 4:15 )
	Total time: 8:37
	WARNING: All tracks are allocated
	This last message only occurs if the total time of all tracks is less
      than 74 mins.
*******************************************************************************/

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

#define MAXTRACKS 100

void readTrackTimes(int []);
int findNextTrack(int []);
void printAllocation(int [], int [], int);

void readTrackTimes(int times[]) {
	char fn[256];
	FILE* data;
	int mins, secs, track = 0;
	int flag = 0;

	printf("File name? ");
	scanf("%s", fn);
	if ((data = fopen(fn, "r")) == NULL) {
		printf("File not found\n");
		exit(1);
	}
	do {
		flag = fscanf(data, "%d:%d", &mins, &secs);
		if (flag == 2)
			times[track++] = mins * 60 + secs;
	} while (flag != EOF);
		
}





int findNextTrack(int times[]) {
	int track = 0;
	int longest = 0;
	int index = -1;

	while (times[track] != 0) {
		if (times[track] > longest) {
			longest = times[track];
			index = track;
		}
		++track;
	}
	return index;
}

void printAllocation(int times[], int used[], int total) {
	int track = 0;
	int trackNum = 0;

	while (times[track] != 0) {
		if (used[track] == 1) {
			printf("Track %d (%d:%02d)\n",
					++trackNum, times[track] / 60,
					times[track] % 60);
		}
		++track;
	}

	printf("Total time: %d:%02d\n", total / 60, total %60);
	if (track == trackNum)
		printf("WARNING: All files allocated\n");
}

int main() {
	int trackTimes[MAXTRACKS] = { 0 };
	int trackUsed[MAXTRACKS] = { 0 };
	int track;
	int timeUsed = 0;

	readTrackTimes(trackTimes);
	while ((track = findNextTrack(trackTimes)) != -1) {
		if (track == -1 ||
			timeUsed + trackTimes[track] > 74 * 60)
			break;
		trackUsed[track] = 1;
		timeUsed += trackTimes[track];
		++track;
	}

	printAllocation(trackTimes, trackUsed, timeUsed);

	return 0;
}

