/* movie.c */

#include <stdio.h>

#include "movie.h"
#include "render.h"
#include "camera.h"
#include "error.h"

unsigned moviemode, movieOptions;

static FILE *OpenFile(char *format, int iterationr)
{
	char filename[100];
	FILE *fp;

	sprintf(filename, format, iterationr);
	fp = fopen(filename, "w");

	if (!fp) 
		Error(NULL, "Can't open file '%s' for writing", filename);

	return fp;
}

void MovieSaveFrame(unsigned movieOptions, int iterationr, char *stats)
{
	FILE *fp;
	int rendermode = RenderGetMode();

	RenderSetOutlineDrawing(FALSE);
	RenderShowLinks(FALSE);

	if (movieOptions & MOVIE_SAVE_RADIANCE) {
		if ((fp = OpenFile("%04d-radiance.ppm", iterationr)) != (FILE *)NULL) {
			RenderSetMode(RENDER_RADIANCE);
			RenderScene();
			SaveScreen(fp);
			fclose(fp);
		}		
	}
 
	if (movieOptions & MOVIE_SAVE_UNSHOT_RADIANCE) {
		if ((fp = OpenFile("%04d-unshot-radiance.ppm", iterationr)) != (FILE *)NULL) {
			RenderSetMode(RENDER_UNSHOT_RADIANCE);
			RenderScene();
			SaveScreen(fp);
			fclose(fp);
		}		
	} 

	if (movieOptions & MOVIE_SAVE_IMPORTANCE) {
		if ((fp = OpenFile("%04d-importance.ppm", iterationr)) != (FILE *)NULL) {
			RenderSetMode(RENDER_IMPORTANCE);
			RenderScene();
			SaveScreen(fp);
			fclose(fp);
		}		
	} 

	if (movieOptions & MOVIE_SAVE_UNSHOT_IMPORTANCE) {
		if ((fp = OpenFile("%04d-unshot-importance.ppm", iterationr)) != (FILE *)NULL) {
			RenderSetMode(RENDER_UNSHOT_IMPORTANCE);
			RenderScene();
			SaveScreen(fp);
			fclose(fp);
		}		
	}

	if (movieOptions >= MOVIE_SAVE_ALT_RADIANCE && 
	    CameraAlternate(&Camera) != (CAMERA *)NULL) {

	if (movieOptions & MOVIE_SAVE_ALT_RADIANCE) {
		if ((fp = OpenFile("%04d-alt-radiance.ppm", iterationr)) != (FILE *)NULL) {
			RenderSetMode(RENDER_RADIANCE);
			RenderScene();
			SaveScreen(fp);
			fclose(fp);
		}		
	}
 
	if (movieOptions & MOVIE_SAVE_ALT_UNSHOT_RADIANCE) {
		if ((fp = OpenFile("%04d-alt-unshot-radiance.ppm", iterationr)) != (FILE *)NULL) {
			RenderSetMode(RENDER_UNSHOT_RADIANCE);
			RenderScene();
			SaveScreen(fp);
			fclose(fp);
		}		
	} 

	if (movieOptions & MOVIE_SAVE_ALT_IMPORTANCE) {
		if ((fp = OpenFile("%04d-alt-importance.ppm", iterationr)) != (FILE *)NULL) {
			RenderSetMode(RENDER_IMPORTANCE);
			RenderScene();
			SaveScreen(fp);
			fclose(fp);
		}		
	} 

	if (movieOptions & MOVIE_SAVE_ALT_UNSHOT_IMPORTANCE) {
		if ((fp = OpenFile("%04d-alt-unshot-importance.ppm", iterationr)) != (FILE *)NULL) {
			RenderSetMode(RENDER_UNSHOT_IMPORTANCE);
			RenderScene();
			SaveScreen(fp);
			fclose(fp);
		}		
	}

		CameraAlternate(&Camera);
	}

	if ((fp = OpenFile("%04d-stats", iterationr)) != (FILE *)NULL) {
		fprintf(fp, "%s", stats);
		fclose(fp);
	}

	RenderSetMode(rendermode);
}


