+struct tag * tag_list(const char *tag, uint64_t offset, uint64_t *count, int direction) {
+ char filename[512];
+ struct stat st;
+ struct tag *taglist;
+ struct tag *retlist;
+ uint64_t n_tag_records;
+
+ switch(tag[0]) {
+ case '#':
+ snprintf(filename, 512, "%s/%s", HASH_TAGS_PATH, tag + 1);
+ break;
+ case '@':
+ snprintf(filename, 512, "%s/%s", AUTHOR_TAGS_PATH, tag + 1);
+ break;
+ default:
+ fprintf(stderr, "Invalid tag type: %s\n", tag);
+ return 0;
+ }
+
+ int tag_fd = open(filename, O_RDONLY, 0600);
+ if (tag_fd == -1) {
+ perror("Could not open tag file");
+ *count = 0;
+ return NULL;
+ }
+
+ fstat(tag_fd, &st);
+ if (st.st_size == 0) {
+ close(tag_fd);
+ *count = 0;
+ return NULL;
+ }
+ n_tag_records = st.st_size / sizeof(struct tag);
+ if (*count > n_tag_records)
+ *count = n_tag_records;
+ if (offset > n_tag_records) {
+ fprintf(stderr, "Cannot access tag record beyond end\n");
+ return NULL;
+ }
+
+ taglist = (struct tag *) mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, tag_fd, 0);
+ if (taglist == MAP_FAILED) {
+ perror("Could not mmap tag file");
+ goto tag_list_map_failed;
+ }
+ retlist = (struct tag *) malloc(sizeof(struct tag) * *count);
+ if (retlist == NULL) {
+ perror("Could not allocate memory for tag list");
+ goto tag_list_malloc_failed;
+ }
+ switch(direction) {
+ case 1:
+ memcpy(retlist, taglist + offset, sizeof(struct tag) * *count);
+ break;
+ case -1:
+ memcpy(retlist, taglist + (n_tag_records - *count - offset), sizeof(struct tag) * *count);
+ break;
+ }
+
+ munmap(taglist, st.st_size);
+ return retlist;
+
+tag_list_malloc_failed:
+ munmap(taglist, st.st_size);
+tag_list_map_failed:
+ close(tag_fd);
+tag_list_open_failed:
+ return NULL;