cammy/bin/main.c
2016-05-15 23:23:05 -05:00

121 lines
2.6 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <errno.h>
#include "pnglite.h"
#include <cammy/sram.h>
#include <cammy/photo.h>
static void usage(int argc, char **argv, const char *message, ...) {
if (message) {
va_list args;
va_start(args, message);
vfprintf(stderr, message, args);
va_end(args);
fprintf(stderr, "\n");
}
fprintf(stderr, "usage: %s file.sav photo1..30 photo.png\n", argv[0]);
exit(1);
}
static inline uint8_t *buf_malloc(png_t *png) {
return malloc(4 * png->width * png->height);
}
int main(int argc, char **argv) {
cammy_sram *sram;
png_t *png;
int photo = 0;
uint8_t *buf;
int error;
if (argc < 2) {
usage(argc, argv, "No save file provided");
} else if (argc < 3) {
usage(argc, argv, "No photo number provided");
} else if (argc < 4) {
usage(argc, argv, "No photo provided");
}
photo = atoi(argv[2]);
if (photo < 1 || photo > CAMMY_SRAM_PHOTO_COUNT) {
usage(argc, argv, "Invalid photo number");
}
if ((sram = cammy_sram_open(argv[1])) == NULL) {
fprintf(stderr, "%s: %s: %s: %s\n",
argv[0], "cammy_sram_open()", argv[1], strerror(errno));
goto error_sram_open;
}
png_init(malloc, free);
if ((png = malloc(sizeof(*png))) == NULL) {
goto error_malloc_png;
}
if ((error = png_open_file_read(png, argv[3])) < 0) {
fprintf(stderr, "%s: %s: %s: %s\n",
argv[0], "png_open_file_read()", argv[3], png_error_string(error));
goto error_png_open_file_read;
}
if (png->width != CAMMY_PHOTO_WIDTH
|| png->height != CAMMY_PHOTO_HEIGHT) {
fprintf(stderr, "%s: %s: %s\n",
argv[0], argv[3], "Invalid image dimensions");
goto error_invalid_dimensions;
}
if ((buf = buf_malloc(png)) == NULL) {
fprintf(stderr, "%s: %s: %s\n",
argv[0], "malloc()", strerror(errno));
goto error_buf_malloc;
}
if ((error = png_get_data(png, buf)) < 0) {
fprintf(stderr, "%s: %s: %s: %s\n",
argv[0], "png_get_data()", argv[3], png_error_string(error));
goto error_png_get_data;
}
cammy_photo_import(&sram->data->photos[photo-1], buf, (int)png->bpp);
free(buf);
png_close_file(png);
free(png);
cammy_sram_close(sram);
return 0;
error_png_get_data:
free(buf);
error_buf_malloc:
error_invalid_dimensions:
png_close_file(png);
error_png_open_file_read:
free(png);
error_malloc_png:
cammy_sram_close(sram);
error_sram_open:
return 1;
}