From 0a13ff9a4815d1ad07f9655d1d662dd9e0a284f0 Mon Sep 17 00:00:00 2001
From: David Phillips <dbphillipsnz@gmail.com>
Date: Mon, 6 Jul 2015 11:47:24 +1200
Subject: Specify custom filename format

---
 README.md       |  9 ++++-----
 cue-bin-split.c | 19 ++++++++++++++++---
 2 files changed, 20 insertions(+), 8 deletions(-)

diff --git a/README.md b/README.md
index bddd675..c88c66a 100644
--- a/README.md
+++ b/README.md
@@ -11,8 +11,6 @@ Warning
 -------
 Try running `grep -i FIXME *.c`
 
-**This will overwrite any existing file with the same name as an output file**
-
 
 Sample Usage
 ------------
@@ -20,7 +18,8 @@ Assuming you want to use the first indices of each track as a boundary,
 
 	grep "INDEX 01" cue-file | \
 	  sed -e 's/INDEX 01//g' | \
-	  cue-bin-split raw-file channels samples-rate bytes-per-sample
+	  cue-bin-split raw-file channels samples-rate bytes-per-sample name-format
 
-will output a bunch of files track_0001 through track_nnnn.
-You might then push them through ffmpeg or something to get them to another format.
+Where format is something like `track_%04d`.
+This will output a bunch of files named accordingly.
+You might then push them through ffmpeg or something to get them to another audio format.
diff --git a/cue-bin-split.c b/cue-bin-split.c
index 69423ae..0a1e7ab 100644
--- a/cue-bin-split.c
+++ b/cue-bin-split.c
@@ -33,8 +33,9 @@ int main(int argc, char **argv)
 {
 	FILE *fin = NULL;
 	FILE *fout = NULL;
+	char *format = NULL;
 	char *in_fname = NULL;
-	char out_fname[] = "track-0000";
+	char out_fname[] = "track-000000000000"; /* That should do it */
 	int m = 0;
 	int s = 0;
 	int frame = 0;
@@ -53,17 +54,19 @@ int main(int argc, char **argv)
 
 	/* FIXME Use getopt */
 	/* FIXME Replace assertions with useful checks+messages */
-	assert(argc == 5);
+	assert(argc == 6);
 
 	in_fname = argv[1];
 	channels = atoi(argv[2]);
 	rate = atoi(argv[3]);
 	sample_size = atoi(argv[4]);
+	format = argv[5];
 
 	assert(channels > 0);
 	assert(rate > 0);
 	assert(sample_size > 0);
 	assert(in_fname != NULL);
+	assert(format != NULL);
 
 	/* Open it up */
 	if ((fin = fopen(in_fname, "r")) == NULL)
@@ -83,13 +86,22 @@ int main(int argc, char **argv)
 	while ( ( items = fscanf(stdin, "%d:%d:%d\n", &m, &s, &frame) ) )
 	{
 		index++;
-		sprintf(out_fname, "track_%04d", index);
+
+		i = snprintf(out_fname, sizeof(out_fname), format, index);
+		if (i == sizeof(out_fname))
+		{
+			fprintf(stderr, "Filename too large for buffer\n");
+			fclose(fin);
+			return EXIT_FAILURE;
+		}
+
 
 		/* Open output file */
 		if ((fout = fopen(out_fname, "w")) == NULL)
 		{
 			fprintf(stderr,"Failed to open '%s': ", out_fname);
 			perror("fopen");
+			fclose(fin);
 			return EXIT_FAILURE;
 		}
 
@@ -148,5 +160,6 @@ int main(int argc, char **argv)
 		if (finish < 0)
 			break;
 	}
+	return 0;
 }
 
-- 
cgit v1.1