cammy/bin/import.c

120 lines
2.6 KiB
C
Raw Normal View History

#include <stdio.h>
#include <stdlib.h>
2016-07-06 17:12:47 -05:00
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <cammy/photo.h>
#include <cammy/sram.h>
#include "pnglite.h"
#include "commands.h"
2016-07-06 17:12:47 -05:00
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: %1$s import file.sav 1..30 input.png\n", argv[0]);
exit(1);
}
int cammy_import(int argc, char **argv) {
cammy_sram *sram;
png_t *png;
int photo = 0;
uint8_t *buf;
int error;
if (argc < 3) {
2016-07-06 17:12:47 -05:00
usage(argc, argv, "No save file provided");
} else if (argc < 4) {
2016-07-06 17:12:47 -05:00
usage(argc, argv, "No photo number provided");
} else if (argc < 5) {
2016-07-06 17:12:47 -05:00
usage(argc, argv, "No photo provided");
}
photo = atoi(argv[3]);
if (photo < 1 || photo > CAMMY_SRAM_PHOTO_COUNT) {
2016-07-06 17:12:47 -05:00
usage(argc, argv, "Invalid photo number");
}
if ((sram = cammy_sram_open(argv[2])) == NULL) {
fprintf(stderr, "%s: %s: %s: %s\n",
argv[0], "cammy_sram_open()", argv[2], 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[4])) < 0) {
fprintf(stderr, "%s: %s: %s: %s\n",
argv[0], "png_open_file_read()", argv[4], 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[4], "Invalid image dimensions");
goto error_invalid_dimensions;
}
if ((buf = malloc(png->width * png->height * png->bpp)) == NULL) {
fprintf(stderr, "%s: %s: %s\n",
argv[0], "malloc()", strerror(errno));
goto error_malloc_buf;
}
if ((error = png_get_data(png, buf)) < 0) {
fprintf(stderr, "%s: %s: %s: %s\n",
argv[0], "png_get_data()", argv[4], 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_malloc_buf:
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;
}