// mkmus
//
// This program takes two arguments:
//  - Path to a list of files to injest
//  - Path to output file
//
// and makes a valid EA SND .MUS file out of it.
//

#include <iostream>
#include <fstream>
#include <string>

#define VERBOSE
#define ALIGN_TO_DWORD(offset) ((offset + 3) & ~3)

auto tell_size(std::ifstream& ifs) {
	auto old = ifs.tellg();
	ifs.seekg(0, std::ifstream::end);
	auto len = ifs.tellg();
	
	ifs.seekg(old, std::ifstream::beg);
	return len;
}

int main(int argc, char** argv) {
	if(argc != 3) {
		std::cout << "Usage: " << argv[0] << " [listfile] [output MUS file]\n";
		return 1;
	}
	
	std::ifstream list_input(argv[1]);
	std::ofstream mus_output(argv[2], std::ofstream::binary);
	auto written_bytes = 0;
	
	
	if(!list_input) {
		std::cout << "Could not open list - exiting.\n";
		return 1;
	}
	
	std::string file;
	
	while(std::getline(list_input, file)) {
#ifdef VERBOSE
		std::cout << "Processing " << file << " ...\n";
#endif
		std::ifstream asf_ifs(file, std::ifstream::binary);
		
		if(!asf_ifs) {
			std::cout << "Could not open ASF file - exiting.\n";
			return 1;
		}
		
		// Concat the asf into the file
		char buf[4096]{};
		while(asf_ifs) {
			asf_ifs.read(&buf[0], 4096);
			auto real_len = asf_ifs.gcount(); // real amount of bytes read
			std::cout << "really read " << real_len << "bytes from file " << file << '\n';
			mus_output.write(&buf[0], real_len);
		}
			
		// Align to DWORD boundary
		mus_output.seekp(ALIGN_TO_DWORD((int)mus_output.tellp()), std::ofstream::beg);
	}
	
	std::cout << "Done, i hope?\n";
	return 0;
}
