
#include <dirent.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include <inttypes.h>
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>

#include "filelist.h"
#include "fizmo.h"
#include "tracelog.h"
#include "babel.h"
#include "iff.h"
#include "types.h"
#include "config.h"

static int nof_files_found;
static int nof_files_searched;
static int nof_directories_searched;

static char *serial_input = NULL;
static int serial_input_size = 0;
static char *title_input = NULL;
static int title_input_size = 0;
static char *author_input = NULL;
static int author_input_size = 0;
static char *description_input = NULL;
static int description_input_size = 0;
static char *filename_input = NULL;
static int filename_input_size = 0;
static char *blorbfile_input = NULL;
static int blorbfile_input_size = 0;
static char *filetype_input = NULL;
static int filetype_input_size = 0;

static char *unquoted_serial_input = NULL;
static char *unquoted_title_input = NULL;
static char *unquoted_author_input = NULL;
static char *unquoted_description_input = NULL;
static char *unquoted_filename_input = NULL;
static char *unquoted_blorbfile_input = NULL;
static char *unquoted_filetype_input = NULL;

static char filetype_raw[] = "raw";
static char filetype_zblorb[] = "zblorb";

static uint16_t release_input;
static long storyfile_timestamp_input;
static int length_input;
static uint16_t checksum_input;
static int version_input;
FILE *in;
static int nof_files_searched;
static bool show_progress = false;


// 1,268,210 files in 243,656 directories.

void new_file_searched(char *filename, char *UNUSED(dirname))
{
  float percentage;

  if (filename != NULL)
  {
    nof_files_searched++;
    percentage = ((double)nof_files_searched / (double)nof_files_found) * 100;
    printf("\rUpdating story-list, scanning %d files, %3.0lf%% done.",
        nof_files_found, percentage);
    fflush(stdout);
    //printf("file:%s\n", filename);
  }
  else
  {
    nof_directories_searched++;
    //printf("%s (%d)\n", dirname, nof_directories_searched);
  }

  if ( (nof_files_searched != 0) && (nof_files_searched % 100 == 0) )
  {
    //printf("%d files.\n", nof_files);
  }
}


void free_unquote_buffers()
{
  if (unquoted_serial_input != NULL)
  {
    free(unquoted_serial_input);
    unquoted_serial_input = NULL;
  }
  if (unquoted_title_input != NULL)
  {
    free(unquoted_title_input);
    unquoted_title_input = NULL;
  }
  if (unquoted_author_input != NULL)
  {
    free(unquoted_author_input);
    unquoted_author_input = NULL;
  }
  if (unquoted_description_input != NULL)
  {
    free(unquoted_description_input);
    unquoted_description_input = NULL;
  }
  if (unquoted_filename_input != NULL)
  {
    free(unquoted_filename_input);
    unquoted_filename_input = NULL;
  }
  if (unquoted_blorbfile_input != NULL)
  {
    free(unquoted_blorbfile_input);
    unquoted_blorbfile_input = NULL;
  }
  if (unquoted_filetype_input != NULL)
  {
    free(unquoted_filetype_input);
    unquoted_filetype_input = NULL;
  }
}


void abort_entry_input()
{
  if (serial_input != NULL)
  {
    free(serial_input);
    serial_input = NULL;
  }
  serial_input_size = 0;

  if (title_input != NULL)
  {
    free(title_input);
    title_input = NULL;
  }
  title_input_size = 0;

  if (author_input != NULL)
  {
    free(author_input);
    author_input = NULL;
  }
  author_input_size = 0;

  if (description_input != NULL)
  {
    free(description_input);
    description_input = NULL;
  }
  description_input_size = 0;

  if (filename_input != NULL)
  {
    free(filename_input);
    filename_input = NULL;
  }
  filename_input_size = 0;

  if (blorbfile_input != NULL)
  {
    free(blorbfile_input);
    blorbfile_input = NULL;
  }
  blorbfile_input_size = 0;

  if (filetype_input != NULL)
  {
    free(filetype_input);
    filetype_input = NULL;
  }
  filetype_input_size = 0;

  free_unquote_buffers();

  fclose(in);
}


void free_z_story_list_entry(struct z_story_list_entry *entry)
{
  if (entry->serial != NULL)
    free(entry->serial);
  if (entry->title != NULL)
    free(entry->title);
  if (entry->author != NULL)
    free(entry->author);
  if (entry->description != NULL)
    free(entry->description);
  if (entry->filename != NULL)
    free(entry->filename);
  if (entry->blorbfile != NULL)
    free(entry->blorbfile);
  if (entry->filetype != NULL)
    free(entry->filetype);
  free(entry);
}


void free_z_story_list(struct z_story_list *story_list)
{
  if (story_list == NULL)
    return;

  while (story_list->nof_entries > 0)
  {
    free_z_story_list_entry(story_list->entries[story_list->nof_entries - 1]);
    story_list->nof_entries--;
  }

  free(story_list->entries);
  free(story_list);
}


int parse_next_story_entry()
{
  bool parse_error;
  int index;
  int data;
  long offset;
  long size;

  parse_error = false;

  index = 0;
  release_input = 0;
  while (index < 5)
  {
    if ((data = fgetc(in)) == EOF)
    {
      if (index == 0) break;
      else { abort_entry_input(); TRACE_LOG("#0\n"); return -1; }
    }
    if (data == '\t') break;
    if (isdigit(data) == 0) { parse_error = true; break; }
    release_input *= 10;
    release_input += (data - '0');
    index++;
  }

  if ( (index == 5) && (fgetc(in) != '\t') )
  { abort_entry_input(); TRACE_LOG("#1\n"); return -1; }

  offset = ftell(in);
  while ((data = fgetc(in)) != '\t')
    if (data == EOF)
    { abort_entry_input(); TRACE_LOG("#2\n"); return -1; }
  size = ftell(in) - offset - 1;
  if (ensure_mem_size(&serial_input, &serial_input_size, size + 2) == -1)
  { abort_entry_input(); TRACE_LOG("#3\n"); return -1; }
  if (size > 0)
  {
    fseek(in, -(size+1), SEEK_CUR);
    if (fread(serial_input, size+1, 1, in) != 1)
    { abort_entry_input(); TRACE_LOG("#4\n"); return -1; }
  }
  serial_input[size] = '\0';
  unquoted_serial_input = unquote_special_chars(serial_input);

  index = 0;
  length_input = 0;
  do
  {
    if ((data = fgetc(in)) == EOF)
    { abort_entry_input(); TRACE_LOG("#5\n"); return -1; }
    if (data != '\t')
    {
      if (isdigit(data) == 0) { parse_error = true; break; }
      length_input *= 10;
      length_input += (data - '0');
    }
  }
  while (data != '\t');

  index = 0;
  checksum_input = 0;
  while (index < 5)
  {
    if ((data = fgetc(in)) == EOF)
    { abort_entry_input(); TRACE_LOG("#6\n"); return -1; }
    if (data == '\t') break;
    if (isdigit(data) == 0) { TRACE_LOG("#7\n"); return -1; }
    checksum_input *= 10;
    checksum_input += (data - '0');
    index++;
  }
  TRACE_LOG("cs:%d\n", checksum_input);

  if ( (index == 5) && (fgetc(in) != '\t') )
  { abort_entry_input(); TRACE_LOG("#8\n"); return -1; }

  if ((data = fgetc(in)) == EOF)
  { abort_entry_input(); TRACE_LOG("#9\n"); return -1; }
  TRACE_LOG("data:%c\n", data);
  if (isdigit(data) == 0)
  { abort_entry_input(); TRACE_LOG("#10\n"); return -1; }
  version_input = data - '0';
  TRACE_LOG("versioninput:%c\n", version_input);

  if (fgetc(in) != '\t')
  { abort_entry_input(); TRACE_LOG("#11\n"); return -1; }

  offset = ftell(in);
  while ((data = fgetc(in)) != '\t')
    if (data == EOF)
    { abort_entry_input(); TRACE_LOG("#12\n"); return -1; }
  size = ftell(in) - offset - 1;
  if (ensure_mem_size(&title_input, &title_input_size, size + 2) == -1)
  { abort_entry_input(); TRACE_LOG("#13\n"); return -1; }
  if (size > 0)
  {
    fseek(in, -(size+1), SEEK_CUR);
    if (fread(title_input, size+1, 1, in) != 1)
    { abort_entry_input(); TRACE_LOG("#14\n"); return -1; }
  }
  title_input[size] = '\0';
  unquoted_title_input = unquote_special_chars(title_input);
  //printf("title:[%s]\n", title_input);

  offset = ftell(in);
  while ((data = fgetc(in)) != '\t')
    if (data == EOF) { abort_entry_input(); TRACE_LOG("#15\n"); return -1; }
  size = ftell(in) - offset - 1;
  if (ensure_mem_size(&author_input, &author_input_size, size + 2) == -1)
  { abort_entry_input(); TRACE_LOG("#16\n"); return -1; }
  if (size > 0)
  {
    fseek(in, -(size+1), SEEK_CUR);
    if (fread(author_input, size+1, 1, in) != 1)
    { abort_entry_input(); TRACE_LOG("#17\n"); return -1; }
  }
  author_input[size] = '\0';
  unquoted_author_input = unquote_special_chars(author_input);
  //printf("author:[%s]\n", author_input);

  offset = ftell(in);
  while ((data = fgetc(in)) != '\t')
    if (data == EOF)
    { abort_entry_input(); TRACE_LOG("#18\n"); return -1; }
  size = ftell(in) - offset - 1;
  if (ensure_mem_size(&description_input, &description_input_size, size+2)==-1)
  { abort_entry_input(); TRACE_LOG("#19\n"); return -1; }
  if (size > 0)
  {
    fseek(in, -(size+1), SEEK_CUR);
    if (fread(description_input, size+1, 1, in) != 1)
    { abort_entry_input(); TRACE_LOG("#20\n"); return -1; }
  }
  description_input[size] = '\0';
  unquoted_description_input = unquote_special_chars(description_input);
  //printf("desc:[%s]\n", description_input);

  offset = ftell(in);
  while ((data = fgetc(in)) != '\t')
    if (data == EOF)
    { abort_entry_input(); TRACE_LOG("#21\n"); return -1; }
  size = ftell(in) - offset - 1;
  if (ensure_mem_size(&filename_input, &filename_input_size, size + 2) == -1)
  { abort_entry_input(); TRACE_LOG("#22\n"); return -1; }
  if (size > 0)
  {
    fseek(in, -(size+1), SEEK_CUR);
    if (fread(filename_input, size+1, 1, in) != 1)
    { abort_entry_input(); TRACE_LOG("#23\n"); return -1; }
  }
  filename_input[size] = '\0';
  unquoted_filename_input = unquote_special_chars(filename_input);

  offset = ftell(in);
  while ((data = fgetc(in)) != '\t')
    if (data == EOF)
    { abort_entry_input(); TRACE_LOG("#24\n"); return -1; }
  size = ftell(in) - offset - 1;
  if (ensure_mem_size(&blorbfile_input, &blorbfile_input_size, size + 2) == -1)
  { abort_entry_input(); TRACE_LOG("#25\n"); return -1; }
  if (size > 0)
  {
    fseek(in, -(size+1), SEEK_CUR);
    if (fread(blorbfile_input, size+1, 1, in) != 1)
    { abort_entry_input(); TRACE_LOG("#26\n"); return -1; }
  }
  blorbfile_input[size] = '\0';
  unquoted_blorbfile_input = unquote_special_chars(blorbfile_input);

  offset = ftell(in);
  while ((data = fgetc(in)) != '\t')
    if (data == EOF)
    { abort_entry_input(); TRACE_LOG("#27\n"); return -1; }
  size = ftell(in) - offset - 1;
  if (ensure_mem_size(&filetype_input, &filetype_input_size, size + 2) == -1)
  { abort_entry_input(); TRACE_LOG("#28\n"); return -1; }
  if (size > 0)
  {
    fseek(in, -(size+1), SEEK_CUR);
    if (fread(filetype_input, size+1, 1, in) != 1)
    { abort_entry_input(); TRACE_LOG("#29\n"); return -1; }
  }
  filetype_input[size] = '\0';
  unquoted_filetype_input = unquote_special_chars(filetype_input);

  index = 0;
  storyfile_timestamp_input = 0;
  while (index < 16)
  {
    if ((data = fgetc(in)) == EOF)
    { abort_entry_input(); TRACE_LOG("#30\n"); return -1; }
    if (data == '\n')
    { ungetc(data, in); break; }
    if (isdigit(data) == 0) { parse_error = true; break; }
    storyfile_timestamp_input *= 10;
    storyfile_timestamp_input += (data - '0');
    index++;
  }
  //printf("filename:[%s]\n", filename_input);

  /*
  printf("%d|%s|%d|%s|%s|%s|%s\n", release_input, serial_input,
      checksum_input, title_input, author_input, description_input,
      filename_input);
  */

  while ((data = fgetc(in)) != '\n')
    if (data == EOF) break;

  return 0;
}


static char *get_filelist_name()
{
  char *dir_name = get_fizmo_config_dir_name();
  char *filename;

  if (dir_name == NULL)
    return NULL;

  filename = malloc(strlen(dir_name) + 16);
  strcpy(filename, dir_name);
  strcat(filename, "/story-list.txt");

  return filename;
}


static FILE *open_story_list(char *mode)
{
  char *filename;
  FILE *result;

  if ((filename = get_filelist_name()) == NULL)
    return NULL;
  //printf("%s\n", filename);

  result = fopen(filename, mode);
  free(filename);
  return result;
}


struct z_story_list_entry *store_current_entry()
{
  struct z_story_list_entry *result;

  if ((result = malloc(sizeof(struct z_story_list_entry))) == NULL)
    return NULL;

  //printf("storing %s, %d, %d\n", serial_input, release_input, length_input);

  result->release_number = release_input;
  result->serial = fizmo_strdup(unquoted_serial_input);
  result->z_code_version = version_input;
  result->length = length_input;
  result->checksum = checksum_input;
  result->title = fizmo_strdup(unquoted_title_input);
  result->author = fizmo_strdup(unquoted_author_input);
  result->description = fizmo_strdup(unquoted_description_input);
  result->filename = fizmo_strdup(unquoted_filename_input);
  result->blorbfile = fizmo_strdup(unquoted_blorbfile_input);
  result->filetype = fizmo_strdup(unquoted_filetype_input);
  //result->entry_line_index = line_index;
  result->storyfile_timestamp = storyfile_timestamp_input;

  return result;
}


struct z_story_list_entry *add_entry_to_story_list(
    struct z_story_list *story_list, char *title, char *author,
    char *description, char *serial, int version, int length,
    uint16_t checksum, uint16_t release, char *story_filename,
    char *story_blorbfile, char *story_filetype, long storyfile_timestamp)
//, int line_index)
{
  void *ptr;
  struct z_story_list_entry *result;
  int insert_index;

  //printf("Adding %d:%s\n", story_list->nof_entries, story_filename);

  TRACE_LOG("New story: %s, \"%s\".\n",
      story_filename,
      description != NULL ? description : "");

  if (story_list->nof_entries == story_list->nof_entries_allocated)
  {
    if ((ptr = (struct z_story_list_entry**)fizmo_realloc(
            story_list->entries,
            sizeof(struct z_story_list_entry*)
            * (story_list->nof_entries_allocated + 10))) == NULL)
      return NULL;

    story_list->entries = ptr;
    story_list->nof_entries_allocated += 10;
  }

  if ((result = malloc(sizeof(struct z_story_list_entry))) == NULL)
    return NULL;

  result->release_number = release;
  result->serial = fizmo_strdup(serial);
  result->z_code_version = version;
  result->length = length;
  result->checksum = checksum;
  result->title = fizmo_strdup(title);
  result->author = fizmo_strdup(author);
  result->description = fizmo_strdup(description);
  result->filename = fizmo_strdup(story_filename);
  result->blorbfile
    = (story_blorbfile != NULL ? fizmo_strdup(story_blorbfile) : NULL);
  result->filetype = fizmo_strdup(story_filetype);
  result->storyfile_timestamp = storyfile_timestamp;

  insert_index = 0;
  while (insert_index < story_list->nof_entries)
  {
    if (strcmp(result->title, story_list->entries[insert_index]->title) < 0)
      break;
    insert_index++;
  }

  if (insert_index < story_list->nof_entries)
  {
    memmove(
        story_list->entries + insert_index + 1,
        story_list->entries + insert_index,
        (story_list->nof_entries - insert_index)
        * sizeof(struct z_story_list_entry*));
  }

  story_list->entries[insert_index] = result;
  story_list->nof_entries++;

  return result;
}


struct z_story_list *get_empty_z_story_list()
{
  struct z_story_list *result;

  if ((result = malloc(sizeof(struct z_story_list))) == NULL)
    return NULL;

  result->nof_entries_allocated = 0;
  result->nof_entries = 0;
  result->entries = NULL;

  return result;
}


struct z_story_list *get_z_story_list()
{
  int data;
  struct z_story_list *result = get_empty_z_story_list();

  if ((in = open_story_list("r")) == NULL)
    return result;

  for(;;)
  {
    if ((data = fgetc(in)) == EOF)
    {
      abort_entry_input();
      return result;
    }
    else
      ungetc(data, in);

    if (parse_next_story_entry() == -1)
    {
      abort_entry_input();
      return result;
    }

    add_entry_to_story_list(
        result,
        unquoted_title_input,
        unquoted_author_input,
        unquoted_description_input,
        unquoted_serial_input,
        version_input,
        length_input,
        checksum_input,
        release_input,
        unquoted_filename_input,
        unquoted_blorbfile_input,
        unquoted_filetype_input,
        storyfile_timestamp_input);
  }
}


 // This method reads story info from a parsed list. For other purposes, see
// function "get_z_story_entry_from_list".
static struct z_story_list_entry *get_z_story_entry(char *serial,
    uint16_t release, int length, struct z_story_list *story_list)
{
  struct z_story_list_entry *entry;
  int i = 0;

  if (story_list == NULL)
    return NULL;

  //printf("looking for: %s, %d, %d\n", serial, release, length);

  while (i < story_list->nof_entries)
  {
    entry = story_list->entries[i];
    /*
    printf("cmp(%d): %s/%s, %d/%d, %d/%d\n", i,entry->serial, serial,
        entry->release_number, release,
        entry->length, length);
    */

    if (
        (strcmp(entry->serial, serial) == 0)
        &&
        (entry->release_number == release)
        &&
        (entry->length == length)
       )
    {
      //printf("Found\n");
      return entry;
    }

    i++;
  }

  return NULL;
}


// This method will parse entries in the story-list until a matching one
// has been found. It will discard all non-matches and return only a single
// entry, making it useful for retrieving data about a single story when
// the list is not needed. To get an entry from an already parsed list, see
// "get_z_story_entry" instead.
struct z_story_list_entry *get_z_story_entry_from_list(char *serial,
    uint16_t release, uint16_t checksum)
{
  struct z_story_list_entry *result;
  int data;

  if ((in = open_story_list("r")) == NULL)
    return NULL;

  for(;;)
  {
    if ((data = fgetc(in)) == EOF)
    {
      abort_entry_input();
      return NULL;
    }
    else
      ungetc(data, in);

    if (parse_next_story_entry() == -1)
    {
      abort_entry_input();
      return NULL;
    }

    if (
        (strcmp(serial_input, serial) == 0)
        && (release_input == release)
        && (checksum_input == checksum) )
    {
      result = store_current_entry(); //line_index);
      abort_entry_input();
      return result;
    }
  }
}


int remove_entry_from_list(struct z_story_list *story_list,
    struct z_story_list_entry *entry)
{
  int entry_index = 0;

  while (entry_index < story_list->nof_entries)
  {
    if (story_list->entries[entry_index] == entry)
      break;
    entry_index++;
  }

  if (entry_index >= story_list->nof_entries)
    return -1;

  if (entry_index + 1 < story_list->nof_entries)
  {
    memmove(
        story_list->entries + entry_index,
        story_list->entries + entry_index + 1,
        sizeof(struct z_story_list_entry*)
        * (story_list->nof_entries - entry_index - 1));
  }

  story_list->nof_entries--;

  return 0;
}


static int detect_and_add_z_file(char *filename, char *blorb_filename,
    struct babel_info *babel, struct z_story_list *story_list)
{
  FILE *infile;
  uint8_t buf[30];
  uint32_t val;
  char serial[7];
  int version;
  uint16_t checksum;
  uint16_t release;
  struct babel_story_info *b_info = NULL;
  char *title;
  char *author;
  char *description;
  char *ptr, *ptr2;
  int length;
  long storyfile_timestamp;
  char *empty_string = "";
  struct stat stat_buf;
  struct z_story_list_entry *entry;
  int chunk_length = -1;
  struct babel_info *file_babel = NULL;
  bool file_is_zblorb;
  char *cwd = NULL;
  char *abs_filename = NULL;

  if (filename == NULL)
    return -1;

  if (filename[0] != '/')
  {
    cwd = getcwd(NULL, 0);
    abs_filename = fizmo_malloc(strlen(cwd) + strlen(filename) + 2);
    sprintf(abs_filename, "%s/%s", cwd, filename);
  }
  else
    abs_filename = filename;

  if ((infile = fopen(abs_filename, "r")) == NULL)
  {
    if (cwd != NULL)
    {
      free(cwd);
      free(abs_filename);
    }
    return -1;
  }

  if (fstat(fileno(infile), &stat_buf) != 0)
  {
    fclose(infile);
    if (cwd != NULL)
    {
      free(cwd);
      free(abs_filename);
    }
    return -1;
  }

  storyfile_timestamp = stat_buf.st_ctime;

  if (fread(buf, 30, 1, infile) != 1)
  {
    fclose(infile);
    if (cwd != NULL)
    {
      free(cwd);
      free(abs_filename);
    }
    return -1;
  }

  if (memcmp(buf, "FORM", 4) == 0)
  {
    // IFF file.

    if (
        (is_form_type(infile, "IFRS") != true)
        ||
        (find_chunk("ZCOD", infile) == -1)
       )
    {
      fclose(infile);
      if (cwd != NULL)
      {
        free(cwd);
        free(abs_filename);
      }
      return -1;
    }

    file_is_zblorb = true;

    if (find_chunk("IFmd", infile) == 0)
    {
      read_chunk_length(infile);
      chunk_length = get_last_chunk_length();
      file_babel = load_babel_info_from_blorb(
          infile, chunk_length, abs_filename, &stat_buf);
      babel = file_babel;
    }

    find_chunk("ZCOD", infile);
    read_chunk_length(infile);
    length = get_last_chunk_length();

    if (fread(buf, 30, 1, infile) != 1)
    {
      fclose(infile);
      if (cwd != NULL)
      {
        free(cwd);
        free(abs_filename);
      }
      return -1;
    }
  }
  else
  {
    fseek(infile, 0, SEEK_END);
    length = ftell(infile);
    file_is_zblorb = false;
  }
  fclose(infile);

  val = (buf[16] << 24) | (buf[17] << 16) | (buf[18] << 8) | (buf[19]);
  if (
      ((val & 0xbe00f0f0) != 0x3030)
      ||
      (*buf < 1)
      ||
      (*buf > 8)
     )
  {
    if (cwd != NULL)
    {
      free(cwd);
      free(abs_filename);
    }
    return -2;
  }

  version = *buf;
  memcpy(serial, buf + 0x12, 6);
  serial[6] = '\0';
  checksum = (buf[0x1c] << 8) | buf[0x1d];
  release = (buf[2] << 8) | buf[3];

  if ((entry = get_z_story_entry(serial, release, length, story_list))
      != NULL)
  {
    // We already have the story in our story-list. If we have a raw file
    // we can just quit if the support-blorbfilename is the same (raw files
    // don't contain metadata which might have changed).
    if (
        (file_is_zblorb == false)
        &&
        (
         ( (entry->blorbfile == NULL) && (blorb_filename != NULL) )
         // ||  (Don't delete blorb file)
         // ( (blorb_filename == NULL) && (entry->blorbfile != NULL) )
         ||
         (
          (entry->blorbfile != NULL)
          &&
          (blorb_filename != NULL)
          &&
          (strcmp(blorb_filename, entry->blorbfile) == 0)
         )
        )
       )
    {
      if (cwd != NULL)
      {
        free(cwd);
        free(abs_filename);
      }
      return -3;
    }

    //printf("%ld / %ld\n", storyfile_timestamp, entry->storyfile_timestamp);

    // In case new file is a zblorb and we have save a raw file, remove the
    // raw and keep the blorb (so we can get images and sound). We'll also
    // re-read the file contents if the file has changed (metadata might
    // have been altered).
    if (
        (strcmp(entry->filetype, filetype_raw) == 0)
        ||
        (storyfile_timestamp > entry->storyfile_timestamp)
       )
    {
      remove_entry_from_list(story_list, entry);
      //printf("%s...\n", abs_filename);
    }
    else
    {
      if (cwd != NULL)
      {
        free(cwd);
        free(abs_filename);
      }
      return -4;
    }
  }

  ptr2 = NULL;

  if ((b_info = get_babel_story_info(
          release, serial, checksum, babel, file_is_zblorb)) != NULL)
  {
    title = (b_info->title == NULL ? empty_string : b_info->title);
    author = (b_info->author == NULL ? empty_string : b_info->author);
    description
      = (b_info->description != NULL)
      ? b_info->description
      : empty_string;
  }
  else
  {
    if ((title = strrchr(abs_filename, '/')) == NULL)
      title = abs_filename;
    else
      title++;

    if ((ptr = strrchr(title, '.')) != NULL)
    {
      TRACE_LOG("strdup: %s\n", title);
      ptr2 = fizmo_strdup(title);
      ptr = strrchr(ptr2, '.');

      if (
          ( (strlen(ptr) == 3)
            && (ptr[1] == 'z')
            && (isdigit(ptr[2]) != 0) )
          ||
          (strcasecmp(ptr, ".dat") == 0)
         )
        *ptr = '\0';

      *ptr2 = toupper(*ptr2);

      title = ptr2;
    }

    author = empty_string;
    description = empty_string;
  }

  add_entry_to_story_list(
      story_list,
      title,
      author,
      description,
      serial,
      version,
      length,
      checksum,
      release,
      abs_filename,
      file_is_zblorb ? NULL : blorb_filename,
      file_is_zblorb ? filetype_zblorb : filetype_raw,
      storyfile_timestamp);

  if (b_info != NULL)
    free_babel_story_info(b_info);

  if (ptr2 != NULL)
    free(ptr2);

  if (file_babel != NULL)
    free_babel_info(file_babel);

  if (cwd != NULL)
  {
    free(cwd);
    free(abs_filename);
  }

  return 0;
}


static int count_files(char *abs_dir_name, bool recursive)
{
  DIR *current_dir;
  struct dirent dir_entry;
  struct dirent* ptr;
  char *dirname = NULL;
  int dirname_size = 0;
  int len;
  int result = 0;
  char *cwd = getcwd(NULL, 0);
  int fildes;
  int fstat_retval;
  struct stat stat_buf;

  if ((chdir(abs_dir_name)) == -1)
  {
    free(cwd);
    return 0;
  }

  if ((current_dir = opendir(".")) == NULL)
  {
    printf("\"%s\":\n", abs_dir_name);
    perror("could not opendir");
    chdir(cwd);
    free(cwd);
    return 0;
  }

  while (
      (readdir_r(current_dir, &dir_entry, &ptr) == 0)
      &&
      (ptr != NULL)
      )
  {
    if (
        (strcmp(dir_entry.d_name, ".") == 0)
        ||
        (strcmp(dir_entry.d_name, "..") == 0)
       )
      continue;

    len = strlen(abs_dir_name) + strlen(dir_entry.d_name) + 2;
    if (len > dirname_size)
    {
      dirname = (char*)fizmo_realloc(dirname, len);
      dirname_size = len;
    }

    strcpy(dirname, abs_dir_name);
    if (dirname[strlen(dirname) - 1] != '/')
      strcat(dirname, "/");
    strcat(dirname, dir_entry.d_name);

    // No d_type in struct dirent in cygwin, using fstat instead.
    // http://cygwin.com/ml/cygwin/2005-04/msg01040.html
    if ((fildes = open(dir_entry.d_name, O_RDONLY)) != -1)
    {
      fstat_retval = fstat(fildes, &stat_buf);
      close(fildes);

      if (fstat_retval == 0)
      {
        if ((stat_buf.st_mode & S_IFDIR) != 0)
        {
          if (recursive == true)
            result += count_files(dirname, true);
        }
        else
        {
          result++;
        }
      }
    }
  }

  if (dirname != NULL)
    free(dirname);

  closedir(current_dir);

  chdir(cwd);
  free(cwd);

  //printf("result:%d\n", result);

  return result;
}


static int search_dir(char *abs_dir_name,
    void (*update_func)(char *filename, char *dirname),
    struct z_story_list *story_list, bool recursive, struct babel_info *babel)
{
  DIR *current_dir;
  struct dirent dir_entry;
  struct dirent* ptr;
  char *dirname = NULL;
  int dirname_size = 0;
  int len;
  int fildes;
  int fstat_retval;
  struct stat stat_buf;
  char *cwd = getcwd(NULL, 0);

  //printf("Trying to readdir \"%s\".\n", abs_dir_name);

  if ((chdir(abs_dir_name)) == -1)
  {
    return -1;
  }
  //printf("chdir %s okay.\n", abs_dir_name);

  if ((current_dir = opendir(".")) == NULL)
  {
    printf("\"%s\":\n", abs_dir_name);
    perror("could not opendir");
    return -1;
  }

  if ( (show_progress == true) && (update_func != NULL) )
    update_func(NULL, abs_dir_name);

  while (
      (readdir_r(current_dir, &dir_entry, &ptr) == 0)
      &&
      (ptr != NULL)
      )
  {
    if (
        (strcmp(dir_entry.d_name, ".") == 0)
        ||
        (strcmp(dir_entry.d_name, "..") == 0)
       )
      continue;

    //printf("#:%s\n", dir_entry.d_name);

    len = strlen(abs_dir_name) + strlen(dir_entry.d_name) + 2;
    if (len > dirname_size)
    {
      dirname = (char*)fizmo_realloc(dirname, len);
      dirname_size = len;
    }

    strcpy(dirname, abs_dir_name);
    if (dirname[strlen(dirname) - 1] != '/')
      strcat(dirname, "/");
    strcat(dirname, dir_entry.d_name);

    // No d_type in struct dirent in cygwin, using fstat instead.
    // http://cygwin.com/ml/cygwin/2005-04/msg01040.html
    if ((fildes = open(dir_entry.d_name, O_RDONLY)) != -1)
    {
      fstat_retval = fstat(fildes, &stat_buf);
      close(fildes);

      if (fstat_retval == 0)
      {
        if ((stat_buf.st_mode & S_IFDIR) != 0)
	{
	  if (recursive == true)
	    search_dir(dirname, update_func, story_list, true, babel);
	}
	else
	{
          if ( (show_progress == true) && (update_func != NULL) )
            update_func(dir_entry.d_name, NULL);
	  //printf("%s\n", dir_entry.d_name);
	  detect_and_add_z_file(dirname, NULL, babel, story_list);
	}
      }
    }
  }

  if (dirname != NULL)
    free(dirname);

  closedir(current_dir);

  chdir(cwd);
  free(cwd);

  return 0;
}


void build_filelist(char *root_dir, struct z_story_list *story_list,
    bool recursive, struct babel_info *babel)
{
  char *cwd = getcwd(NULL, 0);
  char *absrootdir;

  if (root_dir == NULL)
    search_dir("/", &new_file_searched, story_list, recursive, babel);
  else
  {
    if ((chdir(root_dir)) == -1)
      detect_and_add_z_file(root_dir, NULL, babel, story_list);
    else
    {
      absrootdir = getcwd(NULL, 0); // Avoid relative names like "./zork1.z3".
      search_dir(absrootdir, &new_file_searched, story_list, recursive, babel);
      free(absrootdir);
    }
  }

  chdir(cwd);
  free(cwd);
}


void save_story_list(struct z_story_list *story_list)
{
  FILE *out;
  struct z_story_list_entry *entry;
  int i = 0;
  char *quoted_serial = NULL;
  char *quoted_title = NULL;
  char *quoted_author = NULL;
  char *quoted_description = NULL;
  char *quoted_filename = NULL;
  char *quoted_blorbname = NULL;
  char *quoted_filetype= NULL;

  if ((out = open_story_list("w")) == NULL)
    return;

  while (i < story_list->nof_entries)
  {
    entry = story_list->entries[i++];

    quoted_serial = quote_special_chars(entry->serial);
    quoted_title = quote_special_chars(entry->title);
    quoted_author = quote_special_chars(entry->author);
    quoted_description = quote_special_chars(entry->description);
    quoted_filename = quote_special_chars(entry->filename);
    quoted_blorbname = quote_special_chars(entry->blorbfile);
    quoted_filetype = quote_special_chars(entry->filetype);

    //printf("%d/%d\n", i, story_list->nof_entries);

    fprintf(
        out,
        "%d\t%s\t%d\t%d\t%d\t%s\t%s\t%s\t%s\t%s\t%s\t%ld\n",
        entry->release_number,
        quoted_serial,
        entry->length,
        entry->checksum,
        entry->z_code_version,
        (quoted_title == NULL ? "" : quoted_title),
        (quoted_author == NULL ? "" : quoted_author),
        (quoted_description == NULL ? "" : quoted_description),
        quoted_filename,
        (quoted_blorbname == NULL ? "" : quoted_blorbname),
        quoted_filetype,
        entry->storyfile_timestamp);

    if (quoted_serial != NULL)
      free(quoted_serial);

    if (quoted_title != NULL)
      free(quoted_title);

    if (quoted_author != NULL)
      free(quoted_author);

    if (quoted_description != NULL)
      free(quoted_description);

    if (quoted_filename != NULL)
      free(quoted_filename);

    if (quoted_blorbname != NULL)
      free(quoted_blorbname);

    if (quoted_filetype != NULL)
      free(quoted_filetype);
  }

  fclose(out);
}


struct z_story_list *update_fizmo_story_list(char *fizmo_dir)
{
  struct z_story_list *result;
  struct z_story_list_entry *entry;
  char *str, *path;
  FILE *file;
  struct babel_info *babel;
  int i;

  nof_files_found = 0;
  nof_files_searched = 0;
  nof_directories_searched = 0;

  ensure_dot_fizmo_dir_exists();

  babel = load_babel_info();

  if (babel_files_have_changed(babel) == true)
  {
    // Don't load current list of story, rebuild index with the newly
    // changed babel data.
    result = get_empty_z_story_list();
    store_babel_info_timestamps(babel);
  }
  else
  {
    // Babel data is the same, use pre-indexed story list.
    result = get_z_story_list();
    i = 0;
    while (i < result->nof_entries)
    {
      entry = result->entries[i];
      if ((file = fopen(entry->filename, "r")) == NULL)
        remove_entry_from_list(result, entry);
      else
      {
        fclose(file);
        i++;
      }
    }
  }

  //nof_files_found = count_files(".", false);

  if (fizmo_dir != NULL)
    nof_files_found += count_files(fizmo_dir, false);

  if ((str = getenv("ZCODE_PATH")) == NULL)
    str = getenv("INFOCOM_PATH");

  if (str != NULL)
    set_configuration_value("z-code-path", str);

  if ((str = get_configuration_value("z-code-path")) != NULL)
  {
    path = strtok(str, ":");
    while (path != NULL)
    {
      nof_files_found += count_files(path, false);
      path = strtok(NULL, ":");
    }
  }

  if ((str = getenv("ZCODE_ROOT_PATH")) != NULL)
  {
    path = strtok(str, ":");
    while (path != NULL)
    {
      nof_files_found += count_files(path, true);
      path = strtok(NULL, ":");
    }
  }

  if (nof_files_found >= NUMBER_OF_FILES_TO_SHOW_PROGRESS_FOR)
    show_progress = true;
  else
    show_progress = false;

  //printf("\n"); // newline for \r-progress indicator

  //build_filelist(".", result, false, babel);

  if (fizmo_dir != NULL)
    build_filelist(fizmo_dir, result, false, babel);

  if ((str = getenv("ZCODE_PATH")) == NULL)
    str = getenv("INFOCOM_PATH");

  if (str != NULL)
    set_configuration_value("z-code-path", str);

  if ((str = get_configuration_value("z-code-path")) != NULL)
  {
    path = strtok(str, ":");
    while (path != NULL)
    {
      build_filelist(path, result, false, babel);
      path = strtok(NULL, ":");
    }
  }

  if ((str = getenv("ZCODE_ROOT_PATH")) != NULL)
  {
    path = strtok(str, ":");
    while (path != NULL)
    {
      build_filelist(path, result, true, babel);
      path = strtok(NULL, ":");
    }
  }

  if (show_progress == true)
    printf("\n");

  TRACE_LOG("noffiles: %d\n", result->nof_entries);

  save_story_list(result);
  store_babel_info_timestamps(babel);

  free_babel_info(babel);

  return result;
}


void detect_and_add_single_z_file(char *input_filename, char *blorb_filename)
{
  struct z_story_list *z_story_list = get_z_story_list();
  struct babel_info *babel = load_babel_info();

  TRACE_LOG("noffiles: %d\n", z_story_list->nof_entries);

  detect_and_add_z_file(input_filename, blorb_filename, babel, z_story_list);

  TRACE_LOG("noffiles: %d\n", z_story_list->nof_entries);

  save_story_list(z_story_list);
  store_babel_info_timestamps(babel);
  free_z_story_list(z_story_list);
  free_babel_info(babel);
}


void search_directory(char *absolute_dirname, bool recursive)
{
  struct z_story_list *z_story_list = get_z_story_list();
  struct babel_info *babel = load_babel_info();

  if ((nof_files_found = count_files(absolute_dirname, recursive)) > 0)
  {
    show_progress = true;
    nof_files_searched = 0;
    nof_directories_searched = 0;
    build_filelist(absolute_dirname, z_story_list, recursive, babel);
  }

  //printf("%d, %s\n", z_story_list->nof_entries, absolute_dirname);
  save_story_list(z_story_list);
  store_babel_info_timestamps(babel);
  free_z_story_list(z_story_list);
  free_babel_info(babel);
}

