main.c (1856B)
1 #include<sqlite3.h> 2 #include<stdlib.h> 3 #include<stdio.h> 4 #include<string.h> 5 #include"bibleverse.h" 6 7 #define DB_NAME "/usr/local/share/bibleverse/bibleverse.db" 8 #define BOOK_NAME_LEN 200 9 10 static char* usage_err = "Usage: bibleverse <book> <chapter>[:verse[-verse]]\n"; 11 12 int main(int argc, char** argv) { 13 14 int is_book_numbered = 0; 15 sqlite3* db; 16 17 if(argc > 4 || argc < 3) { 18 fprintf(stderr, usage_err); 19 20 return 1; 21 } 22 23 int rc = sqlite3_open(DB_NAME, &db); 24 25 if(rc != SQLITE_OK) { 26 fprintf(stderr, "Cannot open database %s: %s\n", DB_NAME, sqlite3_errmsg(db)); 27 sqlite3_close(db); 28 29 return 1; 30 } 31 32 char book_name[BOOK_NAME_LEN] = {0}; 33 34 if(isNumber(argv[1])) { 35 is_book_numbered = 1; 36 snprintf(book_name, sizeof(book_name), "%s %s", argv[1], argv[2]); 37 } else { 38 snprintf(book_name, sizeof(book_name), "%s", argv[1]); 39 } 40 41 struct book* books = find_book(book_name, db); 42 43 if(books == NULL) { 44 fprintf(stderr, "\nFailed to find a requested book\n"); 45 sqlite3_close(db); 46 47 return 1; 48 } 49 50 char* verse_numbers = argv[2 + is_book_numbered]; 51 52 if(verse_numbers == NULL) { 53 fprintf(stderr, usage_err); 54 sqlite3_close(db); 55 56 return 1; 57 } 58 59 size_t verse_len = strlen(verse_numbers); 60 char* orig_verse_numbers = malloc(verse_len * sizeof(char*) + 1); 61 memcpy(orig_verse_numbers, verse_numbers, verse_len); 62 orig_verse_numbers[verse_len] = '\0'; 63 64 struct verse* ver = parse_verse_numbers(verse_numbers); 65 66 if(ver == NULL) { 67 fprintf(stderr, "Failed to parse the verse (range) \"%s\"\n", orig_verse_numbers); 68 free(orig_verse_numbers); 69 sqlite3_close(db); 70 71 return 1; 72 } 73 74 rc = print_verses(books[0].id, books[0].name, ver, db); 75 76 free(orig_verse_numbers); 77 free(books[0].name); 78 free(books); 79 free(ver); 80 81 if(rc) { 82 fprintf(stderr, "Failed to print requested verse(s)\n"); 83 sqlite3_close(db); 84 85 return 1; 86 } 87 88 sqlite3_close(db); 89 90 return 0; 91 } 92