/*
 * subconv.c - modificate subtitle timings to match another framerate
 * For now oly the MicroDVD subtitle format is supported
 *
 * TODO: 
 * - support and automaticaly recognize more subtitle formats
 * - automate regocnition of old framerate
 * - clean up some parts of the code
 * Changelog:
 * 1.0 - first version
 * Author: Ivan Petrushev <ivanatora@gmail.com>
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
	FILE *fh, *out;
	char newfilename[300];
	char buff[1024], temp[10], contents[1024], new_line[1024];	// some temporary char arrays
	int i, started = 0, c_started = 0, c_temp = 0, i_temp = 0, old_num, new_num1=0 , new_num2=0; // some indicators
	float old_fps, new_fps;
	int c = 0;	// line counter - why
	//printf("ARG[%d]: %s\n", argc, argv[1]);
	if (argc != 2){
		printf ("Usage: ./subconv filename\n");
		return 1;
	}
	fh = fopen(argv[1], "r");
	if (!fh){
		printf("Cant read from %s", argv[1]);
		return 1;
	}
	sprintf(newfilename, "New_%s", argv[1]);
	out = fopen(newfilename, "w");
	if (!out){
		printf("Can't open %s!", newfilename);
		return 1;
	}
	printf("Old framerate: ");
	scanf("%f", &old_fps);
	printf("New framerate: ");
	scanf("%f", &new_fps);
	printf("Changing times...\n");
	while (fgets(buff, 1024, fh)){		// get a line of subtitle file
		c++;
		printf("Line %d... ", c);
		//printf("%s", buff);
		for (i=0; i<1024; i++){		// parse the line
			if (buff[i] == '{') {	// start of a time
				started = 1;
				i_temp = 0;
			}
			else if (buff[i] == '}') {	// end of a time
				started = 0;
				c_started = 1;
				c_temp = 0;
				temp[i_temp] = '\0';
				old_num = atoi(temp);
				if (new_num1 == 0){	// end of the first time
					new_num1 = (old_num / old_fps) * new_fps;
				}
				else {			// end of the second time
					new_num2 = (old_num / old_fps) * new_fps;
				}
				printf("Found num: <%d> (1): %d (2)%d\n", old_num, new_num1, new_num2);
				old_num = 0;
			}
			else if (started == 1){		// in the middle of the time string
				temp[i_temp] = buff[i];
				i_temp++;
			}
			else if (c_started == 1){	// content part started - TODO: optimize this
				contents[c_temp] = buff[i];
				c_temp++;
				if (buff[i] == '\n'){
					contents[c_temp] = '\0';
					sprintf(new_line, "{%d}{%d} %s", new_num1, new_num2, contents);
					//printf("%s", new_line);
					fwrite(new_line, strlen(new_line), 1, out); 	// append line to the output file
					c_started = 0;
					new_num1 = 0;
					new_num2 = 0;
				}
			}
		}
		printf("done\n");
	}
	fclose(fh);
	fclose(out);
	//system("PAUSE");
	return 0;
}

