From 1a91764c1692ebdcd14ee8de1b12a2161be2194e Mon Sep 17 00:00:00 2001 From: Patrick McDermott Date: Thu, 18 Jul 2019 14:20:09 -0400 Subject: main(): Add option parsing --- diff --git a/src/main.c b/src/main.c index 86c2f95..6825179 100644 --- a/src/main.c +++ b/src/main.c @@ -20,6 +20,8 @@ */ #include +#include +#include #include "font.h" #include "i18n.h" @@ -30,20 +32,67 @@ int main(int argc, char **argv) { struct font *font; + int w; + int h; + int opt; + char *end; + const char *input; + const char *output; FILE *fp; struct text *text; struct image *image; - if (argc != 4) { + font = NULL; + w = 0; + h = 0; + while ((opt = getopt(argc, argv, "f:w:h:")) != -1) { + switch (opt) { + case 'f': + font = font_find(optarg); + if (!font) { + printf(_("Font \"%s\" not found\n"), + optarg); + return 1; + } + break; + case 'w': + w = strtol(optarg, &end, 10); + if (*optarg == '\0' || *end != '\0' || w <= 0) { + printf(_("Width must be an integer " + "greater than " + "0\n")); + return 1; + } + break; + case 'h': + h = strtol(optarg, &end, 10); + if (*optarg == '\0' || *end != '\0' || h <= 0) { + printf(_("Height must be an integer " + "greater than " + "0\n")); + return 1; + } + break; + default: + printf(_("Invalid option\n")); + return 1; + } + } + argc -= optind; + if (argc != 2) { return 1; } + if (!font) { + font = font_default(); + } + input = argv[optind++]; + output = argv[optind++]; - font = font_find(argv[1]); - if (strcmp(argv[2], "-") != 0) { - fp = fopen(argv[2], "r"); + if (strcmp(input, "-") != 0) { + fp = fopen(input, "r"); if (!fp) { printf(_("Error: Cannot open \"%s\" for reading\n"), - argv[2]); + input); return 1; } } else { @@ -53,9 +102,13 @@ main(int argc, char **argv) if (fp != stdin) { fclose(fp); } - text_set_width(text, 80); - text_set_height(text, 25); - image = image_new(argv[3]); + if (w > 0) { + text_set_width(text, w); + } + if (h > 0) { + text_set_height(text, h); + } + image = image_new(output); image_render(image, text, font); text_destroy(&text); image_destroy(&image); -- cgit v0.9.1