static int open_db_table(char *name, FILE **file_ptr, 
                         int *count_ptr, int record_size)
{
  long file_length;
  int file_records;
  FILE *file;

  /* We want to open for reading and writing, but
     create if necessary. Here we open for append
     to create if needed, then reopen as we need */
  file = fopen(name,"a+");
  if(!file)
    return DVD_ERR_NO_FILE;
  file_length = ftell(file);

  file = freopen(name, "r+", file);

  file_records = file_length/record_size;
  if(file_records * record_size != file_length)
    return DVD_ERR_BAD_TABLE;

  if(file_records == 0) {
    /* We just created the file. As we use id zero as a
       sentinel we need to reserve the first entry in the
       file, so add a dummy record here */
    file_records = 1;
  }

  *file_ptr = file;
  *count_ptr = file_records;
  return DVD_SUCCESS;
}

int dvd_open_db()
{
  /* Only open the database table once */
  if(dvd_db_ok)
    return DVD_SUCCESS;

  /*  if(open_db_table(MEMBER_FILE, &member_file, 
      &member_count, sizeof(dvd_store_member)))
      return DVD_ERR_BAD_MEMBER_TABLE; */

  if(open_db_table(TITLE_FILE, &title_file, 
                   &title_count, sizeof(dvd_title)))
    return DVD_ERR_BAD_TITLE_TABLE;

  if(open_db_table(DISK_FILE, &disk_file, 
                   &disk_count, sizeof(dvd_disk)))
    return DVD_ERR_BAD_DISK_TABLE;

  if(open_db_table(RENTAL_FILE, &rental_file, 
                   &rental_count, sizeof(dvd_rental)))
    return DVD_ERR_BAD_RENTAL_TABLE;

  if(open_db_table(RESERVE_FILE, &reserve_file, 
                   &reserve_count, sizeof(dvd_reserve)))
    return DVD_ERR_BAD_RESERVE_TABLE;

  dvd_db_ok = 1;
  return DVD_SUCCESS;
}

int dvd_close_db()
{
  /* Close the database tables
     Ought to check return result from the fclose
  */
  if(member_file) 
    fclose(member_file);
  if(title_file)
    fclose(title_file);
  if(disk_file)
    fclose(disk_file);
  dvd_db_ok = 0;
  
  return DVD_SUCCESS;
}

static int file_set(FILE *file, long file_position, int size, void *data)
{
  if(fseek(file, file_position, SEEK_SET) != 0)
    return DVD_ERR_BAD_SEEK;

  if(fwrite(data, size, 1, file) != 1)
    return DVD_ERR_BAD_WRITE;

  return DVD_SUCCESS;
}

static int file_get(FILE *file, long file_position, int size, void *data)
{
  if(fseek(file, file_position, SEEK_SET) != 0)
    return DVD_ERR_BAD_SEEK;

  if(fread(data, size, 1, file) != 1)
    return DVD_ERR_BAD_READ;

  return DVD_SUCCESS;
}
