#include <stdio.h>
#include <acl/file.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>

#define panicio	{\
	perror(*filepath);\
	return 1;\
}
#define getNumber strtol(nextnumber + 1, &nextnumber, 10)

struct hotel {
	uint_least16_t minutes;
	uint_least8_t rating;
};

int main(int argc, char *argv[]) {
	for(char **filepath = argv + 1; filepath - argv < argc; ++filepath) {
		printf("%s:\n", *filepath);
		uint_least16_t numberHotels, totalMinutes;
		struct hotel *hotels;
		{
			char *inputText;
			{
				FILE *inputFile = fopen(*filepath, "rb");
				if(inputFile == NULL) panicio;
				bool success;
				inputText = acl_ReadTextFile(inputFile, &success);
				if(!success) panicio;
				fclose(inputFile);
			}
			{
				char *nextnumber;
				numberHotels = strtol(inputText, &nextnumber, 10) + 1;
				totalMinutes = getNumber;
				hotels = malloc(numberHotels * sizeof *hotels);
				for(uint_least16_t i = 0; i < numberHotels; ++i) {
					hotels[i].minutes = getNumber;
					hotels[i].rating = 10 * getNumber;
					hotels[i].rating += getNumber;
				}
				hotels[numberHotels - 1] = (struct hotel){ .minutes = totalMinutes, .rating = 50};
			}
			free(inputText);
		}
		{
			struct hotel hotelRoute[4];
			uint_least8_t stoppedHotels;
			{
				uint_least8_t rating = 50;
				do {
					uint_least16_t lastHotelMinutes = 0;
					struct hotel *possibleStop = NULL;
					stoppedHotels = 0;
					for(struct hotel *currentHotel = hotels; currentHotel - hotels < numberHotels; ++currentHotel) {
						if(currentHotel->minutes - lastHotelMinutes > 360) {
							if(possibleStop == NULL || stoppedHotels >= 4) break;
							hotelRoute[stoppedHotels] = *possibleStop;
							lastHotelMinutes = possibleStop->minutes;
							currentHotel = possibleStop;
							++stoppedHotels;
						}
						if(currentHotel->rating >= rating) possibleStop = currentHotel;
					}
					--rating;
				} while(rating && (!stoppedHotels || totalMinutes - hotelRoute[stoppedHotels - 1].minutes > 360));
			}
			for(struct hotel *hotelPrint = hotelRoute; hotelPrint - hotelRoute < stoppedHotels; ++hotelPrint) {
				printf("Entfernung vom Start: %" PRIuLEAST16 " Minuten, Bewertung: %" PRIuLEAST8 "\n", hotelPrint->minutes, hotelPrint->rating);
			}
		}
		free(hotels);
	}
}
