From 6e367459f78f0c19ab70911871bfa6b366ed9710 Mon Sep 17 00:00:00 2001
From: Antonio Ospite <ospite@studenti.unina.it>
Date: Wed, 20 Mar 2013 17:36:55 +0100
Subject: [PATCH 1/1] Allow saving the screen to an output file

---
 scrolling/sdl-scrolling.c | 37 +++++++++++++++++++++++++++++++++++--
 1 file changed, 35 insertions(+), 2 deletions(-)

diff --git a/scrolling/sdl-scrolling.c b/scrolling/sdl-scrolling.c
index 4f49e25..4b9475f 100644
--- a/scrolling/sdl-scrolling.c
+++ b/scrolling/sdl-scrolling.c
@@ -17,6 +17,10 @@
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */
 
+#include <unistd.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
 #include <errno.h>
 #include <SDL.h>
 #include <SDL_image.h>
@@ -70,8 +74,10 @@ int main(int argc, char *argv[])
 	Uint32 time_start;
 	Uint32 time_end;
 
-	if (argc != 2) {
-		fprintf(stderr, "usage: %s <image>\n", argv[0]);
+	int output_fd = -1;
+
+	if (argc < 2) {
+		fprintf(stderr, "usage: %s <image> [<output file>]\n", argv[0]);
 		return -EINVAL;
 	}
 
@@ -90,6 +96,20 @@ int main(int argc, char *argv[])
 		goto out;
 	}
 
+	/* Set up the output file */
+	if (argc >= 3) {
+		if (strncmp(argv[2], "-", 1) == 0) {
+			output_fd = STDOUT_FILENO;
+		} else {
+			output_fd = open(argv[2], O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
+			if (output_fd < 0) {
+				perror("open");
+				ret = output_fd;
+				goto out;
+			}
+		}
+	}
+
 	lastframe_limit = (map->h - HEIGHT);
 
 	if (SDL_NumJoysticks() > 0)
@@ -148,6 +168,16 @@ int main(int argc, char *argv[])
 		SDL_BlitSurface(map, &viewport, screen, NULL);
 		SDL_Flip(screen);
 
+		if (output_fd >= 0) {
+			int len = screen->w * screen->h * screen->format->BytesPerPixel;
+
+			ret = write(output_fd, screen->pixels, len);
+			if (ret != len) {
+				fprintf(stderr, "invalid write\n");
+				running = 0;
+			}
+		}
+
 		time_end = SDL_GetTicks();
 		if (time_end - time_start < 1000 / FPS)
 			SDL_Delay((1000 / FPS) - (time_end - time_start));
@@ -155,6 +185,9 @@ int main(int argc, char *argv[])
 
 	ret = 0;
 
+	if (output_fd >= 0)
+		close(output_fd);
+
 	if (SDL_JoystickOpened(0))
 		SDL_JoystickClose(joystick);
 
-- 
2.1.4